echarts.common.js 2.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581
  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. || navigator.userAgent.indexOf('Node.js') === 0) {
  86. env.node = true;
  87. env.svgSupported = true;
  88. }
  89. else {
  90. detect(navigator.userAgent, env);
  91. }
  92. function detect(ua, env) {
  93. var browser = env.browser;
  94. var firefox = ua.match(/Firefox\/([\d.]+)/);
  95. var ie = ua.match(/MSIE\s([\d.]+)/)
  96. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  97. var edge = ua.match(/Edge?\/([\d.]+)/);
  98. var weChat = (/micromessenger/i).test(ua);
  99. if (firefox) {
  100. browser.firefox = true;
  101. browser.version = firefox[1];
  102. }
  103. if (ie) {
  104. browser.ie = true;
  105. browser.version = ie[1];
  106. }
  107. if (edge) {
  108. browser.edge = true;
  109. browser.version = edge[1];
  110. browser.newEdge = +edge[1].split('.')[0] > 18;
  111. }
  112. if (weChat) {
  113. browser.weChat = true;
  114. }
  115. env.svgSupported = typeof SVGRect !== 'undefined';
  116. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  117. env.pointerEventsSupported = 'onpointerdown' in window
  118. && (browser.edge || (browser.ie && +browser.version >= 11));
  119. env.domSupported = typeof document !== 'undefined';
  120. var style = document.documentElement.style;
  121. env.transform3dSupported = ((browser.ie && 'transition' in style)
  122. || browser.edge
  123. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  124. || 'MozPerspective' in style)
  125. && !('OTransition' in style);
  126. env.transformSupported = env.transform3dSupported
  127. || (browser.ie && +browser.version >= 9);
  128. }
  129. var DEFAULT_FONT_SIZE = 12;
  130. var DEFAULT_FONT_FAMILY = 'sans-serif';
  131. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  132. var OFFSET = 20;
  133. var SCALE = 100;
  134. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  135. function getTextWidthMap(mapStr) {
  136. var map = {};
  137. if (typeof JSON === 'undefined') {
  138. return map;
  139. }
  140. for (var i = 0; i < mapStr.length; i++) {
  141. var char = String.fromCharCode(i + 32);
  142. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  143. map[char] = size;
  144. }
  145. return map;
  146. }
  147. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  148. var platformApi = {
  149. createCanvas: function () {
  150. return typeof document !== 'undefined'
  151. && document.createElement('canvas');
  152. },
  153. measureText: (function () {
  154. var _ctx;
  155. var _cachedFont;
  156. return function (text, font) {
  157. if (!_ctx) {
  158. var canvas = platformApi.createCanvas();
  159. _ctx = canvas && canvas.getContext('2d');
  160. }
  161. if (_ctx) {
  162. if (_cachedFont !== font) {
  163. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  164. }
  165. return _ctx.measureText(text);
  166. }
  167. else {
  168. text = text || '';
  169. font = font || DEFAULT_FONT;
  170. var res = /((?:\d+)?\.?\d*)px/.exec(font);
  171. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  172. var width = 0;
  173. if (font.indexOf('mono') >= 0) {
  174. width = fontSize * text.length;
  175. }
  176. else {
  177. for (var i = 0; i < text.length; i++) {
  178. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  179. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  180. }
  181. }
  182. return { width: width };
  183. }
  184. };
  185. })(),
  186. loadImage: function (src, onload, onerror) {
  187. var image = new Image();
  188. image.onload = onload;
  189. image.onerror = onerror;
  190. image.src = src;
  191. return image;
  192. }
  193. };
  194. function setPlatformAPI(newPlatformApis) {
  195. for (var key in platformApi) {
  196. if (newPlatformApis[key]) {
  197. platformApi[key] = newPlatformApis[key];
  198. }
  199. }
  200. }
  201. var BUILTIN_OBJECT = reduce([
  202. 'Function',
  203. 'RegExp',
  204. 'Date',
  205. 'Error',
  206. 'CanvasGradient',
  207. 'CanvasPattern',
  208. 'Image',
  209. 'Canvas'
  210. ], function (obj, val) {
  211. obj['[object ' + val + ']'] = true;
  212. return obj;
  213. }, {});
  214. var TYPED_ARRAY = reduce([
  215. 'Int8',
  216. 'Uint8',
  217. 'Uint8Clamped',
  218. 'Int16',
  219. 'Uint16',
  220. 'Int32',
  221. 'Uint32',
  222. 'Float32',
  223. 'Float64'
  224. ], function (obj, val) {
  225. obj['[object ' + val + 'Array]'] = true;
  226. return obj;
  227. }, {});
  228. var objToString = Object.prototype.toString;
  229. var arrayProto = Array.prototype;
  230. var nativeForEach = arrayProto.forEach;
  231. var nativeFilter = arrayProto.filter;
  232. var nativeSlice = arrayProto.slice;
  233. var nativeMap = arrayProto.map;
  234. var ctorFunction = function () { }.constructor;
  235. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  236. var protoKey = '__proto__';
  237. var idStart = 0x0907;
  238. function guid() {
  239. return idStart++;
  240. }
  241. function logError() {
  242. var args = [];
  243. for (var _i = 0; _i < arguments.length; _i++) {
  244. args[_i] = arguments[_i];
  245. }
  246. if (typeof console !== 'undefined') {
  247. console.error.apply(console, args);
  248. }
  249. }
  250. function clone(source) {
  251. if (source == null || typeof source !== 'object') {
  252. return source;
  253. }
  254. var result = source;
  255. var typeStr = objToString.call(source);
  256. if (typeStr === '[object Array]') {
  257. if (!isPrimitive(source)) {
  258. result = [];
  259. for (var i = 0, len = source.length; i < len; i++) {
  260. result[i] = clone(source[i]);
  261. }
  262. }
  263. }
  264. else if (TYPED_ARRAY[typeStr]) {
  265. if (!isPrimitive(source)) {
  266. var Ctor = source.constructor;
  267. if (Ctor.from) {
  268. result = Ctor.from(source);
  269. }
  270. else {
  271. result = new Ctor(source.length);
  272. for (var i = 0, len = source.length; i < len; i++) {
  273. result[i] = source[i];
  274. }
  275. }
  276. }
  277. }
  278. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  279. result = {};
  280. for (var key in source) {
  281. if (source.hasOwnProperty(key) && key !== protoKey) {
  282. result[key] = clone(source[key]);
  283. }
  284. }
  285. }
  286. return result;
  287. }
  288. function merge(target, source, overwrite) {
  289. if (!isObject(source) || !isObject(target)) {
  290. return overwrite ? clone(source) : target;
  291. }
  292. for (var key in source) {
  293. if (source.hasOwnProperty(key) && key !== protoKey) {
  294. var targetProp = target[key];
  295. var sourceProp = source[key];
  296. if (isObject(sourceProp)
  297. && isObject(targetProp)
  298. && !isArray(sourceProp)
  299. && !isArray(targetProp)
  300. && !isDom(sourceProp)
  301. && !isDom(targetProp)
  302. && !isBuiltInObject(sourceProp)
  303. && !isBuiltInObject(targetProp)
  304. && !isPrimitive(sourceProp)
  305. && !isPrimitive(targetProp)) {
  306. merge(targetProp, sourceProp, overwrite);
  307. }
  308. else if (overwrite || !(key in target)) {
  309. target[key] = clone(source[key]);
  310. }
  311. }
  312. }
  313. return target;
  314. }
  315. function mergeAll(targetAndSources, overwrite) {
  316. var result = targetAndSources[0];
  317. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  318. result = merge(result, targetAndSources[i], overwrite);
  319. }
  320. return result;
  321. }
  322. function extend(target, source) {
  323. if (Object.assign) {
  324. Object.assign(target, source);
  325. }
  326. else {
  327. for (var key in source) {
  328. if (source.hasOwnProperty(key) && key !== protoKey) {
  329. target[key] = source[key];
  330. }
  331. }
  332. }
  333. return target;
  334. }
  335. function defaults(target, source, overlay) {
  336. var keysArr = keys(source);
  337. for (var i = 0; i < keysArr.length; i++) {
  338. var key = keysArr[i];
  339. if ((overlay ? source[key] != null : target[key] == null)) {
  340. target[key] = source[key];
  341. }
  342. }
  343. return target;
  344. }
  345. var createCanvas = platformApi.createCanvas;
  346. function indexOf(array, value) {
  347. if (array) {
  348. if (array.indexOf) {
  349. return array.indexOf(value);
  350. }
  351. for (var i = 0, len = array.length; i < len; i++) {
  352. if (array[i] === value) {
  353. return i;
  354. }
  355. }
  356. }
  357. return -1;
  358. }
  359. function inherits(clazz, baseClazz) {
  360. var clazzPrototype = clazz.prototype;
  361. function F() { }
  362. F.prototype = baseClazz.prototype;
  363. clazz.prototype = new F();
  364. for (var prop in clazzPrototype) {
  365. if (clazzPrototype.hasOwnProperty(prop)) {
  366. clazz.prototype[prop] = clazzPrototype[prop];
  367. }
  368. }
  369. clazz.prototype.constructor = clazz;
  370. clazz.superClass = baseClazz;
  371. }
  372. function mixin(target, source, override) {
  373. target = 'prototype' in target ? target.prototype : target;
  374. source = 'prototype' in source ? source.prototype : source;
  375. if (Object.getOwnPropertyNames) {
  376. var keyList = Object.getOwnPropertyNames(source);
  377. for (var i = 0; i < keyList.length; i++) {
  378. var key = keyList[i];
  379. if (key !== 'constructor') {
  380. if ((override ? source[key] != null : target[key] == null)) {
  381. target[key] = source[key];
  382. }
  383. }
  384. }
  385. }
  386. else {
  387. defaults(target, source, override);
  388. }
  389. }
  390. function isArrayLike(data) {
  391. if (!data) {
  392. return false;
  393. }
  394. if (typeof data === 'string') {
  395. return false;
  396. }
  397. return typeof data.length === 'number';
  398. }
  399. function each(arr, cb, context) {
  400. if (!(arr && cb)) {
  401. return;
  402. }
  403. if (arr.forEach && arr.forEach === nativeForEach) {
  404. arr.forEach(cb, context);
  405. }
  406. else if (arr.length === +arr.length) {
  407. for (var i = 0, len = arr.length; i < len; i++) {
  408. cb.call(context, arr[i], i, arr);
  409. }
  410. }
  411. else {
  412. for (var key in arr) {
  413. if (arr.hasOwnProperty(key)) {
  414. cb.call(context, arr[key], key, arr);
  415. }
  416. }
  417. }
  418. }
  419. function map(arr, cb, context) {
  420. if (!arr) {
  421. return [];
  422. }
  423. if (!cb) {
  424. return slice(arr);
  425. }
  426. if (arr.map && arr.map === nativeMap) {
  427. return arr.map(cb, context);
  428. }
  429. else {
  430. var result = [];
  431. for (var i = 0, len = arr.length; i < len; i++) {
  432. result.push(cb.call(context, arr[i], i, arr));
  433. }
  434. return result;
  435. }
  436. }
  437. function reduce(arr, cb, memo, context) {
  438. if (!(arr && cb)) {
  439. return;
  440. }
  441. for (var i = 0, len = arr.length; i < len; i++) {
  442. memo = cb.call(context, memo, arr[i], i, arr);
  443. }
  444. return memo;
  445. }
  446. function filter(arr, cb, context) {
  447. if (!arr) {
  448. return [];
  449. }
  450. if (!cb) {
  451. return slice(arr);
  452. }
  453. if (arr.filter && arr.filter === nativeFilter) {
  454. return arr.filter(cb, context);
  455. }
  456. else {
  457. var result = [];
  458. for (var i = 0, len = arr.length; i < len; i++) {
  459. if (cb.call(context, arr[i], i, arr)) {
  460. result.push(arr[i]);
  461. }
  462. }
  463. return result;
  464. }
  465. }
  466. function find(arr, cb, context) {
  467. if (!(arr && cb)) {
  468. return;
  469. }
  470. for (var i = 0, len = arr.length; i < len; i++) {
  471. if (cb.call(context, arr[i], i, arr)) {
  472. return arr[i];
  473. }
  474. }
  475. }
  476. function keys(obj) {
  477. if (!obj) {
  478. return [];
  479. }
  480. if (Object.keys) {
  481. return Object.keys(obj);
  482. }
  483. var keyList = [];
  484. for (var key in obj) {
  485. if (obj.hasOwnProperty(key)) {
  486. keyList.push(key);
  487. }
  488. }
  489. return keyList;
  490. }
  491. function bindPolyfill(func, context) {
  492. var args = [];
  493. for (var _i = 2; _i < arguments.length; _i++) {
  494. args[_i - 2] = arguments[_i];
  495. }
  496. return function () {
  497. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  498. };
  499. }
  500. var bind = (protoFunction && isFunction(protoFunction.bind))
  501. ? protoFunction.call.bind(protoFunction.bind)
  502. : bindPolyfill;
  503. function curry(func) {
  504. var args = [];
  505. for (var _i = 1; _i < arguments.length; _i++) {
  506. args[_i - 1] = arguments[_i];
  507. }
  508. return function () {
  509. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  510. };
  511. }
  512. function isArray(value) {
  513. if (Array.isArray) {
  514. return Array.isArray(value);
  515. }
  516. return objToString.call(value) === '[object Array]';
  517. }
  518. function isFunction(value) {
  519. return typeof value === 'function';
  520. }
  521. function isString(value) {
  522. return typeof value === 'string';
  523. }
  524. function isStringSafe(value) {
  525. return objToString.call(value) === '[object String]';
  526. }
  527. function isNumber(value) {
  528. return typeof value === 'number';
  529. }
  530. function isObject(value) {
  531. var type = typeof value;
  532. return type === 'function' || (!!value && type === 'object');
  533. }
  534. function isBuiltInObject(value) {
  535. return !!BUILTIN_OBJECT[objToString.call(value)];
  536. }
  537. function isTypedArray(value) {
  538. return !!TYPED_ARRAY[objToString.call(value)];
  539. }
  540. function isDom(value) {
  541. return typeof value === 'object'
  542. && typeof value.nodeType === 'number'
  543. && typeof value.ownerDocument === 'object';
  544. }
  545. function isGradientObject(value) {
  546. return value.colorStops != null;
  547. }
  548. function isImagePatternObject(value) {
  549. return value.image != null;
  550. }
  551. function isRegExp(value) {
  552. return objToString.call(value) === '[object RegExp]';
  553. }
  554. function eqNaN(value) {
  555. return value !== value;
  556. }
  557. function retrieve() {
  558. var args = [];
  559. for (var _i = 0; _i < arguments.length; _i++) {
  560. args[_i] = arguments[_i];
  561. }
  562. for (var i = 0, len = args.length; i < len; i++) {
  563. if (args[i] != null) {
  564. return args[i];
  565. }
  566. }
  567. }
  568. function retrieve2(value0, value1) {
  569. return value0 != null
  570. ? value0
  571. : value1;
  572. }
  573. function retrieve3(value0, value1, value2) {
  574. return value0 != null
  575. ? value0
  576. : value1 != null
  577. ? value1
  578. : value2;
  579. }
  580. function slice(arr) {
  581. var args = [];
  582. for (var _i = 1; _i < arguments.length; _i++) {
  583. args[_i - 1] = arguments[_i];
  584. }
  585. return nativeSlice.apply(arr, args);
  586. }
  587. function normalizeCssArray(val) {
  588. if (typeof (val) === 'number') {
  589. return [val, val, val, val];
  590. }
  591. var len = val.length;
  592. if (len === 2) {
  593. return [val[0], val[1], val[0], val[1]];
  594. }
  595. else if (len === 3) {
  596. return [val[0], val[1], val[2], val[1]];
  597. }
  598. return val;
  599. }
  600. function assert(condition, message) {
  601. if (!condition) {
  602. throw new Error(message);
  603. }
  604. }
  605. function trim(str) {
  606. if (str == null) {
  607. return null;
  608. }
  609. else if (typeof str.trim === 'function') {
  610. return str.trim();
  611. }
  612. else {
  613. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  614. }
  615. }
  616. var primitiveKey = '__ec_primitive__';
  617. function setAsPrimitive(obj) {
  618. obj[primitiveKey] = true;
  619. }
  620. function isPrimitive(obj) {
  621. return obj[primitiveKey];
  622. }
  623. var MapPolyfill = (function () {
  624. function MapPolyfill() {
  625. this.data = {};
  626. }
  627. MapPolyfill.prototype["delete"] = function (key) {
  628. var existed = this.has(key);
  629. if (existed) {
  630. delete this.data[key];
  631. }
  632. return existed;
  633. };
  634. MapPolyfill.prototype.has = function (key) {
  635. return this.data.hasOwnProperty(key);
  636. };
  637. MapPolyfill.prototype.get = function (key) {
  638. return this.data[key];
  639. };
  640. MapPolyfill.prototype.set = function (key, value) {
  641. this.data[key] = value;
  642. return this;
  643. };
  644. MapPolyfill.prototype.keys = function () {
  645. return keys(this.data);
  646. };
  647. MapPolyfill.prototype.forEach = function (callback) {
  648. var data = this.data;
  649. for (var key in data) {
  650. if (data.hasOwnProperty(key)) {
  651. callback(data[key], key);
  652. }
  653. }
  654. };
  655. return MapPolyfill;
  656. }());
  657. var isNativeMapSupported = typeof Map === 'function';
  658. function maybeNativeMap() {
  659. return (isNativeMapSupported ? new Map() : new MapPolyfill());
  660. }
  661. var HashMap = (function () {
  662. function HashMap(obj) {
  663. var isArr = isArray(obj);
  664. this.data = maybeNativeMap();
  665. var thisMap = this;
  666. (obj instanceof HashMap)
  667. ? obj.each(visit)
  668. : (obj && each(obj, visit));
  669. function visit(value, key) {
  670. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  671. }
  672. }
  673. HashMap.prototype.hasKey = function (key) {
  674. return this.data.has(key);
  675. };
  676. HashMap.prototype.get = function (key) {
  677. return this.data.get(key);
  678. };
  679. HashMap.prototype.set = function (key, value) {
  680. this.data.set(key, value);
  681. return value;
  682. };
  683. HashMap.prototype.each = function (cb, context) {
  684. this.data.forEach(function (value, key) {
  685. cb.call(context, value, key);
  686. });
  687. };
  688. HashMap.prototype.keys = function () {
  689. var keys = this.data.keys();
  690. return isNativeMapSupported
  691. ? Array.from(keys)
  692. : keys;
  693. };
  694. HashMap.prototype.removeKey = function (key) {
  695. this.data["delete"](key);
  696. };
  697. return HashMap;
  698. }());
  699. function createHashMap(obj) {
  700. return new HashMap(obj);
  701. }
  702. function concatArray(a, b) {
  703. var newArray = new a.constructor(a.length + b.length);
  704. for (var i = 0; i < a.length; i++) {
  705. newArray[i] = a[i];
  706. }
  707. var offset = a.length;
  708. for (var i = 0; i < b.length; i++) {
  709. newArray[i + offset] = b[i];
  710. }
  711. return newArray;
  712. }
  713. function createObject(proto, properties) {
  714. var obj;
  715. if (Object.create) {
  716. obj = Object.create(proto);
  717. }
  718. else {
  719. var StyleCtor = function () { };
  720. StyleCtor.prototype = proto;
  721. obj = new StyleCtor();
  722. }
  723. if (properties) {
  724. extend(obj, properties);
  725. }
  726. return obj;
  727. }
  728. function disableUserSelect(dom) {
  729. var domStyle = dom.style;
  730. domStyle.webkitUserSelect = 'none';
  731. domStyle.userSelect = 'none';
  732. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  733. domStyle['-webkit-touch-callout'] = 'none';
  734. }
  735. function hasOwn(own, prop) {
  736. return own.hasOwnProperty(prop);
  737. }
  738. function noop() { }
  739. var RADIAN_TO_DEGREE = 180 / Math.PI;
  740. var util = /*#__PURE__*/Object.freeze({
  741. __proto__: null,
  742. guid: guid,
  743. logError: logError,
  744. clone: clone,
  745. merge: merge,
  746. mergeAll: mergeAll,
  747. extend: extend,
  748. defaults: defaults,
  749. createCanvas: createCanvas,
  750. indexOf: indexOf,
  751. inherits: inherits,
  752. mixin: mixin,
  753. isArrayLike: isArrayLike,
  754. each: each,
  755. map: map,
  756. reduce: reduce,
  757. filter: filter,
  758. find: find,
  759. keys: keys,
  760. bind: bind,
  761. curry: curry,
  762. isArray: isArray,
  763. isFunction: isFunction,
  764. isString: isString,
  765. isStringSafe: isStringSafe,
  766. isNumber: isNumber,
  767. isObject: isObject,
  768. isBuiltInObject: isBuiltInObject,
  769. isTypedArray: isTypedArray,
  770. isDom: isDom,
  771. isGradientObject: isGradientObject,
  772. isImagePatternObject: isImagePatternObject,
  773. isRegExp: isRegExp,
  774. eqNaN: eqNaN,
  775. retrieve: retrieve,
  776. retrieve2: retrieve2,
  777. retrieve3: retrieve3,
  778. slice: slice,
  779. normalizeCssArray: normalizeCssArray,
  780. assert: assert,
  781. trim: trim,
  782. setAsPrimitive: setAsPrimitive,
  783. isPrimitive: isPrimitive,
  784. HashMap: HashMap,
  785. createHashMap: createHashMap,
  786. concatArray: concatArray,
  787. createObject: createObject,
  788. disableUserSelect: disableUserSelect,
  789. hasOwn: hasOwn,
  790. noop: noop,
  791. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  792. });
  793. function create(x, y) {
  794. if (x == null) {
  795. x = 0;
  796. }
  797. if (y == null) {
  798. y = 0;
  799. }
  800. return [x, y];
  801. }
  802. function copy(out, v) {
  803. out[0] = v[0];
  804. out[1] = v[1];
  805. return out;
  806. }
  807. function clone$1(v) {
  808. return [v[0], v[1]];
  809. }
  810. function set(out, a, b) {
  811. out[0] = a;
  812. out[1] = b;
  813. return out;
  814. }
  815. function add(out, v1, v2) {
  816. out[0] = v1[0] + v2[0];
  817. out[1] = v1[1] + v2[1];
  818. return out;
  819. }
  820. function scaleAndAdd(out, v1, v2, a) {
  821. out[0] = v1[0] + v2[0] * a;
  822. out[1] = v1[1] + v2[1] * a;
  823. return out;
  824. }
  825. function sub(out, v1, v2) {
  826. out[0] = v1[0] - v2[0];
  827. out[1] = v1[1] - v2[1];
  828. return out;
  829. }
  830. function len(v) {
  831. return Math.sqrt(lenSquare(v));
  832. }
  833. var length = len;
  834. function lenSquare(v) {
  835. return v[0] * v[0] + v[1] * v[1];
  836. }
  837. var lengthSquare = lenSquare;
  838. function mul(out, v1, v2) {
  839. out[0] = v1[0] * v2[0];
  840. out[1] = v1[1] * v2[1];
  841. return out;
  842. }
  843. function div(out, v1, v2) {
  844. out[0] = v1[0] / v2[0];
  845. out[1] = v1[1] / v2[1];
  846. return out;
  847. }
  848. function dot(v1, v2) {
  849. return v1[0] * v2[0] + v1[1] * v2[1];
  850. }
  851. function scale(out, v, s) {
  852. out[0] = v[0] * s;
  853. out[1] = v[1] * s;
  854. return out;
  855. }
  856. function normalize(out, v) {
  857. var d = len(v);
  858. if (d === 0) {
  859. out[0] = 0;
  860. out[1] = 0;
  861. }
  862. else {
  863. out[0] = v[0] / d;
  864. out[1] = v[1] / d;
  865. }
  866. return out;
  867. }
  868. function distance(v1, v2) {
  869. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  870. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  871. }
  872. var dist = distance;
  873. function distanceSquare(v1, v2) {
  874. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  875. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  876. }
  877. var distSquare = distanceSquare;
  878. function negate(out, v) {
  879. out[0] = -v[0];
  880. out[1] = -v[1];
  881. return out;
  882. }
  883. function lerp(out, v1, v2, t) {
  884. out[0] = v1[0] + t * (v2[0] - v1[0]);
  885. out[1] = v1[1] + t * (v2[1] - v1[1]);
  886. return out;
  887. }
  888. function applyTransform(out, v, m) {
  889. var x = v[0];
  890. var y = v[1];
  891. out[0] = m[0] * x + m[2] * y + m[4];
  892. out[1] = m[1] * x + m[3] * y + m[5];
  893. return out;
  894. }
  895. function min(out, v1, v2) {
  896. out[0] = Math.min(v1[0], v2[0]);
  897. out[1] = Math.min(v1[1], v2[1]);
  898. return out;
  899. }
  900. function max(out, v1, v2) {
  901. out[0] = Math.max(v1[0], v2[0]);
  902. out[1] = Math.max(v1[1], v2[1]);
  903. return out;
  904. }
  905. var vector = /*#__PURE__*/Object.freeze({
  906. __proto__: null,
  907. create: create,
  908. copy: copy,
  909. clone: clone$1,
  910. set: set,
  911. add: add,
  912. scaleAndAdd: scaleAndAdd,
  913. sub: sub,
  914. len: len,
  915. length: length,
  916. lenSquare: lenSquare,
  917. lengthSquare: lengthSquare,
  918. mul: mul,
  919. div: div,
  920. dot: dot,
  921. scale: scale,
  922. normalize: normalize,
  923. distance: distance,
  924. dist: dist,
  925. distanceSquare: distanceSquare,
  926. distSquare: distSquare,
  927. negate: negate,
  928. lerp: lerp,
  929. applyTransform: applyTransform,
  930. min: min,
  931. max: max
  932. });
  933. var Param = (function () {
  934. function Param(target, e) {
  935. this.target = target;
  936. this.topTarget = e && e.topTarget;
  937. }
  938. return Param;
  939. }());
  940. var Draggable = (function () {
  941. function Draggable(handler) {
  942. this.handler = handler;
  943. handler.on('mousedown', this._dragStart, this);
  944. handler.on('mousemove', this._drag, this);
  945. handler.on('mouseup', this._dragEnd, this);
  946. }
  947. Draggable.prototype._dragStart = function (e) {
  948. var draggingTarget = e.target;
  949. while (draggingTarget && !draggingTarget.draggable) {
  950. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  951. }
  952. if (draggingTarget) {
  953. this._draggingTarget = draggingTarget;
  954. draggingTarget.dragging = true;
  955. this._x = e.offsetX;
  956. this._y = e.offsetY;
  957. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  958. }
  959. };
  960. Draggable.prototype._drag = function (e) {
  961. var draggingTarget = this._draggingTarget;
  962. if (draggingTarget) {
  963. var x = e.offsetX;
  964. var y = e.offsetY;
  965. var dx = x - this._x;
  966. var dy = y - this._y;
  967. this._x = x;
  968. this._y = y;
  969. draggingTarget.drift(dx, dy, e);
  970. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  971. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  972. var lastDropTarget = this._dropTarget;
  973. this._dropTarget = dropTarget;
  974. if (draggingTarget !== dropTarget) {
  975. if (lastDropTarget && dropTarget !== lastDropTarget) {
  976. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  977. }
  978. if (dropTarget && dropTarget !== lastDropTarget) {
  979. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  980. }
  981. }
  982. }
  983. };
  984. Draggable.prototype._dragEnd = function (e) {
  985. var draggingTarget = this._draggingTarget;
  986. if (draggingTarget) {
  987. draggingTarget.dragging = false;
  988. }
  989. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  990. if (this._dropTarget) {
  991. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  992. }
  993. this._draggingTarget = null;
  994. this._dropTarget = null;
  995. };
  996. return Draggable;
  997. }());
  998. var Eventful = (function () {
  999. function Eventful(eventProcessors) {
  1000. if (eventProcessors) {
  1001. this._$eventProcessor = eventProcessors;
  1002. }
  1003. }
  1004. Eventful.prototype.on = function (event, query, handler, context) {
  1005. if (!this._$handlers) {
  1006. this._$handlers = {};
  1007. }
  1008. var _h = this._$handlers;
  1009. if (typeof query === 'function') {
  1010. context = handler;
  1011. handler = query;
  1012. query = null;
  1013. }
  1014. if (!handler || !event) {
  1015. return this;
  1016. }
  1017. var eventProcessor = this._$eventProcessor;
  1018. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1019. query = eventProcessor.normalizeQuery(query);
  1020. }
  1021. if (!_h[event]) {
  1022. _h[event] = [];
  1023. }
  1024. for (var i = 0; i < _h[event].length; i++) {
  1025. if (_h[event][i].h === handler) {
  1026. return this;
  1027. }
  1028. }
  1029. var wrap = {
  1030. h: handler,
  1031. query: query,
  1032. ctx: (context || this),
  1033. callAtLast: handler.zrEventfulCallAtLast
  1034. };
  1035. var lastIndex = _h[event].length - 1;
  1036. var lastWrap = _h[event][lastIndex];
  1037. (lastWrap && lastWrap.callAtLast)
  1038. ? _h[event].splice(lastIndex, 0, wrap)
  1039. : _h[event].push(wrap);
  1040. return this;
  1041. };
  1042. Eventful.prototype.isSilent = function (eventName) {
  1043. var _h = this._$handlers;
  1044. return !_h || !_h[eventName] || !_h[eventName].length;
  1045. };
  1046. Eventful.prototype.off = function (eventType, handler) {
  1047. var _h = this._$handlers;
  1048. if (!_h) {
  1049. return this;
  1050. }
  1051. if (!eventType) {
  1052. this._$handlers = {};
  1053. return this;
  1054. }
  1055. if (handler) {
  1056. if (_h[eventType]) {
  1057. var newList = [];
  1058. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1059. if (_h[eventType][i].h !== handler) {
  1060. newList.push(_h[eventType][i]);
  1061. }
  1062. }
  1063. _h[eventType] = newList;
  1064. }
  1065. if (_h[eventType] && _h[eventType].length === 0) {
  1066. delete _h[eventType];
  1067. }
  1068. }
  1069. else {
  1070. delete _h[eventType];
  1071. }
  1072. return this;
  1073. };
  1074. Eventful.prototype.trigger = function (eventType) {
  1075. var args = [];
  1076. for (var _i = 1; _i < arguments.length; _i++) {
  1077. args[_i - 1] = arguments[_i];
  1078. }
  1079. if (!this._$handlers) {
  1080. return this;
  1081. }
  1082. var _h = this._$handlers[eventType];
  1083. var eventProcessor = this._$eventProcessor;
  1084. if (_h) {
  1085. var argLen = args.length;
  1086. var len = _h.length;
  1087. for (var i = 0; i < len; i++) {
  1088. var hItem = _h[i];
  1089. if (eventProcessor
  1090. && eventProcessor.filter
  1091. && hItem.query != null
  1092. && !eventProcessor.filter(eventType, hItem.query)) {
  1093. continue;
  1094. }
  1095. switch (argLen) {
  1096. case 0:
  1097. hItem.h.call(hItem.ctx);
  1098. break;
  1099. case 1:
  1100. hItem.h.call(hItem.ctx, args[0]);
  1101. break;
  1102. case 2:
  1103. hItem.h.call(hItem.ctx, args[0], args[1]);
  1104. break;
  1105. default:
  1106. hItem.h.apply(hItem.ctx, args);
  1107. break;
  1108. }
  1109. }
  1110. }
  1111. eventProcessor && eventProcessor.afterTrigger
  1112. && eventProcessor.afterTrigger(eventType);
  1113. return this;
  1114. };
  1115. Eventful.prototype.triggerWithContext = function (type) {
  1116. var args = [];
  1117. for (var _i = 1; _i < arguments.length; _i++) {
  1118. args[_i - 1] = arguments[_i];
  1119. }
  1120. if (!this._$handlers) {
  1121. return this;
  1122. }
  1123. var _h = this._$handlers[type];
  1124. var eventProcessor = this._$eventProcessor;
  1125. if (_h) {
  1126. var argLen = args.length;
  1127. var ctx = args[argLen - 1];
  1128. var len = _h.length;
  1129. for (var i = 0; i < len; i++) {
  1130. var hItem = _h[i];
  1131. if (eventProcessor
  1132. && eventProcessor.filter
  1133. && hItem.query != null
  1134. && !eventProcessor.filter(type, hItem.query)) {
  1135. continue;
  1136. }
  1137. switch (argLen) {
  1138. case 0:
  1139. hItem.h.call(ctx);
  1140. break;
  1141. case 1:
  1142. hItem.h.call(ctx, args[0]);
  1143. break;
  1144. case 2:
  1145. hItem.h.call(ctx, args[0], args[1]);
  1146. break;
  1147. default:
  1148. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1149. break;
  1150. }
  1151. }
  1152. }
  1153. eventProcessor && eventProcessor.afterTrigger
  1154. && eventProcessor.afterTrigger(type);
  1155. return this;
  1156. };
  1157. return Eventful;
  1158. }());
  1159. var LN2 = Math.log(2);
  1160. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1161. var cacheKey = rowMask + '-' + colMask;
  1162. var fullRank = rows.length;
  1163. if (detCache.hasOwnProperty(cacheKey)) {
  1164. return detCache[cacheKey];
  1165. }
  1166. if (rank === 1) {
  1167. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1168. return rows[rowStart][colStart];
  1169. }
  1170. var subRowMask = rowMask | (1 << rowStart);
  1171. var subRowStart = rowStart + 1;
  1172. while (rowMask & (1 << subRowStart)) {
  1173. subRowStart++;
  1174. }
  1175. var sum = 0;
  1176. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1177. var colTag = 1 << j;
  1178. if (!(colTag & colMask)) {
  1179. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1180. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1181. colLocalIdx++;
  1182. }
  1183. }
  1184. detCache[cacheKey] = sum;
  1185. return sum;
  1186. }
  1187. function buildTransformer(src, dest) {
  1188. var mA = [
  1189. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1190. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1191. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1192. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1193. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1194. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1195. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1196. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1197. ];
  1198. var detCache = {};
  1199. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1200. if (det === 0) {
  1201. return;
  1202. }
  1203. var vh = [];
  1204. for (var i = 0; i < 8; i++) {
  1205. for (var j = 0; j < 8; j++) {
  1206. vh[j] == null && (vh[j] = 0);
  1207. vh[j] += ((i + j) % 2 ? -1 : 1)
  1208. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1209. / det * dest[i];
  1210. }
  1211. }
  1212. return function (out, srcPointX, srcPointY) {
  1213. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1214. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1215. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1216. };
  1217. }
  1218. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1219. var _calcOut = [];
  1220. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1221. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1222. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1223. }
  1224. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1225. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1226. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1227. var markers = prepareCoordMarkers(el, saved);
  1228. var transformer = preparePointerTransformer(markers, saved, inverse);
  1229. if (transformer) {
  1230. transformer(out, inX, inY);
  1231. return true;
  1232. }
  1233. }
  1234. return false;
  1235. }
  1236. function prepareCoordMarkers(el, saved) {
  1237. var markers = saved.markers;
  1238. if (markers) {
  1239. return markers;
  1240. }
  1241. markers = saved.markers = [];
  1242. var propLR = ['left', 'right'];
  1243. var propTB = ['top', 'bottom'];
  1244. for (var i = 0; i < 4; i++) {
  1245. var marker = document.createElement('div');
  1246. var stl = marker.style;
  1247. var idxLR = i % 2;
  1248. var idxTB = (i >> 1) % 2;
  1249. stl.cssText = [
  1250. 'position: absolute',
  1251. 'visibility: hidden',
  1252. 'padding: 0',
  1253. 'margin: 0',
  1254. 'border-width: 0',
  1255. 'user-select: none',
  1256. 'width:0',
  1257. 'height:0',
  1258. propLR[idxLR] + ':0',
  1259. propTB[idxTB] + ':0',
  1260. propLR[1 - idxLR] + ':auto',
  1261. propTB[1 - idxTB] + ':auto',
  1262. ''
  1263. ].join('!important;');
  1264. el.appendChild(marker);
  1265. markers.push(marker);
  1266. }
  1267. return markers;
  1268. }
  1269. function preparePointerTransformer(markers, saved, inverse) {
  1270. var transformerName = inverse ? 'invTrans' : 'trans';
  1271. var transformer = saved[transformerName];
  1272. var oldSrcCoords = saved.srcCoords;
  1273. var srcCoords = [];
  1274. var destCoords = [];
  1275. var oldCoordTheSame = true;
  1276. for (var i = 0; i < 4; i++) {
  1277. var rect = markers[i].getBoundingClientRect();
  1278. var ii = 2 * i;
  1279. var x = rect.left;
  1280. var y = rect.top;
  1281. srcCoords.push(x, y);
  1282. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1283. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1284. }
  1285. return (oldCoordTheSame && transformer)
  1286. ? transformer
  1287. : (saved.srcCoords = srcCoords,
  1288. saved[transformerName] = inverse
  1289. ? buildTransformer(destCoords, srcCoords)
  1290. : buildTransformer(srcCoords, destCoords));
  1291. }
  1292. function isCanvasEl(el) {
  1293. return el.nodeName.toUpperCase() === 'CANVAS';
  1294. }
  1295. var replaceReg = /([&<>"'])/g;
  1296. var replaceMap = {
  1297. '&': '&amp;',
  1298. '<': '&lt;',
  1299. '>': '&gt;',
  1300. '"': '&quot;',
  1301. '\'': '&#39;'
  1302. };
  1303. function encodeHTML(source) {
  1304. return source == null
  1305. ? ''
  1306. : (source + '').replace(replaceReg, function (str, c) {
  1307. return replaceMap[c];
  1308. });
  1309. }
  1310. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1311. var _calcOut$1 = [];
  1312. var firefoxNotSupportOffsetXY = env.browser.firefox
  1313. && +env.browser.version.split('.')[0] < 39;
  1314. function clientToLocal(el, e, out, calculate) {
  1315. out = out || {};
  1316. if (calculate) {
  1317. calculateZrXY(el, e, out);
  1318. }
  1319. else if (firefoxNotSupportOffsetXY
  1320. && e.layerX != null
  1321. && e.layerX !== e.offsetX) {
  1322. out.zrX = e.layerX;
  1323. out.zrY = e.layerY;
  1324. }
  1325. else if (e.offsetX != null) {
  1326. out.zrX = e.offsetX;
  1327. out.zrY = e.offsetY;
  1328. }
  1329. else {
  1330. calculateZrXY(el, e, out);
  1331. }
  1332. return out;
  1333. }
  1334. function calculateZrXY(el, e, out) {
  1335. if (env.domSupported && el.getBoundingClientRect) {
  1336. var ex = e.clientX;
  1337. var ey = e.clientY;
  1338. if (isCanvasEl(el)) {
  1339. var box = el.getBoundingClientRect();
  1340. out.zrX = ex - box.left;
  1341. out.zrY = ey - box.top;
  1342. return;
  1343. }
  1344. else {
  1345. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1346. out.zrX = _calcOut$1[0];
  1347. out.zrY = _calcOut$1[1];
  1348. return;
  1349. }
  1350. }
  1351. }
  1352. out.zrX = out.zrY = 0;
  1353. }
  1354. function getNativeEvent(e) {
  1355. return e
  1356. || window.event;
  1357. }
  1358. function normalizeEvent(el, e, calculate) {
  1359. e = getNativeEvent(e);
  1360. if (e.zrX != null) {
  1361. return e;
  1362. }
  1363. var eventType = e.type;
  1364. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1365. if (!isTouch) {
  1366. clientToLocal(el, e, e, calculate);
  1367. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1368. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1369. }
  1370. else {
  1371. var touch = eventType !== 'touchend'
  1372. ? e.targetTouches[0]
  1373. : e.changedTouches[0];
  1374. touch && clientToLocal(el, touch, e, calculate);
  1375. }
  1376. var button = e.button;
  1377. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1378. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1379. }
  1380. return e;
  1381. }
  1382. function getWheelDeltaMayPolyfill(e) {
  1383. var rawWheelDelta = e.wheelDelta;
  1384. if (rawWheelDelta) {
  1385. return rawWheelDelta;
  1386. }
  1387. var deltaX = e.deltaX;
  1388. var deltaY = e.deltaY;
  1389. if (deltaX == null || deltaY == null) {
  1390. return rawWheelDelta;
  1391. }
  1392. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1393. var sign = deltaY > 0 ? -1
  1394. : deltaY < 0 ? 1
  1395. : deltaX > 0 ? -1
  1396. : 1;
  1397. return 3 * delta * sign;
  1398. }
  1399. function addEventListener(el, name, handler, opt) {
  1400. el.addEventListener(name, handler, opt);
  1401. }
  1402. function removeEventListener(el, name, handler, opt) {
  1403. el.removeEventListener(name, handler, opt);
  1404. }
  1405. var stop = function (e) {
  1406. e.preventDefault();
  1407. e.stopPropagation();
  1408. e.cancelBubble = true;
  1409. };
  1410. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1411. return e.which === 2 || e.which === 3;
  1412. }
  1413. var GestureMgr = (function () {
  1414. function GestureMgr() {
  1415. this._track = [];
  1416. }
  1417. GestureMgr.prototype.recognize = function (event, target, root) {
  1418. this._doTrack(event, target, root);
  1419. return this._recognize(event);
  1420. };
  1421. GestureMgr.prototype.clear = function () {
  1422. this._track.length = 0;
  1423. return this;
  1424. };
  1425. GestureMgr.prototype._doTrack = function (event, target, root) {
  1426. var touches = event.touches;
  1427. if (!touches) {
  1428. return;
  1429. }
  1430. var trackItem = {
  1431. points: [],
  1432. touches: [],
  1433. target: target,
  1434. event: event
  1435. };
  1436. for (var i = 0, len = touches.length; i < len; i++) {
  1437. var touch = touches[i];
  1438. var pos = clientToLocal(root, touch, {});
  1439. trackItem.points.push([pos.zrX, pos.zrY]);
  1440. trackItem.touches.push(touch);
  1441. }
  1442. this._track.push(trackItem);
  1443. };
  1444. GestureMgr.prototype._recognize = function (event) {
  1445. for (var eventName in recognizers) {
  1446. if (recognizers.hasOwnProperty(eventName)) {
  1447. var gestureInfo = recognizers[eventName](this._track, event);
  1448. if (gestureInfo) {
  1449. return gestureInfo;
  1450. }
  1451. }
  1452. }
  1453. };
  1454. return GestureMgr;
  1455. }());
  1456. function dist$1(pointPair) {
  1457. var dx = pointPair[1][0] - pointPair[0][0];
  1458. var dy = pointPair[1][1] - pointPair[0][1];
  1459. return Math.sqrt(dx * dx + dy * dy);
  1460. }
  1461. function center(pointPair) {
  1462. return [
  1463. (pointPair[0][0] + pointPair[1][0]) / 2,
  1464. (pointPair[0][1] + pointPair[1][1]) / 2
  1465. ];
  1466. }
  1467. var recognizers = {
  1468. pinch: function (tracks, event) {
  1469. var trackLen = tracks.length;
  1470. if (!trackLen) {
  1471. return;
  1472. }
  1473. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1474. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1475. if (pinchPre
  1476. && pinchPre.length > 1
  1477. && pinchEnd
  1478. && pinchEnd.length > 1) {
  1479. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1480. !isFinite(pinchScale) && (pinchScale = 1);
  1481. event.pinchScale = pinchScale;
  1482. var pinchCenter = center(pinchEnd);
  1483. event.pinchX = pinchCenter[0];
  1484. event.pinchY = pinchCenter[1];
  1485. return {
  1486. type: 'pinch',
  1487. target: tracks[0].target,
  1488. event: event
  1489. };
  1490. }
  1491. }
  1492. };
  1493. function create$1() {
  1494. return [1, 0, 0, 1, 0, 0];
  1495. }
  1496. function identity(out) {
  1497. out[0] = 1;
  1498. out[1] = 0;
  1499. out[2] = 0;
  1500. out[3] = 1;
  1501. out[4] = 0;
  1502. out[5] = 0;
  1503. return out;
  1504. }
  1505. function copy$1(out, m) {
  1506. out[0] = m[0];
  1507. out[1] = m[1];
  1508. out[2] = m[2];
  1509. out[3] = m[3];
  1510. out[4] = m[4];
  1511. out[5] = m[5];
  1512. return out;
  1513. }
  1514. function mul$1(out, m1, m2) {
  1515. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1516. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1517. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1518. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1519. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1520. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1521. out[0] = out0;
  1522. out[1] = out1;
  1523. out[2] = out2;
  1524. out[3] = out3;
  1525. out[4] = out4;
  1526. out[5] = out5;
  1527. return out;
  1528. }
  1529. function translate(out, a, v) {
  1530. out[0] = a[0];
  1531. out[1] = a[1];
  1532. out[2] = a[2];
  1533. out[3] = a[3];
  1534. out[4] = a[4] + v[0];
  1535. out[5] = a[5] + v[1];
  1536. return out;
  1537. }
  1538. function rotate(out, a, rad, pivot) {
  1539. if (pivot === void 0) { pivot = [0, 0]; }
  1540. var aa = a[0];
  1541. var ac = a[2];
  1542. var atx = a[4];
  1543. var ab = a[1];
  1544. var ad = a[3];
  1545. var aty = a[5];
  1546. var st = Math.sin(rad);
  1547. var ct = Math.cos(rad);
  1548. out[0] = aa * ct + ab * st;
  1549. out[1] = -aa * st + ab * ct;
  1550. out[2] = ac * ct + ad * st;
  1551. out[3] = -ac * st + ct * ad;
  1552. out[4] = ct * (atx - pivot[0]) + st * (aty - pivot[1]) + pivot[0];
  1553. out[5] = ct * (aty - pivot[1]) - st * (atx - pivot[0]) + pivot[1];
  1554. return out;
  1555. }
  1556. function scale$1(out, a, v) {
  1557. var vx = v[0];
  1558. var vy = v[1];
  1559. out[0] = a[0] * vx;
  1560. out[1] = a[1] * vy;
  1561. out[2] = a[2] * vx;
  1562. out[3] = a[3] * vy;
  1563. out[4] = a[4] * vx;
  1564. out[5] = a[5] * vy;
  1565. return out;
  1566. }
  1567. function invert(out, a) {
  1568. var aa = a[0];
  1569. var ac = a[2];
  1570. var atx = a[4];
  1571. var ab = a[1];
  1572. var ad = a[3];
  1573. var aty = a[5];
  1574. var det = aa * ad - ab * ac;
  1575. if (!det) {
  1576. return null;
  1577. }
  1578. det = 1.0 / det;
  1579. out[0] = ad * det;
  1580. out[1] = -ab * det;
  1581. out[2] = -ac * det;
  1582. out[3] = aa * det;
  1583. out[4] = (ac * aty - ad * atx) * det;
  1584. out[5] = (ab * atx - aa * aty) * det;
  1585. return out;
  1586. }
  1587. function clone$2(a) {
  1588. var b = create$1();
  1589. copy$1(b, a);
  1590. return b;
  1591. }
  1592. var matrix = /*#__PURE__*/Object.freeze({
  1593. __proto__: null,
  1594. create: create$1,
  1595. identity: identity,
  1596. copy: copy$1,
  1597. mul: mul$1,
  1598. translate: translate,
  1599. rotate: rotate,
  1600. scale: scale$1,
  1601. invert: invert,
  1602. clone: clone$2
  1603. });
  1604. var Point = (function () {
  1605. function Point(x, y) {
  1606. this.x = x || 0;
  1607. this.y = y || 0;
  1608. }
  1609. Point.prototype.copy = function (other) {
  1610. this.x = other.x;
  1611. this.y = other.y;
  1612. return this;
  1613. };
  1614. Point.prototype.clone = function () {
  1615. return new Point(this.x, this.y);
  1616. };
  1617. Point.prototype.set = function (x, y) {
  1618. this.x = x;
  1619. this.y = y;
  1620. return this;
  1621. };
  1622. Point.prototype.equal = function (other) {
  1623. return other.x === this.x && other.y === this.y;
  1624. };
  1625. Point.prototype.add = function (other) {
  1626. this.x += other.x;
  1627. this.y += other.y;
  1628. return this;
  1629. };
  1630. Point.prototype.scale = function (scalar) {
  1631. this.x *= scalar;
  1632. this.y *= scalar;
  1633. };
  1634. Point.prototype.scaleAndAdd = function (other, scalar) {
  1635. this.x += other.x * scalar;
  1636. this.y += other.y * scalar;
  1637. };
  1638. Point.prototype.sub = function (other) {
  1639. this.x -= other.x;
  1640. this.y -= other.y;
  1641. return this;
  1642. };
  1643. Point.prototype.dot = function (other) {
  1644. return this.x * other.x + this.y * other.y;
  1645. };
  1646. Point.prototype.len = function () {
  1647. return Math.sqrt(this.x * this.x + this.y * this.y);
  1648. };
  1649. Point.prototype.lenSquare = function () {
  1650. return this.x * this.x + this.y * this.y;
  1651. };
  1652. Point.prototype.normalize = function () {
  1653. var len = this.len();
  1654. this.x /= len;
  1655. this.y /= len;
  1656. return this;
  1657. };
  1658. Point.prototype.distance = function (other) {
  1659. var dx = this.x - other.x;
  1660. var dy = this.y - other.y;
  1661. return Math.sqrt(dx * dx + dy * dy);
  1662. };
  1663. Point.prototype.distanceSquare = function (other) {
  1664. var dx = this.x - other.x;
  1665. var dy = this.y - other.y;
  1666. return dx * dx + dy * dy;
  1667. };
  1668. Point.prototype.negate = function () {
  1669. this.x = -this.x;
  1670. this.y = -this.y;
  1671. return this;
  1672. };
  1673. Point.prototype.transform = function (m) {
  1674. if (!m) {
  1675. return;
  1676. }
  1677. var x = this.x;
  1678. var y = this.y;
  1679. this.x = m[0] * x + m[2] * y + m[4];
  1680. this.y = m[1] * x + m[3] * y + m[5];
  1681. return this;
  1682. };
  1683. Point.prototype.toArray = function (out) {
  1684. out[0] = this.x;
  1685. out[1] = this.y;
  1686. return out;
  1687. };
  1688. Point.prototype.fromArray = function (input) {
  1689. this.x = input[0];
  1690. this.y = input[1];
  1691. };
  1692. Point.set = function (p, x, y) {
  1693. p.x = x;
  1694. p.y = y;
  1695. };
  1696. Point.copy = function (p, p2) {
  1697. p.x = p2.x;
  1698. p.y = p2.y;
  1699. };
  1700. Point.len = function (p) {
  1701. return Math.sqrt(p.x * p.x + p.y * p.y);
  1702. };
  1703. Point.lenSquare = function (p) {
  1704. return p.x * p.x + p.y * p.y;
  1705. };
  1706. Point.dot = function (p0, p1) {
  1707. return p0.x * p1.x + p0.y * p1.y;
  1708. };
  1709. Point.add = function (out, p0, p1) {
  1710. out.x = p0.x + p1.x;
  1711. out.y = p0.y + p1.y;
  1712. };
  1713. Point.sub = function (out, p0, p1) {
  1714. out.x = p0.x - p1.x;
  1715. out.y = p0.y - p1.y;
  1716. };
  1717. Point.scale = function (out, p0, scalar) {
  1718. out.x = p0.x * scalar;
  1719. out.y = p0.y * scalar;
  1720. };
  1721. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1722. out.x = p0.x + p1.x * scalar;
  1723. out.y = p0.y + p1.y * scalar;
  1724. };
  1725. Point.lerp = function (out, p0, p1, t) {
  1726. var onet = 1 - t;
  1727. out.x = onet * p0.x + t * p1.x;
  1728. out.y = onet * p0.y + t * p1.y;
  1729. };
  1730. return Point;
  1731. }());
  1732. var mathMin = Math.min;
  1733. var mathMax = Math.max;
  1734. var lt = new Point();
  1735. var rb = new Point();
  1736. var lb = new Point();
  1737. var rt = new Point();
  1738. var minTv = new Point();
  1739. var maxTv = new Point();
  1740. var BoundingRect = (function () {
  1741. function BoundingRect(x, y, width, height) {
  1742. if (width < 0) {
  1743. x = x + width;
  1744. width = -width;
  1745. }
  1746. if (height < 0) {
  1747. y = y + height;
  1748. height = -height;
  1749. }
  1750. this.x = x;
  1751. this.y = y;
  1752. this.width = width;
  1753. this.height = height;
  1754. }
  1755. BoundingRect.prototype.union = function (other) {
  1756. var x = mathMin(other.x, this.x);
  1757. var y = mathMin(other.y, this.y);
  1758. if (isFinite(this.x) && isFinite(this.width)) {
  1759. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1760. }
  1761. else {
  1762. this.width = other.width;
  1763. }
  1764. if (isFinite(this.y) && isFinite(this.height)) {
  1765. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1766. }
  1767. else {
  1768. this.height = other.height;
  1769. }
  1770. this.x = x;
  1771. this.y = y;
  1772. };
  1773. BoundingRect.prototype.applyTransform = function (m) {
  1774. BoundingRect.applyTransform(this, this, m);
  1775. };
  1776. BoundingRect.prototype.calculateTransform = function (b) {
  1777. var a = this;
  1778. var sx = b.width / a.width;
  1779. var sy = b.height / a.height;
  1780. var m = create$1();
  1781. translate(m, m, [-a.x, -a.y]);
  1782. scale$1(m, m, [sx, sy]);
  1783. translate(m, m, [b.x, b.y]);
  1784. return m;
  1785. };
  1786. BoundingRect.prototype.intersect = function (b, mtv) {
  1787. if (!b) {
  1788. return false;
  1789. }
  1790. if (!(b instanceof BoundingRect)) {
  1791. b = BoundingRect.create(b);
  1792. }
  1793. var a = this;
  1794. var ax0 = a.x;
  1795. var ax1 = a.x + a.width;
  1796. var ay0 = a.y;
  1797. var ay1 = a.y + a.height;
  1798. var bx0 = b.x;
  1799. var bx1 = b.x + b.width;
  1800. var by0 = b.y;
  1801. var by1 = b.y + b.height;
  1802. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1803. if (mtv) {
  1804. var dMin = Infinity;
  1805. var dMax = 0;
  1806. var d0 = Math.abs(ax1 - bx0);
  1807. var d1 = Math.abs(bx1 - ax0);
  1808. var d2 = Math.abs(ay1 - by0);
  1809. var d3 = Math.abs(by1 - ay0);
  1810. var dx = Math.min(d0, d1);
  1811. var dy = Math.min(d2, d3);
  1812. if (ax1 < bx0 || bx1 < ax0) {
  1813. if (dx > dMax) {
  1814. dMax = dx;
  1815. if (d0 < d1) {
  1816. Point.set(maxTv, -d0, 0);
  1817. }
  1818. else {
  1819. Point.set(maxTv, d1, 0);
  1820. }
  1821. }
  1822. }
  1823. else {
  1824. if (dx < dMin) {
  1825. dMin = dx;
  1826. if (d0 < d1) {
  1827. Point.set(minTv, d0, 0);
  1828. }
  1829. else {
  1830. Point.set(minTv, -d1, 0);
  1831. }
  1832. }
  1833. }
  1834. if (ay1 < by0 || by1 < ay0) {
  1835. if (dy > dMax) {
  1836. dMax = dy;
  1837. if (d2 < d3) {
  1838. Point.set(maxTv, 0, -d2);
  1839. }
  1840. else {
  1841. Point.set(maxTv, 0, d3);
  1842. }
  1843. }
  1844. }
  1845. else {
  1846. if (dx < dMin) {
  1847. dMin = dx;
  1848. if (d2 < d3) {
  1849. Point.set(minTv, 0, d2);
  1850. }
  1851. else {
  1852. Point.set(minTv, 0, -d3);
  1853. }
  1854. }
  1855. }
  1856. }
  1857. if (mtv) {
  1858. Point.copy(mtv, overlap ? minTv : maxTv);
  1859. }
  1860. return overlap;
  1861. };
  1862. BoundingRect.prototype.contain = function (x, y) {
  1863. var rect = this;
  1864. return x >= rect.x
  1865. && x <= (rect.x + rect.width)
  1866. && y >= rect.y
  1867. && y <= (rect.y + rect.height);
  1868. };
  1869. BoundingRect.prototype.clone = function () {
  1870. return new BoundingRect(this.x, this.y, this.width, this.height);
  1871. };
  1872. BoundingRect.prototype.copy = function (other) {
  1873. BoundingRect.copy(this, other);
  1874. };
  1875. BoundingRect.prototype.plain = function () {
  1876. return {
  1877. x: this.x,
  1878. y: this.y,
  1879. width: this.width,
  1880. height: this.height
  1881. };
  1882. };
  1883. BoundingRect.prototype.isFinite = function () {
  1884. return isFinite(this.x)
  1885. && isFinite(this.y)
  1886. && isFinite(this.width)
  1887. && isFinite(this.height);
  1888. };
  1889. BoundingRect.prototype.isZero = function () {
  1890. return this.width === 0 || this.height === 0;
  1891. };
  1892. BoundingRect.create = function (rect) {
  1893. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1894. };
  1895. BoundingRect.copy = function (target, source) {
  1896. target.x = source.x;
  1897. target.y = source.y;
  1898. target.width = source.width;
  1899. target.height = source.height;
  1900. };
  1901. BoundingRect.applyTransform = function (target, source, m) {
  1902. if (!m) {
  1903. if (target !== source) {
  1904. BoundingRect.copy(target, source);
  1905. }
  1906. return;
  1907. }
  1908. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1909. var sx = m[0];
  1910. var sy = m[3];
  1911. var tx = m[4];
  1912. var ty = m[5];
  1913. target.x = source.x * sx + tx;
  1914. target.y = source.y * sy + ty;
  1915. target.width = source.width * sx;
  1916. target.height = source.height * sy;
  1917. if (target.width < 0) {
  1918. target.x += target.width;
  1919. target.width = -target.width;
  1920. }
  1921. if (target.height < 0) {
  1922. target.y += target.height;
  1923. target.height = -target.height;
  1924. }
  1925. return;
  1926. }
  1927. lt.x = lb.x = source.x;
  1928. lt.y = rt.y = source.y;
  1929. rb.x = rt.x = source.x + source.width;
  1930. rb.y = lb.y = source.y + source.height;
  1931. lt.transform(m);
  1932. rt.transform(m);
  1933. rb.transform(m);
  1934. lb.transform(m);
  1935. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1936. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1937. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1938. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1939. target.width = maxX - target.x;
  1940. target.height = maxY - target.y;
  1941. };
  1942. return BoundingRect;
  1943. }());
  1944. var SILENT = 'silent';
  1945. function makeEventPacket(eveType, targetInfo, event) {
  1946. return {
  1947. type: eveType,
  1948. event: event,
  1949. target: targetInfo.target,
  1950. topTarget: targetInfo.topTarget,
  1951. cancelBubble: false,
  1952. offsetX: event.zrX,
  1953. offsetY: event.zrY,
  1954. gestureEvent: event.gestureEvent,
  1955. pinchX: event.pinchX,
  1956. pinchY: event.pinchY,
  1957. pinchScale: event.pinchScale,
  1958. wheelDelta: event.zrDelta,
  1959. zrByTouch: event.zrByTouch,
  1960. which: event.which,
  1961. stop: stopEvent
  1962. };
  1963. }
  1964. function stopEvent() {
  1965. stop(this.event);
  1966. }
  1967. var EmptyProxy = (function (_super) {
  1968. __extends(EmptyProxy, _super);
  1969. function EmptyProxy() {
  1970. var _this = _super !== null && _super.apply(this, arguments) || this;
  1971. _this.handler = null;
  1972. return _this;
  1973. }
  1974. EmptyProxy.prototype.dispose = function () { };
  1975. EmptyProxy.prototype.setCursor = function () { };
  1976. return EmptyProxy;
  1977. }(Eventful));
  1978. var HoveredResult = (function () {
  1979. function HoveredResult(x, y) {
  1980. this.x = x;
  1981. this.y = y;
  1982. }
  1983. return HoveredResult;
  1984. }());
  1985. var handlerNames = [
  1986. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1987. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1988. ];
  1989. var tmpRect = new BoundingRect(0, 0, 0, 0);
  1990. var Handler = (function (_super) {
  1991. __extends(Handler, _super);
  1992. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  1993. var _this = _super.call(this) || this;
  1994. _this._hovered = new HoveredResult(0, 0);
  1995. _this.storage = storage;
  1996. _this.painter = painter;
  1997. _this.painterRoot = painterRoot;
  1998. _this._pointerSize = pointerSize;
  1999. proxy = proxy || new EmptyProxy();
  2000. _this.proxy = null;
  2001. _this.setHandlerProxy(proxy);
  2002. _this._draggingMgr = new Draggable(_this);
  2003. return _this;
  2004. }
  2005. Handler.prototype.setHandlerProxy = function (proxy) {
  2006. if (this.proxy) {
  2007. this.proxy.dispose();
  2008. }
  2009. if (proxy) {
  2010. each(handlerNames, function (name) {
  2011. proxy.on && proxy.on(name, this[name], this);
  2012. }, this);
  2013. proxy.handler = this;
  2014. }
  2015. this.proxy = proxy;
  2016. };
  2017. Handler.prototype.mousemove = function (event) {
  2018. var x = event.zrX;
  2019. var y = event.zrY;
  2020. var isOutside = isOutsideBoundary(this, x, y);
  2021. var lastHovered = this._hovered;
  2022. var lastHoveredTarget = lastHovered.target;
  2023. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2024. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2025. lastHoveredTarget = lastHovered.target;
  2026. }
  2027. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2028. var hoveredTarget = hovered.target;
  2029. var proxy = this.proxy;
  2030. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2031. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2032. this.dispatchToElement(lastHovered, 'mouseout', event);
  2033. }
  2034. this.dispatchToElement(hovered, 'mousemove', event);
  2035. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2036. this.dispatchToElement(hovered, 'mouseover', event);
  2037. }
  2038. };
  2039. Handler.prototype.mouseout = function (event) {
  2040. var eventControl = event.zrEventControl;
  2041. if (eventControl !== 'only_globalout') {
  2042. this.dispatchToElement(this._hovered, 'mouseout', event);
  2043. }
  2044. if (eventControl !== 'no_globalout') {
  2045. this.trigger('globalout', { type: 'globalout', event: event });
  2046. }
  2047. };
  2048. Handler.prototype.resize = function () {
  2049. this._hovered = new HoveredResult(0, 0);
  2050. };
  2051. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2052. var handler = this[eventName];
  2053. handler && handler.call(this, eventArgs);
  2054. };
  2055. Handler.prototype.dispose = function () {
  2056. this.proxy.dispose();
  2057. this.storage = null;
  2058. this.proxy = null;
  2059. this.painter = null;
  2060. };
  2061. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2062. var proxy = this.proxy;
  2063. proxy.setCursor && proxy.setCursor(cursorStyle);
  2064. };
  2065. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2066. targetInfo = targetInfo || {};
  2067. var el = targetInfo.target;
  2068. if (el && el.silent) {
  2069. return;
  2070. }
  2071. var eventKey = ('on' + eventName);
  2072. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2073. while (el) {
  2074. el[eventKey]
  2075. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2076. el.trigger(eventName, eventPacket);
  2077. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2078. if (eventPacket.cancelBubble) {
  2079. break;
  2080. }
  2081. }
  2082. if (!eventPacket.cancelBubble) {
  2083. this.trigger(eventName, eventPacket);
  2084. if (this.painter && this.painter.eachOtherLayer) {
  2085. this.painter.eachOtherLayer(function (layer) {
  2086. if (typeof (layer[eventKey]) === 'function') {
  2087. layer[eventKey].call(layer, eventPacket);
  2088. }
  2089. if (layer.trigger) {
  2090. layer.trigger(eventName, eventPacket);
  2091. }
  2092. });
  2093. }
  2094. }
  2095. };
  2096. Handler.prototype.findHover = function (x, y, exclude) {
  2097. var list = this.storage.getDisplayList();
  2098. var out = new HoveredResult(x, y);
  2099. setHoverTarget(list, out, x, y, exclude);
  2100. if (this._pointerSize && !out.target) {
  2101. var candidates = [];
  2102. var pointerSize = this._pointerSize;
  2103. var targetSizeHalf = pointerSize / 2;
  2104. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2105. for (var i = list.length - 1; i >= 0; i--) {
  2106. var el = list[i];
  2107. if (el !== exclude
  2108. && !el.ignore
  2109. && !el.ignoreCoarsePointer
  2110. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2111. tmpRect.copy(el.getBoundingRect());
  2112. if (el.transform) {
  2113. tmpRect.applyTransform(el.transform);
  2114. }
  2115. if (tmpRect.intersect(pointerRect)) {
  2116. candidates.push(el);
  2117. }
  2118. }
  2119. }
  2120. if (candidates.length) {
  2121. var rStep = 4;
  2122. var thetaStep = Math.PI / 12;
  2123. var PI2 = Math.PI * 2;
  2124. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2125. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2126. var x1 = x + r * Math.cos(theta);
  2127. var y1 = y + r * Math.sin(theta);
  2128. setHoverTarget(candidates, out, x1, y1, exclude);
  2129. if (out.target) {
  2130. return out;
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. return out;
  2137. };
  2138. Handler.prototype.processGesture = function (event, stage) {
  2139. if (!this._gestureMgr) {
  2140. this._gestureMgr = new GestureMgr();
  2141. }
  2142. var gestureMgr = this._gestureMgr;
  2143. stage === 'start' && gestureMgr.clear();
  2144. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2145. stage === 'end' && gestureMgr.clear();
  2146. if (gestureInfo) {
  2147. var type = gestureInfo.type;
  2148. event.gestureEvent = type;
  2149. var res = new HoveredResult();
  2150. res.target = gestureInfo.target;
  2151. this.dispatchToElement(res, type, gestureInfo.event);
  2152. }
  2153. };
  2154. return Handler;
  2155. }(Eventful));
  2156. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2157. Handler.prototype[name] = function (event) {
  2158. var x = event.zrX;
  2159. var y = event.zrY;
  2160. var isOutside = isOutsideBoundary(this, x, y);
  2161. var hovered;
  2162. var hoveredTarget;
  2163. if (name !== 'mouseup' || !isOutside) {
  2164. hovered = this.findHover(x, y);
  2165. hoveredTarget = hovered.target;
  2166. }
  2167. if (name === 'mousedown') {
  2168. this._downEl = hoveredTarget;
  2169. this._downPoint = [event.zrX, event.zrY];
  2170. this._upEl = hoveredTarget;
  2171. }
  2172. else if (name === 'mouseup') {
  2173. this._upEl = hoveredTarget;
  2174. }
  2175. else if (name === 'click') {
  2176. if (this._downEl !== this._upEl
  2177. || !this._downPoint
  2178. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2179. return;
  2180. }
  2181. this._downPoint = null;
  2182. }
  2183. this.dispatchToElement(hovered, name, event);
  2184. };
  2185. });
  2186. function isHover(displayable, x, y) {
  2187. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2188. var el = displayable;
  2189. var isSilent = void 0;
  2190. var ignoreClip = false;
  2191. while (el) {
  2192. if (el.ignoreClip) {
  2193. ignoreClip = true;
  2194. }
  2195. if (!ignoreClip) {
  2196. var clipPath = el.getClipPath();
  2197. if (clipPath && !clipPath.contain(x, y)) {
  2198. return false;
  2199. }
  2200. }
  2201. if (el.silent) {
  2202. isSilent = true;
  2203. }
  2204. var hostEl = el.__hostTarget;
  2205. el = hostEl ? hostEl : el.parent;
  2206. }
  2207. return isSilent ? SILENT : true;
  2208. }
  2209. return false;
  2210. }
  2211. function setHoverTarget(list, out, x, y, exclude) {
  2212. for (var i = list.length - 1; i >= 0; i--) {
  2213. var el = list[i];
  2214. var hoverCheckResult = void 0;
  2215. if (el !== exclude
  2216. && !el.ignore
  2217. && (hoverCheckResult = isHover(el, x, y))) {
  2218. !out.topTarget && (out.topTarget = el);
  2219. if (hoverCheckResult !== SILENT) {
  2220. out.target = el;
  2221. break;
  2222. }
  2223. }
  2224. }
  2225. }
  2226. function isOutsideBoundary(handlerInstance, x, y) {
  2227. var painter = handlerInstance.painter;
  2228. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2229. }
  2230. var DEFAULT_MIN_MERGE = 32;
  2231. var DEFAULT_MIN_GALLOPING = 7;
  2232. function minRunLength(n) {
  2233. var r = 0;
  2234. while (n >= DEFAULT_MIN_MERGE) {
  2235. r |= n & 1;
  2236. n >>= 1;
  2237. }
  2238. return n + r;
  2239. }
  2240. function makeAscendingRun(array, lo, hi, compare) {
  2241. var runHi = lo + 1;
  2242. if (runHi === hi) {
  2243. return 1;
  2244. }
  2245. if (compare(array[runHi++], array[lo]) < 0) {
  2246. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2247. runHi++;
  2248. }
  2249. reverseRun(array, lo, runHi);
  2250. }
  2251. else {
  2252. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2253. runHi++;
  2254. }
  2255. }
  2256. return runHi - lo;
  2257. }
  2258. function reverseRun(array, lo, hi) {
  2259. hi--;
  2260. while (lo < hi) {
  2261. var t = array[lo];
  2262. array[lo++] = array[hi];
  2263. array[hi--] = t;
  2264. }
  2265. }
  2266. function binaryInsertionSort(array, lo, hi, start, compare) {
  2267. if (start === lo) {
  2268. start++;
  2269. }
  2270. for (; start < hi; start++) {
  2271. var pivot = array[start];
  2272. var left = lo;
  2273. var right = start;
  2274. var mid;
  2275. while (left < right) {
  2276. mid = left + right >>> 1;
  2277. if (compare(pivot, array[mid]) < 0) {
  2278. right = mid;
  2279. }
  2280. else {
  2281. left = mid + 1;
  2282. }
  2283. }
  2284. var n = start - left;
  2285. switch (n) {
  2286. case 3:
  2287. array[left + 3] = array[left + 2];
  2288. case 2:
  2289. array[left + 2] = array[left + 1];
  2290. case 1:
  2291. array[left + 1] = array[left];
  2292. break;
  2293. default:
  2294. while (n > 0) {
  2295. array[left + n] = array[left + n - 1];
  2296. n--;
  2297. }
  2298. }
  2299. array[left] = pivot;
  2300. }
  2301. }
  2302. function gallopLeft(value, array, start, length, hint, compare) {
  2303. var lastOffset = 0;
  2304. var maxOffset = 0;
  2305. var offset = 1;
  2306. if (compare(value, array[start + hint]) > 0) {
  2307. maxOffset = length - hint;
  2308. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2309. lastOffset = offset;
  2310. offset = (offset << 1) + 1;
  2311. if (offset <= 0) {
  2312. offset = maxOffset;
  2313. }
  2314. }
  2315. if (offset > maxOffset) {
  2316. offset = maxOffset;
  2317. }
  2318. lastOffset += hint;
  2319. offset += hint;
  2320. }
  2321. else {
  2322. maxOffset = hint + 1;
  2323. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2324. lastOffset = offset;
  2325. offset = (offset << 1) + 1;
  2326. if (offset <= 0) {
  2327. offset = maxOffset;
  2328. }
  2329. }
  2330. if (offset > maxOffset) {
  2331. offset = maxOffset;
  2332. }
  2333. var tmp = lastOffset;
  2334. lastOffset = hint - offset;
  2335. offset = hint - tmp;
  2336. }
  2337. lastOffset++;
  2338. while (lastOffset < offset) {
  2339. var m = lastOffset + (offset - lastOffset >>> 1);
  2340. if (compare(value, array[start + m]) > 0) {
  2341. lastOffset = m + 1;
  2342. }
  2343. else {
  2344. offset = m;
  2345. }
  2346. }
  2347. return offset;
  2348. }
  2349. function gallopRight(value, array, start, length, hint, compare) {
  2350. var lastOffset = 0;
  2351. var maxOffset = 0;
  2352. var offset = 1;
  2353. if (compare(value, array[start + hint]) < 0) {
  2354. maxOffset = hint + 1;
  2355. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2356. lastOffset = offset;
  2357. offset = (offset << 1) + 1;
  2358. if (offset <= 0) {
  2359. offset = maxOffset;
  2360. }
  2361. }
  2362. if (offset > maxOffset) {
  2363. offset = maxOffset;
  2364. }
  2365. var tmp = lastOffset;
  2366. lastOffset = hint - offset;
  2367. offset = hint - tmp;
  2368. }
  2369. else {
  2370. maxOffset = length - hint;
  2371. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2372. lastOffset = offset;
  2373. offset = (offset << 1) + 1;
  2374. if (offset <= 0) {
  2375. offset = maxOffset;
  2376. }
  2377. }
  2378. if (offset > maxOffset) {
  2379. offset = maxOffset;
  2380. }
  2381. lastOffset += hint;
  2382. offset += hint;
  2383. }
  2384. lastOffset++;
  2385. while (lastOffset < offset) {
  2386. var m = lastOffset + (offset - lastOffset >>> 1);
  2387. if (compare(value, array[start + m]) < 0) {
  2388. offset = m;
  2389. }
  2390. else {
  2391. lastOffset = m + 1;
  2392. }
  2393. }
  2394. return offset;
  2395. }
  2396. function TimSort(array, compare) {
  2397. var minGallop = DEFAULT_MIN_GALLOPING;
  2398. var runStart;
  2399. var runLength;
  2400. var stackSize = 0;
  2401. var tmp = [];
  2402. runStart = [];
  2403. runLength = [];
  2404. function pushRun(_runStart, _runLength) {
  2405. runStart[stackSize] = _runStart;
  2406. runLength[stackSize] = _runLength;
  2407. stackSize += 1;
  2408. }
  2409. function mergeRuns() {
  2410. while (stackSize > 1) {
  2411. var n = stackSize - 2;
  2412. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2413. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2414. if (runLength[n - 1] < runLength[n + 1]) {
  2415. n--;
  2416. }
  2417. }
  2418. else if (runLength[n] > runLength[n + 1]) {
  2419. break;
  2420. }
  2421. mergeAt(n);
  2422. }
  2423. }
  2424. function forceMergeRuns() {
  2425. while (stackSize > 1) {
  2426. var n = stackSize - 2;
  2427. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2428. n--;
  2429. }
  2430. mergeAt(n);
  2431. }
  2432. }
  2433. function mergeAt(i) {
  2434. var start1 = runStart[i];
  2435. var length1 = runLength[i];
  2436. var start2 = runStart[i + 1];
  2437. var length2 = runLength[i + 1];
  2438. runLength[i] = length1 + length2;
  2439. if (i === stackSize - 3) {
  2440. runStart[i + 1] = runStart[i + 2];
  2441. runLength[i + 1] = runLength[i + 2];
  2442. }
  2443. stackSize--;
  2444. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2445. start1 += k;
  2446. length1 -= k;
  2447. if (length1 === 0) {
  2448. return;
  2449. }
  2450. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2451. if (length2 === 0) {
  2452. return;
  2453. }
  2454. if (length1 <= length2) {
  2455. mergeLow(start1, length1, start2, length2);
  2456. }
  2457. else {
  2458. mergeHigh(start1, length1, start2, length2);
  2459. }
  2460. }
  2461. function mergeLow(start1, length1, start2, length2) {
  2462. var i = 0;
  2463. for (i = 0; i < length1; i++) {
  2464. tmp[i] = array[start1 + i];
  2465. }
  2466. var cursor1 = 0;
  2467. var cursor2 = start2;
  2468. var dest = start1;
  2469. array[dest++] = array[cursor2++];
  2470. if (--length2 === 0) {
  2471. for (i = 0; i < length1; i++) {
  2472. array[dest + i] = tmp[cursor1 + i];
  2473. }
  2474. return;
  2475. }
  2476. if (length1 === 1) {
  2477. for (i = 0; i < length2; i++) {
  2478. array[dest + i] = array[cursor2 + i];
  2479. }
  2480. array[dest + length2] = tmp[cursor1];
  2481. return;
  2482. }
  2483. var _minGallop = minGallop;
  2484. var count1;
  2485. var count2;
  2486. var exit;
  2487. while (1) {
  2488. count1 = 0;
  2489. count2 = 0;
  2490. exit = false;
  2491. do {
  2492. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2493. array[dest++] = array[cursor2++];
  2494. count2++;
  2495. count1 = 0;
  2496. if (--length2 === 0) {
  2497. exit = true;
  2498. break;
  2499. }
  2500. }
  2501. else {
  2502. array[dest++] = tmp[cursor1++];
  2503. count1++;
  2504. count2 = 0;
  2505. if (--length1 === 1) {
  2506. exit = true;
  2507. break;
  2508. }
  2509. }
  2510. } while ((count1 | count2) < _minGallop);
  2511. if (exit) {
  2512. break;
  2513. }
  2514. do {
  2515. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2516. if (count1 !== 0) {
  2517. for (i = 0; i < count1; i++) {
  2518. array[dest + i] = tmp[cursor1 + i];
  2519. }
  2520. dest += count1;
  2521. cursor1 += count1;
  2522. length1 -= count1;
  2523. if (length1 <= 1) {
  2524. exit = true;
  2525. break;
  2526. }
  2527. }
  2528. array[dest++] = array[cursor2++];
  2529. if (--length2 === 0) {
  2530. exit = true;
  2531. break;
  2532. }
  2533. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2534. if (count2 !== 0) {
  2535. for (i = 0; i < count2; i++) {
  2536. array[dest + i] = array[cursor2 + i];
  2537. }
  2538. dest += count2;
  2539. cursor2 += count2;
  2540. length2 -= count2;
  2541. if (length2 === 0) {
  2542. exit = true;
  2543. break;
  2544. }
  2545. }
  2546. array[dest++] = tmp[cursor1++];
  2547. if (--length1 === 1) {
  2548. exit = true;
  2549. break;
  2550. }
  2551. _minGallop--;
  2552. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2553. if (exit) {
  2554. break;
  2555. }
  2556. if (_minGallop < 0) {
  2557. _minGallop = 0;
  2558. }
  2559. _minGallop += 2;
  2560. }
  2561. minGallop = _minGallop;
  2562. minGallop < 1 && (minGallop = 1);
  2563. if (length1 === 1) {
  2564. for (i = 0; i < length2; i++) {
  2565. array[dest + i] = array[cursor2 + i];
  2566. }
  2567. array[dest + length2] = tmp[cursor1];
  2568. }
  2569. else if (length1 === 0) {
  2570. throw new Error();
  2571. }
  2572. else {
  2573. for (i = 0; i < length1; i++) {
  2574. array[dest + i] = tmp[cursor1 + i];
  2575. }
  2576. }
  2577. }
  2578. function mergeHigh(start1, length1, start2, length2) {
  2579. var i = 0;
  2580. for (i = 0; i < length2; i++) {
  2581. tmp[i] = array[start2 + i];
  2582. }
  2583. var cursor1 = start1 + length1 - 1;
  2584. var cursor2 = length2 - 1;
  2585. var dest = start2 + length2 - 1;
  2586. var customCursor = 0;
  2587. var customDest = 0;
  2588. array[dest--] = array[cursor1--];
  2589. if (--length1 === 0) {
  2590. customCursor = dest - (length2 - 1);
  2591. for (i = 0; i < length2; i++) {
  2592. array[customCursor + i] = tmp[i];
  2593. }
  2594. return;
  2595. }
  2596. if (length2 === 1) {
  2597. dest -= length1;
  2598. cursor1 -= length1;
  2599. customDest = dest + 1;
  2600. customCursor = cursor1 + 1;
  2601. for (i = length1 - 1; i >= 0; i--) {
  2602. array[customDest + i] = array[customCursor + i];
  2603. }
  2604. array[dest] = tmp[cursor2];
  2605. return;
  2606. }
  2607. var _minGallop = minGallop;
  2608. while (true) {
  2609. var count1 = 0;
  2610. var count2 = 0;
  2611. var exit = false;
  2612. do {
  2613. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2614. array[dest--] = array[cursor1--];
  2615. count1++;
  2616. count2 = 0;
  2617. if (--length1 === 0) {
  2618. exit = true;
  2619. break;
  2620. }
  2621. }
  2622. else {
  2623. array[dest--] = tmp[cursor2--];
  2624. count2++;
  2625. count1 = 0;
  2626. if (--length2 === 1) {
  2627. exit = true;
  2628. break;
  2629. }
  2630. }
  2631. } while ((count1 | count2) < _minGallop);
  2632. if (exit) {
  2633. break;
  2634. }
  2635. do {
  2636. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2637. if (count1 !== 0) {
  2638. dest -= count1;
  2639. cursor1 -= count1;
  2640. length1 -= count1;
  2641. customDest = dest + 1;
  2642. customCursor = cursor1 + 1;
  2643. for (i = count1 - 1; i >= 0; i--) {
  2644. array[customDest + i] = array[customCursor + i];
  2645. }
  2646. if (length1 === 0) {
  2647. exit = true;
  2648. break;
  2649. }
  2650. }
  2651. array[dest--] = tmp[cursor2--];
  2652. if (--length2 === 1) {
  2653. exit = true;
  2654. break;
  2655. }
  2656. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2657. if (count2 !== 0) {
  2658. dest -= count2;
  2659. cursor2 -= count2;
  2660. length2 -= count2;
  2661. customDest = dest + 1;
  2662. customCursor = cursor2 + 1;
  2663. for (i = 0; i < count2; i++) {
  2664. array[customDest + i] = tmp[customCursor + i];
  2665. }
  2666. if (length2 <= 1) {
  2667. exit = true;
  2668. break;
  2669. }
  2670. }
  2671. array[dest--] = array[cursor1--];
  2672. if (--length1 === 0) {
  2673. exit = true;
  2674. break;
  2675. }
  2676. _minGallop--;
  2677. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2678. if (exit) {
  2679. break;
  2680. }
  2681. if (_minGallop < 0) {
  2682. _minGallop = 0;
  2683. }
  2684. _minGallop += 2;
  2685. }
  2686. minGallop = _minGallop;
  2687. if (minGallop < 1) {
  2688. minGallop = 1;
  2689. }
  2690. if (length2 === 1) {
  2691. dest -= length1;
  2692. cursor1 -= length1;
  2693. customDest = dest + 1;
  2694. customCursor = cursor1 + 1;
  2695. for (i = length1 - 1; i >= 0; i--) {
  2696. array[customDest + i] = array[customCursor + i];
  2697. }
  2698. array[dest] = tmp[cursor2];
  2699. }
  2700. else if (length2 === 0) {
  2701. throw new Error();
  2702. }
  2703. else {
  2704. customCursor = dest - (length2 - 1);
  2705. for (i = 0; i < length2; i++) {
  2706. array[customCursor + i] = tmp[i];
  2707. }
  2708. }
  2709. }
  2710. return {
  2711. mergeRuns: mergeRuns,
  2712. forceMergeRuns: forceMergeRuns,
  2713. pushRun: pushRun
  2714. };
  2715. }
  2716. function sort(array, compare, lo, hi) {
  2717. if (!lo) {
  2718. lo = 0;
  2719. }
  2720. if (!hi) {
  2721. hi = array.length;
  2722. }
  2723. var remaining = hi - lo;
  2724. if (remaining < 2) {
  2725. return;
  2726. }
  2727. var runLength = 0;
  2728. if (remaining < DEFAULT_MIN_MERGE) {
  2729. runLength = makeAscendingRun(array, lo, hi, compare);
  2730. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2731. return;
  2732. }
  2733. var ts = TimSort(array, compare);
  2734. var minRun = minRunLength(remaining);
  2735. do {
  2736. runLength = makeAscendingRun(array, lo, hi, compare);
  2737. if (runLength < minRun) {
  2738. var force = remaining;
  2739. if (force > minRun) {
  2740. force = minRun;
  2741. }
  2742. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2743. runLength = force;
  2744. }
  2745. ts.pushRun(lo, runLength);
  2746. ts.mergeRuns();
  2747. remaining -= runLength;
  2748. lo += runLength;
  2749. } while (remaining !== 0);
  2750. ts.forceMergeRuns();
  2751. }
  2752. var REDRAW_BIT = 1;
  2753. var STYLE_CHANGED_BIT = 2;
  2754. var SHAPE_CHANGED_BIT = 4;
  2755. var invalidZErrorLogged = false;
  2756. function logInvalidZError() {
  2757. if (invalidZErrorLogged) {
  2758. return;
  2759. }
  2760. invalidZErrorLogged = true;
  2761. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2762. }
  2763. function shapeCompareFunc(a, b) {
  2764. if (a.zlevel === b.zlevel) {
  2765. if (a.z === b.z) {
  2766. return a.z2 - b.z2;
  2767. }
  2768. return a.z - b.z;
  2769. }
  2770. return a.zlevel - b.zlevel;
  2771. }
  2772. var Storage = (function () {
  2773. function Storage() {
  2774. this._roots = [];
  2775. this._displayList = [];
  2776. this._displayListLen = 0;
  2777. this.displayableSortFunc = shapeCompareFunc;
  2778. }
  2779. Storage.prototype.traverse = function (cb, context) {
  2780. for (var i = 0; i < this._roots.length; i++) {
  2781. this._roots[i].traverse(cb, context);
  2782. }
  2783. };
  2784. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2785. includeIgnore = includeIgnore || false;
  2786. var displayList = this._displayList;
  2787. if (update || !displayList.length) {
  2788. this.updateDisplayList(includeIgnore);
  2789. }
  2790. return displayList;
  2791. };
  2792. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2793. this._displayListLen = 0;
  2794. var roots = this._roots;
  2795. var displayList = this._displayList;
  2796. for (var i = 0, len = roots.length; i < len; i++) {
  2797. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2798. }
  2799. displayList.length = this._displayListLen;
  2800. sort(displayList, shapeCompareFunc);
  2801. };
  2802. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2803. if (el.ignore && !includeIgnore) {
  2804. return;
  2805. }
  2806. el.beforeUpdate();
  2807. el.update();
  2808. el.afterUpdate();
  2809. var userSetClipPath = el.getClipPath();
  2810. if (el.ignoreClip) {
  2811. clipPaths = null;
  2812. }
  2813. else if (userSetClipPath) {
  2814. if (clipPaths) {
  2815. clipPaths = clipPaths.slice();
  2816. }
  2817. else {
  2818. clipPaths = [];
  2819. }
  2820. var currentClipPath = userSetClipPath;
  2821. var parentClipPath = el;
  2822. while (currentClipPath) {
  2823. currentClipPath.parent = parentClipPath;
  2824. currentClipPath.updateTransform();
  2825. clipPaths.push(currentClipPath);
  2826. parentClipPath = currentClipPath;
  2827. currentClipPath = currentClipPath.getClipPath();
  2828. }
  2829. }
  2830. if (el.childrenRef) {
  2831. var children = el.childrenRef();
  2832. for (var i = 0; i < children.length; i++) {
  2833. var child = children[i];
  2834. if (el.__dirty) {
  2835. child.__dirty |= REDRAW_BIT;
  2836. }
  2837. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2838. }
  2839. el.__dirty = 0;
  2840. }
  2841. else {
  2842. var disp = el;
  2843. if (clipPaths && clipPaths.length) {
  2844. disp.__clipPaths = clipPaths;
  2845. }
  2846. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2847. disp.__clipPaths = [];
  2848. }
  2849. if (isNaN(disp.z)) {
  2850. logInvalidZError();
  2851. disp.z = 0;
  2852. }
  2853. if (isNaN(disp.z2)) {
  2854. logInvalidZError();
  2855. disp.z2 = 0;
  2856. }
  2857. if (isNaN(disp.zlevel)) {
  2858. logInvalidZError();
  2859. disp.zlevel = 0;
  2860. }
  2861. this._displayList[this._displayListLen++] = disp;
  2862. }
  2863. var decalEl = el.getDecalElement && el.getDecalElement();
  2864. if (decalEl) {
  2865. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2866. }
  2867. var textGuide = el.getTextGuideLine();
  2868. if (textGuide) {
  2869. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2870. }
  2871. var textEl = el.getTextContent();
  2872. if (textEl) {
  2873. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2874. }
  2875. };
  2876. Storage.prototype.addRoot = function (el) {
  2877. if (el.__zr && el.__zr.storage === this) {
  2878. return;
  2879. }
  2880. this._roots.push(el);
  2881. };
  2882. Storage.prototype.delRoot = function (el) {
  2883. if (el instanceof Array) {
  2884. for (var i = 0, l = el.length; i < l; i++) {
  2885. this.delRoot(el[i]);
  2886. }
  2887. return;
  2888. }
  2889. var idx = indexOf(this._roots, el);
  2890. if (idx >= 0) {
  2891. this._roots.splice(idx, 1);
  2892. }
  2893. };
  2894. Storage.prototype.delAllRoots = function () {
  2895. this._roots = [];
  2896. this._displayList = [];
  2897. this._displayListLen = 0;
  2898. return;
  2899. };
  2900. Storage.prototype.getRoots = function () {
  2901. return this._roots;
  2902. };
  2903. Storage.prototype.dispose = function () {
  2904. this._displayList = null;
  2905. this._roots = null;
  2906. };
  2907. return Storage;
  2908. }());
  2909. var requestAnimationFrame;
  2910. requestAnimationFrame = (env.hasGlobalWindow
  2911. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2912. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2913. || window.mozRequestAnimationFrame
  2914. || window.webkitRequestAnimationFrame)) || function (func) {
  2915. return setTimeout(func, 16);
  2916. };
  2917. var requestAnimationFrame$1 = requestAnimationFrame;
  2918. var easingFuncs = {
  2919. linear: function (k) {
  2920. return k;
  2921. },
  2922. quadraticIn: function (k) {
  2923. return k * k;
  2924. },
  2925. quadraticOut: function (k) {
  2926. return k * (2 - k);
  2927. },
  2928. quadraticInOut: function (k) {
  2929. if ((k *= 2) < 1) {
  2930. return 0.5 * k * k;
  2931. }
  2932. return -0.5 * (--k * (k - 2) - 1);
  2933. },
  2934. cubicIn: function (k) {
  2935. return k * k * k;
  2936. },
  2937. cubicOut: function (k) {
  2938. return --k * k * k + 1;
  2939. },
  2940. cubicInOut: function (k) {
  2941. if ((k *= 2) < 1) {
  2942. return 0.5 * k * k * k;
  2943. }
  2944. return 0.5 * ((k -= 2) * k * k + 2);
  2945. },
  2946. quarticIn: function (k) {
  2947. return k * k * k * k;
  2948. },
  2949. quarticOut: function (k) {
  2950. return 1 - (--k * k * k * k);
  2951. },
  2952. quarticInOut: function (k) {
  2953. if ((k *= 2) < 1) {
  2954. return 0.5 * k * k * k * k;
  2955. }
  2956. return -0.5 * ((k -= 2) * k * k * k - 2);
  2957. },
  2958. quinticIn: function (k) {
  2959. return k * k * k * k * k;
  2960. },
  2961. quinticOut: function (k) {
  2962. return --k * k * k * k * k + 1;
  2963. },
  2964. quinticInOut: function (k) {
  2965. if ((k *= 2) < 1) {
  2966. return 0.5 * k * k * k * k * k;
  2967. }
  2968. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2969. },
  2970. sinusoidalIn: function (k) {
  2971. return 1 - Math.cos(k * Math.PI / 2);
  2972. },
  2973. sinusoidalOut: function (k) {
  2974. return Math.sin(k * Math.PI / 2);
  2975. },
  2976. sinusoidalInOut: function (k) {
  2977. return 0.5 * (1 - Math.cos(Math.PI * k));
  2978. },
  2979. exponentialIn: function (k) {
  2980. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2981. },
  2982. exponentialOut: function (k) {
  2983. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2984. },
  2985. exponentialInOut: function (k) {
  2986. if (k === 0) {
  2987. return 0;
  2988. }
  2989. if (k === 1) {
  2990. return 1;
  2991. }
  2992. if ((k *= 2) < 1) {
  2993. return 0.5 * Math.pow(1024, k - 1);
  2994. }
  2995. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2996. },
  2997. circularIn: function (k) {
  2998. return 1 - Math.sqrt(1 - k * k);
  2999. },
  3000. circularOut: function (k) {
  3001. return Math.sqrt(1 - (--k * k));
  3002. },
  3003. circularInOut: function (k) {
  3004. if ((k *= 2) < 1) {
  3005. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3006. }
  3007. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3008. },
  3009. elasticIn: function (k) {
  3010. var s;
  3011. var a = 0.1;
  3012. var p = 0.4;
  3013. if (k === 0) {
  3014. return 0;
  3015. }
  3016. if (k === 1) {
  3017. return 1;
  3018. }
  3019. if (!a || a < 1) {
  3020. a = 1;
  3021. s = p / 4;
  3022. }
  3023. else {
  3024. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3025. }
  3026. return -(a * Math.pow(2, 10 * (k -= 1))
  3027. * Math.sin((k - s) * (2 * Math.PI) / p));
  3028. },
  3029. elasticOut: function (k) {
  3030. var s;
  3031. var a = 0.1;
  3032. var p = 0.4;
  3033. if (k === 0) {
  3034. return 0;
  3035. }
  3036. if (k === 1) {
  3037. return 1;
  3038. }
  3039. if (!a || a < 1) {
  3040. a = 1;
  3041. s = p / 4;
  3042. }
  3043. else {
  3044. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3045. }
  3046. return (a * Math.pow(2, -10 * k)
  3047. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3048. },
  3049. elasticInOut: function (k) {
  3050. var s;
  3051. var a = 0.1;
  3052. var p = 0.4;
  3053. if (k === 0) {
  3054. return 0;
  3055. }
  3056. if (k === 1) {
  3057. return 1;
  3058. }
  3059. if (!a || a < 1) {
  3060. a = 1;
  3061. s = p / 4;
  3062. }
  3063. else {
  3064. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3065. }
  3066. if ((k *= 2) < 1) {
  3067. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3068. * Math.sin((k - s) * (2 * Math.PI) / p));
  3069. }
  3070. return a * Math.pow(2, -10 * (k -= 1))
  3071. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3072. },
  3073. backIn: function (k) {
  3074. var s = 1.70158;
  3075. return k * k * ((s + 1) * k - s);
  3076. },
  3077. backOut: function (k) {
  3078. var s = 1.70158;
  3079. return --k * k * ((s + 1) * k + s) + 1;
  3080. },
  3081. backInOut: function (k) {
  3082. var s = 1.70158 * 1.525;
  3083. if ((k *= 2) < 1) {
  3084. return 0.5 * (k * k * ((s + 1) * k - s));
  3085. }
  3086. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3087. },
  3088. bounceIn: function (k) {
  3089. return 1 - easingFuncs.bounceOut(1 - k);
  3090. },
  3091. bounceOut: function (k) {
  3092. if (k < (1 / 2.75)) {
  3093. return 7.5625 * k * k;
  3094. }
  3095. else if (k < (2 / 2.75)) {
  3096. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3097. }
  3098. else if (k < (2.5 / 2.75)) {
  3099. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3100. }
  3101. else {
  3102. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3103. }
  3104. },
  3105. bounceInOut: function (k) {
  3106. if (k < 0.5) {
  3107. return easingFuncs.bounceIn(k * 2) * 0.5;
  3108. }
  3109. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3110. }
  3111. };
  3112. var mathPow = Math.pow;
  3113. var mathSqrt = Math.sqrt;
  3114. var EPSILON = 1e-8;
  3115. var EPSILON_NUMERIC = 1e-4;
  3116. var THREE_SQRT = mathSqrt(3);
  3117. var ONE_THIRD = 1 / 3;
  3118. var _v0 = create();
  3119. var _v1 = create();
  3120. var _v2 = create();
  3121. function isAroundZero(val) {
  3122. return val > -EPSILON && val < EPSILON;
  3123. }
  3124. function isNotAroundZero(val) {
  3125. return val > EPSILON || val < -EPSILON;
  3126. }
  3127. function cubicAt(p0, p1, p2, p3, t) {
  3128. var onet = 1 - t;
  3129. return onet * onet * (onet * p0 + 3 * t * p1)
  3130. + t * t * (t * p3 + 3 * onet * p2);
  3131. }
  3132. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3133. var onet = 1 - t;
  3134. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3135. + (p3 - p2) * t * t);
  3136. }
  3137. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3138. var a = p3 + 3 * (p1 - p2) - p0;
  3139. var b = 3 * (p2 - p1 * 2 + p0);
  3140. var c = 3 * (p1 - p0);
  3141. var d = p0 - val;
  3142. var A = b * b - 3 * a * c;
  3143. var B = b * c - 9 * a * d;
  3144. var C = c * c - 3 * b * d;
  3145. var n = 0;
  3146. if (isAroundZero(A) && isAroundZero(B)) {
  3147. if (isAroundZero(b)) {
  3148. roots[0] = 0;
  3149. }
  3150. else {
  3151. var t1 = -c / b;
  3152. if (t1 >= 0 && t1 <= 1) {
  3153. roots[n++] = t1;
  3154. }
  3155. }
  3156. }
  3157. else {
  3158. var disc = B * B - 4 * A * C;
  3159. if (isAroundZero(disc)) {
  3160. var K = B / A;
  3161. var t1 = -b / a + K;
  3162. var t2 = -K / 2;
  3163. if (t1 >= 0 && t1 <= 1) {
  3164. roots[n++] = t1;
  3165. }
  3166. if (t2 >= 0 && t2 <= 1) {
  3167. roots[n++] = t2;
  3168. }
  3169. }
  3170. else if (disc > 0) {
  3171. var discSqrt = mathSqrt(disc);
  3172. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3173. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3174. if (Y1 < 0) {
  3175. Y1 = -mathPow(-Y1, ONE_THIRD);
  3176. }
  3177. else {
  3178. Y1 = mathPow(Y1, ONE_THIRD);
  3179. }
  3180. if (Y2 < 0) {
  3181. Y2 = -mathPow(-Y2, ONE_THIRD);
  3182. }
  3183. else {
  3184. Y2 = mathPow(Y2, ONE_THIRD);
  3185. }
  3186. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3187. if (t1 >= 0 && t1 <= 1) {
  3188. roots[n++] = t1;
  3189. }
  3190. }
  3191. else {
  3192. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3193. var theta = Math.acos(T) / 3;
  3194. var ASqrt = mathSqrt(A);
  3195. var tmp = Math.cos(theta);
  3196. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3197. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3198. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3199. if (t1 >= 0 && t1 <= 1) {
  3200. roots[n++] = t1;
  3201. }
  3202. if (t2 >= 0 && t2 <= 1) {
  3203. roots[n++] = t2;
  3204. }
  3205. if (t3 >= 0 && t3 <= 1) {
  3206. roots[n++] = t3;
  3207. }
  3208. }
  3209. }
  3210. return n;
  3211. }
  3212. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3213. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3214. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3215. var c = 3 * p1 - 3 * p0;
  3216. var n = 0;
  3217. if (isAroundZero(a)) {
  3218. if (isNotAroundZero(b)) {
  3219. var t1 = -c / b;
  3220. if (t1 >= 0 && t1 <= 1) {
  3221. extrema[n++] = t1;
  3222. }
  3223. }
  3224. }
  3225. else {
  3226. var disc = b * b - 4 * a * c;
  3227. if (isAroundZero(disc)) {
  3228. extrema[0] = -b / (2 * a);
  3229. }
  3230. else if (disc > 0) {
  3231. var discSqrt = mathSqrt(disc);
  3232. var t1 = (-b + discSqrt) / (2 * a);
  3233. var t2 = (-b - discSqrt) / (2 * a);
  3234. if (t1 >= 0 && t1 <= 1) {
  3235. extrema[n++] = t1;
  3236. }
  3237. if (t2 >= 0 && t2 <= 1) {
  3238. extrema[n++] = t2;
  3239. }
  3240. }
  3241. }
  3242. return n;
  3243. }
  3244. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3245. var p01 = (p1 - p0) * t + p0;
  3246. var p12 = (p2 - p1) * t + p1;
  3247. var p23 = (p3 - p2) * t + p2;
  3248. var p012 = (p12 - p01) * t + p01;
  3249. var p123 = (p23 - p12) * t + p12;
  3250. var p0123 = (p123 - p012) * t + p012;
  3251. out[0] = p0;
  3252. out[1] = p01;
  3253. out[2] = p012;
  3254. out[3] = p0123;
  3255. out[4] = p0123;
  3256. out[5] = p123;
  3257. out[6] = p23;
  3258. out[7] = p3;
  3259. }
  3260. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3261. var t;
  3262. var interval = 0.005;
  3263. var d = Infinity;
  3264. var prev;
  3265. var next;
  3266. var d1;
  3267. var d2;
  3268. _v0[0] = x;
  3269. _v0[1] = y;
  3270. for (var _t = 0; _t < 1; _t += 0.05) {
  3271. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3272. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3273. d1 = distSquare(_v0, _v1);
  3274. if (d1 < d) {
  3275. t = _t;
  3276. d = d1;
  3277. }
  3278. }
  3279. d = Infinity;
  3280. for (var i = 0; i < 32; i++) {
  3281. if (interval < EPSILON_NUMERIC) {
  3282. break;
  3283. }
  3284. prev = t - interval;
  3285. next = t + interval;
  3286. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3287. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3288. d1 = distSquare(_v1, _v0);
  3289. if (prev >= 0 && d1 < d) {
  3290. t = prev;
  3291. d = d1;
  3292. }
  3293. else {
  3294. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3295. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3296. d2 = distSquare(_v2, _v0);
  3297. if (next <= 1 && d2 < d) {
  3298. t = next;
  3299. d = d2;
  3300. }
  3301. else {
  3302. interval *= 0.5;
  3303. }
  3304. }
  3305. }
  3306. if (out) {
  3307. out[0] = cubicAt(x0, x1, x2, x3, t);
  3308. out[1] = cubicAt(y0, y1, y2, y3, t);
  3309. }
  3310. return mathSqrt(d);
  3311. }
  3312. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3313. var px = x0;
  3314. var py = y0;
  3315. var d = 0;
  3316. var step = 1 / iteration;
  3317. for (var i = 1; i <= iteration; i++) {
  3318. var t = i * step;
  3319. var x = cubicAt(x0, x1, x2, x3, t);
  3320. var y = cubicAt(y0, y1, y2, y3, t);
  3321. var dx = x - px;
  3322. var dy = y - py;
  3323. d += Math.sqrt(dx * dx + dy * dy);
  3324. px = x;
  3325. py = y;
  3326. }
  3327. return d;
  3328. }
  3329. function quadraticAt(p0, p1, p2, t) {
  3330. var onet = 1 - t;
  3331. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3332. }
  3333. function quadraticDerivativeAt(p0, p1, p2, t) {
  3334. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3335. }
  3336. function quadraticRootAt(p0, p1, p2, val, roots) {
  3337. var a = p0 - 2 * p1 + p2;
  3338. var b = 2 * (p1 - p0);
  3339. var c = p0 - val;
  3340. var n = 0;
  3341. if (isAroundZero(a)) {
  3342. if (isNotAroundZero(b)) {
  3343. var t1 = -c / b;
  3344. if (t1 >= 0 && t1 <= 1) {
  3345. roots[n++] = t1;
  3346. }
  3347. }
  3348. }
  3349. else {
  3350. var disc = b * b - 4 * a * c;
  3351. if (isAroundZero(disc)) {
  3352. var t1 = -b / (2 * a);
  3353. if (t1 >= 0 && t1 <= 1) {
  3354. roots[n++] = t1;
  3355. }
  3356. }
  3357. else if (disc > 0) {
  3358. var discSqrt = mathSqrt(disc);
  3359. var t1 = (-b + discSqrt) / (2 * a);
  3360. var t2 = (-b - discSqrt) / (2 * a);
  3361. if (t1 >= 0 && t1 <= 1) {
  3362. roots[n++] = t1;
  3363. }
  3364. if (t2 >= 0 && t2 <= 1) {
  3365. roots[n++] = t2;
  3366. }
  3367. }
  3368. }
  3369. return n;
  3370. }
  3371. function quadraticExtremum(p0, p1, p2) {
  3372. var divider = p0 + p2 - 2 * p1;
  3373. if (divider === 0) {
  3374. return 0.5;
  3375. }
  3376. else {
  3377. return (p0 - p1) / divider;
  3378. }
  3379. }
  3380. function quadraticSubdivide(p0, p1, p2, t, out) {
  3381. var p01 = (p1 - p0) * t + p0;
  3382. var p12 = (p2 - p1) * t + p1;
  3383. var p012 = (p12 - p01) * t + p01;
  3384. out[0] = p0;
  3385. out[1] = p01;
  3386. out[2] = p012;
  3387. out[3] = p012;
  3388. out[4] = p12;
  3389. out[5] = p2;
  3390. }
  3391. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3392. var t;
  3393. var interval = 0.005;
  3394. var d = Infinity;
  3395. _v0[0] = x;
  3396. _v0[1] = y;
  3397. for (var _t = 0; _t < 1; _t += 0.05) {
  3398. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3399. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3400. var d1 = distSquare(_v0, _v1);
  3401. if (d1 < d) {
  3402. t = _t;
  3403. d = d1;
  3404. }
  3405. }
  3406. d = Infinity;
  3407. for (var i = 0; i < 32; i++) {
  3408. if (interval < EPSILON_NUMERIC) {
  3409. break;
  3410. }
  3411. var prev = t - interval;
  3412. var next = t + interval;
  3413. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3414. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3415. var d1 = distSquare(_v1, _v0);
  3416. if (prev >= 0 && d1 < d) {
  3417. t = prev;
  3418. d = d1;
  3419. }
  3420. else {
  3421. _v2[0] = quadraticAt(x0, x1, x2, next);
  3422. _v2[1] = quadraticAt(y0, y1, y2, next);
  3423. var d2 = distSquare(_v2, _v0);
  3424. if (next <= 1 && d2 < d) {
  3425. t = next;
  3426. d = d2;
  3427. }
  3428. else {
  3429. interval *= 0.5;
  3430. }
  3431. }
  3432. }
  3433. if (out) {
  3434. out[0] = quadraticAt(x0, x1, x2, t);
  3435. out[1] = quadraticAt(y0, y1, y2, t);
  3436. }
  3437. return mathSqrt(d);
  3438. }
  3439. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3440. var px = x0;
  3441. var py = y0;
  3442. var d = 0;
  3443. var step = 1 / iteration;
  3444. for (var i = 1; i <= iteration; i++) {
  3445. var t = i * step;
  3446. var x = quadraticAt(x0, x1, x2, t);
  3447. var y = quadraticAt(y0, y1, y2, t);
  3448. var dx = x - px;
  3449. var dy = y - py;
  3450. d += Math.sqrt(dx * dx + dy * dy);
  3451. px = x;
  3452. py = y;
  3453. }
  3454. return d;
  3455. }
  3456. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3457. function createCubicEasingFunc(cubicEasingStr) {
  3458. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3459. if (cubic) {
  3460. var points = cubic[1].split(',');
  3461. var a_1 = +trim(points[0]);
  3462. var b_1 = +trim(points[1]);
  3463. var c_1 = +trim(points[2]);
  3464. var d_1 = +trim(points[3]);
  3465. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3466. return;
  3467. }
  3468. var roots_1 = [];
  3469. return function (p) {
  3470. return p <= 0
  3471. ? 0 : p >= 1
  3472. ? 1
  3473. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3474. };
  3475. }
  3476. }
  3477. var Clip = (function () {
  3478. function Clip(opts) {
  3479. this._inited = false;
  3480. this._startTime = 0;
  3481. this._pausedTime = 0;
  3482. this._paused = false;
  3483. this._life = opts.life || 1000;
  3484. this._delay = opts.delay || 0;
  3485. this.loop = opts.loop || false;
  3486. this.onframe = opts.onframe || noop;
  3487. this.ondestroy = opts.ondestroy || noop;
  3488. this.onrestart = opts.onrestart || noop;
  3489. opts.easing && this.setEasing(opts.easing);
  3490. }
  3491. Clip.prototype.step = function (globalTime, deltaTime) {
  3492. if (!this._inited) {
  3493. this._startTime = globalTime + this._delay;
  3494. this._inited = true;
  3495. }
  3496. if (this._paused) {
  3497. this._pausedTime += deltaTime;
  3498. return;
  3499. }
  3500. var life = this._life;
  3501. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3502. var percent = elapsedTime / life;
  3503. if (percent < 0) {
  3504. percent = 0;
  3505. }
  3506. percent = Math.min(percent, 1);
  3507. var easingFunc = this.easingFunc;
  3508. var schedule = easingFunc ? easingFunc(percent) : percent;
  3509. this.onframe(schedule);
  3510. if (percent === 1) {
  3511. if (this.loop) {
  3512. var remainder = elapsedTime % life;
  3513. this._startTime = globalTime - remainder;
  3514. this._pausedTime = 0;
  3515. this.onrestart();
  3516. }
  3517. else {
  3518. return true;
  3519. }
  3520. }
  3521. return false;
  3522. };
  3523. Clip.prototype.pause = function () {
  3524. this._paused = true;
  3525. };
  3526. Clip.prototype.resume = function () {
  3527. this._paused = false;
  3528. };
  3529. Clip.prototype.setEasing = function (easing) {
  3530. this.easing = easing;
  3531. this.easingFunc = isFunction(easing)
  3532. ? easing
  3533. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3534. };
  3535. return Clip;
  3536. }());
  3537. var Entry = (function () {
  3538. function Entry(val) {
  3539. this.value = val;
  3540. }
  3541. return Entry;
  3542. }());
  3543. var LinkedList = (function () {
  3544. function LinkedList() {
  3545. this._len = 0;
  3546. }
  3547. LinkedList.prototype.insert = function (val) {
  3548. var entry = new Entry(val);
  3549. this.insertEntry(entry);
  3550. return entry;
  3551. };
  3552. LinkedList.prototype.insertEntry = function (entry) {
  3553. if (!this.head) {
  3554. this.head = this.tail = entry;
  3555. }
  3556. else {
  3557. this.tail.next = entry;
  3558. entry.prev = this.tail;
  3559. entry.next = null;
  3560. this.tail = entry;
  3561. }
  3562. this._len++;
  3563. };
  3564. LinkedList.prototype.remove = function (entry) {
  3565. var prev = entry.prev;
  3566. var next = entry.next;
  3567. if (prev) {
  3568. prev.next = next;
  3569. }
  3570. else {
  3571. this.head = next;
  3572. }
  3573. if (next) {
  3574. next.prev = prev;
  3575. }
  3576. else {
  3577. this.tail = prev;
  3578. }
  3579. entry.next = entry.prev = null;
  3580. this._len--;
  3581. };
  3582. LinkedList.prototype.len = function () {
  3583. return this._len;
  3584. };
  3585. LinkedList.prototype.clear = function () {
  3586. this.head = this.tail = null;
  3587. this._len = 0;
  3588. };
  3589. return LinkedList;
  3590. }());
  3591. var LRU = (function () {
  3592. function LRU(maxSize) {
  3593. this._list = new LinkedList();
  3594. this._maxSize = 10;
  3595. this._map = {};
  3596. this._maxSize = maxSize;
  3597. }
  3598. LRU.prototype.put = function (key, value) {
  3599. var list = this._list;
  3600. var map = this._map;
  3601. var removed = null;
  3602. if (map[key] == null) {
  3603. var len = list.len();
  3604. var entry = this._lastRemovedEntry;
  3605. if (len >= this._maxSize && len > 0) {
  3606. var leastUsedEntry = list.head;
  3607. list.remove(leastUsedEntry);
  3608. delete map[leastUsedEntry.key];
  3609. removed = leastUsedEntry.value;
  3610. this._lastRemovedEntry = leastUsedEntry;
  3611. }
  3612. if (entry) {
  3613. entry.value = value;
  3614. }
  3615. else {
  3616. entry = new Entry(value);
  3617. }
  3618. entry.key = key;
  3619. list.insertEntry(entry);
  3620. map[key] = entry;
  3621. }
  3622. return removed;
  3623. };
  3624. LRU.prototype.get = function (key) {
  3625. var entry = this._map[key];
  3626. var list = this._list;
  3627. if (entry != null) {
  3628. if (entry !== list.tail) {
  3629. list.remove(entry);
  3630. list.insertEntry(entry);
  3631. }
  3632. return entry.value;
  3633. }
  3634. };
  3635. LRU.prototype.clear = function () {
  3636. this._list.clear();
  3637. this._map = {};
  3638. };
  3639. LRU.prototype.len = function () {
  3640. return this._list.len();
  3641. };
  3642. return LRU;
  3643. }());
  3644. var kCSSColorTable = {
  3645. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3646. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3647. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3648. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3649. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3650. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3651. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3652. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3653. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3654. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3655. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3656. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3657. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3658. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3659. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3660. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3661. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3662. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3663. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3664. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3665. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3666. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3667. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3668. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3669. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3670. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3671. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3672. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3673. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3674. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3675. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3676. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3677. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3678. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3679. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3680. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3681. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3682. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3683. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3684. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3685. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3686. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3687. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3688. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3689. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3690. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3691. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3692. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3693. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3694. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3695. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3696. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3697. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3698. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3699. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3700. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3701. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3702. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3703. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3704. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3705. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3706. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3707. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3708. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3709. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3710. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3711. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3712. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3713. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3714. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3715. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3716. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3717. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3718. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3719. };
  3720. function clampCssByte(i) {
  3721. i = Math.round(i);
  3722. return i < 0 ? 0 : i > 255 ? 255 : i;
  3723. }
  3724. function clampCssAngle(i) {
  3725. i = Math.round(i);
  3726. return i < 0 ? 0 : i > 360 ? 360 : i;
  3727. }
  3728. function clampCssFloat(f) {
  3729. return f < 0 ? 0 : f > 1 ? 1 : f;
  3730. }
  3731. function parseCssInt(val) {
  3732. var str = val;
  3733. if (str.length && str.charAt(str.length - 1) === '%') {
  3734. return clampCssByte(parseFloat(str) / 100 * 255);
  3735. }
  3736. return clampCssByte(parseInt(str, 10));
  3737. }
  3738. function parseCssFloat(val) {
  3739. var str = val;
  3740. if (str.length && str.charAt(str.length - 1) === '%') {
  3741. return clampCssFloat(parseFloat(str) / 100);
  3742. }
  3743. return clampCssFloat(parseFloat(str));
  3744. }
  3745. function cssHueToRgb(m1, m2, h) {
  3746. if (h < 0) {
  3747. h += 1;
  3748. }
  3749. else if (h > 1) {
  3750. h -= 1;
  3751. }
  3752. if (h * 6 < 1) {
  3753. return m1 + (m2 - m1) * h * 6;
  3754. }
  3755. if (h * 2 < 1) {
  3756. return m2;
  3757. }
  3758. if (h * 3 < 2) {
  3759. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3760. }
  3761. return m1;
  3762. }
  3763. function lerpNumber(a, b, p) {
  3764. return a + (b - a) * p;
  3765. }
  3766. function setRgba(out, r, g, b, a) {
  3767. out[0] = r;
  3768. out[1] = g;
  3769. out[2] = b;
  3770. out[3] = a;
  3771. return out;
  3772. }
  3773. function copyRgba(out, a) {
  3774. out[0] = a[0];
  3775. out[1] = a[1];
  3776. out[2] = a[2];
  3777. out[3] = a[3];
  3778. return out;
  3779. }
  3780. var colorCache = new LRU(20);
  3781. var lastRemovedArr = null;
  3782. function putToCache(colorStr, rgbaArr) {
  3783. if (lastRemovedArr) {
  3784. copyRgba(lastRemovedArr, rgbaArr);
  3785. }
  3786. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3787. }
  3788. function parse(colorStr, rgbaArr) {
  3789. if (!colorStr) {
  3790. return;
  3791. }
  3792. rgbaArr = rgbaArr || [];
  3793. var cached = colorCache.get(colorStr);
  3794. if (cached) {
  3795. return copyRgba(rgbaArr, cached);
  3796. }
  3797. colorStr = colorStr + '';
  3798. var str = colorStr.replace(/ /g, '').toLowerCase();
  3799. if (str in kCSSColorTable) {
  3800. copyRgba(rgbaArr, kCSSColorTable[str]);
  3801. putToCache(colorStr, rgbaArr);
  3802. return rgbaArr;
  3803. }
  3804. var strLen = str.length;
  3805. if (str.charAt(0) === '#') {
  3806. if (strLen === 4 || strLen === 5) {
  3807. var iv = parseInt(str.slice(1, 4), 16);
  3808. if (!(iv >= 0 && iv <= 0xfff)) {
  3809. setRgba(rgbaArr, 0, 0, 0, 1);
  3810. return;
  3811. }
  3812. setRgba(rgbaArr, ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), (iv & 0xf0) | ((iv & 0xf0) >> 4), (iv & 0xf) | ((iv & 0xf) << 4), strLen === 5 ? parseInt(str.slice(4), 16) / 0xf : 1);
  3813. putToCache(colorStr, rgbaArr);
  3814. return rgbaArr;
  3815. }
  3816. else if (strLen === 7 || strLen === 9) {
  3817. var iv = parseInt(str.slice(1, 7), 16);
  3818. if (!(iv >= 0 && iv <= 0xffffff)) {
  3819. setRgba(rgbaArr, 0, 0, 0, 1);
  3820. return;
  3821. }
  3822. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3823. putToCache(colorStr, rgbaArr);
  3824. return rgbaArr;
  3825. }
  3826. return;
  3827. }
  3828. var op = str.indexOf('(');
  3829. var ep = str.indexOf(')');
  3830. if (op !== -1 && ep + 1 === strLen) {
  3831. var fname = str.substr(0, op);
  3832. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3833. var alpha = 1;
  3834. switch (fname) {
  3835. case 'rgba':
  3836. if (params.length !== 4) {
  3837. return params.length === 3
  3838. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3839. : setRgba(rgbaArr, 0, 0, 0, 1);
  3840. }
  3841. alpha = parseCssFloat(params.pop());
  3842. case 'rgb':
  3843. if (params.length >= 3) {
  3844. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3845. putToCache(colorStr, rgbaArr);
  3846. return rgbaArr;
  3847. }
  3848. else {
  3849. setRgba(rgbaArr, 0, 0, 0, 1);
  3850. return;
  3851. }
  3852. case 'hsla':
  3853. if (params.length !== 4) {
  3854. setRgba(rgbaArr, 0, 0, 0, 1);
  3855. return;
  3856. }
  3857. params[3] = parseCssFloat(params[3]);
  3858. hsla2rgba(params, rgbaArr);
  3859. putToCache(colorStr, rgbaArr);
  3860. return rgbaArr;
  3861. case 'hsl':
  3862. if (params.length !== 3) {
  3863. setRgba(rgbaArr, 0, 0, 0, 1);
  3864. return;
  3865. }
  3866. hsla2rgba(params, rgbaArr);
  3867. putToCache(colorStr, rgbaArr);
  3868. return rgbaArr;
  3869. default:
  3870. return;
  3871. }
  3872. }
  3873. setRgba(rgbaArr, 0, 0, 0, 1);
  3874. return;
  3875. }
  3876. function hsla2rgba(hsla, rgba) {
  3877. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3878. var s = parseCssFloat(hsla[1]);
  3879. var l = parseCssFloat(hsla[2]);
  3880. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3881. var m1 = l * 2 - m2;
  3882. rgba = rgba || [];
  3883. setRgba(rgba, clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255), 1);
  3884. if (hsla.length === 4) {
  3885. rgba[3] = hsla[3];
  3886. }
  3887. return rgba;
  3888. }
  3889. function rgba2hsla(rgba) {
  3890. if (!rgba) {
  3891. return;
  3892. }
  3893. var R = rgba[0] / 255;
  3894. var G = rgba[1] / 255;
  3895. var B = rgba[2] / 255;
  3896. var vMin = Math.min(R, G, B);
  3897. var vMax = Math.max(R, G, B);
  3898. var delta = vMax - vMin;
  3899. var L = (vMax + vMin) / 2;
  3900. var H;
  3901. var S;
  3902. if (delta === 0) {
  3903. H = 0;
  3904. S = 0;
  3905. }
  3906. else {
  3907. if (L < 0.5) {
  3908. S = delta / (vMax + vMin);
  3909. }
  3910. else {
  3911. S = delta / (2 - vMax - vMin);
  3912. }
  3913. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3914. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3915. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3916. if (R === vMax) {
  3917. H = deltaB - deltaG;
  3918. }
  3919. else if (G === vMax) {
  3920. H = (1 / 3) + deltaR - deltaB;
  3921. }
  3922. else if (B === vMax) {
  3923. H = (2 / 3) + deltaG - deltaR;
  3924. }
  3925. if (H < 0) {
  3926. H += 1;
  3927. }
  3928. if (H > 1) {
  3929. H -= 1;
  3930. }
  3931. }
  3932. var hsla = [H * 360, S, L];
  3933. if (rgba[3] != null) {
  3934. hsla.push(rgba[3]);
  3935. }
  3936. return hsla;
  3937. }
  3938. function lift(color, level) {
  3939. var colorArr = parse(color);
  3940. if (colorArr) {
  3941. for (var i = 0; i < 3; i++) {
  3942. if (level < 0) {
  3943. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3944. }
  3945. else {
  3946. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3947. }
  3948. if (colorArr[i] > 255) {
  3949. colorArr[i] = 255;
  3950. }
  3951. else if (colorArr[i] < 0) {
  3952. colorArr[i] = 0;
  3953. }
  3954. }
  3955. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3956. }
  3957. }
  3958. function toHex(color) {
  3959. var colorArr = parse(color);
  3960. if (colorArr) {
  3961. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3962. }
  3963. }
  3964. function fastLerp(normalizedValue, colors, out) {
  3965. if (!(colors && colors.length)
  3966. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3967. return;
  3968. }
  3969. out = out || [];
  3970. var value = normalizedValue * (colors.length - 1);
  3971. var leftIndex = Math.floor(value);
  3972. var rightIndex = Math.ceil(value);
  3973. var leftColor = colors[leftIndex];
  3974. var rightColor = colors[rightIndex];
  3975. var dv = value - leftIndex;
  3976. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3977. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3978. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3979. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3980. return out;
  3981. }
  3982. var fastMapToColor = fastLerp;
  3983. function lerp$1(normalizedValue, colors, fullOutput) {
  3984. if (!(colors && colors.length)
  3985. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3986. return;
  3987. }
  3988. var value = normalizedValue * (colors.length - 1);
  3989. var leftIndex = Math.floor(value);
  3990. var rightIndex = Math.ceil(value);
  3991. var leftColor = parse(colors[leftIndex]);
  3992. var rightColor = parse(colors[rightIndex]);
  3993. var dv = value - leftIndex;
  3994. var color = stringify([
  3995. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3996. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3997. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3998. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3999. ], 'rgba');
  4000. return fullOutput
  4001. ? {
  4002. color: color,
  4003. leftIndex: leftIndex,
  4004. rightIndex: rightIndex,
  4005. value: value
  4006. }
  4007. : color;
  4008. }
  4009. var mapToColor = lerp$1;
  4010. function modifyHSL(color, h, s, l) {
  4011. var colorArr = parse(color);
  4012. if (color) {
  4013. colorArr = rgba2hsla(colorArr);
  4014. h != null && (colorArr[0] = clampCssAngle(h));
  4015. s != null && (colorArr[1] = parseCssFloat(s));
  4016. l != null && (colorArr[2] = parseCssFloat(l));
  4017. return stringify(hsla2rgba(colorArr), 'rgba');
  4018. }
  4019. }
  4020. function modifyAlpha(color, alpha) {
  4021. var colorArr = parse(color);
  4022. if (colorArr && alpha != null) {
  4023. colorArr[3] = clampCssFloat(alpha);
  4024. return stringify(colorArr, 'rgba');
  4025. }
  4026. }
  4027. function stringify(arrColor, type) {
  4028. if (!arrColor || !arrColor.length) {
  4029. return;
  4030. }
  4031. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4032. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4033. colorStr += ',' + arrColor[3];
  4034. }
  4035. return type + '(' + colorStr + ')';
  4036. }
  4037. function lum(color, backgroundLum) {
  4038. var arr = parse(color);
  4039. return arr
  4040. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4041. + (1 - arr[3]) * backgroundLum
  4042. : 0;
  4043. }
  4044. function random() {
  4045. return stringify([
  4046. Math.round(Math.random() * 255),
  4047. Math.round(Math.random() * 255),
  4048. Math.round(Math.random() * 255)
  4049. ], 'rgb');
  4050. }
  4051. var liftedColorCache = new LRU(100);
  4052. function liftColor(color) {
  4053. if (isString(color)) {
  4054. var liftedColor = liftedColorCache.get(color);
  4055. if (!liftedColor) {
  4056. liftedColor = lift(color, -0.1);
  4057. liftedColorCache.put(color, liftedColor);
  4058. }
  4059. return liftedColor;
  4060. }
  4061. else if (isGradientObject(color)) {
  4062. var ret = extend({}, color);
  4063. ret.colorStops = map(color.colorStops, function (stop) { return ({
  4064. offset: stop.offset,
  4065. color: lift(stop.color, -0.1)
  4066. }); });
  4067. return ret;
  4068. }
  4069. return color;
  4070. }
  4071. var color = /*#__PURE__*/Object.freeze({
  4072. __proto__: null,
  4073. parse: parse,
  4074. lift: lift,
  4075. toHex: toHex,
  4076. fastLerp: fastLerp,
  4077. fastMapToColor: fastMapToColor,
  4078. lerp: lerp$1,
  4079. mapToColor: mapToColor,
  4080. modifyHSL: modifyHSL,
  4081. modifyAlpha: modifyAlpha,
  4082. stringify: stringify,
  4083. lum: lum,
  4084. random: random,
  4085. liftColor: liftColor
  4086. });
  4087. var mathRound = Math.round;
  4088. function normalizeColor(color) {
  4089. var opacity;
  4090. if (!color || color === 'transparent') {
  4091. color = 'none';
  4092. }
  4093. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  4094. var arr = parse(color);
  4095. if (arr) {
  4096. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  4097. opacity = arr[3];
  4098. }
  4099. }
  4100. return {
  4101. color: color,
  4102. opacity: opacity == null ? 1 : opacity
  4103. };
  4104. }
  4105. var EPSILON$1 = 1e-4;
  4106. function isAroundZero$1(transform) {
  4107. return transform < EPSILON$1 && transform > -EPSILON$1;
  4108. }
  4109. function round3(transform) {
  4110. return mathRound(transform * 1e3) / 1e3;
  4111. }
  4112. function round4(transform) {
  4113. return mathRound(transform * 1e4) / 1e4;
  4114. }
  4115. function getMatrixStr(m) {
  4116. return 'matrix('
  4117. + round3(m[0]) + ','
  4118. + round3(m[1]) + ','
  4119. + round3(m[2]) + ','
  4120. + round3(m[3]) + ','
  4121. + round4(m[4]) + ','
  4122. + round4(m[5])
  4123. + ')';
  4124. }
  4125. var TEXT_ALIGN_TO_ANCHOR = {
  4126. left: 'start',
  4127. right: 'end',
  4128. center: 'middle',
  4129. middle: 'middle'
  4130. };
  4131. function adjustTextY(y, lineHeight, textBaseline) {
  4132. if (textBaseline === 'top') {
  4133. y += lineHeight / 2;
  4134. }
  4135. else if (textBaseline === 'bottom') {
  4136. y -= lineHeight / 2;
  4137. }
  4138. return y;
  4139. }
  4140. function hasShadow(style) {
  4141. return style
  4142. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  4143. }
  4144. function getShadowKey(displayable) {
  4145. var style = displayable.style;
  4146. var globalScale = displayable.getGlobalScale();
  4147. return [
  4148. style.shadowColor,
  4149. (style.shadowBlur || 0).toFixed(2),
  4150. (style.shadowOffsetX || 0).toFixed(2),
  4151. (style.shadowOffsetY || 0).toFixed(2),
  4152. globalScale[0],
  4153. globalScale[1]
  4154. ].join(',');
  4155. }
  4156. function isImagePattern(val) {
  4157. return val && (!!val.image);
  4158. }
  4159. function isSVGPattern(val) {
  4160. return val && (!!val.svgElement);
  4161. }
  4162. function isPattern(val) {
  4163. return isImagePattern(val) || isSVGPattern(val);
  4164. }
  4165. function isLinearGradient(val) {
  4166. return val.type === 'linear';
  4167. }
  4168. function isRadialGradient(val) {
  4169. return val.type === 'radial';
  4170. }
  4171. function isGradient(val) {
  4172. return val && (val.type === 'linear'
  4173. || val.type === 'radial');
  4174. }
  4175. function getIdURL(id) {
  4176. return "url(#" + id + ")";
  4177. }
  4178. function getPathPrecision(el) {
  4179. var scale = el.getGlobalScale();
  4180. var size = Math.max(scale[0], scale[1]);
  4181. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  4182. }
  4183. function getSRTTransformString(transform) {
  4184. var x = transform.x || 0;
  4185. var y = transform.y || 0;
  4186. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  4187. var scaleX = retrieve2(transform.scaleX, 1);
  4188. var scaleY = retrieve2(transform.scaleY, 1);
  4189. var skewX = transform.skewX || 0;
  4190. var skewY = transform.skewY || 0;
  4191. var res = [];
  4192. if (x || y) {
  4193. res.push("translate(" + x + "px," + y + "px)");
  4194. }
  4195. if (rotation) {
  4196. res.push("rotate(" + rotation + ")");
  4197. }
  4198. if (scaleX !== 1 || scaleY !== 1) {
  4199. res.push("scale(" + scaleX + "," + scaleY + ")");
  4200. }
  4201. if (skewX || skewY) {
  4202. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  4203. }
  4204. return res.join(' ');
  4205. }
  4206. var encodeBase64 = (function () {
  4207. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  4208. return function (str) {
  4209. return window.btoa(unescape(encodeURIComponent(str)));
  4210. };
  4211. }
  4212. if (typeof Buffer !== 'undefined') {
  4213. return function (str) {
  4214. return Buffer.from(str).toString('base64');
  4215. };
  4216. }
  4217. return function (str) {
  4218. if ("development" !== 'production') {
  4219. logError('Base64 isn\'t natively supported in the current environment.');
  4220. }
  4221. return null;
  4222. };
  4223. })();
  4224. var arraySlice = Array.prototype.slice;
  4225. function interpolateNumber(p0, p1, percent) {
  4226. return (p1 - p0) * percent + p0;
  4227. }
  4228. function interpolate1DArray(out, p0, p1, percent) {
  4229. var len = p0.length;
  4230. for (var i = 0; i < len; i++) {
  4231. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4232. }
  4233. return out;
  4234. }
  4235. function interpolate2DArray(out, p0, p1, percent) {
  4236. var len = p0.length;
  4237. var len2 = len && p0[0].length;
  4238. for (var i = 0; i < len; i++) {
  4239. if (!out[i]) {
  4240. out[i] = [];
  4241. }
  4242. for (var j = 0; j < len2; j++) {
  4243. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4244. }
  4245. }
  4246. return out;
  4247. }
  4248. function add1DArray(out, p0, p1, sign) {
  4249. var len = p0.length;
  4250. for (var i = 0; i < len; i++) {
  4251. out[i] = p0[i] + p1[i] * sign;
  4252. }
  4253. return out;
  4254. }
  4255. function add2DArray(out, p0, p1, sign) {
  4256. var len = p0.length;
  4257. var len2 = len && p0[0].length;
  4258. for (var i = 0; i < len; i++) {
  4259. if (!out[i]) {
  4260. out[i] = [];
  4261. }
  4262. for (var j = 0; j < len2; j++) {
  4263. out[i][j] = p0[i][j] + p1[i][j] * sign;
  4264. }
  4265. }
  4266. return out;
  4267. }
  4268. function fillColorStops(val0, val1) {
  4269. var len0 = val0.length;
  4270. var len1 = val1.length;
  4271. var shorterArr = len0 > len1 ? val1 : val0;
  4272. var shorterLen = Math.min(len0, len1);
  4273. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4274. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4275. shorterArr.push({
  4276. offset: last.offset,
  4277. color: last.color.slice()
  4278. });
  4279. }
  4280. }
  4281. function fillArray(val0, val1, arrDim) {
  4282. var arr0 = val0;
  4283. var arr1 = val1;
  4284. if (!arr0.push || !arr1.push) {
  4285. return;
  4286. }
  4287. var arr0Len = arr0.length;
  4288. var arr1Len = arr1.length;
  4289. if (arr0Len !== arr1Len) {
  4290. var isPreviousLarger = arr0Len > arr1Len;
  4291. if (isPreviousLarger) {
  4292. arr0.length = arr1Len;
  4293. }
  4294. else {
  4295. for (var i = arr0Len; i < arr1Len; i++) {
  4296. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4297. }
  4298. }
  4299. }
  4300. var len2 = arr0[0] && arr0[0].length;
  4301. for (var i = 0; i < arr0.length; i++) {
  4302. if (arrDim === 1) {
  4303. if (isNaN(arr0[i])) {
  4304. arr0[i] = arr1[i];
  4305. }
  4306. }
  4307. else {
  4308. for (var j = 0; j < len2; j++) {
  4309. if (isNaN(arr0[i][j])) {
  4310. arr0[i][j] = arr1[i][j];
  4311. }
  4312. }
  4313. }
  4314. }
  4315. }
  4316. function cloneValue(value) {
  4317. if (isArrayLike(value)) {
  4318. var len = value.length;
  4319. if (isArrayLike(value[0])) {
  4320. var ret = [];
  4321. for (var i = 0; i < len; i++) {
  4322. ret.push(arraySlice.call(value[i]));
  4323. }
  4324. return ret;
  4325. }
  4326. return arraySlice.call(value);
  4327. }
  4328. return value;
  4329. }
  4330. function rgba2String(rgba) {
  4331. rgba[0] = Math.floor(rgba[0]) || 0;
  4332. rgba[1] = Math.floor(rgba[1]) || 0;
  4333. rgba[2] = Math.floor(rgba[2]) || 0;
  4334. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4335. return 'rgba(' + rgba.join(',') + ')';
  4336. }
  4337. function guessArrayDim(value) {
  4338. return isArrayLike(value && value[0]) ? 2 : 1;
  4339. }
  4340. var VALUE_TYPE_NUMBER = 0;
  4341. var VALUE_TYPE_1D_ARRAY = 1;
  4342. var VALUE_TYPE_2D_ARRAY = 2;
  4343. var VALUE_TYPE_COLOR = 3;
  4344. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4345. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4346. var VALUE_TYPE_UNKOWN = 6;
  4347. function isGradientValueType(valType) {
  4348. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4349. }
  4350. function isArrayValueType(valType) {
  4351. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4352. }
  4353. var tmpRgba = [0, 0, 0, 0];
  4354. var Track = (function () {
  4355. function Track(propName) {
  4356. this.keyframes = [];
  4357. this.discrete = false;
  4358. this._invalid = false;
  4359. this._needsSort = false;
  4360. this._lastFr = 0;
  4361. this._lastFrP = 0;
  4362. this.propName = propName;
  4363. }
  4364. Track.prototype.isFinished = function () {
  4365. return this._finished;
  4366. };
  4367. Track.prototype.setFinished = function () {
  4368. this._finished = true;
  4369. if (this._additiveTrack) {
  4370. this._additiveTrack.setFinished();
  4371. }
  4372. };
  4373. Track.prototype.needsAnimate = function () {
  4374. return this.keyframes.length >= 1;
  4375. };
  4376. Track.prototype.getAdditiveTrack = function () {
  4377. return this._additiveTrack;
  4378. };
  4379. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4380. this._needsSort = true;
  4381. var keyframes = this.keyframes;
  4382. var len = keyframes.length;
  4383. var discrete = false;
  4384. var valType = VALUE_TYPE_UNKOWN;
  4385. var value = rawValue;
  4386. if (isArrayLike(rawValue)) {
  4387. var arrayDim = guessArrayDim(rawValue);
  4388. valType = arrayDim;
  4389. if (arrayDim === 1 && !isNumber(rawValue[0])
  4390. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4391. discrete = true;
  4392. }
  4393. }
  4394. else {
  4395. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4396. valType = VALUE_TYPE_NUMBER;
  4397. }
  4398. else if (isString(rawValue)) {
  4399. if (!isNaN(+rawValue)) {
  4400. valType = VALUE_TYPE_NUMBER;
  4401. }
  4402. else {
  4403. var colorArray = parse(rawValue);
  4404. if (colorArray) {
  4405. value = colorArray;
  4406. valType = VALUE_TYPE_COLOR;
  4407. }
  4408. }
  4409. }
  4410. else if (isGradientObject(rawValue)) {
  4411. var parsedGradient = extend({}, value);
  4412. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4413. offset: colorStop.offset,
  4414. color: parse(colorStop.color)
  4415. }); });
  4416. if (isLinearGradient(rawValue)) {
  4417. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4418. }
  4419. else if (isRadialGradient(rawValue)) {
  4420. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4421. }
  4422. value = parsedGradient;
  4423. }
  4424. }
  4425. if (len === 0) {
  4426. this.valType = valType;
  4427. }
  4428. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4429. discrete = true;
  4430. }
  4431. this.discrete = this.discrete || discrete;
  4432. var kf = {
  4433. time: time,
  4434. value: value,
  4435. rawValue: rawValue,
  4436. percent: 0
  4437. };
  4438. if (easing) {
  4439. kf.easing = easing;
  4440. kf.easingFunc = isFunction(easing)
  4441. ? easing
  4442. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4443. }
  4444. keyframes.push(kf);
  4445. return kf;
  4446. };
  4447. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4448. var kfs = this.keyframes;
  4449. if (this._needsSort) {
  4450. kfs.sort(function (a, b) {
  4451. return a.time - b.time;
  4452. });
  4453. }
  4454. var valType = this.valType;
  4455. var kfsLen = kfs.length;
  4456. var lastKf = kfs[kfsLen - 1];
  4457. var isDiscrete = this.discrete;
  4458. var isArr = isArrayValueType(valType);
  4459. var isGradient = isGradientValueType(valType);
  4460. for (var i = 0; i < kfsLen; i++) {
  4461. var kf = kfs[i];
  4462. var value = kf.value;
  4463. var lastValue = lastKf.value;
  4464. kf.percent = kf.time / maxTime;
  4465. if (!isDiscrete) {
  4466. if (isArr && i !== kfsLen - 1) {
  4467. fillArray(value, lastValue, valType);
  4468. }
  4469. else if (isGradient) {
  4470. fillColorStops(value.colorStops, lastValue.colorStops);
  4471. }
  4472. }
  4473. }
  4474. if (!isDiscrete
  4475. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4476. && additiveTrack
  4477. && this.needsAnimate()
  4478. && additiveTrack.needsAnimate()
  4479. && valType === additiveTrack.valType
  4480. && !additiveTrack._finished) {
  4481. this._additiveTrack = additiveTrack;
  4482. var startValue = kfs[0].value;
  4483. for (var i = 0; i < kfsLen; i++) {
  4484. if (valType === VALUE_TYPE_NUMBER) {
  4485. kfs[i].additiveValue = kfs[i].value - startValue;
  4486. }
  4487. else if (valType === VALUE_TYPE_COLOR) {
  4488. kfs[i].additiveValue =
  4489. add1DArray([], kfs[i].value, startValue, -1);
  4490. }
  4491. else if (isArrayValueType(valType)) {
  4492. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4493. ? add1DArray([], kfs[i].value, startValue, -1)
  4494. : add2DArray([], kfs[i].value, startValue, -1);
  4495. }
  4496. }
  4497. }
  4498. };
  4499. Track.prototype.step = function (target, percent) {
  4500. if (this._finished) {
  4501. return;
  4502. }
  4503. if (this._additiveTrack && this._additiveTrack._finished) {
  4504. this._additiveTrack = null;
  4505. }
  4506. var isAdditive = this._additiveTrack != null;
  4507. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4508. var valType = this.valType;
  4509. var keyframes = this.keyframes;
  4510. var kfsNum = keyframes.length;
  4511. var propName = this.propName;
  4512. var isValueColor = valType === VALUE_TYPE_COLOR;
  4513. var frameIdx;
  4514. var lastFrame = this._lastFr;
  4515. var mathMin = Math.min;
  4516. var frame;
  4517. var nextFrame;
  4518. if (kfsNum === 1) {
  4519. frame = nextFrame = keyframes[0];
  4520. }
  4521. else {
  4522. if (percent < 0) {
  4523. frameIdx = 0;
  4524. }
  4525. else if (percent < this._lastFrP) {
  4526. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4527. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4528. if (keyframes[frameIdx].percent <= percent) {
  4529. break;
  4530. }
  4531. }
  4532. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4533. }
  4534. else {
  4535. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4536. if (keyframes[frameIdx].percent > percent) {
  4537. break;
  4538. }
  4539. }
  4540. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4541. }
  4542. nextFrame = keyframes[frameIdx + 1];
  4543. frame = keyframes[frameIdx];
  4544. }
  4545. if (!(frame && nextFrame)) {
  4546. return;
  4547. }
  4548. this._lastFr = frameIdx;
  4549. this._lastFrP = percent;
  4550. var interval = (nextFrame.percent - frame.percent);
  4551. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4552. if (nextFrame.easingFunc) {
  4553. w = nextFrame.easingFunc(w);
  4554. }
  4555. var targetArr = isAdditive ? this._additiveValue
  4556. : (isValueColor ? tmpRgba : target[propName]);
  4557. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4558. targetArr = this._additiveValue = [];
  4559. }
  4560. if (this.discrete) {
  4561. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4562. }
  4563. else if (isArrayValueType(valType)) {
  4564. valType === VALUE_TYPE_1D_ARRAY
  4565. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4566. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4567. }
  4568. else if (isGradientValueType(valType)) {
  4569. var val = frame[valueKey];
  4570. var nextVal_1 = nextFrame[valueKey];
  4571. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4572. target[propName] = {
  4573. type: isLinearGradient_1 ? 'linear' : 'radial',
  4574. x: interpolateNumber(val.x, nextVal_1.x, w),
  4575. y: interpolateNumber(val.y, nextVal_1.y, w),
  4576. colorStops: map(val.colorStops, function (colorStop, idx) {
  4577. var nextColorStop = nextVal_1.colorStops[idx];
  4578. return {
  4579. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4580. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4581. };
  4582. }),
  4583. global: nextVal_1.global
  4584. };
  4585. if (isLinearGradient_1) {
  4586. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4587. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4588. }
  4589. else {
  4590. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4591. }
  4592. }
  4593. else if (isValueColor) {
  4594. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4595. if (!isAdditive) {
  4596. target[propName] = rgba2String(targetArr);
  4597. }
  4598. }
  4599. else {
  4600. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4601. if (isAdditive) {
  4602. this._additiveValue = value;
  4603. }
  4604. else {
  4605. target[propName] = value;
  4606. }
  4607. }
  4608. if (isAdditive) {
  4609. this._addToTarget(target);
  4610. }
  4611. };
  4612. Track.prototype._addToTarget = function (target) {
  4613. var valType = this.valType;
  4614. var propName = this.propName;
  4615. var additiveValue = this._additiveValue;
  4616. if (valType === VALUE_TYPE_NUMBER) {
  4617. target[propName] = target[propName] + additiveValue;
  4618. }
  4619. else if (valType === VALUE_TYPE_COLOR) {
  4620. parse(target[propName], tmpRgba);
  4621. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4622. target[propName] = rgba2String(tmpRgba);
  4623. }
  4624. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4625. add1DArray(target[propName], target[propName], additiveValue, 1);
  4626. }
  4627. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4628. add2DArray(target[propName], target[propName], additiveValue, 1);
  4629. }
  4630. };
  4631. return Track;
  4632. }());
  4633. var Animator = (function () {
  4634. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4635. this._tracks = {};
  4636. this._trackKeys = [];
  4637. this._maxTime = 0;
  4638. this._started = 0;
  4639. this._clip = null;
  4640. this._target = target;
  4641. this._loop = loop;
  4642. if (loop && additiveTo) {
  4643. logError('Can\' use additive animation on looped animation.');
  4644. return;
  4645. }
  4646. this._additiveAnimators = additiveTo;
  4647. this._allowDiscrete = allowDiscreteAnimation;
  4648. }
  4649. Animator.prototype.getMaxTime = function () {
  4650. return this._maxTime;
  4651. };
  4652. Animator.prototype.getDelay = function () {
  4653. return this._delay;
  4654. };
  4655. Animator.prototype.getLoop = function () {
  4656. return this._loop;
  4657. };
  4658. Animator.prototype.getTarget = function () {
  4659. return this._target;
  4660. };
  4661. Animator.prototype.changeTarget = function (target) {
  4662. this._target = target;
  4663. };
  4664. Animator.prototype.when = function (time, props, easing) {
  4665. return this.whenWithKeys(time, props, keys(props), easing);
  4666. };
  4667. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4668. var tracks = this._tracks;
  4669. for (var i = 0; i < propNames.length; i++) {
  4670. var propName = propNames[i];
  4671. var track = tracks[propName];
  4672. if (!track) {
  4673. track = tracks[propName] = new Track(propName);
  4674. var initialValue = void 0;
  4675. var additiveTrack = this._getAdditiveTrack(propName);
  4676. if (additiveTrack) {
  4677. var addtiveTrackKfs = additiveTrack.keyframes;
  4678. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4679. initialValue = lastFinalKf && lastFinalKf.value;
  4680. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4681. initialValue = rgba2String(initialValue);
  4682. }
  4683. }
  4684. else {
  4685. initialValue = this._target[propName];
  4686. }
  4687. if (initialValue == null) {
  4688. continue;
  4689. }
  4690. if (time > 0) {
  4691. track.addKeyframe(0, cloneValue(initialValue), easing);
  4692. }
  4693. this._trackKeys.push(propName);
  4694. }
  4695. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4696. }
  4697. this._maxTime = Math.max(this._maxTime, time);
  4698. return this;
  4699. };
  4700. Animator.prototype.pause = function () {
  4701. this._clip.pause();
  4702. this._paused = true;
  4703. };
  4704. Animator.prototype.resume = function () {
  4705. this._clip.resume();
  4706. this._paused = false;
  4707. };
  4708. Animator.prototype.isPaused = function () {
  4709. return !!this._paused;
  4710. };
  4711. Animator.prototype.duration = function (duration) {
  4712. this._maxTime = duration;
  4713. this._force = true;
  4714. return this;
  4715. };
  4716. Animator.prototype._doneCallback = function () {
  4717. this._setTracksFinished();
  4718. this._clip = null;
  4719. var doneList = this._doneCbs;
  4720. if (doneList) {
  4721. var len = doneList.length;
  4722. for (var i = 0; i < len; i++) {
  4723. doneList[i].call(this);
  4724. }
  4725. }
  4726. };
  4727. Animator.prototype._abortedCallback = function () {
  4728. this._setTracksFinished();
  4729. var animation = this.animation;
  4730. var abortedList = this._abortedCbs;
  4731. if (animation) {
  4732. animation.removeClip(this._clip);
  4733. }
  4734. this._clip = null;
  4735. if (abortedList) {
  4736. for (var i = 0; i < abortedList.length; i++) {
  4737. abortedList[i].call(this);
  4738. }
  4739. }
  4740. };
  4741. Animator.prototype._setTracksFinished = function () {
  4742. var tracks = this._tracks;
  4743. var tracksKeys = this._trackKeys;
  4744. for (var i = 0; i < tracksKeys.length; i++) {
  4745. tracks[tracksKeys[i]].setFinished();
  4746. }
  4747. };
  4748. Animator.prototype._getAdditiveTrack = function (trackName) {
  4749. var additiveTrack;
  4750. var additiveAnimators = this._additiveAnimators;
  4751. if (additiveAnimators) {
  4752. for (var i = 0; i < additiveAnimators.length; i++) {
  4753. var track = additiveAnimators[i].getTrack(trackName);
  4754. if (track) {
  4755. additiveTrack = track;
  4756. }
  4757. }
  4758. }
  4759. return additiveTrack;
  4760. };
  4761. Animator.prototype.start = function (easing) {
  4762. if (this._started > 0) {
  4763. return;
  4764. }
  4765. this._started = 1;
  4766. var self = this;
  4767. var tracks = [];
  4768. var maxTime = this._maxTime || 0;
  4769. for (var i = 0; i < this._trackKeys.length; i++) {
  4770. var propName = this._trackKeys[i];
  4771. var track = this._tracks[propName];
  4772. var additiveTrack = this._getAdditiveTrack(propName);
  4773. var kfs = track.keyframes;
  4774. var kfsNum = kfs.length;
  4775. track.prepare(maxTime, additiveTrack);
  4776. if (track.needsAnimate()) {
  4777. if (!this._allowDiscrete && track.discrete) {
  4778. var lastKf = kfs[kfsNum - 1];
  4779. if (lastKf) {
  4780. self._target[track.propName] = lastKf.rawValue;
  4781. }
  4782. track.setFinished();
  4783. }
  4784. else {
  4785. tracks.push(track);
  4786. }
  4787. }
  4788. }
  4789. if (tracks.length || this._force) {
  4790. var clip = new Clip({
  4791. life: maxTime,
  4792. loop: this._loop,
  4793. delay: this._delay || 0,
  4794. onframe: function (percent) {
  4795. self._started = 2;
  4796. var additiveAnimators = self._additiveAnimators;
  4797. if (additiveAnimators) {
  4798. var stillHasAdditiveAnimator = false;
  4799. for (var i = 0; i < additiveAnimators.length; i++) {
  4800. if (additiveAnimators[i]._clip) {
  4801. stillHasAdditiveAnimator = true;
  4802. break;
  4803. }
  4804. }
  4805. if (!stillHasAdditiveAnimator) {
  4806. self._additiveAnimators = null;
  4807. }
  4808. }
  4809. for (var i = 0; i < tracks.length; i++) {
  4810. tracks[i].step(self._target, percent);
  4811. }
  4812. var onframeList = self._onframeCbs;
  4813. if (onframeList) {
  4814. for (var i = 0; i < onframeList.length; i++) {
  4815. onframeList[i](self._target, percent);
  4816. }
  4817. }
  4818. },
  4819. ondestroy: function () {
  4820. self._doneCallback();
  4821. }
  4822. });
  4823. this._clip = clip;
  4824. if (this.animation) {
  4825. this.animation.addClip(clip);
  4826. }
  4827. if (easing) {
  4828. clip.setEasing(easing);
  4829. }
  4830. }
  4831. else {
  4832. this._doneCallback();
  4833. }
  4834. return this;
  4835. };
  4836. Animator.prototype.stop = function (forwardToLast) {
  4837. if (!this._clip) {
  4838. return;
  4839. }
  4840. var clip = this._clip;
  4841. if (forwardToLast) {
  4842. clip.onframe(1);
  4843. }
  4844. this._abortedCallback();
  4845. };
  4846. Animator.prototype.delay = function (time) {
  4847. this._delay = time;
  4848. return this;
  4849. };
  4850. Animator.prototype.during = function (cb) {
  4851. if (cb) {
  4852. if (!this._onframeCbs) {
  4853. this._onframeCbs = [];
  4854. }
  4855. this._onframeCbs.push(cb);
  4856. }
  4857. return this;
  4858. };
  4859. Animator.prototype.done = function (cb) {
  4860. if (cb) {
  4861. if (!this._doneCbs) {
  4862. this._doneCbs = [];
  4863. }
  4864. this._doneCbs.push(cb);
  4865. }
  4866. return this;
  4867. };
  4868. Animator.prototype.aborted = function (cb) {
  4869. if (cb) {
  4870. if (!this._abortedCbs) {
  4871. this._abortedCbs = [];
  4872. }
  4873. this._abortedCbs.push(cb);
  4874. }
  4875. return this;
  4876. };
  4877. Animator.prototype.getClip = function () {
  4878. return this._clip;
  4879. };
  4880. Animator.prototype.getTrack = function (propName) {
  4881. return this._tracks[propName];
  4882. };
  4883. Animator.prototype.getTracks = function () {
  4884. var _this = this;
  4885. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4886. };
  4887. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4888. if (!propNames.length || !this._clip) {
  4889. return true;
  4890. }
  4891. var tracks = this._tracks;
  4892. var tracksKeys = this._trackKeys;
  4893. for (var i = 0; i < propNames.length; i++) {
  4894. var track = tracks[propNames[i]];
  4895. if (track && !track.isFinished()) {
  4896. if (forwardToLast) {
  4897. track.step(this._target, 1);
  4898. }
  4899. else if (this._started === 1) {
  4900. track.step(this._target, 0);
  4901. }
  4902. track.setFinished();
  4903. }
  4904. }
  4905. var allAborted = true;
  4906. for (var i = 0; i < tracksKeys.length; i++) {
  4907. if (!tracks[tracksKeys[i]].isFinished()) {
  4908. allAborted = false;
  4909. break;
  4910. }
  4911. }
  4912. if (allAborted) {
  4913. this._abortedCallback();
  4914. }
  4915. return allAborted;
  4916. };
  4917. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4918. if (!target) {
  4919. return;
  4920. }
  4921. trackKeys = trackKeys || this._trackKeys;
  4922. for (var i = 0; i < trackKeys.length; i++) {
  4923. var propName = trackKeys[i];
  4924. var track = this._tracks[propName];
  4925. if (!track || track.isFinished()) {
  4926. continue;
  4927. }
  4928. var kfs = track.keyframes;
  4929. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4930. if (kf) {
  4931. target[propName] = cloneValue(kf.rawValue);
  4932. }
  4933. }
  4934. };
  4935. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4936. trackKeys = trackKeys || keys(finalProps);
  4937. for (var i = 0; i < trackKeys.length; i++) {
  4938. var propName = trackKeys[i];
  4939. var track = this._tracks[propName];
  4940. if (!track) {
  4941. continue;
  4942. }
  4943. var kfs = track.keyframes;
  4944. if (kfs.length > 1) {
  4945. var lastKf = kfs.pop();
  4946. track.addKeyframe(lastKf.time, finalProps[propName]);
  4947. track.prepare(this._maxTime, track.getAdditiveTrack());
  4948. }
  4949. }
  4950. };
  4951. return Animator;
  4952. }());
  4953. function getTime() {
  4954. return new Date().getTime();
  4955. }
  4956. var Animation = (function (_super) {
  4957. __extends(Animation, _super);
  4958. function Animation(opts) {
  4959. var _this = _super.call(this) || this;
  4960. _this._running = false;
  4961. _this._time = 0;
  4962. _this._pausedTime = 0;
  4963. _this._pauseStart = 0;
  4964. _this._paused = false;
  4965. opts = opts || {};
  4966. _this.stage = opts.stage || {};
  4967. return _this;
  4968. }
  4969. Animation.prototype.addClip = function (clip) {
  4970. if (clip.animation) {
  4971. this.removeClip(clip);
  4972. }
  4973. if (!this._head) {
  4974. this._head = this._tail = clip;
  4975. }
  4976. else {
  4977. this._tail.next = clip;
  4978. clip.prev = this._tail;
  4979. clip.next = null;
  4980. this._tail = clip;
  4981. }
  4982. clip.animation = this;
  4983. };
  4984. Animation.prototype.addAnimator = function (animator) {
  4985. animator.animation = this;
  4986. var clip = animator.getClip();
  4987. if (clip) {
  4988. this.addClip(clip);
  4989. }
  4990. };
  4991. Animation.prototype.removeClip = function (clip) {
  4992. if (!clip.animation) {
  4993. return;
  4994. }
  4995. var prev = clip.prev;
  4996. var next = clip.next;
  4997. if (prev) {
  4998. prev.next = next;
  4999. }
  5000. else {
  5001. this._head = next;
  5002. }
  5003. if (next) {
  5004. next.prev = prev;
  5005. }
  5006. else {
  5007. this._tail = prev;
  5008. }
  5009. clip.next = clip.prev = clip.animation = null;
  5010. };
  5011. Animation.prototype.removeAnimator = function (animator) {
  5012. var clip = animator.getClip();
  5013. if (clip) {
  5014. this.removeClip(clip);
  5015. }
  5016. animator.animation = null;
  5017. };
  5018. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  5019. var time = getTime() - this._pausedTime;
  5020. var delta = time - this._time;
  5021. var clip = this._head;
  5022. while (clip) {
  5023. var nextClip = clip.next;
  5024. var finished = clip.step(time, delta);
  5025. if (finished) {
  5026. clip.ondestroy();
  5027. this.removeClip(clip);
  5028. clip = nextClip;
  5029. }
  5030. else {
  5031. clip = nextClip;
  5032. }
  5033. }
  5034. this._time = time;
  5035. if (!notTriggerFrameAndStageUpdate) {
  5036. this.trigger('frame', delta);
  5037. this.stage.update && this.stage.update();
  5038. }
  5039. };
  5040. Animation.prototype._startLoop = function () {
  5041. var self = this;
  5042. this._running = true;
  5043. function step() {
  5044. if (self._running) {
  5045. requestAnimationFrame$1(step);
  5046. !self._paused && self.update();
  5047. }
  5048. }
  5049. requestAnimationFrame$1(step);
  5050. };
  5051. Animation.prototype.start = function () {
  5052. if (this._running) {
  5053. return;
  5054. }
  5055. this._time = getTime();
  5056. this._pausedTime = 0;
  5057. this._startLoop();
  5058. };
  5059. Animation.prototype.stop = function () {
  5060. this._running = false;
  5061. };
  5062. Animation.prototype.pause = function () {
  5063. if (!this._paused) {
  5064. this._pauseStart = getTime();
  5065. this._paused = true;
  5066. }
  5067. };
  5068. Animation.prototype.resume = function () {
  5069. if (this._paused) {
  5070. this._pausedTime += getTime() - this._pauseStart;
  5071. this._paused = false;
  5072. }
  5073. };
  5074. Animation.prototype.clear = function () {
  5075. var clip = this._head;
  5076. while (clip) {
  5077. var nextClip = clip.next;
  5078. clip.prev = clip.next = clip.animation = null;
  5079. clip = nextClip;
  5080. }
  5081. this._head = this._tail = null;
  5082. };
  5083. Animation.prototype.isFinished = function () {
  5084. return this._head == null;
  5085. };
  5086. Animation.prototype.animate = function (target, options) {
  5087. options = options || {};
  5088. this.start();
  5089. var animator = new Animator(target, options.loop);
  5090. this.addAnimator(animator);
  5091. return animator;
  5092. };
  5093. return Animation;
  5094. }(Eventful));
  5095. var TOUCH_CLICK_DELAY = 300;
  5096. var globalEventSupported = env.domSupported;
  5097. var localNativeListenerNames = (function () {
  5098. var mouseHandlerNames = [
  5099. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5100. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5101. ];
  5102. var touchHandlerNames = [
  5103. 'touchstart', 'touchend', 'touchmove'
  5104. ];
  5105. var pointerEventNameMap = {
  5106. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5107. };
  5108. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5109. var nm = name.replace('mouse', 'pointer');
  5110. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5111. });
  5112. return {
  5113. mouse: mouseHandlerNames,
  5114. touch: touchHandlerNames,
  5115. pointer: pointerHandlerNames
  5116. };
  5117. })();
  5118. var globalNativeListenerNames = {
  5119. mouse: ['mousemove', 'mouseup'],
  5120. pointer: ['pointermove', 'pointerup']
  5121. };
  5122. var wheelEventSupported = false;
  5123. function isPointerFromTouch(event) {
  5124. var pointerType = event.pointerType;
  5125. return pointerType === 'pen' || pointerType === 'touch';
  5126. }
  5127. function setTouchTimer(scope) {
  5128. scope.touching = true;
  5129. if (scope.touchTimer != null) {
  5130. clearTimeout(scope.touchTimer);
  5131. scope.touchTimer = null;
  5132. }
  5133. scope.touchTimer = setTimeout(function () {
  5134. scope.touching = false;
  5135. scope.touchTimer = null;
  5136. }, 700);
  5137. }
  5138. function markTouch(event) {
  5139. event && (event.zrByTouch = true);
  5140. }
  5141. function normalizeGlobalEvent(instance, event) {
  5142. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5143. }
  5144. function isLocalEl(instance, el) {
  5145. var elTmp = el;
  5146. var isLocal = false;
  5147. while (elTmp && elTmp.nodeType !== 9
  5148. && !(isLocal = elTmp.domBelongToZr
  5149. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5150. elTmp = elTmp.parentNode;
  5151. }
  5152. return isLocal;
  5153. }
  5154. var FakeGlobalEvent = (function () {
  5155. function FakeGlobalEvent(instance, event) {
  5156. this.stopPropagation = noop;
  5157. this.stopImmediatePropagation = noop;
  5158. this.preventDefault = noop;
  5159. this.type = event.type;
  5160. this.target = this.currentTarget = instance.dom;
  5161. this.pointerType = event.pointerType;
  5162. this.clientX = event.clientX;
  5163. this.clientY = event.clientY;
  5164. }
  5165. return FakeGlobalEvent;
  5166. }());
  5167. var localDOMHandlers = {
  5168. mousedown: function (event) {
  5169. event = normalizeEvent(this.dom, event);
  5170. this.__mayPointerCapture = [event.zrX, event.zrY];
  5171. this.trigger('mousedown', event);
  5172. },
  5173. mousemove: function (event) {
  5174. event = normalizeEvent(this.dom, event);
  5175. var downPoint = this.__mayPointerCapture;
  5176. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5177. this.__togglePointerCapture(true);
  5178. }
  5179. this.trigger('mousemove', event);
  5180. },
  5181. mouseup: function (event) {
  5182. event = normalizeEvent(this.dom, event);
  5183. this.__togglePointerCapture(false);
  5184. this.trigger('mouseup', event);
  5185. },
  5186. mouseout: function (event) {
  5187. event = normalizeEvent(this.dom, event);
  5188. var element = event.toElement || event.relatedTarget;
  5189. if (!isLocalEl(this, element)) {
  5190. if (this.__pointerCapturing) {
  5191. event.zrEventControl = 'no_globalout';
  5192. }
  5193. this.trigger('mouseout', event);
  5194. }
  5195. },
  5196. wheel: function (event) {
  5197. wheelEventSupported = true;
  5198. event = normalizeEvent(this.dom, event);
  5199. this.trigger('mousewheel', event);
  5200. },
  5201. mousewheel: function (event) {
  5202. if (wheelEventSupported) {
  5203. return;
  5204. }
  5205. event = normalizeEvent(this.dom, event);
  5206. this.trigger('mousewheel', event);
  5207. },
  5208. touchstart: function (event) {
  5209. event = normalizeEvent(this.dom, event);
  5210. markTouch(event);
  5211. this.__lastTouchMoment = new Date();
  5212. this.handler.processGesture(event, 'start');
  5213. localDOMHandlers.mousemove.call(this, event);
  5214. localDOMHandlers.mousedown.call(this, event);
  5215. },
  5216. touchmove: function (event) {
  5217. event = normalizeEvent(this.dom, event);
  5218. markTouch(event);
  5219. this.handler.processGesture(event, 'change');
  5220. localDOMHandlers.mousemove.call(this, event);
  5221. },
  5222. touchend: function (event) {
  5223. event = normalizeEvent(this.dom, event);
  5224. markTouch(event);
  5225. this.handler.processGesture(event, 'end');
  5226. localDOMHandlers.mouseup.call(this, event);
  5227. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5228. localDOMHandlers.click.call(this, event);
  5229. }
  5230. },
  5231. pointerdown: function (event) {
  5232. localDOMHandlers.mousedown.call(this, event);
  5233. },
  5234. pointermove: function (event) {
  5235. if (!isPointerFromTouch(event)) {
  5236. localDOMHandlers.mousemove.call(this, event);
  5237. }
  5238. },
  5239. pointerup: function (event) {
  5240. localDOMHandlers.mouseup.call(this, event);
  5241. },
  5242. pointerout: function (event) {
  5243. if (!isPointerFromTouch(event)) {
  5244. localDOMHandlers.mouseout.call(this, event);
  5245. }
  5246. }
  5247. };
  5248. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5249. localDOMHandlers[name] = function (event) {
  5250. event = normalizeEvent(this.dom, event);
  5251. this.trigger(name, event);
  5252. };
  5253. });
  5254. var globalDOMHandlers = {
  5255. pointermove: function (event) {
  5256. if (!isPointerFromTouch(event)) {
  5257. globalDOMHandlers.mousemove.call(this, event);
  5258. }
  5259. },
  5260. pointerup: function (event) {
  5261. globalDOMHandlers.mouseup.call(this, event);
  5262. },
  5263. mousemove: function (event) {
  5264. this.trigger('mousemove', event);
  5265. },
  5266. mouseup: function (event) {
  5267. var pointerCaptureReleasing = this.__pointerCapturing;
  5268. this.__togglePointerCapture(false);
  5269. this.trigger('mouseup', event);
  5270. if (pointerCaptureReleasing) {
  5271. event.zrEventControl = 'only_globalout';
  5272. this.trigger('mouseout', event);
  5273. }
  5274. }
  5275. };
  5276. function mountLocalDOMEventListeners(instance, scope) {
  5277. var domHandlers = scope.domHandlers;
  5278. if (env.pointerEventsSupported) {
  5279. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5280. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5281. domHandlers[nativeEventName].call(instance, event);
  5282. });
  5283. });
  5284. }
  5285. else {
  5286. if (env.touchEventsSupported) {
  5287. each(localNativeListenerNames.touch, function (nativeEventName) {
  5288. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5289. domHandlers[nativeEventName].call(instance, event);
  5290. setTouchTimer(scope);
  5291. });
  5292. });
  5293. }
  5294. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5295. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5296. event = getNativeEvent(event);
  5297. if (!scope.touching) {
  5298. domHandlers[nativeEventName].call(instance, event);
  5299. }
  5300. });
  5301. });
  5302. }
  5303. }
  5304. function mountGlobalDOMEventListeners(instance, scope) {
  5305. if (env.pointerEventsSupported) {
  5306. each(globalNativeListenerNames.pointer, mount);
  5307. }
  5308. else if (!env.touchEventsSupported) {
  5309. each(globalNativeListenerNames.mouse, mount);
  5310. }
  5311. function mount(nativeEventName) {
  5312. function nativeEventListener(event) {
  5313. event = getNativeEvent(event);
  5314. if (!isLocalEl(instance, event.target)) {
  5315. event = normalizeGlobalEvent(instance, event);
  5316. scope.domHandlers[nativeEventName].call(instance, event);
  5317. }
  5318. }
  5319. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5320. }
  5321. }
  5322. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5323. scope.mounted[nativeEventName] = listener;
  5324. scope.listenerOpts[nativeEventName] = opt;
  5325. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5326. }
  5327. function unmountDOMEventListeners(scope) {
  5328. var mounted = scope.mounted;
  5329. for (var nativeEventName in mounted) {
  5330. if (mounted.hasOwnProperty(nativeEventName)) {
  5331. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5332. }
  5333. }
  5334. scope.mounted = {};
  5335. }
  5336. var DOMHandlerScope = (function () {
  5337. function DOMHandlerScope(domTarget, domHandlers) {
  5338. this.mounted = {};
  5339. this.listenerOpts = {};
  5340. this.touching = false;
  5341. this.domTarget = domTarget;
  5342. this.domHandlers = domHandlers;
  5343. }
  5344. return DOMHandlerScope;
  5345. }());
  5346. var HandlerDomProxy = (function (_super) {
  5347. __extends(HandlerDomProxy, _super);
  5348. function HandlerDomProxy(dom, painterRoot) {
  5349. var _this = _super.call(this) || this;
  5350. _this.__pointerCapturing = false;
  5351. _this.dom = dom;
  5352. _this.painterRoot = painterRoot;
  5353. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5354. if (globalEventSupported) {
  5355. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5356. }
  5357. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5358. return _this;
  5359. }
  5360. HandlerDomProxy.prototype.dispose = function () {
  5361. unmountDOMEventListeners(this._localHandlerScope);
  5362. if (globalEventSupported) {
  5363. unmountDOMEventListeners(this._globalHandlerScope);
  5364. }
  5365. };
  5366. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5367. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5368. };
  5369. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5370. this.__mayPointerCapture = null;
  5371. if (globalEventSupported
  5372. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5373. this.__pointerCapturing = isPointerCapturing;
  5374. var globalHandlerScope = this._globalHandlerScope;
  5375. isPointerCapturing
  5376. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5377. : unmountDOMEventListeners(globalHandlerScope);
  5378. }
  5379. };
  5380. return HandlerDomProxy;
  5381. }(Eventful));
  5382. var dpr = 1;
  5383. if (env.hasGlobalWindow) {
  5384. dpr = Math.max(window.devicePixelRatio
  5385. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5386. || 1, 1);
  5387. }
  5388. var devicePixelRatio = dpr;
  5389. var DARK_MODE_THRESHOLD = 0.4;
  5390. var DARK_LABEL_COLOR = '#333';
  5391. var LIGHT_LABEL_COLOR = '#ccc';
  5392. var LIGHTER_LABEL_COLOR = '#eee';
  5393. var mIdentity = identity;
  5394. var EPSILON$2 = 5e-5;
  5395. function isNotAroundZero$1(val) {
  5396. return val > EPSILON$2 || val < -EPSILON$2;
  5397. }
  5398. var scaleTmp = [];
  5399. var tmpTransform = [];
  5400. var originTransform = create$1();
  5401. var abs = Math.abs;
  5402. var Transformable = (function () {
  5403. function Transformable() {
  5404. }
  5405. Transformable.prototype.getLocalTransform = function (m) {
  5406. return Transformable.getLocalTransform(this, m);
  5407. };
  5408. Transformable.prototype.setPosition = function (arr) {
  5409. this.x = arr[0];
  5410. this.y = arr[1];
  5411. };
  5412. Transformable.prototype.setScale = function (arr) {
  5413. this.scaleX = arr[0];
  5414. this.scaleY = arr[1];
  5415. };
  5416. Transformable.prototype.setSkew = function (arr) {
  5417. this.skewX = arr[0];
  5418. this.skewY = arr[1];
  5419. };
  5420. Transformable.prototype.setOrigin = function (arr) {
  5421. this.originX = arr[0];
  5422. this.originY = arr[1];
  5423. };
  5424. Transformable.prototype.needLocalTransform = function () {
  5425. return isNotAroundZero$1(this.rotation)
  5426. || isNotAroundZero$1(this.x)
  5427. || isNotAroundZero$1(this.y)
  5428. || isNotAroundZero$1(this.scaleX - 1)
  5429. || isNotAroundZero$1(this.scaleY - 1)
  5430. || isNotAroundZero$1(this.skewX)
  5431. || isNotAroundZero$1(this.skewY);
  5432. };
  5433. Transformable.prototype.updateTransform = function () {
  5434. var parentTransform = this.parent && this.parent.transform;
  5435. var needLocalTransform = this.needLocalTransform();
  5436. var m = this.transform;
  5437. if (!(needLocalTransform || parentTransform)) {
  5438. if (m) {
  5439. mIdentity(m);
  5440. this.invTransform = null;
  5441. }
  5442. return;
  5443. }
  5444. m = m || create$1();
  5445. if (needLocalTransform) {
  5446. this.getLocalTransform(m);
  5447. }
  5448. else {
  5449. mIdentity(m);
  5450. }
  5451. if (parentTransform) {
  5452. if (needLocalTransform) {
  5453. mul$1(m, parentTransform, m);
  5454. }
  5455. else {
  5456. copy$1(m, parentTransform);
  5457. }
  5458. }
  5459. this.transform = m;
  5460. this._resolveGlobalScaleRatio(m);
  5461. };
  5462. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5463. var globalScaleRatio = this.globalScaleRatio;
  5464. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5465. this.getGlobalScale(scaleTmp);
  5466. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5467. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5468. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5469. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5470. m[0] *= sx;
  5471. m[1] *= sx;
  5472. m[2] *= sy;
  5473. m[3] *= sy;
  5474. }
  5475. this.invTransform = this.invTransform || create$1();
  5476. invert(this.invTransform, m);
  5477. };
  5478. Transformable.prototype.getComputedTransform = function () {
  5479. var transformNode = this;
  5480. var ancestors = [];
  5481. while (transformNode) {
  5482. ancestors.push(transformNode);
  5483. transformNode = transformNode.parent;
  5484. }
  5485. while (transformNode = ancestors.pop()) {
  5486. transformNode.updateTransform();
  5487. }
  5488. return this.transform;
  5489. };
  5490. Transformable.prototype.setLocalTransform = function (m) {
  5491. if (!m) {
  5492. return;
  5493. }
  5494. var sx = m[0] * m[0] + m[1] * m[1];
  5495. var sy = m[2] * m[2] + m[3] * m[3];
  5496. var rotation = Math.atan2(m[1], m[0]);
  5497. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5498. sy = Math.sqrt(sy) * Math.cos(shearX);
  5499. sx = Math.sqrt(sx);
  5500. this.skewX = shearX;
  5501. this.skewY = 0;
  5502. this.rotation = -rotation;
  5503. this.x = +m[4];
  5504. this.y = +m[5];
  5505. this.scaleX = sx;
  5506. this.scaleY = sy;
  5507. this.originX = 0;
  5508. this.originY = 0;
  5509. };
  5510. Transformable.prototype.decomposeTransform = function () {
  5511. if (!this.transform) {
  5512. return;
  5513. }
  5514. var parent = this.parent;
  5515. var m = this.transform;
  5516. if (parent && parent.transform) {
  5517. parent.invTransform = parent.invTransform || create$1();
  5518. mul$1(tmpTransform, parent.invTransform, m);
  5519. m = tmpTransform;
  5520. }
  5521. var ox = this.originX;
  5522. var oy = this.originY;
  5523. if (ox || oy) {
  5524. originTransform[4] = ox;
  5525. originTransform[5] = oy;
  5526. mul$1(tmpTransform, m, originTransform);
  5527. tmpTransform[4] -= ox;
  5528. tmpTransform[5] -= oy;
  5529. m = tmpTransform;
  5530. }
  5531. this.setLocalTransform(m);
  5532. };
  5533. Transformable.prototype.getGlobalScale = function (out) {
  5534. var m = this.transform;
  5535. out = out || [];
  5536. if (!m) {
  5537. out[0] = 1;
  5538. out[1] = 1;
  5539. return out;
  5540. }
  5541. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5542. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5543. if (m[0] < 0) {
  5544. out[0] = -out[0];
  5545. }
  5546. if (m[3] < 0) {
  5547. out[1] = -out[1];
  5548. }
  5549. return out;
  5550. };
  5551. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5552. var v2 = [x, y];
  5553. var invTransform = this.invTransform;
  5554. if (invTransform) {
  5555. applyTransform(v2, v2, invTransform);
  5556. }
  5557. return v2;
  5558. };
  5559. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5560. var v2 = [x, y];
  5561. var transform = this.transform;
  5562. if (transform) {
  5563. applyTransform(v2, v2, transform);
  5564. }
  5565. return v2;
  5566. };
  5567. Transformable.prototype.getLineScale = function () {
  5568. var m = this.transform;
  5569. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5570. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5571. : 1;
  5572. };
  5573. Transformable.prototype.copyTransform = function (source) {
  5574. copyTransform(this, source);
  5575. };
  5576. Transformable.getLocalTransform = function (target, m) {
  5577. m = m || [];
  5578. var ox = target.originX || 0;
  5579. var oy = target.originY || 0;
  5580. var sx = target.scaleX;
  5581. var sy = target.scaleY;
  5582. var ax = target.anchorX;
  5583. var ay = target.anchorY;
  5584. var rotation = target.rotation || 0;
  5585. var x = target.x;
  5586. var y = target.y;
  5587. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5588. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5589. if (ox || oy || ax || ay) {
  5590. var dx = ox + ax;
  5591. var dy = oy + ay;
  5592. m[4] = -dx * sx - skewX * dy * sy;
  5593. m[5] = -dy * sy - skewY * dx * sx;
  5594. }
  5595. else {
  5596. m[4] = m[5] = 0;
  5597. }
  5598. m[0] = sx;
  5599. m[3] = sy;
  5600. m[1] = skewY * sx;
  5601. m[2] = skewX * sy;
  5602. rotation && rotate(m, m, rotation);
  5603. m[4] += ox + x;
  5604. m[5] += oy + y;
  5605. return m;
  5606. };
  5607. Transformable.initDefaultProps = (function () {
  5608. var proto = Transformable.prototype;
  5609. proto.scaleX =
  5610. proto.scaleY =
  5611. proto.globalScaleRatio = 1;
  5612. proto.x =
  5613. proto.y =
  5614. proto.originX =
  5615. proto.originY =
  5616. proto.skewX =
  5617. proto.skewY =
  5618. proto.rotation =
  5619. proto.anchorX =
  5620. proto.anchorY = 0;
  5621. })();
  5622. return Transformable;
  5623. }());
  5624. var TRANSFORMABLE_PROPS = [
  5625. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5626. ];
  5627. function copyTransform(target, source) {
  5628. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5629. var propName = TRANSFORMABLE_PROPS[i];
  5630. target[propName] = source[propName];
  5631. }
  5632. }
  5633. var textWidthCache = {};
  5634. function getWidth(text, font) {
  5635. font = font || DEFAULT_FONT;
  5636. var cacheOfFont = textWidthCache[font];
  5637. if (!cacheOfFont) {
  5638. cacheOfFont = textWidthCache[font] = new LRU(500);
  5639. }
  5640. var width = cacheOfFont.get(text);
  5641. if (width == null) {
  5642. width = platformApi.measureText(text, font).width;
  5643. cacheOfFont.put(text, width);
  5644. }
  5645. return width;
  5646. }
  5647. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5648. var width = getWidth(text, font);
  5649. var height = getLineHeight(font);
  5650. var x = adjustTextX(0, width, textAlign);
  5651. var y = adjustTextY$1(0, height, textBaseline);
  5652. var rect = new BoundingRect(x, y, width, height);
  5653. return rect;
  5654. }
  5655. function getBoundingRect(text, font, textAlign, textBaseline) {
  5656. var textLines = ((text || '') + '').split('\n');
  5657. var len = textLines.length;
  5658. if (len === 1) {
  5659. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5660. }
  5661. else {
  5662. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5663. for (var i = 0; i < textLines.length; i++) {
  5664. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5665. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5666. }
  5667. return uniondRect;
  5668. }
  5669. }
  5670. function adjustTextX(x, width, textAlign) {
  5671. if (textAlign === 'right') {
  5672. x -= width;
  5673. }
  5674. else if (textAlign === 'center') {
  5675. x -= width / 2;
  5676. }
  5677. return x;
  5678. }
  5679. function adjustTextY$1(y, height, verticalAlign) {
  5680. if (verticalAlign === 'middle') {
  5681. y -= height / 2;
  5682. }
  5683. else if (verticalAlign === 'bottom') {
  5684. y -= height;
  5685. }
  5686. return y;
  5687. }
  5688. function getLineHeight(font) {
  5689. return getWidth('国', font);
  5690. }
  5691. function parsePercent(value, maxValue) {
  5692. if (typeof value === 'string') {
  5693. if (value.lastIndexOf('%') >= 0) {
  5694. return parseFloat(value) / 100 * maxValue;
  5695. }
  5696. return parseFloat(value);
  5697. }
  5698. return value;
  5699. }
  5700. function calculateTextPosition(out, opts, rect) {
  5701. var textPosition = opts.position || 'inside';
  5702. var distance = opts.distance != null ? opts.distance : 5;
  5703. var height = rect.height;
  5704. var width = rect.width;
  5705. var halfHeight = height / 2;
  5706. var x = rect.x;
  5707. var y = rect.y;
  5708. var textAlign = 'left';
  5709. var textVerticalAlign = 'top';
  5710. if (textPosition instanceof Array) {
  5711. x += parsePercent(textPosition[0], rect.width);
  5712. y += parsePercent(textPosition[1], rect.height);
  5713. textAlign = null;
  5714. textVerticalAlign = null;
  5715. }
  5716. else {
  5717. switch (textPosition) {
  5718. case 'left':
  5719. x -= distance;
  5720. y += halfHeight;
  5721. textAlign = 'right';
  5722. textVerticalAlign = 'middle';
  5723. break;
  5724. case 'right':
  5725. x += distance + width;
  5726. y += halfHeight;
  5727. textVerticalAlign = 'middle';
  5728. break;
  5729. case 'top':
  5730. x += width / 2;
  5731. y -= distance;
  5732. textAlign = 'center';
  5733. textVerticalAlign = 'bottom';
  5734. break;
  5735. case 'bottom':
  5736. x += width / 2;
  5737. y += height + distance;
  5738. textAlign = 'center';
  5739. break;
  5740. case 'inside':
  5741. x += width / 2;
  5742. y += halfHeight;
  5743. textAlign = 'center';
  5744. textVerticalAlign = 'middle';
  5745. break;
  5746. case 'insideLeft':
  5747. x += distance;
  5748. y += halfHeight;
  5749. textVerticalAlign = 'middle';
  5750. break;
  5751. case 'insideRight':
  5752. x += width - distance;
  5753. y += halfHeight;
  5754. textAlign = 'right';
  5755. textVerticalAlign = 'middle';
  5756. break;
  5757. case 'insideTop':
  5758. x += width / 2;
  5759. y += distance;
  5760. textAlign = 'center';
  5761. break;
  5762. case 'insideBottom':
  5763. x += width / 2;
  5764. y += height - distance;
  5765. textAlign = 'center';
  5766. textVerticalAlign = 'bottom';
  5767. break;
  5768. case 'insideTopLeft':
  5769. x += distance;
  5770. y += distance;
  5771. break;
  5772. case 'insideTopRight':
  5773. x += width - distance;
  5774. y += distance;
  5775. textAlign = 'right';
  5776. break;
  5777. case 'insideBottomLeft':
  5778. x += distance;
  5779. y += height - distance;
  5780. textVerticalAlign = 'bottom';
  5781. break;
  5782. case 'insideBottomRight':
  5783. x += width - distance;
  5784. y += height - distance;
  5785. textAlign = 'right';
  5786. textVerticalAlign = 'bottom';
  5787. break;
  5788. }
  5789. }
  5790. out = out || {};
  5791. out.x = x;
  5792. out.y = y;
  5793. out.align = textAlign;
  5794. out.verticalAlign = textVerticalAlign;
  5795. return out;
  5796. }
  5797. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5798. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5799. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5800. obj[key] = true;
  5801. return obj;
  5802. }, { ignore: false });
  5803. var tmpTextPosCalcRes = {};
  5804. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5805. var Element = (function () {
  5806. function Element(props) {
  5807. this.id = guid();
  5808. this.animators = [];
  5809. this.currentStates = [];
  5810. this.states = {};
  5811. this._init(props);
  5812. }
  5813. Element.prototype._init = function (props) {
  5814. this.attr(props);
  5815. };
  5816. Element.prototype.drift = function (dx, dy, e) {
  5817. switch (this.draggable) {
  5818. case 'horizontal':
  5819. dy = 0;
  5820. break;
  5821. case 'vertical':
  5822. dx = 0;
  5823. break;
  5824. }
  5825. var m = this.transform;
  5826. if (!m) {
  5827. m = this.transform = [1, 0, 0, 1, 0, 0];
  5828. }
  5829. m[4] += dx;
  5830. m[5] += dy;
  5831. this.decomposeTransform();
  5832. this.markRedraw();
  5833. };
  5834. Element.prototype.beforeUpdate = function () { };
  5835. Element.prototype.afterUpdate = function () { };
  5836. Element.prototype.update = function () {
  5837. this.updateTransform();
  5838. if (this.__dirty) {
  5839. this.updateInnerText();
  5840. }
  5841. };
  5842. Element.prototype.updateInnerText = function (forceUpdate) {
  5843. var textEl = this._textContent;
  5844. if (textEl && (!textEl.ignore || forceUpdate)) {
  5845. if (!this.textConfig) {
  5846. this.textConfig = {};
  5847. }
  5848. var textConfig = this.textConfig;
  5849. var isLocal = textConfig.local;
  5850. var innerTransformable = textEl.innerTransformable;
  5851. var textAlign = void 0;
  5852. var textVerticalAlign = void 0;
  5853. var textStyleChanged = false;
  5854. innerTransformable.parent = isLocal ? this : null;
  5855. var innerOrigin = false;
  5856. innerTransformable.copyTransform(textEl);
  5857. if (textConfig.position != null) {
  5858. var layoutRect = tmpBoundingRect;
  5859. if (textConfig.layoutRect) {
  5860. layoutRect.copy(textConfig.layoutRect);
  5861. }
  5862. else {
  5863. layoutRect.copy(this.getBoundingRect());
  5864. }
  5865. if (!isLocal) {
  5866. layoutRect.applyTransform(this.transform);
  5867. }
  5868. if (this.calculateTextPosition) {
  5869. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5870. }
  5871. else {
  5872. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5873. }
  5874. innerTransformable.x = tmpTextPosCalcRes.x;
  5875. innerTransformable.y = tmpTextPosCalcRes.y;
  5876. textAlign = tmpTextPosCalcRes.align;
  5877. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5878. var textOrigin = textConfig.origin;
  5879. if (textOrigin && textConfig.rotation != null) {
  5880. var relOriginX = void 0;
  5881. var relOriginY = void 0;
  5882. if (textOrigin === 'center') {
  5883. relOriginX = layoutRect.width * 0.5;
  5884. relOriginY = layoutRect.height * 0.5;
  5885. }
  5886. else {
  5887. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5888. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5889. }
  5890. innerOrigin = true;
  5891. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5892. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5893. }
  5894. }
  5895. if (textConfig.rotation != null) {
  5896. innerTransformable.rotation = textConfig.rotation;
  5897. }
  5898. var textOffset = textConfig.offset;
  5899. if (textOffset) {
  5900. innerTransformable.x += textOffset[0];
  5901. innerTransformable.y += textOffset[1];
  5902. if (!innerOrigin) {
  5903. innerTransformable.originX = -textOffset[0];
  5904. innerTransformable.originY = -textOffset[1];
  5905. }
  5906. }
  5907. var isInside = textConfig.inside == null
  5908. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5909. : textConfig.inside;
  5910. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5911. var textFill = void 0;
  5912. var textStroke = void 0;
  5913. var autoStroke = void 0;
  5914. if (isInside && this.canBeInsideText()) {
  5915. textFill = textConfig.insideFill;
  5916. textStroke = textConfig.insideStroke;
  5917. if (textFill == null || textFill === 'auto') {
  5918. textFill = this.getInsideTextFill();
  5919. }
  5920. if (textStroke == null || textStroke === 'auto') {
  5921. textStroke = this.getInsideTextStroke(textFill);
  5922. autoStroke = true;
  5923. }
  5924. }
  5925. else {
  5926. textFill = textConfig.outsideFill;
  5927. textStroke = textConfig.outsideStroke;
  5928. if (textFill == null || textFill === 'auto') {
  5929. textFill = this.getOutsideFill();
  5930. }
  5931. if (textStroke == null || textStroke === 'auto') {
  5932. textStroke = this.getOutsideStroke(textFill);
  5933. autoStroke = true;
  5934. }
  5935. }
  5936. textFill = textFill || '#000';
  5937. if (textFill !== innerTextDefaultStyle.fill
  5938. || textStroke !== innerTextDefaultStyle.stroke
  5939. || autoStroke !== innerTextDefaultStyle.autoStroke
  5940. || textAlign !== innerTextDefaultStyle.align
  5941. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5942. textStyleChanged = true;
  5943. innerTextDefaultStyle.fill = textFill;
  5944. innerTextDefaultStyle.stroke = textStroke;
  5945. innerTextDefaultStyle.autoStroke = autoStroke;
  5946. innerTextDefaultStyle.align = textAlign;
  5947. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5948. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5949. }
  5950. textEl.__dirty |= REDRAW_BIT;
  5951. if (textStyleChanged) {
  5952. textEl.dirtyStyle(true);
  5953. }
  5954. }
  5955. };
  5956. Element.prototype.canBeInsideText = function () {
  5957. return true;
  5958. };
  5959. Element.prototype.getInsideTextFill = function () {
  5960. return '#fff';
  5961. };
  5962. Element.prototype.getInsideTextStroke = function (textFill) {
  5963. return '#000';
  5964. };
  5965. Element.prototype.getOutsideFill = function () {
  5966. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5967. };
  5968. Element.prototype.getOutsideStroke = function (textFill) {
  5969. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5970. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5971. if (!colorArr) {
  5972. colorArr = [255, 255, 255, 1];
  5973. }
  5974. var alpha = colorArr[3];
  5975. var isDark = this.__zr.isDarkMode();
  5976. for (var i = 0; i < 3; i++) {
  5977. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5978. }
  5979. colorArr[3] = 1;
  5980. return stringify(colorArr, 'rgba');
  5981. };
  5982. Element.prototype.traverse = function (cb, context) { };
  5983. Element.prototype.attrKV = function (key, value) {
  5984. if (key === 'textConfig') {
  5985. this.setTextConfig(value);
  5986. }
  5987. else if (key === 'textContent') {
  5988. this.setTextContent(value);
  5989. }
  5990. else if (key === 'clipPath') {
  5991. this.setClipPath(value);
  5992. }
  5993. else if (key === 'extra') {
  5994. this.extra = this.extra || {};
  5995. extend(this.extra, value);
  5996. }
  5997. else {
  5998. this[key] = value;
  5999. }
  6000. };
  6001. Element.prototype.hide = function () {
  6002. this.ignore = true;
  6003. this.markRedraw();
  6004. };
  6005. Element.prototype.show = function () {
  6006. this.ignore = false;
  6007. this.markRedraw();
  6008. };
  6009. Element.prototype.attr = function (keyOrObj, value) {
  6010. if (typeof keyOrObj === 'string') {
  6011. this.attrKV(keyOrObj, value);
  6012. }
  6013. else if (isObject(keyOrObj)) {
  6014. var obj = keyOrObj;
  6015. var keysArr = keys(obj);
  6016. for (var i = 0; i < keysArr.length; i++) {
  6017. var key = keysArr[i];
  6018. this.attrKV(key, keyOrObj[key]);
  6019. }
  6020. }
  6021. this.markRedraw();
  6022. return this;
  6023. };
  6024. Element.prototype.saveCurrentToNormalState = function (toState) {
  6025. this._innerSaveToNormal(toState);
  6026. var normalState = this._normalState;
  6027. for (var i = 0; i < this.animators.length; i++) {
  6028. var animator = this.animators[i];
  6029. var fromStateTransition = animator.__fromStateTransition;
  6030. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6031. continue;
  6032. }
  6033. var targetName = animator.targetName;
  6034. var target = targetName
  6035. ? normalState[targetName] : normalState;
  6036. animator.saveTo(target);
  6037. }
  6038. };
  6039. Element.prototype._innerSaveToNormal = function (toState) {
  6040. var normalState = this._normalState;
  6041. if (!normalState) {
  6042. normalState = this._normalState = {};
  6043. }
  6044. if (toState.textConfig && !normalState.textConfig) {
  6045. normalState.textConfig = this.textConfig;
  6046. }
  6047. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6048. };
  6049. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6050. for (var i = 0; i < primaryKeys.length; i++) {
  6051. var key = primaryKeys[i];
  6052. if (toState[key] != null && !(key in normalState)) {
  6053. normalState[key] = this[key];
  6054. }
  6055. }
  6056. };
  6057. Element.prototype.hasState = function () {
  6058. return this.currentStates.length > 0;
  6059. };
  6060. Element.prototype.getState = function (name) {
  6061. return this.states[name];
  6062. };
  6063. Element.prototype.ensureState = function (name) {
  6064. var states = this.states;
  6065. if (!states[name]) {
  6066. states[name] = {};
  6067. }
  6068. return states[name];
  6069. };
  6070. Element.prototype.clearStates = function (noAnimation) {
  6071. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6072. };
  6073. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6074. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6075. var hasStates = this.hasState();
  6076. if (!hasStates && toNormalState) {
  6077. return;
  6078. }
  6079. var currentStates = this.currentStates;
  6080. var animationCfg = this.stateTransition;
  6081. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6082. return;
  6083. }
  6084. var state;
  6085. if (this.stateProxy && !toNormalState) {
  6086. state = this.stateProxy(stateName);
  6087. }
  6088. if (!state) {
  6089. state = (this.states && this.states[stateName]);
  6090. }
  6091. if (!state && !toNormalState) {
  6092. logError("State " + stateName + " not exists.");
  6093. return;
  6094. }
  6095. if (!toNormalState) {
  6096. this.saveCurrentToNormalState(state);
  6097. }
  6098. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6099. if (useHoverLayer) {
  6100. this._toggleHoverLayerFlag(true);
  6101. }
  6102. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6103. var textContent = this._textContent;
  6104. var textGuide = this._textGuide;
  6105. if (textContent) {
  6106. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6107. }
  6108. if (textGuide) {
  6109. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6110. }
  6111. if (toNormalState) {
  6112. this.currentStates = [];
  6113. this._normalState = {};
  6114. }
  6115. else {
  6116. if (!keepCurrentStates) {
  6117. this.currentStates = [stateName];
  6118. }
  6119. else {
  6120. this.currentStates.push(stateName);
  6121. }
  6122. }
  6123. this._updateAnimationTargets();
  6124. this.markRedraw();
  6125. if (!useHoverLayer && this.__inHover) {
  6126. this._toggleHoverLayerFlag(false);
  6127. this.__dirty &= ~REDRAW_BIT;
  6128. }
  6129. return state;
  6130. };
  6131. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6132. if (!states.length) {
  6133. this.clearStates();
  6134. }
  6135. else {
  6136. var stateObjects = [];
  6137. var currentStates = this.currentStates;
  6138. var len = states.length;
  6139. var notChange = len === currentStates.length;
  6140. if (notChange) {
  6141. for (var i = 0; i < len; i++) {
  6142. if (states[i] !== currentStates[i]) {
  6143. notChange = false;
  6144. break;
  6145. }
  6146. }
  6147. }
  6148. if (notChange) {
  6149. return;
  6150. }
  6151. for (var i = 0; i < len; i++) {
  6152. var stateName = states[i];
  6153. var stateObj = void 0;
  6154. if (this.stateProxy) {
  6155. stateObj = this.stateProxy(stateName, states);
  6156. }
  6157. if (!stateObj) {
  6158. stateObj = this.states[stateName];
  6159. }
  6160. if (stateObj) {
  6161. stateObjects.push(stateObj);
  6162. }
  6163. }
  6164. var lastStateObj = stateObjects[len - 1];
  6165. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6166. if (useHoverLayer) {
  6167. this._toggleHoverLayerFlag(true);
  6168. }
  6169. var mergedState = this._mergeStates(stateObjects);
  6170. var animationCfg = this.stateTransition;
  6171. this.saveCurrentToNormalState(mergedState);
  6172. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6173. var textContent = this._textContent;
  6174. var textGuide = this._textGuide;
  6175. if (textContent) {
  6176. textContent.useStates(states, noAnimation, useHoverLayer);
  6177. }
  6178. if (textGuide) {
  6179. textGuide.useStates(states, noAnimation, useHoverLayer);
  6180. }
  6181. this._updateAnimationTargets();
  6182. this.currentStates = states.slice();
  6183. this.markRedraw();
  6184. if (!useHoverLayer && this.__inHover) {
  6185. this._toggleHoverLayerFlag(false);
  6186. this.__dirty &= ~REDRAW_BIT;
  6187. }
  6188. }
  6189. };
  6190. Element.prototype.isSilent = function () {
  6191. var isSilent = this.silent;
  6192. var ancestor = this.parent;
  6193. while (!isSilent && ancestor) {
  6194. if (ancestor.silent) {
  6195. isSilent = true;
  6196. break;
  6197. }
  6198. ancestor = ancestor.parent;
  6199. }
  6200. return isSilent;
  6201. };
  6202. Element.prototype._updateAnimationTargets = function () {
  6203. for (var i = 0; i < this.animators.length; i++) {
  6204. var animator = this.animators[i];
  6205. if (animator.targetName) {
  6206. animator.changeTarget(this[animator.targetName]);
  6207. }
  6208. }
  6209. };
  6210. Element.prototype.removeState = function (state) {
  6211. var idx = indexOf(this.currentStates, state);
  6212. if (idx >= 0) {
  6213. var currentStates = this.currentStates.slice();
  6214. currentStates.splice(idx, 1);
  6215. this.useStates(currentStates);
  6216. }
  6217. };
  6218. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6219. var currentStates = this.currentStates.slice();
  6220. var idx = indexOf(currentStates, oldState);
  6221. var newStateExists = indexOf(currentStates, newState) >= 0;
  6222. if (idx >= 0) {
  6223. if (!newStateExists) {
  6224. currentStates[idx] = newState;
  6225. }
  6226. else {
  6227. currentStates.splice(idx, 1);
  6228. }
  6229. }
  6230. else if (forceAdd && !newStateExists) {
  6231. currentStates.push(newState);
  6232. }
  6233. this.useStates(currentStates);
  6234. };
  6235. Element.prototype.toggleState = function (state, enable) {
  6236. if (enable) {
  6237. this.useState(state, true);
  6238. }
  6239. else {
  6240. this.removeState(state);
  6241. }
  6242. };
  6243. Element.prototype._mergeStates = function (states) {
  6244. var mergedState = {};
  6245. var mergedTextConfig;
  6246. for (var i = 0; i < states.length; i++) {
  6247. var state = states[i];
  6248. extend(mergedState, state);
  6249. if (state.textConfig) {
  6250. mergedTextConfig = mergedTextConfig || {};
  6251. extend(mergedTextConfig, state.textConfig);
  6252. }
  6253. }
  6254. if (mergedTextConfig) {
  6255. mergedState.textConfig = mergedTextConfig;
  6256. }
  6257. return mergedState;
  6258. };
  6259. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6260. var needsRestoreToNormal = !(state && keepCurrentStates);
  6261. if (state && state.textConfig) {
  6262. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6263. extend(this.textConfig, state.textConfig);
  6264. }
  6265. else if (needsRestoreToNormal) {
  6266. if (normalState.textConfig) {
  6267. this.textConfig = normalState.textConfig;
  6268. }
  6269. }
  6270. var transitionTarget = {};
  6271. var hasTransition = false;
  6272. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6273. var key = PRIMARY_STATES_KEYS[i];
  6274. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6275. if (state && state[key] != null) {
  6276. if (propNeedsTransition) {
  6277. hasTransition = true;
  6278. transitionTarget[key] = state[key];
  6279. }
  6280. else {
  6281. this[key] = state[key];
  6282. }
  6283. }
  6284. else if (needsRestoreToNormal) {
  6285. if (normalState[key] != null) {
  6286. if (propNeedsTransition) {
  6287. hasTransition = true;
  6288. transitionTarget[key] = normalState[key];
  6289. }
  6290. else {
  6291. this[key] = normalState[key];
  6292. }
  6293. }
  6294. }
  6295. }
  6296. if (!transition) {
  6297. for (var i = 0; i < this.animators.length; i++) {
  6298. var animator = this.animators[i];
  6299. var targetName = animator.targetName;
  6300. if (!animator.getLoop()) {
  6301. animator.__changeFinalValue(targetName
  6302. ? (state || normalState)[targetName]
  6303. : (state || normalState));
  6304. }
  6305. }
  6306. }
  6307. if (hasTransition) {
  6308. this._transitionState(stateName, transitionTarget, animationCfg);
  6309. }
  6310. };
  6311. Element.prototype._attachComponent = function (componentEl) {
  6312. if (componentEl.__zr && !componentEl.__hostTarget) {
  6313. if ("development" !== 'production') {
  6314. throw new Error('Text element has been added to zrender.');
  6315. }
  6316. return;
  6317. }
  6318. if (componentEl === this) {
  6319. if ("development" !== 'production') {
  6320. throw new Error('Recursive component attachment.');
  6321. }
  6322. return;
  6323. }
  6324. var zr = this.__zr;
  6325. if (zr) {
  6326. componentEl.addSelfToZr(zr);
  6327. }
  6328. componentEl.__zr = zr;
  6329. componentEl.__hostTarget = this;
  6330. };
  6331. Element.prototype._detachComponent = function (componentEl) {
  6332. if (componentEl.__zr) {
  6333. componentEl.removeSelfFromZr(componentEl.__zr);
  6334. }
  6335. componentEl.__zr = null;
  6336. componentEl.__hostTarget = null;
  6337. };
  6338. Element.prototype.getClipPath = function () {
  6339. return this._clipPath;
  6340. };
  6341. Element.prototype.setClipPath = function (clipPath) {
  6342. if (this._clipPath && this._clipPath !== clipPath) {
  6343. this.removeClipPath();
  6344. }
  6345. this._attachComponent(clipPath);
  6346. this._clipPath = clipPath;
  6347. this.markRedraw();
  6348. };
  6349. Element.prototype.removeClipPath = function () {
  6350. var clipPath = this._clipPath;
  6351. if (clipPath) {
  6352. this._detachComponent(clipPath);
  6353. this._clipPath = null;
  6354. this.markRedraw();
  6355. }
  6356. };
  6357. Element.prototype.getTextContent = function () {
  6358. return this._textContent;
  6359. };
  6360. Element.prototype.setTextContent = function (textEl) {
  6361. var previousTextContent = this._textContent;
  6362. if (previousTextContent === textEl) {
  6363. return;
  6364. }
  6365. if (previousTextContent && previousTextContent !== textEl) {
  6366. this.removeTextContent();
  6367. }
  6368. if ("development" !== 'production') {
  6369. if (textEl.__zr && !textEl.__hostTarget) {
  6370. throw new Error('Text element has been added to zrender.');
  6371. }
  6372. }
  6373. textEl.innerTransformable = new Transformable();
  6374. this._attachComponent(textEl);
  6375. this._textContent = textEl;
  6376. this.markRedraw();
  6377. };
  6378. Element.prototype.setTextConfig = function (cfg) {
  6379. if (!this.textConfig) {
  6380. this.textConfig = {};
  6381. }
  6382. extend(this.textConfig, cfg);
  6383. this.markRedraw();
  6384. };
  6385. Element.prototype.removeTextConfig = function () {
  6386. this.textConfig = null;
  6387. this.markRedraw();
  6388. };
  6389. Element.prototype.removeTextContent = function () {
  6390. var textEl = this._textContent;
  6391. if (textEl) {
  6392. textEl.innerTransformable = null;
  6393. this._detachComponent(textEl);
  6394. this._textContent = null;
  6395. this._innerTextDefaultStyle = null;
  6396. this.markRedraw();
  6397. }
  6398. };
  6399. Element.prototype.getTextGuideLine = function () {
  6400. return this._textGuide;
  6401. };
  6402. Element.prototype.setTextGuideLine = function (guideLine) {
  6403. if (this._textGuide && this._textGuide !== guideLine) {
  6404. this.removeTextGuideLine();
  6405. }
  6406. this._attachComponent(guideLine);
  6407. this._textGuide = guideLine;
  6408. this.markRedraw();
  6409. };
  6410. Element.prototype.removeTextGuideLine = function () {
  6411. var textGuide = this._textGuide;
  6412. if (textGuide) {
  6413. this._detachComponent(textGuide);
  6414. this._textGuide = null;
  6415. this.markRedraw();
  6416. }
  6417. };
  6418. Element.prototype.markRedraw = function () {
  6419. this.__dirty |= REDRAW_BIT;
  6420. var zr = this.__zr;
  6421. if (zr) {
  6422. if (this.__inHover) {
  6423. zr.refreshHover();
  6424. }
  6425. else {
  6426. zr.refresh();
  6427. }
  6428. }
  6429. if (this.__hostTarget) {
  6430. this.__hostTarget.markRedraw();
  6431. }
  6432. };
  6433. Element.prototype.dirty = function () {
  6434. this.markRedraw();
  6435. };
  6436. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6437. this.__inHover = inHover;
  6438. var textContent = this._textContent;
  6439. var textGuide = this._textGuide;
  6440. if (textContent) {
  6441. textContent.__inHover = inHover;
  6442. }
  6443. if (textGuide) {
  6444. textGuide.__inHover = inHover;
  6445. }
  6446. };
  6447. Element.prototype.addSelfToZr = function (zr) {
  6448. if (this.__zr === zr) {
  6449. return;
  6450. }
  6451. this.__zr = zr;
  6452. var animators = this.animators;
  6453. if (animators) {
  6454. for (var i = 0; i < animators.length; i++) {
  6455. zr.animation.addAnimator(animators[i]);
  6456. }
  6457. }
  6458. if (this._clipPath) {
  6459. this._clipPath.addSelfToZr(zr);
  6460. }
  6461. if (this._textContent) {
  6462. this._textContent.addSelfToZr(zr);
  6463. }
  6464. if (this._textGuide) {
  6465. this._textGuide.addSelfToZr(zr);
  6466. }
  6467. };
  6468. Element.prototype.removeSelfFromZr = function (zr) {
  6469. if (!this.__zr) {
  6470. return;
  6471. }
  6472. this.__zr = null;
  6473. var animators = this.animators;
  6474. if (animators) {
  6475. for (var i = 0; i < animators.length; i++) {
  6476. zr.animation.removeAnimator(animators[i]);
  6477. }
  6478. }
  6479. if (this._clipPath) {
  6480. this._clipPath.removeSelfFromZr(zr);
  6481. }
  6482. if (this._textContent) {
  6483. this._textContent.removeSelfFromZr(zr);
  6484. }
  6485. if (this._textGuide) {
  6486. this._textGuide.removeSelfFromZr(zr);
  6487. }
  6488. };
  6489. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6490. var target = key ? this[key] : this;
  6491. if ("development" !== 'production') {
  6492. if (!target) {
  6493. logError('Property "'
  6494. + key
  6495. + '" is not existed in element '
  6496. + this.id);
  6497. return;
  6498. }
  6499. }
  6500. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6501. key && (animator.targetName = key);
  6502. this.addAnimator(animator, key);
  6503. return animator;
  6504. };
  6505. Element.prototype.addAnimator = function (animator, key) {
  6506. var zr = this.__zr;
  6507. var el = this;
  6508. animator.during(function () {
  6509. el.updateDuringAnimation(key);
  6510. }).done(function () {
  6511. var animators = el.animators;
  6512. var idx = indexOf(animators, animator);
  6513. if (idx >= 0) {
  6514. animators.splice(idx, 1);
  6515. }
  6516. });
  6517. this.animators.push(animator);
  6518. if (zr) {
  6519. zr.animation.addAnimator(animator);
  6520. }
  6521. zr && zr.wakeUp();
  6522. };
  6523. Element.prototype.updateDuringAnimation = function (key) {
  6524. this.markRedraw();
  6525. };
  6526. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6527. var animators = this.animators;
  6528. var len = animators.length;
  6529. var leftAnimators = [];
  6530. for (var i = 0; i < len; i++) {
  6531. var animator = animators[i];
  6532. if (!scope || scope === animator.scope) {
  6533. animator.stop(forwardToLast);
  6534. }
  6535. else {
  6536. leftAnimators.push(animator);
  6537. }
  6538. }
  6539. this.animators = leftAnimators;
  6540. return this;
  6541. };
  6542. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6543. animateTo(this, target, cfg, animationProps);
  6544. };
  6545. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6546. animateTo(this, target, cfg, animationProps, true);
  6547. };
  6548. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6549. var animators = animateTo(this, target, cfg, animationProps);
  6550. for (var i = 0; i < animators.length; i++) {
  6551. animators[i].__fromStateTransition = stateName;
  6552. }
  6553. };
  6554. Element.prototype.getBoundingRect = function () {
  6555. return null;
  6556. };
  6557. Element.prototype.getPaintRect = function () {
  6558. return null;
  6559. };
  6560. Element.initDefaultProps = (function () {
  6561. var elProto = Element.prototype;
  6562. elProto.type = 'element';
  6563. elProto.name = '';
  6564. elProto.ignore =
  6565. elProto.silent =
  6566. elProto.isGroup =
  6567. elProto.draggable =
  6568. elProto.dragging =
  6569. elProto.ignoreClip =
  6570. elProto.__inHover = false;
  6571. elProto.__dirty = REDRAW_BIT;
  6572. var logs = {};
  6573. function logDeprecatedError(key, xKey, yKey) {
  6574. if (!logs[key + xKey + yKey]) {
  6575. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6576. logs[key + xKey + yKey] = true;
  6577. }
  6578. }
  6579. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6580. Object.defineProperty(elProto, key, {
  6581. get: function () {
  6582. if ("development" !== 'production') {
  6583. logDeprecatedError(key, xKey, yKey);
  6584. }
  6585. if (!this[privateKey]) {
  6586. var pos = this[privateKey] = [];
  6587. enhanceArray(this, pos);
  6588. }
  6589. return this[privateKey];
  6590. },
  6591. set: function (pos) {
  6592. if ("development" !== 'production') {
  6593. logDeprecatedError(key, xKey, yKey);
  6594. }
  6595. this[xKey] = pos[0];
  6596. this[yKey] = pos[1];
  6597. this[privateKey] = pos;
  6598. enhanceArray(this, pos);
  6599. }
  6600. });
  6601. function enhanceArray(self, pos) {
  6602. Object.defineProperty(pos, 0, {
  6603. get: function () {
  6604. return self[xKey];
  6605. },
  6606. set: function (val) {
  6607. self[xKey] = val;
  6608. }
  6609. });
  6610. Object.defineProperty(pos, 1, {
  6611. get: function () {
  6612. return self[yKey];
  6613. },
  6614. set: function (val) {
  6615. self[yKey] = val;
  6616. }
  6617. });
  6618. }
  6619. }
  6620. if (Object.defineProperty) {
  6621. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6622. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6623. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6624. }
  6625. })();
  6626. return Element;
  6627. }());
  6628. mixin(Element, Eventful);
  6629. mixin(Element, Transformable);
  6630. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6631. cfg = cfg || {};
  6632. var animators = [];
  6633. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6634. var finishCount = animators.length;
  6635. var doneHappened = false;
  6636. var cfgDone = cfg.done;
  6637. var cfgAborted = cfg.aborted;
  6638. var doneCb = function () {
  6639. doneHappened = true;
  6640. finishCount--;
  6641. if (finishCount <= 0) {
  6642. doneHappened
  6643. ? (cfgDone && cfgDone())
  6644. : (cfgAborted && cfgAborted());
  6645. }
  6646. };
  6647. var abortedCb = function () {
  6648. finishCount--;
  6649. if (finishCount <= 0) {
  6650. doneHappened
  6651. ? (cfgDone && cfgDone())
  6652. : (cfgAborted && cfgAborted());
  6653. }
  6654. };
  6655. if (!finishCount) {
  6656. cfgDone && cfgDone();
  6657. }
  6658. if (animators.length > 0 && cfg.during) {
  6659. animators[0].during(function (target, percent) {
  6660. cfg.during(percent);
  6661. });
  6662. }
  6663. for (var i = 0; i < animators.length; i++) {
  6664. var animator = animators[i];
  6665. if (doneCb) {
  6666. animator.done(doneCb);
  6667. }
  6668. if (abortedCb) {
  6669. animator.aborted(abortedCb);
  6670. }
  6671. if (cfg.force) {
  6672. animator.duration(cfg.duration);
  6673. }
  6674. animator.start(cfg.easing);
  6675. }
  6676. return animators;
  6677. }
  6678. function copyArrShallow(source, target, len) {
  6679. for (var i = 0; i < len; i++) {
  6680. source[i] = target[i];
  6681. }
  6682. }
  6683. function is2DArray(value) {
  6684. return isArrayLike(value[0]);
  6685. }
  6686. function copyValue(target, source, key) {
  6687. if (isArrayLike(source[key])) {
  6688. if (!isArrayLike(target[key])) {
  6689. target[key] = [];
  6690. }
  6691. if (isTypedArray(source[key])) {
  6692. var len = source[key].length;
  6693. if (target[key].length !== len) {
  6694. target[key] = new (source[key].constructor)(len);
  6695. copyArrShallow(target[key], source[key], len);
  6696. }
  6697. }
  6698. else {
  6699. var sourceArr = source[key];
  6700. var targetArr = target[key];
  6701. var len0 = sourceArr.length;
  6702. if (is2DArray(sourceArr)) {
  6703. var len1 = sourceArr[0].length;
  6704. for (var i = 0; i < len0; i++) {
  6705. if (!targetArr[i]) {
  6706. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6707. }
  6708. else {
  6709. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6710. }
  6711. }
  6712. }
  6713. else {
  6714. copyArrShallow(targetArr, sourceArr, len0);
  6715. }
  6716. targetArr.length = sourceArr.length;
  6717. }
  6718. }
  6719. else {
  6720. target[key] = source[key];
  6721. }
  6722. }
  6723. function isValueSame(val1, val2) {
  6724. return val1 === val2
  6725. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6726. }
  6727. function is1DArraySame(arr0, arr1) {
  6728. var len = arr0.length;
  6729. if (len !== arr1.length) {
  6730. return false;
  6731. }
  6732. for (var i = 0; i < len; i++) {
  6733. if (arr0[i] !== arr1[i]) {
  6734. return false;
  6735. }
  6736. }
  6737. return true;
  6738. }
  6739. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6740. var targetKeys = keys(target);
  6741. var duration = cfg.duration;
  6742. var delay = cfg.delay;
  6743. var additive = cfg.additive;
  6744. var setToFinal = cfg.setToFinal;
  6745. var animateAll = !isObject(animationProps);
  6746. var existsAnimators = animatable.animators;
  6747. var animationKeys = [];
  6748. for (var k = 0; k < targetKeys.length; k++) {
  6749. var innerKey = targetKeys[k];
  6750. var targetVal = target[innerKey];
  6751. if (targetVal != null && animateObj[innerKey] != null
  6752. && (animateAll || animationProps[innerKey])) {
  6753. if (isObject(targetVal)
  6754. && !isArrayLike(targetVal)
  6755. && !isGradientObject(targetVal)) {
  6756. if (topKey) {
  6757. if (!reverse) {
  6758. animateObj[innerKey] = targetVal;
  6759. animatable.updateDuringAnimation(topKey);
  6760. }
  6761. continue;
  6762. }
  6763. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6764. }
  6765. else {
  6766. animationKeys.push(innerKey);
  6767. }
  6768. }
  6769. else if (!reverse) {
  6770. animateObj[innerKey] = targetVal;
  6771. animatable.updateDuringAnimation(topKey);
  6772. animationKeys.push(innerKey);
  6773. }
  6774. }
  6775. var keyLen = animationKeys.length;
  6776. if (!additive && keyLen) {
  6777. for (var i = 0; i < existsAnimators.length; i++) {
  6778. var animator = existsAnimators[i];
  6779. if (animator.targetName === topKey) {
  6780. var allAborted = animator.stopTracks(animationKeys);
  6781. if (allAborted) {
  6782. var idx = indexOf(existsAnimators, animator);
  6783. existsAnimators.splice(idx, 1);
  6784. }
  6785. }
  6786. }
  6787. }
  6788. if (!cfg.force) {
  6789. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6790. keyLen = animationKeys.length;
  6791. }
  6792. if (keyLen > 0
  6793. || (cfg.force && !animators.length)) {
  6794. var revertedSource = void 0;
  6795. var reversedTarget = void 0;
  6796. var sourceClone = void 0;
  6797. if (reverse) {
  6798. reversedTarget = {};
  6799. if (setToFinal) {
  6800. revertedSource = {};
  6801. }
  6802. for (var i = 0; i < keyLen; i++) {
  6803. var innerKey = animationKeys[i];
  6804. reversedTarget[innerKey] = animateObj[innerKey];
  6805. if (setToFinal) {
  6806. revertedSource[innerKey] = target[innerKey];
  6807. }
  6808. else {
  6809. animateObj[innerKey] = target[innerKey];
  6810. }
  6811. }
  6812. }
  6813. else if (setToFinal) {
  6814. sourceClone = {};
  6815. for (var i = 0; i < keyLen; i++) {
  6816. var innerKey = animationKeys[i];
  6817. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6818. copyValue(animateObj, target, innerKey);
  6819. }
  6820. }
  6821. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6822. animator.targetName = topKey;
  6823. if (cfg.scope) {
  6824. animator.scope = cfg.scope;
  6825. }
  6826. if (setToFinal && revertedSource) {
  6827. animator.whenWithKeys(0, revertedSource, animationKeys);
  6828. }
  6829. if (sourceClone) {
  6830. animator.whenWithKeys(0, sourceClone, animationKeys);
  6831. }
  6832. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6833. animatable.addAnimator(animator, topKey);
  6834. animators.push(animator);
  6835. }
  6836. }
  6837. var Group = (function (_super) {
  6838. __extends(Group, _super);
  6839. function Group(opts) {
  6840. var _this = _super.call(this) || this;
  6841. _this.isGroup = true;
  6842. _this._children = [];
  6843. _this.attr(opts);
  6844. return _this;
  6845. }
  6846. Group.prototype.childrenRef = function () {
  6847. return this._children;
  6848. };
  6849. Group.prototype.children = function () {
  6850. return this._children.slice();
  6851. };
  6852. Group.prototype.childAt = function (idx) {
  6853. return this._children[idx];
  6854. };
  6855. Group.prototype.childOfName = function (name) {
  6856. var children = this._children;
  6857. for (var i = 0; i < children.length; i++) {
  6858. if (children[i].name === name) {
  6859. return children[i];
  6860. }
  6861. }
  6862. };
  6863. Group.prototype.childCount = function () {
  6864. return this._children.length;
  6865. };
  6866. Group.prototype.add = function (child) {
  6867. if (child) {
  6868. if (child !== this && child.parent !== this) {
  6869. this._children.push(child);
  6870. this._doAdd(child);
  6871. }
  6872. if ("development" !== 'production') {
  6873. if (child.__hostTarget) {
  6874. throw 'This elemenet has been used as an attachment';
  6875. }
  6876. }
  6877. }
  6878. return this;
  6879. };
  6880. Group.prototype.addBefore = function (child, nextSibling) {
  6881. if (child && child !== this && child.parent !== this
  6882. && nextSibling && nextSibling.parent === this) {
  6883. var children = this._children;
  6884. var idx = children.indexOf(nextSibling);
  6885. if (idx >= 0) {
  6886. children.splice(idx, 0, child);
  6887. this._doAdd(child);
  6888. }
  6889. }
  6890. return this;
  6891. };
  6892. Group.prototype.replace = function (oldChild, newChild) {
  6893. var idx = indexOf(this._children, oldChild);
  6894. if (idx >= 0) {
  6895. this.replaceAt(newChild, idx);
  6896. }
  6897. return this;
  6898. };
  6899. Group.prototype.replaceAt = function (child, index) {
  6900. var children = this._children;
  6901. var old = children[index];
  6902. if (child && child !== this && child.parent !== this && child !== old) {
  6903. children[index] = child;
  6904. old.parent = null;
  6905. var zr = this.__zr;
  6906. if (zr) {
  6907. old.removeSelfFromZr(zr);
  6908. }
  6909. this._doAdd(child);
  6910. }
  6911. return this;
  6912. };
  6913. Group.prototype._doAdd = function (child) {
  6914. if (child.parent) {
  6915. child.parent.remove(child);
  6916. }
  6917. child.parent = this;
  6918. var zr = this.__zr;
  6919. if (zr && zr !== child.__zr) {
  6920. child.addSelfToZr(zr);
  6921. }
  6922. zr && zr.refresh();
  6923. };
  6924. Group.prototype.remove = function (child) {
  6925. var zr = this.__zr;
  6926. var children = this._children;
  6927. var idx = indexOf(children, child);
  6928. if (idx < 0) {
  6929. return this;
  6930. }
  6931. children.splice(idx, 1);
  6932. child.parent = null;
  6933. if (zr) {
  6934. child.removeSelfFromZr(zr);
  6935. }
  6936. zr && zr.refresh();
  6937. return this;
  6938. };
  6939. Group.prototype.removeAll = function () {
  6940. var children = this._children;
  6941. var zr = this.__zr;
  6942. for (var i = 0; i < children.length; i++) {
  6943. var child = children[i];
  6944. if (zr) {
  6945. child.removeSelfFromZr(zr);
  6946. }
  6947. child.parent = null;
  6948. }
  6949. children.length = 0;
  6950. return this;
  6951. };
  6952. Group.prototype.eachChild = function (cb, context) {
  6953. var children = this._children;
  6954. for (var i = 0; i < children.length; i++) {
  6955. var child = children[i];
  6956. cb.call(context, child, i);
  6957. }
  6958. return this;
  6959. };
  6960. Group.prototype.traverse = function (cb, context) {
  6961. for (var i = 0; i < this._children.length; i++) {
  6962. var child = this._children[i];
  6963. var stopped = cb.call(context, child);
  6964. if (child.isGroup && !stopped) {
  6965. child.traverse(cb, context);
  6966. }
  6967. }
  6968. return this;
  6969. };
  6970. Group.prototype.addSelfToZr = function (zr) {
  6971. _super.prototype.addSelfToZr.call(this, zr);
  6972. for (var i = 0; i < this._children.length; i++) {
  6973. var child = this._children[i];
  6974. child.addSelfToZr(zr);
  6975. }
  6976. };
  6977. Group.prototype.removeSelfFromZr = function (zr) {
  6978. _super.prototype.removeSelfFromZr.call(this, zr);
  6979. for (var i = 0; i < this._children.length; i++) {
  6980. var child = this._children[i];
  6981. child.removeSelfFromZr(zr);
  6982. }
  6983. };
  6984. Group.prototype.getBoundingRect = function (includeChildren) {
  6985. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6986. var children = includeChildren || this._children;
  6987. var tmpMat = [];
  6988. var rect = null;
  6989. for (var i = 0; i < children.length; i++) {
  6990. var child = children[i];
  6991. if (child.ignore || child.invisible) {
  6992. continue;
  6993. }
  6994. var childRect = child.getBoundingRect();
  6995. var transform = child.getLocalTransform(tmpMat);
  6996. if (transform) {
  6997. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6998. rect = rect || tmpRect.clone();
  6999. rect.union(tmpRect);
  7000. }
  7001. else {
  7002. rect = rect || childRect.clone();
  7003. rect.union(childRect);
  7004. }
  7005. }
  7006. return rect || tmpRect;
  7007. };
  7008. return Group;
  7009. }(Element));
  7010. Group.prototype.type = 'group';
  7011. /*!
  7012. * ZRender, a high performance 2d drawing library.
  7013. *
  7014. * Copyright (c) 2013, Baidu Inc.
  7015. * All rights reserved.
  7016. *
  7017. * LICENSE
  7018. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  7019. */
  7020. var painterCtors = {};
  7021. var instances = {};
  7022. function delInstance(id) {
  7023. delete instances[id];
  7024. }
  7025. function isDarkMode(backgroundColor) {
  7026. if (!backgroundColor) {
  7027. return false;
  7028. }
  7029. if (typeof backgroundColor === 'string') {
  7030. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  7031. }
  7032. else if (backgroundColor.colorStops) {
  7033. var colorStops = backgroundColor.colorStops;
  7034. var totalLum = 0;
  7035. var len = colorStops.length;
  7036. for (var i = 0; i < len; i++) {
  7037. totalLum += lum(colorStops[i].color, 1);
  7038. }
  7039. totalLum /= len;
  7040. return totalLum < DARK_MODE_THRESHOLD;
  7041. }
  7042. return false;
  7043. }
  7044. var ZRender = (function () {
  7045. function ZRender(id, dom, opts) {
  7046. var _this = this;
  7047. this._sleepAfterStill = 10;
  7048. this._stillFrameAccum = 0;
  7049. this._needsRefresh = true;
  7050. this._needsRefreshHover = true;
  7051. this._darkMode = false;
  7052. opts = opts || {};
  7053. this.dom = dom;
  7054. this.id = id;
  7055. var storage = new Storage();
  7056. var rendererType = opts.renderer || 'canvas';
  7057. if (!painterCtors[rendererType]) {
  7058. rendererType = keys(painterCtors)[0];
  7059. }
  7060. if ("development" !== 'production') {
  7061. if (!painterCtors[rendererType]) {
  7062. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7063. }
  7064. }
  7065. opts.useDirtyRect = opts.useDirtyRect == null
  7066. ? false
  7067. : opts.useDirtyRect;
  7068. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7069. var ssrMode = opts.ssr || painter.ssrOnly;
  7070. this.storage = storage;
  7071. this.painter = painter;
  7072. var handlerProxy = (!env.node && !env.worker && !ssrMode)
  7073. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7074. : null;
  7075. var useCoarsePointer = opts.useCoarsePointer;
  7076. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7077. ? env.touchEventsSupported
  7078. : !!useCoarsePointer;
  7079. var defaultPointerSize = 44;
  7080. var pointerSize;
  7081. if (usePointerSize) {
  7082. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7083. }
  7084. this.handler = new Handler(storage, painter, handlerProxy, painter.root, pointerSize);
  7085. this.animation = new Animation({
  7086. stage: {
  7087. update: ssrMode ? null : function () { return _this._flush(true); }
  7088. }
  7089. });
  7090. if (!ssrMode) {
  7091. this.animation.start();
  7092. }
  7093. }
  7094. ZRender.prototype.add = function (el) {
  7095. if (this._disposed || !el) {
  7096. return;
  7097. }
  7098. this.storage.addRoot(el);
  7099. el.addSelfToZr(this);
  7100. this.refresh();
  7101. };
  7102. ZRender.prototype.remove = function (el) {
  7103. if (this._disposed || !el) {
  7104. return;
  7105. }
  7106. this.storage.delRoot(el);
  7107. el.removeSelfFromZr(this);
  7108. this.refresh();
  7109. };
  7110. ZRender.prototype.configLayer = function (zLevel, config) {
  7111. if (this._disposed) {
  7112. return;
  7113. }
  7114. if (this.painter.configLayer) {
  7115. this.painter.configLayer(zLevel, config);
  7116. }
  7117. this.refresh();
  7118. };
  7119. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7120. if (this._disposed) {
  7121. return;
  7122. }
  7123. if (this.painter.setBackgroundColor) {
  7124. this.painter.setBackgroundColor(backgroundColor);
  7125. }
  7126. this.refresh();
  7127. this._backgroundColor = backgroundColor;
  7128. this._darkMode = isDarkMode(backgroundColor);
  7129. };
  7130. ZRender.prototype.getBackgroundColor = function () {
  7131. return this._backgroundColor;
  7132. };
  7133. ZRender.prototype.setDarkMode = function (darkMode) {
  7134. this._darkMode = darkMode;
  7135. };
  7136. ZRender.prototype.isDarkMode = function () {
  7137. return this._darkMode;
  7138. };
  7139. ZRender.prototype.refreshImmediately = function (fromInside) {
  7140. if (this._disposed) {
  7141. return;
  7142. }
  7143. if (!fromInside) {
  7144. this.animation.update(true);
  7145. }
  7146. this._needsRefresh = false;
  7147. this.painter.refresh();
  7148. this._needsRefresh = false;
  7149. };
  7150. ZRender.prototype.refresh = function () {
  7151. if (this._disposed) {
  7152. return;
  7153. }
  7154. this._needsRefresh = true;
  7155. this.animation.start();
  7156. };
  7157. ZRender.prototype.flush = function () {
  7158. if (this._disposed) {
  7159. return;
  7160. }
  7161. this._flush(false);
  7162. };
  7163. ZRender.prototype._flush = function (fromInside) {
  7164. var triggerRendered;
  7165. var start = getTime();
  7166. if (this._needsRefresh) {
  7167. triggerRendered = true;
  7168. this.refreshImmediately(fromInside);
  7169. }
  7170. if (this._needsRefreshHover) {
  7171. triggerRendered = true;
  7172. this.refreshHoverImmediately();
  7173. }
  7174. var end = getTime();
  7175. if (triggerRendered) {
  7176. this._stillFrameAccum = 0;
  7177. this.trigger('rendered', {
  7178. elapsedTime: end - start
  7179. });
  7180. }
  7181. else if (this._sleepAfterStill > 0) {
  7182. this._stillFrameAccum++;
  7183. if (this._stillFrameAccum > this._sleepAfterStill) {
  7184. this.animation.stop();
  7185. }
  7186. }
  7187. };
  7188. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7189. this._sleepAfterStill = stillFramesCount;
  7190. };
  7191. ZRender.prototype.wakeUp = function () {
  7192. if (this._disposed) {
  7193. return;
  7194. }
  7195. this.animation.start();
  7196. this._stillFrameAccum = 0;
  7197. };
  7198. ZRender.prototype.refreshHover = function () {
  7199. this._needsRefreshHover = true;
  7200. };
  7201. ZRender.prototype.refreshHoverImmediately = function () {
  7202. if (this._disposed) {
  7203. return;
  7204. }
  7205. this._needsRefreshHover = false;
  7206. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7207. this.painter.refreshHover();
  7208. }
  7209. };
  7210. ZRender.prototype.resize = function (opts) {
  7211. if (this._disposed) {
  7212. return;
  7213. }
  7214. opts = opts || {};
  7215. this.painter.resize(opts.width, opts.height);
  7216. this.handler.resize();
  7217. };
  7218. ZRender.prototype.clearAnimation = function () {
  7219. if (this._disposed) {
  7220. return;
  7221. }
  7222. this.animation.clear();
  7223. };
  7224. ZRender.prototype.getWidth = function () {
  7225. if (this._disposed) {
  7226. return;
  7227. }
  7228. return this.painter.getWidth();
  7229. };
  7230. ZRender.prototype.getHeight = function () {
  7231. if (this._disposed) {
  7232. return;
  7233. }
  7234. return this.painter.getHeight();
  7235. };
  7236. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7237. if (this._disposed) {
  7238. return;
  7239. }
  7240. this.handler.setCursorStyle(cursorStyle);
  7241. };
  7242. ZRender.prototype.findHover = function (x, y) {
  7243. if (this._disposed) {
  7244. return;
  7245. }
  7246. return this.handler.findHover(x, y);
  7247. };
  7248. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7249. if (!this._disposed) {
  7250. this.handler.on(eventName, eventHandler, context);
  7251. }
  7252. return this;
  7253. };
  7254. ZRender.prototype.off = function (eventName, eventHandler) {
  7255. if (this._disposed) {
  7256. return;
  7257. }
  7258. this.handler.off(eventName, eventHandler);
  7259. };
  7260. ZRender.prototype.trigger = function (eventName, event) {
  7261. if (this._disposed) {
  7262. return;
  7263. }
  7264. this.handler.trigger(eventName, event);
  7265. };
  7266. ZRender.prototype.clear = function () {
  7267. if (this._disposed) {
  7268. return;
  7269. }
  7270. var roots = this.storage.getRoots();
  7271. for (var i = 0; i < roots.length; i++) {
  7272. if (roots[i] instanceof Group) {
  7273. roots[i].removeSelfFromZr(this);
  7274. }
  7275. }
  7276. this.storage.delAllRoots();
  7277. this.painter.clear();
  7278. };
  7279. ZRender.prototype.dispose = function () {
  7280. if (this._disposed) {
  7281. return;
  7282. }
  7283. this.animation.stop();
  7284. this.clear();
  7285. this.storage.dispose();
  7286. this.painter.dispose();
  7287. this.handler.dispose();
  7288. this.animation =
  7289. this.storage =
  7290. this.painter =
  7291. this.handler = null;
  7292. this._disposed = true;
  7293. delInstance(this.id);
  7294. };
  7295. return ZRender;
  7296. }());
  7297. function init(dom, opts) {
  7298. var zr = new ZRender(guid(), dom, opts);
  7299. instances[zr.id] = zr;
  7300. return zr;
  7301. }
  7302. function dispose(zr) {
  7303. zr.dispose();
  7304. }
  7305. function disposeAll() {
  7306. for (var key in instances) {
  7307. if (instances.hasOwnProperty(key)) {
  7308. instances[key].dispose();
  7309. }
  7310. }
  7311. instances = {};
  7312. }
  7313. function getInstance(id) {
  7314. return instances[id];
  7315. }
  7316. function registerPainter(name, Ctor) {
  7317. painterCtors[name] = Ctor;
  7318. }
  7319. var ssrDataGetter;
  7320. function getElementSSRData(el) {
  7321. if (typeof ssrDataGetter === 'function') {
  7322. return ssrDataGetter(el);
  7323. }
  7324. }
  7325. function registerSSRDataGetter(getter) {
  7326. ssrDataGetter = getter;
  7327. }
  7328. var version = '5.6.0';
  7329. var zrender = /*#__PURE__*/Object.freeze({
  7330. __proto__: null,
  7331. init: init,
  7332. dispose: dispose,
  7333. disposeAll: disposeAll,
  7334. getInstance: getInstance,
  7335. registerPainter: registerPainter,
  7336. getElementSSRData: getElementSSRData,
  7337. registerSSRDataGetter: registerSSRDataGetter,
  7338. version: version
  7339. });
  7340. var RADIAN_EPSILON = 1e-4;
  7341. // Although chrome already enlarge this number to 100 for `toFixed`, but
  7342. // we sill follow the spec for compatibility.
  7343. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7344. function _trim(str) {
  7345. return str.replace(/^\s+|\s+$/g, '');
  7346. }
  7347. /**
  7348. * Linear mapping a value from domain to range
  7349. * @param val
  7350. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7351. * @param range Range extent range[0] can be bigger than range[1]
  7352. * @param clamp Default to be false
  7353. */
  7354. function linearMap(val, domain, range, clamp) {
  7355. var d0 = domain[0];
  7356. var d1 = domain[1];
  7357. var r0 = range[0];
  7358. var r1 = range[1];
  7359. var subDomain = d1 - d0;
  7360. var subRange = r1 - r0;
  7361. if (subDomain === 0) {
  7362. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7363. }
  7364. // Avoid accuracy problem in edge, such as
  7365. // 146.39 - 62.83 === 83.55999999999999.
  7366. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7367. // It is a little verbose for efficiency considering this method
  7368. // is a hotspot.
  7369. if (clamp) {
  7370. if (subDomain > 0) {
  7371. if (val <= d0) {
  7372. return r0;
  7373. } else if (val >= d1) {
  7374. return r1;
  7375. }
  7376. } else {
  7377. if (val >= d0) {
  7378. return r0;
  7379. } else if (val <= d1) {
  7380. return r1;
  7381. }
  7382. }
  7383. } else {
  7384. if (val === d0) {
  7385. return r0;
  7386. }
  7387. if (val === d1) {
  7388. return r1;
  7389. }
  7390. }
  7391. return (val - d0) / subDomain * subRange + r0;
  7392. }
  7393. /**
  7394. * Convert a percent string to absolute number.
  7395. * Returns NaN if percent is not a valid string or number
  7396. */
  7397. function parsePercent$1(percent, all) {
  7398. switch (percent) {
  7399. case 'center':
  7400. case 'middle':
  7401. percent = '50%';
  7402. break;
  7403. case 'left':
  7404. case 'top':
  7405. percent = '0%';
  7406. break;
  7407. case 'right':
  7408. case 'bottom':
  7409. percent = '100%';
  7410. break;
  7411. }
  7412. if (isString(percent)) {
  7413. if (_trim(percent).match(/%$/)) {
  7414. return parseFloat(percent) / 100 * all;
  7415. }
  7416. return parseFloat(percent);
  7417. }
  7418. return percent == null ? NaN : +percent;
  7419. }
  7420. function round(x, precision, returnStr) {
  7421. if (precision == null) {
  7422. precision = 10;
  7423. }
  7424. // Avoid range error
  7425. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX);
  7426. // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7427. x = (+x).toFixed(precision);
  7428. return returnStr ? x : +x;
  7429. }
  7430. /**
  7431. * Inplacd asc sort arr.
  7432. * The input arr will be modified.
  7433. */
  7434. function asc(arr) {
  7435. arr.sort(function (a, b) {
  7436. return a - b;
  7437. });
  7438. return arr;
  7439. }
  7440. /**
  7441. * Get precision.
  7442. */
  7443. function getPrecision(val) {
  7444. val = +val;
  7445. if (isNaN(val)) {
  7446. return 0;
  7447. }
  7448. // It is much faster than methods converting number to string as follows
  7449. // let tmp = val.toString();
  7450. // return tmp.length - 1 - tmp.indexOf('.');
  7451. // especially when precision is low
  7452. // Notice:
  7453. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7454. // (see https://jsbench.me/2vkpcekkvw/1)
  7455. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7456. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7457. if (val > 1e-14) {
  7458. var e = 1;
  7459. for (var i = 0; i < 15; i++, e *= 10) {
  7460. if (Math.round(val * e) / e === val) {
  7461. return i;
  7462. }
  7463. }
  7464. }
  7465. return getPrecisionSafe(val);
  7466. }
  7467. /**
  7468. * Get precision with slow but safe method
  7469. */
  7470. function getPrecisionSafe(val) {
  7471. // toLowerCase for: '3.4E-12'
  7472. var str = val.toString().toLowerCase();
  7473. // Consider scientific notation: '3.4e-12' '3.4e+12'
  7474. var eIndex = str.indexOf('e');
  7475. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7476. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7477. var dotIndex = str.indexOf('.');
  7478. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7479. return Math.max(0, decimalPartLen - exp);
  7480. }
  7481. /**
  7482. * Minimal dicernible data precisioin according to a single pixel.
  7483. */
  7484. function getPixelPrecision(dataExtent, pixelExtent) {
  7485. var log = Math.log;
  7486. var LN10 = Math.LN10;
  7487. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7488. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  7489. // toFixed() digits argument must be between 0 and 20.
  7490. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7491. return !isFinite(precision) ? 20 : precision;
  7492. }
  7493. /**
  7494. * Get a data of given precision, assuring the sum of percentages
  7495. * in valueList is 1.
  7496. * The largest remainder method is used.
  7497. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7498. *
  7499. * @param valueList a list of all data
  7500. * @param idx index of the data to be processed in valueList
  7501. * @param precision integer number showing digits of precision
  7502. * @return percent ranging from 0 to 100
  7503. */
  7504. function getPercentWithPrecision(valueList, idx, precision) {
  7505. if (!valueList[idx]) {
  7506. return 0;
  7507. }
  7508. var seats = getPercentSeats(valueList, precision);
  7509. return seats[idx] || 0;
  7510. }
  7511. /**
  7512. * Get a data of given precision, assuring the sum of percentages
  7513. * in valueList is 1.
  7514. * The largest remainder method is used.
  7515. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7516. *
  7517. * @param valueList a list of all data
  7518. * @param precision integer number showing digits of precision
  7519. * @return {Array<number>}
  7520. */
  7521. function getPercentSeats(valueList, precision) {
  7522. var sum = reduce(valueList, function (acc, val) {
  7523. return acc + (isNaN(val) ? 0 : val);
  7524. }, 0);
  7525. if (sum === 0) {
  7526. return [];
  7527. }
  7528. var digits = Math.pow(10, precision);
  7529. var votesPerQuota = map(valueList, function (val) {
  7530. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7531. });
  7532. var targetSeats = digits * 100;
  7533. var seats = map(votesPerQuota, function (votes) {
  7534. // Assign automatic seats.
  7535. return Math.floor(votes);
  7536. });
  7537. var currentSum = reduce(seats, function (acc, val) {
  7538. return acc + val;
  7539. }, 0);
  7540. var remainder = map(votesPerQuota, function (votes, idx) {
  7541. return votes - seats[idx];
  7542. });
  7543. // Has remainding votes.
  7544. while (currentSum < targetSeats) {
  7545. // Find next largest remainder.
  7546. var max = Number.NEGATIVE_INFINITY;
  7547. var maxId = null;
  7548. for (var i = 0, len = remainder.length; i < len; ++i) {
  7549. if (remainder[i] > max) {
  7550. max = remainder[i];
  7551. maxId = i;
  7552. }
  7553. }
  7554. // Add a vote to max remainder.
  7555. ++seats[maxId];
  7556. remainder[maxId] = 0;
  7557. ++currentSum;
  7558. }
  7559. return map(seats, function (seat) {
  7560. return seat / digits;
  7561. });
  7562. }
  7563. /**
  7564. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7565. * See <http://0.30000000000000004.com/>
  7566. */
  7567. function addSafe(val0, val1) {
  7568. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1));
  7569. // const multiplier = Math.pow(10, maxPrecision);
  7570. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7571. var sum = val0 + val1;
  7572. // // PENDING: support more?
  7573. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7574. }
  7575. // Number.MAX_SAFE_INTEGER, ie do not support.
  7576. var MAX_SAFE_INTEGER = 9007199254740991;
  7577. /**
  7578. * To 0 - 2 * PI, considering negative radian.
  7579. */
  7580. function remRadian(radian) {
  7581. var pi2 = Math.PI * 2;
  7582. return (radian % pi2 + pi2) % pi2;
  7583. }
  7584. /**
  7585. * @param {type} radian
  7586. * @return {boolean}
  7587. */
  7588. function isRadianAroundZero(val) {
  7589. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7590. }
  7591. // eslint-disable-next-line
  7592. 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
  7593. /**
  7594. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7595. * These values can be accepted:
  7596. * + An instance of Date, represent a time in its own time zone.
  7597. * + Or string in a subset of ISO 8601, only including:
  7598. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7599. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7600. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7601. * all of which will be treated as local time if time zone is not specified
  7602. * (see <https://momentjs.com/>).
  7603. * + Or other string format, including (all of which will be treated as local time):
  7604. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7605. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7606. * + a timestamp, which represent a time in UTC.
  7607. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7608. */
  7609. function parseDate(value) {
  7610. if (value instanceof Date) {
  7611. return value;
  7612. } else if (isString(value)) {
  7613. // Different browsers parse date in different way, so we parse it manually.
  7614. // Some other issues:
  7615. // new Date('1970-01-01') is UTC,
  7616. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7617. // See issue #3623
  7618. var match = TIME_REG.exec(value);
  7619. if (!match) {
  7620. // return Invalid Date.
  7621. return new Date(NaN);
  7622. }
  7623. // Use local time when no timezone offset is specified.
  7624. if (!match[8]) {
  7625. // match[n] can only be string or undefined.
  7626. // But take care of '12' + 1 => '121'.
  7627. 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);
  7628. }
  7629. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7630. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7631. // For example, system timezone is set as "Time Zone: America/Toronto",
  7632. // then these code will get different result:
  7633. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7634. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7635. // So we should not use `new Date`, but use `Date.UTC`.
  7636. else {
  7637. var hour = +match[4] || 0;
  7638. if (match[8].toUpperCase() !== 'Z') {
  7639. hour -= +match[8].slice(0, 3);
  7640. }
  7641. 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));
  7642. }
  7643. } else if (value == null) {
  7644. return new Date(NaN);
  7645. }
  7646. return new Date(Math.round(value));
  7647. }
  7648. /**
  7649. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7650. *
  7651. * @param val
  7652. * @return
  7653. */
  7654. function quantity(val) {
  7655. return Math.pow(10, quantityExponent(val));
  7656. }
  7657. /**
  7658. * Exponent of the quantity of a number
  7659. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7660. *
  7661. * @param val non-negative value
  7662. * @return
  7663. */
  7664. function quantityExponent(val) {
  7665. if (val === 0) {
  7666. return 0;
  7667. }
  7668. var exp = Math.floor(Math.log(val) / Math.LN10);
  7669. /**
  7670. * exp is expected to be the rounded-down result of the base-10 log of val.
  7671. * But due to the precision loss with Math.log(val), we need to restore it
  7672. * using 10^exp to make sure we can get val back from exp. #11249
  7673. */
  7674. if (val / Math.pow(10, exp) >= 10) {
  7675. exp++;
  7676. }
  7677. return exp;
  7678. }
  7679. /**
  7680. * find a “nice” number approximately equal to x. Round the number if round = true,
  7681. * take ceiling if round = false. The primary observation is that the “nicest”
  7682. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7683. *
  7684. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7685. *
  7686. * @param val Non-negative value.
  7687. * @param round
  7688. * @return Niced number
  7689. */
  7690. function nice(val, round) {
  7691. var exponent = quantityExponent(val);
  7692. var exp10 = Math.pow(10, exponent);
  7693. var f = val / exp10; // 1 <= f < 10
  7694. var nf;
  7695. if (round) {
  7696. if (f < 1.5) {
  7697. nf = 1;
  7698. } else if (f < 2.5) {
  7699. nf = 2;
  7700. } else if (f < 4) {
  7701. nf = 3;
  7702. } else if (f < 7) {
  7703. nf = 5;
  7704. } else {
  7705. nf = 10;
  7706. }
  7707. } else {
  7708. if (f < 1) {
  7709. nf = 1;
  7710. } else if (f < 2) {
  7711. nf = 2;
  7712. } else if (f < 3) {
  7713. nf = 3;
  7714. } else if (f < 5) {
  7715. nf = 5;
  7716. } else {
  7717. nf = 10;
  7718. }
  7719. }
  7720. val = nf * exp10;
  7721. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7722. // 20 is the uppper bound of toFixed.
  7723. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7724. }
  7725. /**
  7726. * This code was copied from "d3.js"
  7727. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7728. * See the license statement at the head of this file.
  7729. * @param ascArr
  7730. */
  7731. function quantile(ascArr, p) {
  7732. var H = (ascArr.length - 1) * p + 1;
  7733. var h = Math.floor(H);
  7734. var v = +ascArr[h - 1];
  7735. var e = H - h;
  7736. return e ? v + e * (ascArr[h] - v) : v;
  7737. }
  7738. /**
  7739. * Order intervals asc, and split them when overlap.
  7740. * expect(numberUtil.reformIntervals([
  7741. * {interval: [18, 62], close: [1, 1]},
  7742. * {interval: [-Infinity, -70], close: [0, 0]},
  7743. * {interval: [-70, -26], close: [1, 1]},
  7744. * {interval: [-26, 18], close: [1, 1]},
  7745. * {interval: [62, 150], close: [1, 1]},
  7746. * {interval: [106, 150], close: [1, 1]},
  7747. * {interval: [150, Infinity], close: [0, 0]}
  7748. * ])).toEqual([
  7749. * {interval: [-Infinity, -70], close: [0, 0]},
  7750. * {interval: [-70, -26], close: [1, 1]},
  7751. * {interval: [-26, 18], close: [0, 1]},
  7752. * {interval: [18, 62], close: [0, 1]},
  7753. * {interval: [62, 150], close: [0, 1]},
  7754. * {interval: [150, Infinity], close: [0, 0]}
  7755. * ]);
  7756. * @param list, where `close` mean open or close
  7757. * of the interval, and Infinity can be used.
  7758. * @return The origin list, which has been reformed.
  7759. */
  7760. function reformIntervals(list) {
  7761. list.sort(function (a, b) {
  7762. return littleThan(a, b, 0) ? -1 : 1;
  7763. });
  7764. var curr = -Infinity;
  7765. var currClose = 1;
  7766. for (var i = 0; i < list.length;) {
  7767. var interval = list[i].interval;
  7768. var close_1 = list[i].close;
  7769. for (var lg = 0; lg < 2; lg++) {
  7770. if (interval[lg] <= curr) {
  7771. interval[lg] = curr;
  7772. close_1[lg] = !lg ? 1 - currClose : 1;
  7773. }
  7774. curr = interval[lg];
  7775. currClose = close_1[lg];
  7776. }
  7777. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7778. list.splice(i, 1);
  7779. } else {
  7780. i++;
  7781. }
  7782. }
  7783. return list;
  7784. function littleThan(a, b, lg) {
  7785. 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));
  7786. }
  7787. }
  7788. /**
  7789. * [Numeric is defined as]:
  7790. * `parseFloat(val) == val`
  7791. * For example:
  7792. * numeric:
  7793. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7794. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7795. * not-numeric:
  7796. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7797. * empty string, string with only white-spaces or line-terminal (see es spec),
  7798. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7799. * non-string, ...
  7800. *
  7801. * @test See full test cases in `test/ut/spec/util/number.js`.
  7802. * @return Must be a typeof number. If not numeric, return NaN.
  7803. */
  7804. function numericToNumber(val) {
  7805. var valFloat = parseFloat(val);
  7806. return valFloat == val // eslint-disable-line eqeqeq
  7807. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7808. ? valFloat : NaN;
  7809. }
  7810. /**
  7811. * Definition of "numeric": see `numericToNumber`.
  7812. */
  7813. function isNumeric(val) {
  7814. return !isNaN(numericToNumber(val));
  7815. }
  7816. /**
  7817. * Use random base to prevent users hard code depending on
  7818. * this auto generated marker id.
  7819. * @return An positive integer.
  7820. */
  7821. function getRandomIdBase() {
  7822. return Math.round(Math.random() * 9);
  7823. }
  7824. /**
  7825. * Get the greatest common divisor.
  7826. *
  7827. * @param {number} a one number
  7828. * @param {number} b the other number
  7829. */
  7830. function getGreatestCommonDividor(a, b) {
  7831. if (b === 0) {
  7832. return a;
  7833. }
  7834. return getGreatestCommonDividor(b, a % b);
  7835. }
  7836. /**
  7837. * Get the least common multiple.
  7838. *
  7839. * @param {number} a one number
  7840. * @param {number} b the other number
  7841. */
  7842. function getLeastCommonMultiple(a, b) {
  7843. if (a == null) {
  7844. return b;
  7845. }
  7846. if (b == null) {
  7847. return a;
  7848. }
  7849. return a * b / getGreatestCommonDividor(a, b);
  7850. }
  7851. var ECHARTS_PREFIX = '[ECharts] ';
  7852. var storedLogs = {};
  7853. var hasConsole = typeof console !== 'undefined'
  7854. // eslint-disable-next-line
  7855. && console.warn && console.log;
  7856. function outputLog(type, str, onlyOnce) {
  7857. if (hasConsole) {
  7858. if (onlyOnce) {
  7859. if (storedLogs[str]) {
  7860. return;
  7861. }
  7862. storedLogs[str] = true;
  7863. }
  7864. // eslint-disable-next-line
  7865. console[type](ECHARTS_PREFIX + str);
  7866. }
  7867. }
  7868. function log(str, onlyOnce) {
  7869. outputLog('log', str, onlyOnce);
  7870. }
  7871. function warn(str, onlyOnce) {
  7872. outputLog('warn', str, onlyOnce);
  7873. }
  7874. function error(str, onlyOnce) {
  7875. outputLog('error', str, onlyOnce);
  7876. }
  7877. function deprecateLog(str) {
  7878. if ("development" !== 'production') {
  7879. // Not display duplicate message.
  7880. outputLog('warn', 'DEPRECATED: ' + str, true);
  7881. }
  7882. }
  7883. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7884. if ("development" !== 'production') {
  7885. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7886. }
  7887. }
  7888. /**
  7889. * If in __DEV__ environment, get console printable message for users hint.
  7890. * Parameters are separated by ' '.
  7891. * @usage
  7892. * makePrintable('This is an error on', someVar, someObj);
  7893. *
  7894. * @param hintInfo anything about the current execution context to hint users.
  7895. * @throws Error
  7896. */
  7897. function makePrintable() {
  7898. var hintInfo = [];
  7899. for (var _i = 0; _i < arguments.length; _i++) {
  7900. hintInfo[_i] = arguments[_i];
  7901. }
  7902. var msg = '';
  7903. if ("development" !== 'production') {
  7904. // Fuzzy stringify for print.
  7905. // This code only exist in dev environment.
  7906. var makePrintableStringIfPossible_1 = function (val) {
  7907. 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;
  7908. };
  7909. msg = map(hintInfo, function (arg) {
  7910. if (isString(arg)) {
  7911. // Print without quotation mark for some statement.
  7912. return arg;
  7913. } else {
  7914. var printableStr = makePrintableStringIfPossible_1(arg);
  7915. if (printableStr != null) {
  7916. return printableStr;
  7917. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7918. try {
  7919. return JSON.stringify(arg, function (n, val) {
  7920. var printableStr = makePrintableStringIfPossible_1(val);
  7921. return printableStr == null ? val : printableStr;
  7922. });
  7923. // In most cases the info object is small, so do not line break.
  7924. } catch (err) {
  7925. return '?';
  7926. }
  7927. } else {
  7928. return '?';
  7929. }
  7930. }
  7931. }).join(' ');
  7932. }
  7933. return msg;
  7934. }
  7935. /**
  7936. * @throws Error
  7937. */
  7938. function throwError(msg) {
  7939. throw new Error(msg);
  7940. }
  7941. function interpolateNumber$1(p0, p1, percent) {
  7942. return (p1 - p0) * percent + p0;
  7943. }
  7944. /**
  7945. * Make the name displayable. But we should
  7946. * make sure it is not duplicated with user
  7947. * specified name, so use '\0';
  7948. */
  7949. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7950. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7951. /**
  7952. * If value is not array, then translate it to array.
  7953. * @param {*} value
  7954. * @return {Array} [value] or value
  7955. */
  7956. function normalizeToArray(value) {
  7957. return value instanceof Array ? value : value == null ? [] : [value];
  7958. }
  7959. /**
  7960. * Sync default option between normal and emphasis like `position` and `show`
  7961. * In case some one will write code like
  7962. * label: {
  7963. * show: false,
  7964. * position: 'outside',
  7965. * fontSize: 18
  7966. * },
  7967. * emphasis: {
  7968. * label: { show: true }
  7969. * }
  7970. */
  7971. function defaultEmphasis(opt, key, subOpts) {
  7972. // Caution: performance sensitive.
  7973. if (opt) {
  7974. opt[key] = opt[key] || {};
  7975. opt.emphasis = opt.emphasis || {};
  7976. opt.emphasis[key] = opt.emphasis[key] || {};
  7977. // Default emphasis option from normal
  7978. for (var i = 0, len = subOpts.length; i < len; i++) {
  7979. var subOptName = subOpts[i];
  7980. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7981. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7982. }
  7983. }
  7984. }
  7985. }
  7986. 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'];
  7987. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7988. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7989. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7990. // // FIXME: deprecated, check and remove it.
  7991. // 'textStyle'
  7992. // ]);
  7993. /**
  7994. * The method does not ensure performance.
  7995. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7996. * This helper method retrieves value from data.
  7997. */
  7998. function getDataItemValue(dataItem) {
  7999. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  8000. }
  8001. /**
  8002. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  8003. * This helper method determine if dataItem has extra option besides value
  8004. */
  8005. function isDataItemOption(dataItem) {
  8006. return isObject(dataItem) && !(dataItem instanceof Array);
  8007. // // markLine data can be array
  8008. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  8009. }
  8010. /**
  8011. * Mapping to existings for merge.
  8012. *
  8013. * Mode "normalMege":
  8014. * The mapping result (merge result) will keep the order of the existing
  8015. * component, rather than the order of new option. Because we should ensure
  8016. * some specified index reference (like xAxisIndex) keep work.
  8017. * And in most cases, "merge option" is used to update partial option but not
  8018. * be expected to change the order.
  8019. *
  8020. * Mode "replaceMege":
  8021. * (1) Only the id mapped components will be merged.
  8022. * (2) Other existing components (except internal components) will be removed.
  8023. * (3) Other new options will be used to create new component.
  8024. * (4) The index of the existing components will not be modified.
  8025. * That means their might be "hole" after the removal.
  8026. * The new components are created first at those available index.
  8027. *
  8028. * Mode "replaceAll":
  8029. * This mode try to support that reproduce an echarts instance from another
  8030. * echarts instance (via `getOption`) in some simple cases.
  8031. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  8032. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  8033. * the "hole" in `newCmptOptions` will also be kept.
  8034. * On the contrary, other modes try best to eliminate holes.
  8035. * PENDING: This is an experimental mode yet.
  8036. *
  8037. * @return See the comment of <MappingResult>.
  8038. */
  8039. function mappingToExists(existings, newCmptOptions, mode) {
  8040. var isNormalMergeMode = mode === 'normalMerge';
  8041. var isReplaceMergeMode = mode === 'replaceMerge';
  8042. var isReplaceAllMode = mode === 'replaceAll';
  8043. existings = existings || [];
  8044. newCmptOptions = (newCmptOptions || []).slice();
  8045. var existingIdIdxMap = createHashMap();
  8046. // Validate id and name on user input option.
  8047. each(newCmptOptions, function (cmptOption, index) {
  8048. if (!isObject(cmptOption)) {
  8049. newCmptOptions[index] = null;
  8050. return;
  8051. }
  8052. if ("development" !== 'production') {
  8053. // There is some legacy case that name is set as `false`.
  8054. // But should work normally rather than throw error.
  8055. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  8056. warnInvalidateIdOrName(cmptOption.id);
  8057. }
  8058. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  8059. warnInvalidateIdOrName(cmptOption.name);
  8060. }
  8061. }
  8062. });
  8063. var result = prepareResult(existings, existingIdIdxMap, mode);
  8064. if (isNormalMergeMode || isReplaceMergeMode) {
  8065. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  8066. }
  8067. if (isNormalMergeMode) {
  8068. mappingByName(result, newCmptOptions);
  8069. }
  8070. if (isNormalMergeMode || isReplaceMergeMode) {
  8071. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  8072. } else if (isReplaceAllMode) {
  8073. mappingInReplaceAllMode(result, newCmptOptions);
  8074. }
  8075. makeIdAndName(result);
  8076. // The array `result` MUST NOT contain elided items, otherwise the
  8077. // forEach will omit those items and result in incorrect result.
  8078. return result;
  8079. }
  8080. function prepareResult(existings, existingIdIdxMap, mode) {
  8081. var result = [];
  8082. if (mode === 'replaceAll') {
  8083. return result;
  8084. }
  8085. // Do not use native `map` to in case that the array `existings`
  8086. // contains elided items, which will be omitted.
  8087. for (var index = 0; index < existings.length; index++) {
  8088. var existing = existings[index];
  8089. // Because of replaceMerge, `existing` may be null/undefined.
  8090. if (existing && existing.id != null) {
  8091. existingIdIdxMap.set(existing.id, index);
  8092. }
  8093. // For non-internal-componnets:
  8094. // Mode "normalMerge": all existings kept.
  8095. // Mode "replaceMerge": all existing removed unless mapped by id.
  8096. // For internal-components:
  8097. // go with "replaceMerge" approach in both mode.
  8098. result.push({
  8099. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  8100. newOption: null,
  8101. keyInfo: null,
  8102. brandNew: null
  8103. });
  8104. }
  8105. return result;
  8106. }
  8107. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  8108. // Mapping by id if specified.
  8109. each(newCmptOptions, function (cmptOption, index) {
  8110. if (!cmptOption || cmptOption.id == null) {
  8111. return;
  8112. }
  8113. var optionId = makeComparableKey(cmptOption.id);
  8114. var existingIdx = existingIdIdxMap.get(optionId);
  8115. if (existingIdx != null) {
  8116. var resultItem = result[existingIdx];
  8117. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  8118. resultItem.newOption = cmptOption;
  8119. // In both mode, if id matched, new option will be merged to
  8120. // the existings rather than creating new component model.
  8121. resultItem.existing = existings[existingIdx];
  8122. newCmptOptions[index] = null;
  8123. }
  8124. });
  8125. }
  8126. function mappingByName(result, newCmptOptions) {
  8127. // Mapping by name if specified.
  8128. each(newCmptOptions, function (cmptOption, index) {
  8129. if (!cmptOption || cmptOption.name == null) {
  8130. return;
  8131. }
  8132. for (var i = 0; i < result.length; i++) {
  8133. var existing = result[i].existing;
  8134. if (!result[i].newOption // Consider name: two map to one.
  8135. // Can not match when both ids existing but different.
  8136. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8137. result[i].newOption = cmptOption;
  8138. newCmptOptions[index] = null;
  8139. return;
  8140. }
  8141. }
  8142. });
  8143. }
  8144. function mappingByIndex(result, newCmptOptions, brandNew) {
  8145. each(newCmptOptions, function (cmptOption) {
  8146. if (!cmptOption) {
  8147. return;
  8148. }
  8149. // Find the first place that not mapped by id and not internal component (consider the "hole").
  8150. var resultItem;
  8151. var nextIdx = 0;
  8152. while (
  8153. // Be `!resultItem` only when `nextIdx >= result.length`.
  8154. (resultItem = result[nextIdx]
  8155. // (1) Existing models that already have id should be able to mapped to. Because
  8156. // after mapping performed, model will always be assigned with an id if user not given.
  8157. // After that all models have id.
  8158. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8159. // not be merged to the existings with different id. Because id should not be overwritten.
  8160. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8161. ) && (resultItem.newOption || isComponentIdInternal(resultItem.existing) ||
  8162. // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8163. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8164. nextIdx++;
  8165. }
  8166. if (resultItem) {
  8167. resultItem.newOption = cmptOption;
  8168. resultItem.brandNew = brandNew;
  8169. } else {
  8170. result.push({
  8171. newOption: cmptOption,
  8172. brandNew: brandNew,
  8173. existing: null,
  8174. keyInfo: null
  8175. });
  8176. }
  8177. nextIdx++;
  8178. });
  8179. }
  8180. function mappingInReplaceAllMode(result, newCmptOptions) {
  8181. each(newCmptOptions, function (cmptOption) {
  8182. // The feature "reproduce" requires "hole" will also reproduced
  8183. // in case that component index referring are broken.
  8184. result.push({
  8185. newOption: cmptOption,
  8186. brandNew: true,
  8187. existing: null,
  8188. keyInfo: null
  8189. });
  8190. });
  8191. }
  8192. /**
  8193. * Make id and name for mapping result (result of mappingToExists)
  8194. * into `keyInfo` field.
  8195. */
  8196. function makeIdAndName(mapResult) {
  8197. // We use this id to hash component models and view instances
  8198. // in echarts. id can be specified by user, or auto generated.
  8199. // The id generation rule ensures new view instance are able
  8200. // to mapped to old instance when setOption are called in
  8201. // no-merge mode. So we generate model id by name and plus
  8202. // type in view id.
  8203. // name can be duplicated among components, which is convenient
  8204. // to specify multi components (like series) by one name.
  8205. // Ensure that each id is distinct.
  8206. var idMap = createHashMap();
  8207. each(mapResult, function (item) {
  8208. var existing = item.existing;
  8209. existing && idMap.set(existing.id, item);
  8210. });
  8211. each(mapResult, function (item) {
  8212. var opt = item.newOption;
  8213. // Force ensure id not duplicated.
  8214. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8215. opt && opt.id != null && idMap.set(opt.id, item);
  8216. !item.keyInfo && (item.keyInfo = {});
  8217. });
  8218. // Make name and id.
  8219. each(mapResult, function (item, index) {
  8220. var existing = item.existing;
  8221. var opt = item.newOption;
  8222. var keyInfo = item.keyInfo;
  8223. if (!isObject(opt)) {
  8224. return;
  8225. }
  8226. // Name can be overwritten. Consider case: axis.name = '20km'.
  8227. // But id generated by name will not be changed, which affect
  8228. // only in that case: setOption with 'not merge mode' and view
  8229. // instance will be recreated, which can be accepted.
  8230. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name
  8231. // Avoid that different series has the same name,
  8232. // because name may be used like in color pallet.
  8233. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8234. if (existing) {
  8235. keyInfo.id = makeComparableKey(existing.id);
  8236. } else if (opt.id != null) {
  8237. keyInfo.id = makeComparableKey(opt.id);
  8238. } else {
  8239. // Consider this situatoin:
  8240. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8241. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8242. // Series with the same name between optionA and optionB
  8243. // should be mapped.
  8244. var idNum = 0;
  8245. do {
  8246. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8247. } while (idMap.get(keyInfo.id));
  8248. }
  8249. idMap.set(keyInfo.id, item);
  8250. });
  8251. }
  8252. function keyExistAndEqual(attr, obj1, obj2) {
  8253. var key1 = convertOptionIdName(obj1[attr], null);
  8254. var key2 = convertOptionIdName(obj2[attr], null);
  8255. // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8256. return key1 != null && key2 != null && key1 === key2;
  8257. }
  8258. /**
  8259. * @return return null if not exist.
  8260. */
  8261. function makeComparableKey(val) {
  8262. if ("development" !== 'production') {
  8263. if (val == null) {
  8264. throw new Error();
  8265. }
  8266. }
  8267. return convertOptionIdName(val, '');
  8268. }
  8269. function convertOptionIdName(idOrName, defaultValue) {
  8270. if (idOrName == null) {
  8271. return defaultValue;
  8272. }
  8273. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8274. }
  8275. function warnInvalidateIdOrName(idOrName) {
  8276. if ("development" !== 'production') {
  8277. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8278. }
  8279. }
  8280. function isValidIdOrName(idOrName) {
  8281. return isStringSafe(idOrName) || isNumeric(idOrName);
  8282. }
  8283. function isNameSpecified(componentModel) {
  8284. var name = componentModel.name;
  8285. // Is specified when `indexOf` get -1 or > 0.
  8286. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8287. }
  8288. /**
  8289. * @public
  8290. * @param {Object} cmptOption
  8291. * @return {boolean}
  8292. */
  8293. function isComponentIdInternal(cmptOption) {
  8294. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8295. }
  8296. function makeInternalComponentId(idSuffix) {
  8297. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8298. }
  8299. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8300. // Set mainType and complete subType.
  8301. each(mappingResult, function (item) {
  8302. var newOption = item.newOption;
  8303. if (isObject(newOption)) {
  8304. item.keyInfo.mainType = mainType;
  8305. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8306. }
  8307. });
  8308. }
  8309. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8310. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType
  8311. // Use determineSubType only when there is no existComponent.
  8312. : componentModelCtor.determineSubType(mainType, newCmptOption);
  8313. // tooltip, markline, markpoint may always has no subType
  8314. return subType;
  8315. }
  8316. /**
  8317. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8318. * each of which can be Array or primary type.
  8319. * @return dataIndex If not found, return undefined/null.
  8320. */
  8321. function queryDataIndex(data, payload) {
  8322. if (payload.dataIndexInside != null) {
  8323. return payload.dataIndexInside;
  8324. } else if (payload.dataIndex != null) {
  8325. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8326. return data.indexOfRawIndex(value);
  8327. }) : data.indexOfRawIndex(payload.dataIndex);
  8328. } else if (payload.name != null) {
  8329. return isArray(payload.name) ? map(payload.name, function (value) {
  8330. return data.indexOfName(value);
  8331. }) : data.indexOfName(payload.name);
  8332. }
  8333. }
  8334. /**
  8335. * Enable property storage to any host object.
  8336. * Notice: Serialization is not supported.
  8337. *
  8338. * For example:
  8339. * let inner = zrUitl.makeInner();
  8340. *
  8341. * function some1(hostObj) {
  8342. * inner(hostObj).someProperty = 1212;
  8343. * ...
  8344. * }
  8345. * function some2() {
  8346. * let fields = inner(this);
  8347. * fields.someProperty1 = 1212;
  8348. * fields.someProperty2 = 'xx';
  8349. * ...
  8350. * }
  8351. *
  8352. * @return {Function}
  8353. */
  8354. function makeInner() {
  8355. var key = '__ec_inner_' + innerUniqueIndex++;
  8356. return function (hostObj) {
  8357. return hostObj[key] || (hostObj[key] = {});
  8358. };
  8359. }
  8360. var innerUniqueIndex = getRandomIdBase();
  8361. /**
  8362. * The same behavior as `component.getReferringComponents`.
  8363. */
  8364. function parseFinder(ecModel, finderInput, opt) {
  8365. var _a = preParseFinder(finderInput, opt),
  8366. mainTypeSpecified = _a.mainTypeSpecified,
  8367. queryOptionMap = _a.queryOptionMap,
  8368. others = _a.others;
  8369. var result = others;
  8370. var defaultMainType = opt ? opt.defaultMainType : null;
  8371. if (!mainTypeSpecified && defaultMainType) {
  8372. queryOptionMap.set(defaultMainType, {});
  8373. }
  8374. queryOptionMap.each(function (queryOption, mainType) {
  8375. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8376. useDefault: defaultMainType === mainType,
  8377. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8378. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8379. });
  8380. result[mainType + 'Models'] = queryResult.models;
  8381. result[mainType + 'Model'] = queryResult.models[0];
  8382. });
  8383. return result;
  8384. }
  8385. function preParseFinder(finderInput, opt) {
  8386. var finder;
  8387. if (isString(finderInput)) {
  8388. var obj = {};
  8389. obj[finderInput + 'Index'] = 0;
  8390. finder = obj;
  8391. } else {
  8392. finder = finderInput;
  8393. }
  8394. var queryOptionMap = createHashMap();
  8395. var others = {};
  8396. var mainTypeSpecified = false;
  8397. each(finder, function (value, key) {
  8398. // Exclude 'dataIndex' and other illgal keys.
  8399. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8400. others[key] = value;
  8401. return;
  8402. }
  8403. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8404. var mainType = parsedKey[1];
  8405. var queryType = (parsedKey[2] || '').toLowerCase();
  8406. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8407. return;
  8408. }
  8409. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8410. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8411. queryOption[queryType] = value;
  8412. });
  8413. return {
  8414. mainTypeSpecified: mainTypeSpecified,
  8415. queryOptionMap: queryOptionMap,
  8416. others: others
  8417. };
  8418. }
  8419. var SINGLE_REFERRING = {
  8420. useDefault: true,
  8421. enableAll: false,
  8422. enableNone: false
  8423. };
  8424. var MULTIPLE_REFERRING = {
  8425. useDefault: false,
  8426. enableAll: true,
  8427. enableNone: true
  8428. };
  8429. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8430. opt = opt || SINGLE_REFERRING;
  8431. var indexOption = userOption.index;
  8432. var idOption = userOption.id;
  8433. var nameOption = userOption.name;
  8434. var result = {
  8435. models: null,
  8436. specified: indexOption != null || idOption != null || nameOption != null
  8437. };
  8438. if (!result.specified) {
  8439. // Use the first as default if `useDefault`.
  8440. var firstCmpt = void 0;
  8441. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8442. return result;
  8443. }
  8444. if (indexOption === 'none' || indexOption === false) {
  8445. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8446. result.models = [];
  8447. return result;
  8448. }
  8449. // `queryComponents` will return all components if
  8450. // both all of index/id/name are null/undefined.
  8451. if (indexOption === 'all') {
  8452. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8453. indexOption = idOption = nameOption = null;
  8454. }
  8455. result.models = ecModel.queryComponents({
  8456. mainType: mainType,
  8457. index: indexOption,
  8458. id: idOption,
  8459. name: nameOption
  8460. });
  8461. return result;
  8462. }
  8463. function setAttribute(dom, key, value) {
  8464. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8465. }
  8466. function getAttribute(dom, key) {
  8467. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8468. }
  8469. function getTooltipRenderMode(renderModeOption) {
  8470. if (renderModeOption === 'auto') {
  8471. // Using html when `document` exists, use richText otherwise
  8472. return env.domSupported ? 'html' : 'richText';
  8473. } else {
  8474. return renderModeOption || 'html';
  8475. }
  8476. }
  8477. /**
  8478. * Interpolate raw values of a series with percent
  8479. *
  8480. * @param data data
  8481. * @param labelModel label model of the text element
  8482. * @param sourceValue start value. May be null/undefined when init.
  8483. * @param targetValue end value
  8484. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8485. * @return interpolated values
  8486. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8487. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8488. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8489. * Other cases do not supported.
  8490. */
  8491. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8492. var isAutoPrecision = precision == null || precision === 'auto';
  8493. if (targetValue == null) {
  8494. return targetValue;
  8495. }
  8496. if (isNumber(targetValue)) {
  8497. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8498. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8499. } else if (isString(targetValue)) {
  8500. return percent < 1 ? sourceValue : targetValue;
  8501. } else {
  8502. var interpolated = [];
  8503. var leftArr = sourceValue;
  8504. var rightArr = targetValue;
  8505. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8506. for (var i = 0; i < length_1; ++i) {
  8507. var info = data.getDimensionInfo(i);
  8508. // Don't interpolate ordinal dims
  8509. if (info && info.type === 'ordinal') {
  8510. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8511. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8512. } else {
  8513. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8514. var rightVal = rightArr[i];
  8515. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8516. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8517. }
  8518. }
  8519. return interpolated;
  8520. }
  8521. }
  8522. var TYPE_DELIMITER = '.';
  8523. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8524. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8525. /**
  8526. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8527. * @public
  8528. */
  8529. function parseClassType(componentType) {
  8530. var ret = {
  8531. main: '',
  8532. sub: ''
  8533. };
  8534. if (componentType) {
  8535. var typeArr = componentType.split(TYPE_DELIMITER);
  8536. ret.main = typeArr[0] || '';
  8537. ret.sub = typeArr[1] || '';
  8538. }
  8539. return ret;
  8540. }
  8541. /**
  8542. * @public
  8543. */
  8544. function checkClassType(componentType) {
  8545. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8546. }
  8547. function isExtendedClass(clz) {
  8548. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8549. }
  8550. /**
  8551. * Implements `ExtendableConstructor` for `rootClz`.
  8552. *
  8553. * @usage
  8554. * ```ts
  8555. * class Xxx {}
  8556. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8557. * enableClassExtend(Xxx as XxxConstructor);
  8558. * ```
  8559. */
  8560. function enableClassExtend(rootClz, mandatoryMethods) {
  8561. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8562. rootClz.extend = function (proto) {
  8563. if ("development" !== 'production') {
  8564. each(mandatoryMethods, function (method) {
  8565. if (!proto[method]) {
  8566. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8567. }
  8568. });
  8569. }
  8570. var superClass = this;
  8571. var ExtendedClass;
  8572. if (isESClass(superClass)) {
  8573. ExtendedClass = /** @class */function (_super) {
  8574. __extends(class_1, _super);
  8575. function class_1() {
  8576. return _super.apply(this, arguments) || this;
  8577. }
  8578. return class_1;
  8579. }(superClass);
  8580. } else {
  8581. // For backward compat, we both support ts class inheritance and this
  8582. // "extend" approach.
  8583. // The constructor should keep the same behavior as ts class inheritance:
  8584. // If this constructor/$constructor is not declared, auto invoke the super
  8585. // constructor.
  8586. // If this constructor/$constructor is declared, it is responsible for
  8587. // calling the super constructor.
  8588. ExtendedClass = function () {
  8589. (proto.$constructor || superClass).apply(this, arguments);
  8590. };
  8591. inherits(ExtendedClass, this);
  8592. }
  8593. extend(ExtendedClass.prototype, proto);
  8594. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8595. ExtendedClass.extend = this.extend;
  8596. ExtendedClass.superCall = superCall;
  8597. ExtendedClass.superApply = superApply;
  8598. ExtendedClass.superClass = superClass;
  8599. return ExtendedClass;
  8600. };
  8601. }
  8602. function isESClass(fn) {
  8603. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8604. }
  8605. /**
  8606. * A work around to both support ts extend and this extend mechanism.
  8607. * on sub-class.
  8608. * @usage
  8609. * ```ts
  8610. * class Component { ... }
  8611. * classUtil.enableClassExtend(Component);
  8612. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8613. *
  8614. * class Series extends Component { ... }
  8615. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8616. * Component.markExtend(Series);
  8617. * ```
  8618. */
  8619. function mountExtend(SubClz, SupperClz) {
  8620. SubClz.extend = SupperClz.extend;
  8621. }
  8622. // A random offset.
  8623. var classBase = Math.round(Math.random() * 10);
  8624. /**
  8625. * Implements `CheckableConstructor` for `target`.
  8626. * Can not use instanceof, consider different scope by
  8627. * cross domain or es module import in ec extensions.
  8628. * Mount a method "isInstance()" to Clz.
  8629. *
  8630. * @usage
  8631. * ```ts
  8632. * class Xxx {}
  8633. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8634. * enableClassCheck(Xxx as XxxConstructor)
  8635. * ```
  8636. */
  8637. function enableClassCheck(target) {
  8638. var classAttr = ['__\0is_clz', classBase++].join('_');
  8639. target.prototype[classAttr] = true;
  8640. if ("development" !== 'production') {
  8641. assert(!target.isInstance, 'The method "is" can not be defined.');
  8642. }
  8643. target.isInstance = function (obj) {
  8644. return !!(obj && obj[classAttr]);
  8645. };
  8646. }
  8647. // superCall should have class info, which can not be fetched from 'this'.
  8648. // Consider this case:
  8649. // class A has method f,
  8650. // class B inherits class A, overrides method f, f call superApply('f'),
  8651. // class C inherits class B, does not override method f,
  8652. // then when method of class C is called, dead loop occurred.
  8653. function superCall(context, methodName) {
  8654. var args = [];
  8655. for (var _i = 2; _i < arguments.length; _i++) {
  8656. args[_i - 2] = arguments[_i];
  8657. }
  8658. return this.superClass.prototype[methodName].apply(context, args);
  8659. }
  8660. function superApply(context, methodName, args) {
  8661. return this.superClass.prototype[methodName].apply(context, args);
  8662. }
  8663. /**
  8664. * Implements `ClassManager` for `target`
  8665. *
  8666. * @usage
  8667. * ```ts
  8668. * class Xxx {}
  8669. * type XxxConstructor = typeof Xxx & ClassManager
  8670. * enableClassManagement(Xxx as XxxConstructor);
  8671. * ```
  8672. */
  8673. function enableClassManagement(target) {
  8674. /**
  8675. * Component model classes
  8676. * key: componentType,
  8677. * value:
  8678. * componentClass, when componentType is 'a'
  8679. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8680. */
  8681. var storage = {};
  8682. target.registerClass = function (clz) {
  8683. // `type` should not be a "instance member".
  8684. // If using TS class, should better declared as `static type = 'series.pie'`.
  8685. // otherwise users have to mount `type` on prototype manually.
  8686. // For backward compat and enable instance visit type via `this.type`,
  8687. // we still support fetch `type` from prototype.
  8688. var componentFullType = clz.type || clz.prototype.type;
  8689. if (componentFullType) {
  8690. checkClassType(componentFullType);
  8691. // If only static type declared, we assign it to prototype mandatorily.
  8692. clz.prototype.type = componentFullType;
  8693. var componentTypeInfo = parseClassType(componentFullType);
  8694. if (!componentTypeInfo.sub) {
  8695. if ("development" !== 'production') {
  8696. if (storage[componentTypeInfo.main]) {
  8697. console.warn(componentTypeInfo.main + ' exists.');
  8698. }
  8699. }
  8700. storage[componentTypeInfo.main] = clz;
  8701. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8702. var container = makeContainer(componentTypeInfo);
  8703. container[componentTypeInfo.sub] = clz;
  8704. }
  8705. }
  8706. return clz;
  8707. };
  8708. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8709. var clz = storage[mainType];
  8710. if (clz && clz[IS_CONTAINER]) {
  8711. clz = subType ? clz[subType] : null;
  8712. }
  8713. if (throwWhenNotFound && !clz) {
  8714. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8715. }
  8716. return clz;
  8717. };
  8718. target.getClassesByMainType = function (componentType) {
  8719. var componentTypeInfo = parseClassType(componentType);
  8720. var result = [];
  8721. var obj = storage[componentTypeInfo.main];
  8722. if (obj && obj[IS_CONTAINER]) {
  8723. each(obj, function (o, type) {
  8724. type !== IS_CONTAINER && result.push(o);
  8725. });
  8726. } else {
  8727. result.push(obj);
  8728. }
  8729. return result;
  8730. };
  8731. target.hasClass = function (componentType) {
  8732. // Just consider componentType.main.
  8733. var componentTypeInfo = parseClassType(componentType);
  8734. return !!storage[componentTypeInfo.main];
  8735. };
  8736. /**
  8737. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8738. */
  8739. target.getAllClassMainTypes = function () {
  8740. var types = [];
  8741. each(storage, function (obj, type) {
  8742. types.push(type);
  8743. });
  8744. return types;
  8745. };
  8746. /**
  8747. * If a main type is container and has sub types
  8748. */
  8749. target.hasSubTypes = function (componentType) {
  8750. var componentTypeInfo = parseClassType(componentType);
  8751. var obj = storage[componentTypeInfo.main];
  8752. return obj && obj[IS_CONTAINER];
  8753. };
  8754. function makeContainer(componentTypeInfo) {
  8755. var container = storage[componentTypeInfo.main];
  8756. if (!container || !container[IS_CONTAINER]) {
  8757. container = storage[componentTypeInfo.main] = {};
  8758. container[IS_CONTAINER] = true;
  8759. }
  8760. return container;
  8761. }
  8762. }
  8763. // /**
  8764. // * @param {string|Array.<string>} properties
  8765. // */
  8766. // export function setReadOnly(obj, properties) {
  8767. // FIXME It seems broken in IE8 simulation of IE11
  8768. // if (!zrUtil.isArray(properties)) {
  8769. // properties = properties != null ? [properties] : [];
  8770. // }
  8771. // zrUtil.each(properties, function (prop) {
  8772. // let value = obj[prop];
  8773. // Object.defineProperty
  8774. // && Object.defineProperty(obj, prop, {
  8775. // value: value, writable: false
  8776. // });
  8777. // zrUtil.isArray(obj[prop])
  8778. // && Object.freeze
  8779. // && Object.freeze(obj[prop]);
  8780. // });
  8781. // }
  8782. function makeStyleMapper(properties, ignoreParent) {
  8783. // Normalize
  8784. for (var i = 0; i < properties.length; i++) {
  8785. if (!properties[i][1]) {
  8786. properties[i][1] = properties[i][0];
  8787. }
  8788. }
  8789. ignoreParent = ignoreParent || false;
  8790. return function (model, excludes, includes) {
  8791. var style = {};
  8792. for (var i = 0; i < properties.length; i++) {
  8793. var propName = properties[i][1];
  8794. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8795. continue;
  8796. }
  8797. var val = model.getShallow(propName, ignoreParent);
  8798. if (val != null) {
  8799. style[properties[i][0]] = val;
  8800. }
  8801. }
  8802. // TODO Text or image?
  8803. return style;
  8804. };
  8805. }
  8806. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor']
  8807. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8808. // So do not transfer decal directly.
  8809. ];
  8810. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8811. var AreaStyleMixin = /** @class */function () {
  8812. function AreaStyleMixin() {}
  8813. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8814. return getAreaStyle(this, excludes, includes);
  8815. };
  8816. return AreaStyleMixin;
  8817. }();
  8818. var globalImageCache = new LRU(50);
  8819. function findExistImage(newImageOrSrc) {
  8820. if (typeof newImageOrSrc === 'string') {
  8821. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8822. return cachedImgObj && cachedImgObj.image;
  8823. }
  8824. else {
  8825. return newImageOrSrc;
  8826. }
  8827. }
  8828. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8829. if (!newImageOrSrc) {
  8830. return image;
  8831. }
  8832. else if (typeof newImageOrSrc === 'string') {
  8833. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8834. return image;
  8835. }
  8836. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8837. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8838. if (cachedImgObj) {
  8839. image = cachedImgObj.image;
  8840. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8841. }
  8842. else {
  8843. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8844. image.__zrImageSrc = newImageOrSrc;
  8845. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8846. image: image,
  8847. pending: [pendingWrap]
  8848. });
  8849. }
  8850. return image;
  8851. }
  8852. else {
  8853. return newImageOrSrc;
  8854. }
  8855. }
  8856. function imageOnLoad() {
  8857. var cachedImgObj = this.__cachedImgObj;
  8858. this.onload = this.onerror = this.__cachedImgObj = null;
  8859. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8860. var pendingWrap = cachedImgObj.pending[i];
  8861. var cb = pendingWrap.cb;
  8862. cb && cb(this, pendingWrap.cbPayload);
  8863. pendingWrap.hostEl.dirty();
  8864. }
  8865. cachedImgObj.pending.length = 0;
  8866. }
  8867. function isImageReady(image) {
  8868. return image && image.width && image.height;
  8869. }
  8870. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8871. function truncateText(text, containerWidth, font, ellipsis, options) {
  8872. if (!containerWidth) {
  8873. return '';
  8874. }
  8875. var textLines = (text + '').split('\n');
  8876. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8877. for (var i = 0, len = textLines.length; i < len; i++) {
  8878. textLines[i] = truncateSingleLine(textLines[i], options);
  8879. }
  8880. return textLines.join('\n');
  8881. }
  8882. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8883. options = options || {};
  8884. var preparedOpts = extend({}, options);
  8885. preparedOpts.font = font;
  8886. ellipsis = retrieve2(ellipsis, '...');
  8887. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8888. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8889. preparedOpts.cnCharWidth = getWidth('国', font);
  8890. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8891. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8892. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8893. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8894. contentWidth -= ascCharWidth;
  8895. }
  8896. var ellipsisWidth = getWidth(ellipsis, font);
  8897. if (ellipsisWidth > contentWidth) {
  8898. ellipsis = '';
  8899. ellipsisWidth = 0;
  8900. }
  8901. contentWidth = containerWidth - ellipsisWidth;
  8902. preparedOpts.ellipsis = ellipsis;
  8903. preparedOpts.ellipsisWidth = ellipsisWidth;
  8904. preparedOpts.contentWidth = contentWidth;
  8905. preparedOpts.containerWidth = containerWidth;
  8906. return preparedOpts;
  8907. }
  8908. function truncateSingleLine(textLine, options) {
  8909. var containerWidth = options.containerWidth;
  8910. var font = options.font;
  8911. var contentWidth = options.contentWidth;
  8912. if (!containerWidth) {
  8913. return '';
  8914. }
  8915. var lineWidth = getWidth(textLine, font);
  8916. if (lineWidth <= containerWidth) {
  8917. return textLine;
  8918. }
  8919. for (var j = 0;; j++) {
  8920. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8921. textLine += options.ellipsis;
  8922. break;
  8923. }
  8924. var subLength = j === 0
  8925. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8926. : lineWidth > 0
  8927. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8928. : 0;
  8929. textLine = textLine.substr(0, subLength);
  8930. lineWidth = getWidth(textLine, font);
  8931. }
  8932. if (textLine === '') {
  8933. textLine = options.placeholder;
  8934. }
  8935. return textLine;
  8936. }
  8937. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8938. var width = 0;
  8939. var i = 0;
  8940. for (var len = text.length; i < len && width < contentWidth; i++) {
  8941. var charCode = text.charCodeAt(i);
  8942. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8943. }
  8944. return i;
  8945. }
  8946. function parsePlainText(text, style) {
  8947. text != null && (text += '');
  8948. var overflow = style.overflow;
  8949. var padding = style.padding;
  8950. var font = style.font;
  8951. var truncate = overflow === 'truncate';
  8952. var calculatedLineHeight = getLineHeight(font);
  8953. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8954. var bgColorDrawn = !!(style.backgroundColor);
  8955. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8956. var width = style.width;
  8957. var lines;
  8958. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8959. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8960. }
  8961. else {
  8962. lines = text ? text.split('\n') : [];
  8963. }
  8964. var contentHeight = lines.length * lineHeight;
  8965. var height = retrieve2(style.height, contentHeight);
  8966. if (contentHeight > height && truncateLineOverflow) {
  8967. var lineCount = Math.floor(height / lineHeight);
  8968. lines = lines.slice(0, lineCount);
  8969. }
  8970. if (text && truncate && width != null) {
  8971. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8972. minChar: style.truncateMinChar,
  8973. placeholder: style.placeholder
  8974. });
  8975. for (var i = 0; i < lines.length; i++) {
  8976. lines[i] = truncateSingleLine(lines[i], options);
  8977. }
  8978. }
  8979. var outerHeight = height;
  8980. var contentWidth = 0;
  8981. for (var i = 0; i < lines.length; i++) {
  8982. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8983. }
  8984. if (width == null) {
  8985. width = contentWidth;
  8986. }
  8987. var outerWidth = contentWidth;
  8988. if (padding) {
  8989. outerHeight += padding[0] + padding[2];
  8990. outerWidth += padding[1] + padding[3];
  8991. width += padding[1] + padding[3];
  8992. }
  8993. if (bgColorDrawn) {
  8994. outerWidth = width;
  8995. }
  8996. return {
  8997. lines: lines,
  8998. height: height,
  8999. outerWidth: outerWidth,
  9000. outerHeight: outerHeight,
  9001. lineHeight: lineHeight,
  9002. calculatedLineHeight: calculatedLineHeight,
  9003. contentWidth: contentWidth,
  9004. contentHeight: contentHeight,
  9005. width: width
  9006. };
  9007. }
  9008. var RichTextToken = (function () {
  9009. function RichTextToken() {
  9010. }
  9011. return RichTextToken;
  9012. }());
  9013. var RichTextLine = (function () {
  9014. function RichTextLine(tokens) {
  9015. this.tokens = [];
  9016. if (tokens) {
  9017. this.tokens = tokens;
  9018. }
  9019. }
  9020. return RichTextLine;
  9021. }());
  9022. var RichTextContentBlock = (function () {
  9023. function RichTextContentBlock() {
  9024. this.width = 0;
  9025. this.height = 0;
  9026. this.contentWidth = 0;
  9027. this.contentHeight = 0;
  9028. this.outerWidth = 0;
  9029. this.outerHeight = 0;
  9030. this.lines = [];
  9031. }
  9032. return RichTextContentBlock;
  9033. }());
  9034. function parseRichText(text, style) {
  9035. var contentBlock = new RichTextContentBlock();
  9036. text != null && (text += '');
  9037. if (!text) {
  9038. return contentBlock;
  9039. }
  9040. var topWidth = style.width;
  9041. var topHeight = style.height;
  9042. var overflow = style.overflow;
  9043. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  9044. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  9045. : null;
  9046. var lastIndex = STYLE_REG.lastIndex = 0;
  9047. var result;
  9048. while ((result = STYLE_REG.exec(text)) != null) {
  9049. var matchedIndex = result.index;
  9050. if (matchedIndex > lastIndex) {
  9051. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  9052. }
  9053. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  9054. lastIndex = STYLE_REG.lastIndex;
  9055. }
  9056. if (lastIndex < text.length) {
  9057. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  9058. }
  9059. var pendingList = [];
  9060. var calculatedHeight = 0;
  9061. var calculatedWidth = 0;
  9062. var stlPadding = style.padding;
  9063. var truncate = overflow === 'truncate';
  9064. var truncateLine = style.lineOverflow === 'truncate';
  9065. function finishLine(line, lineWidth, lineHeight) {
  9066. line.width = lineWidth;
  9067. line.lineHeight = lineHeight;
  9068. calculatedHeight += lineHeight;
  9069. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  9070. }
  9071. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  9072. var line = contentBlock.lines[i];
  9073. var lineHeight = 0;
  9074. var lineWidth = 0;
  9075. for (var j = 0; j < line.tokens.length; j++) {
  9076. var token = line.tokens[j];
  9077. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  9078. var textPadding = token.textPadding = tokenStyle.padding;
  9079. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  9080. var font = token.font = tokenStyle.font || style.font;
  9081. token.contentHeight = getLineHeight(font);
  9082. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  9083. token.innerHeight = tokenHeight;
  9084. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  9085. token.height = tokenHeight;
  9086. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  9087. token.align = tokenStyle && tokenStyle.align || style.align;
  9088. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  9089. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  9090. if (j > 0) {
  9091. line.tokens = line.tokens.slice(0, j);
  9092. finishLine(line, lineWidth, lineHeight);
  9093. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  9094. }
  9095. else {
  9096. contentBlock.lines = contentBlock.lines.slice(0, i);
  9097. }
  9098. break outer;
  9099. }
  9100. var styleTokenWidth = tokenStyle.width;
  9101. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  9102. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  9103. token.percentWidth = styleTokenWidth;
  9104. pendingList.push(token);
  9105. token.contentWidth = getWidth(token.text, font);
  9106. }
  9107. else {
  9108. if (tokenWidthNotSpecified) {
  9109. var textBackgroundColor = tokenStyle.backgroundColor;
  9110. var bgImg = textBackgroundColor && textBackgroundColor.image;
  9111. if (bgImg) {
  9112. bgImg = findExistImage(bgImg);
  9113. if (isImageReady(bgImg)) {
  9114. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  9115. }
  9116. }
  9117. }
  9118. var remainTruncWidth = truncate && topWidth != null
  9119. ? topWidth - lineWidth : null;
  9120. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  9121. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  9122. token.text = '';
  9123. token.width = token.contentWidth = 0;
  9124. }
  9125. else {
  9126. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  9127. token.width = token.contentWidth = getWidth(token.text, font);
  9128. }
  9129. }
  9130. else {
  9131. token.contentWidth = getWidth(token.text, font);
  9132. }
  9133. }
  9134. token.width += paddingH;
  9135. lineWidth += token.width;
  9136. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  9137. }
  9138. finishLine(line, lineWidth, lineHeight);
  9139. }
  9140. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  9141. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  9142. contentBlock.contentHeight = calculatedHeight;
  9143. contentBlock.contentWidth = calculatedWidth;
  9144. if (stlPadding) {
  9145. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  9146. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  9147. }
  9148. for (var i = 0; i < pendingList.length; i++) {
  9149. var token = pendingList[i];
  9150. var percentWidth = token.percentWidth;
  9151. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9152. }
  9153. return contentBlock;
  9154. }
  9155. function pushTokens(block, str, style, wrapInfo, styleName) {
  9156. var isEmptyStr = str === '';
  9157. var tokenStyle = styleName && style.rich[styleName] || {};
  9158. var lines = block.lines;
  9159. var font = tokenStyle.font || style.font;
  9160. var newLine = false;
  9161. var strLines;
  9162. var linesWidths;
  9163. if (wrapInfo) {
  9164. var tokenPadding = tokenStyle.padding;
  9165. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9166. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9167. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9168. if (lines.length > 0) {
  9169. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9170. strLines = str.split('\n');
  9171. newLine = true;
  9172. }
  9173. }
  9174. wrapInfo.accumWidth = outerWidth_1;
  9175. }
  9176. else {
  9177. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9178. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9179. linesWidths = res.linesWidths;
  9180. strLines = res.lines;
  9181. }
  9182. }
  9183. else {
  9184. strLines = str.split('\n');
  9185. }
  9186. for (var i = 0; i < strLines.length; i++) {
  9187. var text = strLines[i];
  9188. var token = new RichTextToken();
  9189. token.styleName = styleName;
  9190. token.text = text;
  9191. token.isLineHolder = !text && !isEmptyStr;
  9192. if (typeof tokenStyle.width === 'number') {
  9193. token.width = tokenStyle.width;
  9194. }
  9195. else {
  9196. token.width = linesWidths
  9197. ? linesWidths[i]
  9198. : getWidth(text, font);
  9199. }
  9200. if (!i && !newLine) {
  9201. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9202. var tokensLen = tokens.length;
  9203. (tokensLen === 1 && tokens[0].isLineHolder)
  9204. ? (tokens[0] = token)
  9205. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9206. }
  9207. else {
  9208. lines.push(new RichTextLine([token]));
  9209. }
  9210. }
  9211. }
  9212. function isAlphabeticLetter(ch) {
  9213. var code = ch.charCodeAt(0);
  9214. return code >= 0x20 && code <= 0x24F
  9215. || code >= 0x370 && code <= 0x10FF
  9216. || code >= 0x1200 && code <= 0x13FF
  9217. || code >= 0x1E00 && code <= 0x206F;
  9218. }
  9219. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9220. obj[ch] = true;
  9221. return obj;
  9222. }, {});
  9223. function isWordBreakChar(ch) {
  9224. if (isAlphabeticLetter(ch)) {
  9225. if (breakCharMap[ch]) {
  9226. return true;
  9227. }
  9228. return false;
  9229. }
  9230. return true;
  9231. }
  9232. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9233. var lines = [];
  9234. var linesWidths = [];
  9235. var line = '';
  9236. var currentWord = '';
  9237. var currentWordWidth = 0;
  9238. var accumWidth = 0;
  9239. for (var i = 0; i < text.length; i++) {
  9240. var ch = text.charAt(i);
  9241. if (ch === '\n') {
  9242. if (currentWord) {
  9243. line += currentWord;
  9244. accumWidth += currentWordWidth;
  9245. }
  9246. lines.push(line);
  9247. linesWidths.push(accumWidth);
  9248. line = '';
  9249. currentWord = '';
  9250. currentWordWidth = 0;
  9251. accumWidth = 0;
  9252. continue;
  9253. }
  9254. var chWidth = getWidth(ch, font);
  9255. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9256. if (!lines.length
  9257. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9258. : accumWidth + chWidth > lineWidth) {
  9259. if (!accumWidth) {
  9260. if (inWord) {
  9261. lines.push(currentWord);
  9262. linesWidths.push(currentWordWidth);
  9263. currentWord = ch;
  9264. currentWordWidth = chWidth;
  9265. }
  9266. else {
  9267. lines.push(ch);
  9268. linesWidths.push(chWidth);
  9269. }
  9270. }
  9271. else if (line || currentWord) {
  9272. if (inWord) {
  9273. if (!line) {
  9274. line = currentWord;
  9275. currentWord = '';
  9276. currentWordWidth = 0;
  9277. accumWidth = currentWordWidth;
  9278. }
  9279. lines.push(line);
  9280. linesWidths.push(accumWidth - currentWordWidth);
  9281. currentWord += ch;
  9282. currentWordWidth += chWidth;
  9283. line = '';
  9284. accumWidth = currentWordWidth;
  9285. }
  9286. else {
  9287. if (currentWord) {
  9288. line += currentWord;
  9289. currentWord = '';
  9290. currentWordWidth = 0;
  9291. }
  9292. lines.push(line);
  9293. linesWidths.push(accumWidth);
  9294. line = ch;
  9295. accumWidth = chWidth;
  9296. }
  9297. }
  9298. continue;
  9299. }
  9300. accumWidth += chWidth;
  9301. if (inWord) {
  9302. currentWord += ch;
  9303. currentWordWidth += chWidth;
  9304. }
  9305. else {
  9306. if (currentWord) {
  9307. line += currentWord;
  9308. currentWord = '';
  9309. currentWordWidth = 0;
  9310. }
  9311. line += ch;
  9312. }
  9313. }
  9314. if (!lines.length && !line) {
  9315. line = text;
  9316. currentWord = '';
  9317. currentWordWidth = 0;
  9318. }
  9319. if (currentWord) {
  9320. line += currentWord;
  9321. }
  9322. if (line) {
  9323. lines.push(line);
  9324. linesWidths.push(accumWidth);
  9325. }
  9326. if (lines.length === 1) {
  9327. accumWidth += lastAccumWidth;
  9328. }
  9329. return {
  9330. accumWidth: accumWidth,
  9331. lines: lines,
  9332. linesWidths: linesWidths
  9333. };
  9334. }
  9335. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9336. var DEFAULT_COMMON_STYLE = {
  9337. shadowBlur: 0,
  9338. shadowOffsetX: 0,
  9339. shadowOffsetY: 0,
  9340. shadowColor: '#000',
  9341. opacity: 1,
  9342. blend: 'source-over'
  9343. };
  9344. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9345. style: {
  9346. shadowBlur: true,
  9347. shadowOffsetX: true,
  9348. shadowOffsetY: true,
  9349. shadowColor: true,
  9350. opacity: true
  9351. }
  9352. };
  9353. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9354. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9355. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9356. var Displayable = (function (_super) {
  9357. __extends(Displayable, _super);
  9358. function Displayable(props) {
  9359. return _super.call(this, props) || this;
  9360. }
  9361. Displayable.prototype._init = function (props) {
  9362. var keysArr = keys(props);
  9363. for (var i = 0; i < keysArr.length; i++) {
  9364. var key = keysArr[i];
  9365. if (key === 'style') {
  9366. this.useStyle(props[key]);
  9367. }
  9368. else {
  9369. _super.prototype.attrKV.call(this, key, props[key]);
  9370. }
  9371. }
  9372. if (!this.style) {
  9373. this.useStyle({});
  9374. }
  9375. };
  9376. Displayable.prototype.beforeBrush = function () { };
  9377. Displayable.prototype.afterBrush = function () { };
  9378. Displayable.prototype.innerBeforeBrush = function () { };
  9379. Displayable.prototype.innerAfterBrush = function () { };
  9380. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9381. var m = this.transform;
  9382. if (this.ignore
  9383. || this.invisible
  9384. || this.style.opacity === 0
  9385. || (this.culling
  9386. && isDisplayableCulled(this, viewWidth, viewHeight))
  9387. || (m && !m[0] && !m[3])) {
  9388. return false;
  9389. }
  9390. if (considerClipPath && this.__clipPaths) {
  9391. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9392. if (this.__clipPaths[i].isZeroArea()) {
  9393. return false;
  9394. }
  9395. }
  9396. }
  9397. if (considerAncestors && this.parent) {
  9398. var parent_1 = this.parent;
  9399. while (parent_1) {
  9400. if (parent_1.ignore) {
  9401. return false;
  9402. }
  9403. parent_1 = parent_1.parent;
  9404. }
  9405. }
  9406. return true;
  9407. };
  9408. Displayable.prototype.contain = function (x, y) {
  9409. return this.rectContain(x, y);
  9410. };
  9411. Displayable.prototype.traverse = function (cb, context) {
  9412. cb.call(context, this);
  9413. };
  9414. Displayable.prototype.rectContain = function (x, y) {
  9415. var coord = this.transformCoordToLocal(x, y);
  9416. var rect = this.getBoundingRect();
  9417. return rect.contain(coord[0], coord[1]);
  9418. };
  9419. Displayable.prototype.getPaintRect = function () {
  9420. var rect = this._paintRect;
  9421. if (!this._paintRect || this.__dirty) {
  9422. var transform = this.transform;
  9423. var elRect = this.getBoundingRect();
  9424. var style = this.style;
  9425. var shadowSize = style.shadowBlur || 0;
  9426. var shadowOffsetX = style.shadowOffsetX || 0;
  9427. var shadowOffsetY = style.shadowOffsetY || 0;
  9428. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9429. if (transform) {
  9430. BoundingRect.applyTransform(rect, elRect, transform);
  9431. }
  9432. else {
  9433. rect.copy(elRect);
  9434. }
  9435. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9436. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9437. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9438. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9439. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9440. }
  9441. var tolerance = this.dirtyRectTolerance;
  9442. if (!rect.isZero()) {
  9443. rect.x = Math.floor(rect.x - tolerance);
  9444. rect.y = Math.floor(rect.y - tolerance);
  9445. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9446. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9447. }
  9448. }
  9449. return rect;
  9450. };
  9451. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9452. if (paintRect) {
  9453. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9454. this._prevPaintRect.copy(paintRect);
  9455. }
  9456. else {
  9457. this._prevPaintRect = null;
  9458. }
  9459. };
  9460. Displayable.prototype.getPrevPaintRect = function () {
  9461. return this._prevPaintRect;
  9462. };
  9463. Displayable.prototype.animateStyle = function (loop) {
  9464. return this.animate('style', loop);
  9465. };
  9466. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9467. if (targetKey === 'style') {
  9468. this.dirtyStyle();
  9469. }
  9470. else {
  9471. this.markRedraw();
  9472. }
  9473. };
  9474. Displayable.prototype.attrKV = function (key, value) {
  9475. if (key !== 'style') {
  9476. _super.prototype.attrKV.call(this, key, value);
  9477. }
  9478. else {
  9479. if (!this.style) {
  9480. this.useStyle(value);
  9481. }
  9482. else {
  9483. this.setStyle(value);
  9484. }
  9485. }
  9486. };
  9487. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9488. if (typeof keyOrObj === 'string') {
  9489. this.style[keyOrObj] = value;
  9490. }
  9491. else {
  9492. extend(this.style, keyOrObj);
  9493. }
  9494. this.dirtyStyle();
  9495. return this;
  9496. };
  9497. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9498. if (!notRedraw) {
  9499. this.markRedraw();
  9500. }
  9501. this.__dirty |= STYLE_CHANGED_BIT;
  9502. if (this._rect) {
  9503. this._rect = null;
  9504. }
  9505. };
  9506. Displayable.prototype.dirty = function () {
  9507. this.dirtyStyle();
  9508. };
  9509. Displayable.prototype.styleChanged = function () {
  9510. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9511. };
  9512. Displayable.prototype.styleUpdated = function () {
  9513. this.__dirty &= ~STYLE_CHANGED_BIT;
  9514. };
  9515. Displayable.prototype.createStyle = function (obj) {
  9516. return createObject(DEFAULT_COMMON_STYLE, obj);
  9517. };
  9518. Displayable.prototype.useStyle = function (obj) {
  9519. if (!obj[STYLE_MAGIC_KEY]) {
  9520. obj = this.createStyle(obj);
  9521. }
  9522. if (this.__inHover) {
  9523. this.__hoverStyle = obj;
  9524. }
  9525. else {
  9526. this.style = obj;
  9527. }
  9528. this.dirtyStyle();
  9529. };
  9530. Displayable.prototype.isStyleObject = function (obj) {
  9531. return obj[STYLE_MAGIC_KEY];
  9532. };
  9533. Displayable.prototype._innerSaveToNormal = function (toState) {
  9534. _super.prototype._innerSaveToNormal.call(this, toState);
  9535. var normalState = this._normalState;
  9536. if (toState.style && !normalState.style) {
  9537. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9538. }
  9539. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9540. };
  9541. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9542. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9543. var needsRestoreToNormal = !(state && keepCurrentStates);
  9544. var targetStyle;
  9545. if (state && state.style) {
  9546. if (transition) {
  9547. if (keepCurrentStates) {
  9548. targetStyle = state.style;
  9549. }
  9550. else {
  9551. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9552. this._mergeStyle(targetStyle, state.style);
  9553. }
  9554. }
  9555. else {
  9556. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9557. this._mergeStyle(targetStyle, state.style);
  9558. }
  9559. }
  9560. else if (needsRestoreToNormal) {
  9561. targetStyle = normalState.style;
  9562. }
  9563. if (targetStyle) {
  9564. if (transition) {
  9565. var sourceStyle = this.style;
  9566. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9567. if (needsRestoreToNormal) {
  9568. var changedKeys = keys(sourceStyle);
  9569. for (var i = 0; i < changedKeys.length; i++) {
  9570. var key = changedKeys[i];
  9571. if (key in targetStyle) {
  9572. targetStyle[key] = targetStyle[key];
  9573. this.style[key] = sourceStyle[key];
  9574. }
  9575. }
  9576. }
  9577. var targetKeys = keys(targetStyle);
  9578. for (var i = 0; i < targetKeys.length; i++) {
  9579. var key = targetKeys[i];
  9580. this.style[key] = this.style[key];
  9581. }
  9582. this._transitionState(stateName, {
  9583. style: targetStyle
  9584. }, animationCfg, this.getAnimationStyleProps());
  9585. }
  9586. else {
  9587. this.useStyle(targetStyle);
  9588. }
  9589. }
  9590. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9591. for (var i = 0; i < statesKeys.length; i++) {
  9592. var key = statesKeys[i];
  9593. if (state && state[key] != null) {
  9594. this[key] = state[key];
  9595. }
  9596. else if (needsRestoreToNormal) {
  9597. if (normalState[key] != null) {
  9598. this[key] = normalState[key];
  9599. }
  9600. }
  9601. }
  9602. };
  9603. Displayable.prototype._mergeStates = function (states) {
  9604. var mergedState = _super.prototype._mergeStates.call(this, states);
  9605. var mergedStyle;
  9606. for (var i = 0; i < states.length; i++) {
  9607. var state = states[i];
  9608. if (state.style) {
  9609. mergedStyle = mergedStyle || {};
  9610. this._mergeStyle(mergedStyle, state.style);
  9611. }
  9612. }
  9613. if (mergedStyle) {
  9614. mergedState.style = mergedStyle;
  9615. }
  9616. return mergedState;
  9617. };
  9618. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9619. extend(targetStyle, sourceStyle);
  9620. return targetStyle;
  9621. };
  9622. Displayable.prototype.getAnimationStyleProps = function () {
  9623. return DEFAULT_COMMON_ANIMATION_PROPS;
  9624. };
  9625. Displayable.initDefaultProps = (function () {
  9626. var dispProto = Displayable.prototype;
  9627. dispProto.type = 'displayable';
  9628. dispProto.invisible = false;
  9629. dispProto.z = 0;
  9630. dispProto.z2 = 0;
  9631. dispProto.zlevel = 0;
  9632. dispProto.culling = false;
  9633. dispProto.cursor = 'pointer';
  9634. dispProto.rectHover = false;
  9635. dispProto.incremental = false;
  9636. dispProto._rect = null;
  9637. dispProto.dirtyRectTolerance = 0;
  9638. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9639. })();
  9640. return Displayable;
  9641. }(Element));
  9642. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9643. var viewRect = new BoundingRect(0, 0, 0, 0);
  9644. function isDisplayableCulled(el, width, height) {
  9645. tmpRect$1.copy(el.getBoundingRect());
  9646. if (el.transform) {
  9647. tmpRect$1.applyTransform(el.transform);
  9648. }
  9649. viewRect.width = width;
  9650. viewRect.height = height;
  9651. return !tmpRect$1.intersect(viewRect);
  9652. }
  9653. var mathMin$1 = Math.min;
  9654. var mathMax$1 = Math.max;
  9655. var mathSin = Math.sin;
  9656. var mathCos = Math.cos;
  9657. var PI2 = Math.PI * 2;
  9658. var start = create();
  9659. var end = create();
  9660. var extremity = create();
  9661. function fromLine(x0, y0, x1, y1, min, max) {
  9662. min[0] = mathMin$1(x0, x1);
  9663. min[1] = mathMin$1(y0, y1);
  9664. max[0] = mathMax$1(x0, x1);
  9665. max[1] = mathMax$1(y0, y1);
  9666. }
  9667. var xDim = [];
  9668. var yDim = [];
  9669. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9670. var cubicExtrema$1 = cubicExtrema;
  9671. var cubicAt$1 = cubicAt;
  9672. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9673. min[0] = Infinity;
  9674. min[1] = Infinity;
  9675. max[0] = -Infinity;
  9676. max[1] = -Infinity;
  9677. for (var i = 0; i < n; i++) {
  9678. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9679. min[0] = mathMin$1(x, min[0]);
  9680. max[0] = mathMax$1(x, max[0]);
  9681. }
  9682. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9683. for (var i = 0; i < n; i++) {
  9684. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9685. min[1] = mathMin$1(y, min[1]);
  9686. max[1] = mathMax$1(y, max[1]);
  9687. }
  9688. min[0] = mathMin$1(x0, min[0]);
  9689. max[0] = mathMax$1(x0, max[0]);
  9690. min[0] = mathMin$1(x3, min[0]);
  9691. max[0] = mathMax$1(x3, max[0]);
  9692. min[1] = mathMin$1(y0, min[1]);
  9693. max[1] = mathMax$1(y0, max[1]);
  9694. min[1] = mathMin$1(y3, min[1]);
  9695. max[1] = mathMax$1(y3, max[1]);
  9696. }
  9697. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9698. var quadraticExtremum$1 = quadraticExtremum;
  9699. var quadraticAt$1 = quadraticAt;
  9700. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9701. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9702. var x = quadraticAt$1(x0, x1, x2, tx);
  9703. var y = quadraticAt$1(y0, y1, y2, ty);
  9704. min[0] = mathMin$1(x0, x2, x);
  9705. min[1] = mathMin$1(y0, y2, y);
  9706. max[0] = mathMax$1(x0, x2, x);
  9707. max[1] = mathMax$1(y0, y2, y);
  9708. }
  9709. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9710. var vec2Min = min;
  9711. var vec2Max = max;
  9712. var diff = Math.abs(startAngle - endAngle);
  9713. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9714. min$1[0] = x - rx;
  9715. min$1[1] = y - ry;
  9716. max$1[0] = x + rx;
  9717. max$1[1] = y + ry;
  9718. return;
  9719. }
  9720. start[0] = mathCos(startAngle) * rx + x;
  9721. start[1] = mathSin(startAngle) * ry + y;
  9722. end[0] = mathCos(endAngle) * rx + x;
  9723. end[1] = mathSin(endAngle) * ry + y;
  9724. vec2Min(min$1, start, end);
  9725. vec2Max(max$1, start, end);
  9726. startAngle = startAngle % (PI2);
  9727. if (startAngle < 0) {
  9728. startAngle = startAngle + PI2;
  9729. }
  9730. endAngle = endAngle % (PI2);
  9731. if (endAngle < 0) {
  9732. endAngle = endAngle + PI2;
  9733. }
  9734. if (startAngle > endAngle && !anticlockwise) {
  9735. endAngle += PI2;
  9736. }
  9737. else if (startAngle < endAngle && anticlockwise) {
  9738. startAngle += PI2;
  9739. }
  9740. if (anticlockwise) {
  9741. var tmp = endAngle;
  9742. endAngle = startAngle;
  9743. startAngle = tmp;
  9744. }
  9745. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9746. if (angle > startAngle) {
  9747. extremity[0] = mathCos(angle) * rx + x;
  9748. extremity[1] = mathSin(angle) * ry + y;
  9749. vec2Min(min$1, extremity, min$1);
  9750. vec2Max(max$1, extremity, max$1);
  9751. }
  9752. }
  9753. }
  9754. var CMD = {
  9755. M: 1,
  9756. L: 2,
  9757. C: 3,
  9758. Q: 4,
  9759. A: 5,
  9760. Z: 6,
  9761. R: 7
  9762. };
  9763. var tmpOutX = [];
  9764. var tmpOutY = [];
  9765. var min$1 = [];
  9766. var max$1 = [];
  9767. var min2 = [];
  9768. var max2 = [];
  9769. var mathMin$2 = Math.min;
  9770. var mathMax$2 = Math.max;
  9771. var mathCos$1 = Math.cos;
  9772. var mathSin$1 = Math.sin;
  9773. var mathAbs = Math.abs;
  9774. var PI = Math.PI;
  9775. var PI2$1 = PI * 2;
  9776. var hasTypedArray = typeof Float32Array !== 'undefined';
  9777. var tmpAngles = [];
  9778. function modPI2(radian) {
  9779. var n = Math.round(radian / PI * 1e8) / 1e8;
  9780. return (n % 2) * PI;
  9781. }
  9782. function normalizeArcAngles(angles, anticlockwise) {
  9783. var newStartAngle = modPI2(angles[0]);
  9784. if (newStartAngle < 0) {
  9785. newStartAngle += PI2$1;
  9786. }
  9787. var delta = newStartAngle - angles[0];
  9788. var newEndAngle = angles[1];
  9789. newEndAngle += delta;
  9790. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9791. newEndAngle = newStartAngle + PI2$1;
  9792. }
  9793. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9794. newEndAngle = newStartAngle - PI2$1;
  9795. }
  9796. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9797. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9798. }
  9799. else if (anticlockwise && newStartAngle < newEndAngle) {
  9800. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9801. }
  9802. angles[0] = newStartAngle;
  9803. angles[1] = newEndAngle;
  9804. }
  9805. var PathProxy = (function () {
  9806. function PathProxy(notSaveData) {
  9807. this.dpr = 1;
  9808. this._xi = 0;
  9809. this._yi = 0;
  9810. this._x0 = 0;
  9811. this._y0 = 0;
  9812. this._len = 0;
  9813. if (notSaveData) {
  9814. this._saveData = false;
  9815. }
  9816. if (this._saveData) {
  9817. this.data = [];
  9818. }
  9819. }
  9820. PathProxy.prototype.increaseVersion = function () {
  9821. this._version++;
  9822. };
  9823. PathProxy.prototype.getVersion = function () {
  9824. return this._version;
  9825. };
  9826. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9827. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9828. if (segmentIgnoreThreshold > 0) {
  9829. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9830. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9831. }
  9832. };
  9833. PathProxy.prototype.setDPR = function (dpr) {
  9834. this.dpr = dpr;
  9835. };
  9836. PathProxy.prototype.setContext = function (ctx) {
  9837. this._ctx = ctx;
  9838. };
  9839. PathProxy.prototype.getContext = function () {
  9840. return this._ctx;
  9841. };
  9842. PathProxy.prototype.beginPath = function () {
  9843. this._ctx && this._ctx.beginPath();
  9844. this.reset();
  9845. return this;
  9846. };
  9847. PathProxy.prototype.reset = function () {
  9848. if (this._saveData) {
  9849. this._len = 0;
  9850. }
  9851. if (this._pathSegLen) {
  9852. this._pathSegLen = null;
  9853. this._pathLen = 0;
  9854. }
  9855. this._version++;
  9856. };
  9857. PathProxy.prototype.moveTo = function (x, y) {
  9858. this._drawPendingPt();
  9859. this.addData(CMD.M, x, y);
  9860. this._ctx && this._ctx.moveTo(x, y);
  9861. this._x0 = x;
  9862. this._y0 = y;
  9863. this._xi = x;
  9864. this._yi = y;
  9865. return this;
  9866. };
  9867. PathProxy.prototype.lineTo = function (x, y) {
  9868. var dx = mathAbs(x - this._xi);
  9869. var dy = mathAbs(y - this._yi);
  9870. var exceedUnit = dx > this._ux || dy > this._uy;
  9871. this.addData(CMD.L, x, y);
  9872. if (this._ctx && exceedUnit) {
  9873. this._ctx.lineTo(x, y);
  9874. }
  9875. if (exceedUnit) {
  9876. this._xi = x;
  9877. this._yi = y;
  9878. this._pendingPtDist = 0;
  9879. }
  9880. else {
  9881. var d2 = dx * dx + dy * dy;
  9882. if (d2 > this._pendingPtDist) {
  9883. this._pendingPtX = x;
  9884. this._pendingPtY = y;
  9885. this._pendingPtDist = d2;
  9886. }
  9887. }
  9888. return this;
  9889. };
  9890. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9891. this._drawPendingPt();
  9892. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9893. if (this._ctx) {
  9894. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9895. }
  9896. this._xi = x3;
  9897. this._yi = y3;
  9898. return this;
  9899. };
  9900. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9901. this._drawPendingPt();
  9902. this.addData(CMD.Q, x1, y1, x2, y2);
  9903. if (this._ctx) {
  9904. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9905. }
  9906. this._xi = x2;
  9907. this._yi = y2;
  9908. return this;
  9909. };
  9910. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9911. this._drawPendingPt();
  9912. tmpAngles[0] = startAngle;
  9913. tmpAngles[1] = endAngle;
  9914. normalizeArcAngles(tmpAngles, anticlockwise);
  9915. startAngle = tmpAngles[0];
  9916. endAngle = tmpAngles[1];
  9917. var delta = endAngle - startAngle;
  9918. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9919. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9920. this._xi = mathCos$1(endAngle) * r + cx;
  9921. this._yi = mathSin$1(endAngle) * r + cy;
  9922. return this;
  9923. };
  9924. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9925. this._drawPendingPt();
  9926. if (this._ctx) {
  9927. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9928. }
  9929. return this;
  9930. };
  9931. PathProxy.prototype.rect = function (x, y, w, h) {
  9932. this._drawPendingPt();
  9933. this._ctx && this._ctx.rect(x, y, w, h);
  9934. this.addData(CMD.R, x, y, w, h);
  9935. return this;
  9936. };
  9937. PathProxy.prototype.closePath = function () {
  9938. this._drawPendingPt();
  9939. this.addData(CMD.Z);
  9940. var ctx = this._ctx;
  9941. var x0 = this._x0;
  9942. var y0 = this._y0;
  9943. if (ctx) {
  9944. ctx.closePath();
  9945. }
  9946. this._xi = x0;
  9947. this._yi = y0;
  9948. return this;
  9949. };
  9950. PathProxy.prototype.fill = function (ctx) {
  9951. ctx && ctx.fill();
  9952. this.toStatic();
  9953. };
  9954. PathProxy.prototype.stroke = function (ctx) {
  9955. ctx && ctx.stroke();
  9956. this.toStatic();
  9957. };
  9958. PathProxy.prototype.len = function () {
  9959. return this._len;
  9960. };
  9961. PathProxy.prototype.setData = function (data) {
  9962. var len = data.length;
  9963. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9964. this.data = new Float32Array(len);
  9965. }
  9966. for (var i = 0; i < len; i++) {
  9967. this.data[i] = data[i];
  9968. }
  9969. this._len = len;
  9970. };
  9971. PathProxy.prototype.appendPath = function (path) {
  9972. if (!(path instanceof Array)) {
  9973. path = [path];
  9974. }
  9975. var len = path.length;
  9976. var appendSize = 0;
  9977. var offset = this._len;
  9978. for (var i = 0; i < len; i++) {
  9979. appendSize += path[i].len();
  9980. }
  9981. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9982. this.data = new Float32Array(offset + appendSize);
  9983. }
  9984. for (var i = 0; i < len; i++) {
  9985. var appendPathData = path[i].data;
  9986. for (var k = 0; k < appendPathData.length; k++) {
  9987. this.data[offset++] = appendPathData[k];
  9988. }
  9989. }
  9990. this._len = offset;
  9991. };
  9992. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9993. if (!this._saveData) {
  9994. return;
  9995. }
  9996. var data = this.data;
  9997. if (this._len + arguments.length > data.length) {
  9998. this._expandData();
  9999. data = this.data;
  10000. }
  10001. for (var i = 0; i < arguments.length; i++) {
  10002. data[this._len++] = arguments[i];
  10003. }
  10004. };
  10005. PathProxy.prototype._drawPendingPt = function () {
  10006. if (this._pendingPtDist > 0) {
  10007. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  10008. this._pendingPtDist = 0;
  10009. }
  10010. };
  10011. PathProxy.prototype._expandData = function () {
  10012. if (!(this.data instanceof Array)) {
  10013. var newData = [];
  10014. for (var i = 0; i < this._len; i++) {
  10015. newData[i] = this.data[i];
  10016. }
  10017. this.data = newData;
  10018. }
  10019. };
  10020. PathProxy.prototype.toStatic = function () {
  10021. if (!this._saveData) {
  10022. return;
  10023. }
  10024. this._drawPendingPt();
  10025. var data = this.data;
  10026. if (data instanceof Array) {
  10027. data.length = this._len;
  10028. if (hasTypedArray && this._len > 11) {
  10029. this.data = new Float32Array(data);
  10030. }
  10031. }
  10032. };
  10033. PathProxy.prototype.getBoundingRect = function () {
  10034. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  10035. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  10036. var data = this.data;
  10037. var xi = 0;
  10038. var yi = 0;
  10039. var x0 = 0;
  10040. var y0 = 0;
  10041. var i;
  10042. for (i = 0; i < this._len;) {
  10043. var cmd = data[i++];
  10044. var isFirst = i === 1;
  10045. if (isFirst) {
  10046. xi = data[i];
  10047. yi = data[i + 1];
  10048. x0 = xi;
  10049. y0 = yi;
  10050. }
  10051. switch (cmd) {
  10052. case CMD.M:
  10053. xi = x0 = data[i++];
  10054. yi = y0 = data[i++];
  10055. min2[0] = x0;
  10056. min2[1] = y0;
  10057. max2[0] = x0;
  10058. max2[1] = y0;
  10059. break;
  10060. case CMD.L:
  10061. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  10062. xi = data[i++];
  10063. yi = data[i++];
  10064. break;
  10065. case CMD.C:
  10066. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10067. xi = data[i++];
  10068. yi = data[i++];
  10069. break;
  10070. case CMD.Q:
  10071. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10072. xi = data[i++];
  10073. yi = data[i++];
  10074. break;
  10075. case CMD.A:
  10076. var cx = data[i++];
  10077. var cy = data[i++];
  10078. var rx = data[i++];
  10079. var ry = data[i++];
  10080. var startAngle = data[i++];
  10081. var endAngle = data[i++] + startAngle;
  10082. i += 1;
  10083. var anticlockwise = !data[i++];
  10084. if (isFirst) {
  10085. x0 = mathCos$1(startAngle) * rx + cx;
  10086. y0 = mathSin$1(startAngle) * ry + cy;
  10087. }
  10088. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  10089. xi = mathCos$1(endAngle) * rx + cx;
  10090. yi = mathSin$1(endAngle) * ry + cy;
  10091. break;
  10092. case CMD.R:
  10093. x0 = xi = data[i++];
  10094. y0 = yi = data[i++];
  10095. var width = data[i++];
  10096. var height = data[i++];
  10097. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10098. break;
  10099. case CMD.Z:
  10100. xi = x0;
  10101. yi = y0;
  10102. break;
  10103. }
  10104. min(min$1, min$1, min2);
  10105. max(max$1, max$1, max2);
  10106. }
  10107. if (i === 0) {
  10108. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10109. }
  10110. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  10111. };
  10112. PathProxy.prototype._calculateLength = function () {
  10113. var data = this.data;
  10114. var len = this._len;
  10115. var ux = this._ux;
  10116. var uy = this._uy;
  10117. var xi = 0;
  10118. var yi = 0;
  10119. var x0 = 0;
  10120. var y0 = 0;
  10121. if (!this._pathSegLen) {
  10122. this._pathSegLen = [];
  10123. }
  10124. var pathSegLen = this._pathSegLen;
  10125. var pathTotalLen = 0;
  10126. var segCount = 0;
  10127. for (var i = 0; i < len;) {
  10128. var cmd = data[i++];
  10129. var isFirst = i === 1;
  10130. if (isFirst) {
  10131. xi = data[i];
  10132. yi = data[i + 1];
  10133. x0 = xi;
  10134. y0 = yi;
  10135. }
  10136. var l = -1;
  10137. switch (cmd) {
  10138. case CMD.M:
  10139. xi = x0 = data[i++];
  10140. yi = y0 = data[i++];
  10141. break;
  10142. case CMD.L: {
  10143. var x2 = data[i++];
  10144. var y2 = data[i++];
  10145. var dx = x2 - xi;
  10146. var dy = y2 - yi;
  10147. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  10148. l = Math.sqrt(dx * dx + dy * dy);
  10149. xi = x2;
  10150. yi = y2;
  10151. }
  10152. break;
  10153. }
  10154. case CMD.C: {
  10155. var x1 = data[i++];
  10156. var y1 = data[i++];
  10157. var x2 = data[i++];
  10158. var y2 = data[i++];
  10159. var x3 = data[i++];
  10160. var y3 = data[i++];
  10161. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10162. xi = x3;
  10163. yi = y3;
  10164. break;
  10165. }
  10166. case CMD.Q: {
  10167. var x1 = data[i++];
  10168. var y1 = data[i++];
  10169. var x2 = data[i++];
  10170. var y2 = data[i++];
  10171. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10172. xi = x2;
  10173. yi = y2;
  10174. break;
  10175. }
  10176. case CMD.A:
  10177. var cx = data[i++];
  10178. var cy = data[i++];
  10179. var rx = data[i++];
  10180. var ry = data[i++];
  10181. var startAngle = data[i++];
  10182. var delta = data[i++];
  10183. var endAngle = delta + startAngle;
  10184. i += 1;
  10185. if (isFirst) {
  10186. x0 = mathCos$1(startAngle) * rx + cx;
  10187. y0 = mathSin$1(startAngle) * ry + cy;
  10188. }
  10189. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10190. xi = mathCos$1(endAngle) * rx + cx;
  10191. yi = mathSin$1(endAngle) * ry + cy;
  10192. break;
  10193. case CMD.R: {
  10194. x0 = xi = data[i++];
  10195. y0 = yi = data[i++];
  10196. var width = data[i++];
  10197. var height = data[i++];
  10198. l = width * 2 + height * 2;
  10199. break;
  10200. }
  10201. case CMD.Z: {
  10202. var dx = x0 - xi;
  10203. var dy = y0 - yi;
  10204. l = Math.sqrt(dx * dx + dy * dy);
  10205. xi = x0;
  10206. yi = y0;
  10207. break;
  10208. }
  10209. }
  10210. if (l >= 0) {
  10211. pathSegLen[segCount++] = l;
  10212. pathTotalLen += l;
  10213. }
  10214. }
  10215. this._pathLen = pathTotalLen;
  10216. return pathTotalLen;
  10217. };
  10218. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10219. var d = this.data;
  10220. var ux = this._ux;
  10221. var uy = this._uy;
  10222. var len = this._len;
  10223. var x0;
  10224. var y0;
  10225. var xi;
  10226. var yi;
  10227. var x;
  10228. var y;
  10229. var drawPart = percent < 1;
  10230. var pathSegLen;
  10231. var pathTotalLen;
  10232. var accumLength = 0;
  10233. var segCount = 0;
  10234. var displayedLength;
  10235. var pendingPtDist = 0;
  10236. var pendingPtX;
  10237. var pendingPtY;
  10238. if (drawPart) {
  10239. if (!this._pathSegLen) {
  10240. this._calculateLength();
  10241. }
  10242. pathSegLen = this._pathSegLen;
  10243. pathTotalLen = this._pathLen;
  10244. displayedLength = percent * pathTotalLen;
  10245. if (!displayedLength) {
  10246. return;
  10247. }
  10248. }
  10249. lo: for (var i = 0; i < len;) {
  10250. var cmd = d[i++];
  10251. var isFirst = i === 1;
  10252. if (isFirst) {
  10253. xi = d[i];
  10254. yi = d[i + 1];
  10255. x0 = xi;
  10256. y0 = yi;
  10257. }
  10258. if (cmd !== CMD.L && pendingPtDist > 0) {
  10259. ctx.lineTo(pendingPtX, pendingPtY);
  10260. pendingPtDist = 0;
  10261. }
  10262. switch (cmd) {
  10263. case CMD.M:
  10264. x0 = xi = d[i++];
  10265. y0 = yi = d[i++];
  10266. ctx.moveTo(xi, yi);
  10267. break;
  10268. case CMD.L: {
  10269. x = d[i++];
  10270. y = d[i++];
  10271. var dx = mathAbs(x - xi);
  10272. var dy = mathAbs(y - yi);
  10273. if (dx > ux || dy > uy) {
  10274. if (drawPart) {
  10275. var l = pathSegLen[segCount++];
  10276. if (accumLength + l > displayedLength) {
  10277. var t = (displayedLength - accumLength) / l;
  10278. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10279. break lo;
  10280. }
  10281. accumLength += l;
  10282. }
  10283. ctx.lineTo(x, y);
  10284. xi = x;
  10285. yi = y;
  10286. pendingPtDist = 0;
  10287. }
  10288. else {
  10289. var d2 = dx * dx + dy * dy;
  10290. if (d2 > pendingPtDist) {
  10291. pendingPtX = x;
  10292. pendingPtY = y;
  10293. pendingPtDist = d2;
  10294. }
  10295. }
  10296. break;
  10297. }
  10298. case CMD.C: {
  10299. var x1 = d[i++];
  10300. var y1 = d[i++];
  10301. var x2 = d[i++];
  10302. var y2 = d[i++];
  10303. var x3 = d[i++];
  10304. var y3 = d[i++];
  10305. if (drawPart) {
  10306. var l = pathSegLen[segCount++];
  10307. if (accumLength + l > displayedLength) {
  10308. var t = (displayedLength - accumLength) / l;
  10309. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10310. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10311. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10312. break lo;
  10313. }
  10314. accumLength += l;
  10315. }
  10316. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10317. xi = x3;
  10318. yi = y3;
  10319. break;
  10320. }
  10321. case CMD.Q: {
  10322. var x1 = d[i++];
  10323. var y1 = d[i++];
  10324. var x2 = d[i++];
  10325. var y2 = d[i++];
  10326. if (drawPart) {
  10327. var l = pathSegLen[segCount++];
  10328. if (accumLength + l > displayedLength) {
  10329. var t = (displayedLength - accumLength) / l;
  10330. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10331. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10332. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10333. break lo;
  10334. }
  10335. accumLength += l;
  10336. }
  10337. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10338. xi = x2;
  10339. yi = y2;
  10340. break;
  10341. }
  10342. case CMD.A:
  10343. var cx = d[i++];
  10344. var cy = d[i++];
  10345. var rx = d[i++];
  10346. var ry = d[i++];
  10347. var startAngle = d[i++];
  10348. var delta = d[i++];
  10349. var psi = d[i++];
  10350. var anticlockwise = !d[i++];
  10351. var r = (rx > ry) ? rx : ry;
  10352. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10353. var endAngle = startAngle + delta;
  10354. var breakBuild = false;
  10355. if (drawPart) {
  10356. var l = pathSegLen[segCount++];
  10357. if (accumLength + l > displayedLength) {
  10358. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10359. breakBuild = true;
  10360. }
  10361. accumLength += l;
  10362. }
  10363. if (isEllipse && ctx.ellipse) {
  10364. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10365. }
  10366. else {
  10367. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10368. }
  10369. if (breakBuild) {
  10370. break lo;
  10371. }
  10372. if (isFirst) {
  10373. x0 = mathCos$1(startAngle) * rx + cx;
  10374. y0 = mathSin$1(startAngle) * ry + cy;
  10375. }
  10376. xi = mathCos$1(endAngle) * rx + cx;
  10377. yi = mathSin$1(endAngle) * ry + cy;
  10378. break;
  10379. case CMD.R:
  10380. x0 = xi = d[i];
  10381. y0 = yi = d[i + 1];
  10382. x = d[i++];
  10383. y = d[i++];
  10384. var width = d[i++];
  10385. var height = d[i++];
  10386. if (drawPart) {
  10387. var l = pathSegLen[segCount++];
  10388. if (accumLength + l > displayedLength) {
  10389. var d_1 = displayedLength - accumLength;
  10390. ctx.moveTo(x, y);
  10391. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10392. d_1 -= width;
  10393. if (d_1 > 0) {
  10394. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10395. }
  10396. d_1 -= height;
  10397. if (d_1 > 0) {
  10398. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10399. }
  10400. d_1 -= width;
  10401. if (d_1 > 0) {
  10402. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10403. }
  10404. break lo;
  10405. }
  10406. accumLength += l;
  10407. }
  10408. ctx.rect(x, y, width, height);
  10409. break;
  10410. case CMD.Z:
  10411. if (drawPart) {
  10412. var l = pathSegLen[segCount++];
  10413. if (accumLength + l > displayedLength) {
  10414. var t = (displayedLength - accumLength) / l;
  10415. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10416. break lo;
  10417. }
  10418. accumLength += l;
  10419. }
  10420. ctx.closePath();
  10421. xi = x0;
  10422. yi = y0;
  10423. }
  10424. }
  10425. };
  10426. PathProxy.prototype.clone = function () {
  10427. var newProxy = new PathProxy();
  10428. var data = this.data;
  10429. newProxy.data = data.slice ? data.slice()
  10430. : Array.prototype.slice.call(data);
  10431. newProxy._len = this._len;
  10432. return newProxy;
  10433. };
  10434. PathProxy.CMD = CMD;
  10435. PathProxy.initDefaultProps = (function () {
  10436. var proto = PathProxy.prototype;
  10437. proto._saveData = true;
  10438. proto._ux = 0;
  10439. proto._uy = 0;
  10440. proto._pendingPtDist = 0;
  10441. proto._version = 0;
  10442. })();
  10443. return PathProxy;
  10444. }());
  10445. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10446. if (lineWidth === 0) {
  10447. return false;
  10448. }
  10449. var _l = lineWidth;
  10450. var _a = 0;
  10451. var _b = x0;
  10452. if ((y > y0 + _l && y > y1 + _l)
  10453. || (y < y0 - _l && y < y1 - _l)
  10454. || (x > x0 + _l && x > x1 + _l)
  10455. || (x < x0 - _l && x < x1 - _l)) {
  10456. return false;
  10457. }
  10458. if (x0 !== x1) {
  10459. _a = (y0 - y1) / (x0 - x1);
  10460. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10461. }
  10462. else {
  10463. return Math.abs(x - x0) <= _l / 2;
  10464. }
  10465. var tmp = _a * x - y + _b;
  10466. var _s = tmp * tmp / (_a * _a + 1);
  10467. return _s <= _l / 2 * _l / 2;
  10468. }
  10469. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10470. if (lineWidth === 0) {
  10471. return false;
  10472. }
  10473. var _l = lineWidth;
  10474. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10475. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10476. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10477. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10478. return false;
  10479. }
  10480. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10481. return d <= _l / 2;
  10482. }
  10483. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10484. if (lineWidth === 0) {
  10485. return false;
  10486. }
  10487. var _l = lineWidth;
  10488. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10489. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10490. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10491. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10492. return false;
  10493. }
  10494. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10495. return d <= _l / 2;
  10496. }
  10497. var PI2$2 = Math.PI * 2;
  10498. function normalizeRadian(angle) {
  10499. angle %= PI2$2;
  10500. if (angle < 0) {
  10501. angle += PI2$2;
  10502. }
  10503. return angle;
  10504. }
  10505. var PI2$3 = Math.PI * 2;
  10506. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10507. if (lineWidth === 0) {
  10508. return false;
  10509. }
  10510. var _l = lineWidth;
  10511. x -= cx;
  10512. y -= cy;
  10513. var d = Math.sqrt(x * x + y * y);
  10514. if ((d - _l > r) || (d + _l < r)) {
  10515. return false;
  10516. }
  10517. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10518. return true;
  10519. }
  10520. if (anticlockwise) {
  10521. var tmp = startAngle;
  10522. startAngle = normalizeRadian(endAngle);
  10523. endAngle = normalizeRadian(tmp);
  10524. }
  10525. else {
  10526. startAngle = normalizeRadian(startAngle);
  10527. endAngle = normalizeRadian(endAngle);
  10528. }
  10529. if (startAngle > endAngle) {
  10530. endAngle += PI2$3;
  10531. }
  10532. var angle = Math.atan2(y, x);
  10533. if (angle < 0) {
  10534. angle += PI2$3;
  10535. }
  10536. return (angle >= startAngle && angle <= endAngle)
  10537. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10538. }
  10539. function windingLine(x0, y0, x1, y1, x, y) {
  10540. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10541. return 0;
  10542. }
  10543. if (y1 === y0) {
  10544. return 0;
  10545. }
  10546. var t = (y - y0) / (y1 - y0);
  10547. var dir = y1 < y0 ? 1 : -1;
  10548. if (t === 1 || t === 0) {
  10549. dir = y1 < y0 ? 0.5 : -0.5;
  10550. }
  10551. var x_ = t * (x1 - x0) + x0;
  10552. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10553. }
  10554. var CMD$1 = PathProxy.CMD;
  10555. var PI2$4 = Math.PI * 2;
  10556. var EPSILON$3 = 1e-4;
  10557. function isAroundEqual(a, b) {
  10558. return Math.abs(a - b) < EPSILON$3;
  10559. }
  10560. var roots = [-1, -1, -1];
  10561. var extrema = [-1, -1];
  10562. function swapExtrema() {
  10563. var tmp = extrema[0];
  10564. extrema[0] = extrema[1];
  10565. extrema[1] = tmp;
  10566. }
  10567. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10568. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10569. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10570. return 0;
  10571. }
  10572. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10573. if (nRoots === 0) {
  10574. return 0;
  10575. }
  10576. else {
  10577. var w = 0;
  10578. var nExtrema = -1;
  10579. var y0_ = void 0;
  10580. var y1_ = void 0;
  10581. for (var i = 0; i < nRoots; i++) {
  10582. var t = roots[i];
  10583. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10584. var x_ = cubicAt(x0, x1, x2, x3, t);
  10585. if (x_ < x) {
  10586. continue;
  10587. }
  10588. if (nExtrema < 0) {
  10589. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10590. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10591. swapExtrema();
  10592. }
  10593. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10594. if (nExtrema > 1) {
  10595. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10596. }
  10597. }
  10598. if (nExtrema === 2) {
  10599. if (t < extrema[0]) {
  10600. w += y0_ < y0 ? unit : -unit;
  10601. }
  10602. else if (t < extrema[1]) {
  10603. w += y1_ < y0_ ? unit : -unit;
  10604. }
  10605. else {
  10606. w += y3 < y1_ ? unit : -unit;
  10607. }
  10608. }
  10609. else {
  10610. if (t < extrema[0]) {
  10611. w += y0_ < y0 ? unit : -unit;
  10612. }
  10613. else {
  10614. w += y3 < y0_ ? unit : -unit;
  10615. }
  10616. }
  10617. }
  10618. return w;
  10619. }
  10620. }
  10621. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10622. if ((y > y0 && y > y1 && y > y2)
  10623. || (y < y0 && y < y1 && y < y2)) {
  10624. return 0;
  10625. }
  10626. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10627. if (nRoots === 0) {
  10628. return 0;
  10629. }
  10630. else {
  10631. var t = quadraticExtremum(y0, y1, y2);
  10632. if (t >= 0 && t <= 1) {
  10633. var w = 0;
  10634. var y_ = quadraticAt(y0, y1, y2, t);
  10635. for (var i = 0; i < nRoots; i++) {
  10636. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10637. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10638. if (x_ < x) {
  10639. continue;
  10640. }
  10641. if (roots[i] < t) {
  10642. w += y_ < y0 ? unit : -unit;
  10643. }
  10644. else {
  10645. w += y2 < y_ ? unit : -unit;
  10646. }
  10647. }
  10648. return w;
  10649. }
  10650. else {
  10651. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10652. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10653. if (x_ < x) {
  10654. return 0;
  10655. }
  10656. return y2 < y0 ? unit : -unit;
  10657. }
  10658. }
  10659. }
  10660. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10661. y -= cy;
  10662. if (y > r || y < -r) {
  10663. return 0;
  10664. }
  10665. var tmp = Math.sqrt(r * r - y * y);
  10666. roots[0] = -tmp;
  10667. roots[1] = tmp;
  10668. var dTheta = Math.abs(startAngle - endAngle);
  10669. if (dTheta < 1e-4) {
  10670. return 0;
  10671. }
  10672. if (dTheta >= PI2$4 - 1e-4) {
  10673. startAngle = 0;
  10674. endAngle = PI2$4;
  10675. var dir = anticlockwise ? 1 : -1;
  10676. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10677. return dir;
  10678. }
  10679. else {
  10680. return 0;
  10681. }
  10682. }
  10683. if (startAngle > endAngle) {
  10684. var tmp_1 = startAngle;
  10685. startAngle = endAngle;
  10686. endAngle = tmp_1;
  10687. }
  10688. if (startAngle < 0) {
  10689. startAngle += PI2$4;
  10690. endAngle += PI2$4;
  10691. }
  10692. var w = 0;
  10693. for (var i = 0; i < 2; i++) {
  10694. var x_ = roots[i];
  10695. if (x_ + cx > x) {
  10696. var angle = Math.atan2(y, x_);
  10697. var dir = anticlockwise ? 1 : -1;
  10698. if (angle < 0) {
  10699. angle = PI2$4 + angle;
  10700. }
  10701. if ((angle >= startAngle && angle <= endAngle)
  10702. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10703. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10704. dir = -dir;
  10705. }
  10706. w += dir;
  10707. }
  10708. }
  10709. }
  10710. return w;
  10711. }
  10712. function containPath(path, lineWidth, isStroke, x, y) {
  10713. var data = path.data;
  10714. var len = path.len();
  10715. var w = 0;
  10716. var xi = 0;
  10717. var yi = 0;
  10718. var x0 = 0;
  10719. var y0 = 0;
  10720. var x1;
  10721. var y1;
  10722. for (var i = 0; i < len;) {
  10723. var cmd = data[i++];
  10724. var isFirst = i === 1;
  10725. if (cmd === CMD$1.M && i > 1) {
  10726. if (!isStroke) {
  10727. w += windingLine(xi, yi, x0, y0, x, y);
  10728. }
  10729. }
  10730. if (isFirst) {
  10731. xi = data[i];
  10732. yi = data[i + 1];
  10733. x0 = xi;
  10734. y0 = yi;
  10735. }
  10736. switch (cmd) {
  10737. case CMD$1.M:
  10738. x0 = data[i++];
  10739. y0 = data[i++];
  10740. xi = x0;
  10741. yi = y0;
  10742. break;
  10743. case CMD$1.L:
  10744. if (isStroke) {
  10745. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10746. return true;
  10747. }
  10748. }
  10749. else {
  10750. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10751. }
  10752. xi = data[i++];
  10753. yi = data[i++];
  10754. break;
  10755. case CMD$1.C:
  10756. if (isStroke) {
  10757. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10758. return true;
  10759. }
  10760. }
  10761. else {
  10762. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10763. }
  10764. xi = data[i++];
  10765. yi = data[i++];
  10766. break;
  10767. case CMD$1.Q:
  10768. if (isStroke) {
  10769. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10770. return true;
  10771. }
  10772. }
  10773. else {
  10774. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10775. }
  10776. xi = data[i++];
  10777. yi = data[i++];
  10778. break;
  10779. case CMD$1.A:
  10780. var cx = data[i++];
  10781. var cy = data[i++];
  10782. var rx = data[i++];
  10783. var ry = data[i++];
  10784. var theta = data[i++];
  10785. var dTheta = data[i++];
  10786. i += 1;
  10787. var anticlockwise = !!(1 - data[i++]);
  10788. x1 = Math.cos(theta) * rx + cx;
  10789. y1 = Math.sin(theta) * ry + cy;
  10790. if (!isFirst) {
  10791. w += windingLine(xi, yi, x1, y1, x, y);
  10792. }
  10793. else {
  10794. x0 = x1;
  10795. y0 = y1;
  10796. }
  10797. var _x = (x - cx) * ry / rx + cx;
  10798. if (isStroke) {
  10799. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10800. return true;
  10801. }
  10802. }
  10803. else {
  10804. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10805. }
  10806. xi = Math.cos(theta + dTheta) * rx + cx;
  10807. yi = Math.sin(theta + dTheta) * ry + cy;
  10808. break;
  10809. case CMD$1.R:
  10810. x0 = xi = data[i++];
  10811. y0 = yi = data[i++];
  10812. var width = data[i++];
  10813. var height = data[i++];
  10814. x1 = x0 + width;
  10815. y1 = y0 + height;
  10816. if (isStroke) {
  10817. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10818. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10819. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10820. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10821. return true;
  10822. }
  10823. }
  10824. else {
  10825. w += windingLine(x1, y0, x1, y1, x, y);
  10826. w += windingLine(x0, y1, x0, y0, x, y);
  10827. }
  10828. break;
  10829. case CMD$1.Z:
  10830. if (isStroke) {
  10831. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10832. return true;
  10833. }
  10834. }
  10835. else {
  10836. w += windingLine(xi, yi, x0, y0, x, y);
  10837. }
  10838. xi = x0;
  10839. yi = y0;
  10840. break;
  10841. }
  10842. }
  10843. if (!isStroke && !isAroundEqual(yi, y0)) {
  10844. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10845. }
  10846. return w !== 0;
  10847. }
  10848. function contain(pathProxy, x, y) {
  10849. return containPath(pathProxy, 0, false, x, y);
  10850. }
  10851. function containStroke$4(pathProxy, lineWidth, x, y) {
  10852. return containPath(pathProxy, lineWidth, true, x, y);
  10853. }
  10854. var DEFAULT_PATH_STYLE = defaults({
  10855. fill: '#000',
  10856. stroke: null,
  10857. strokePercent: 1,
  10858. fillOpacity: 1,
  10859. strokeOpacity: 1,
  10860. lineDashOffset: 0,
  10861. lineWidth: 1,
  10862. lineCap: 'butt',
  10863. miterLimit: 10,
  10864. strokeNoScale: false,
  10865. strokeFirst: false
  10866. }, DEFAULT_COMMON_STYLE);
  10867. var DEFAULT_PATH_ANIMATION_PROPS = {
  10868. style: defaults({
  10869. fill: true,
  10870. stroke: true,
  10871. strokePercent: true,
  10872. fillOpacity: true,
  10873. strokeOpacity: true,
  10874. lineDashOffset: true,
  10875. lineWidth: true,
  10876. miterLimit: true
  10877. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10878. };
  10879. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10880. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10881. ]);
  10882. var Path = (function (_super) {
  10883. __extends(Path, _super);
  10884. function Path(opts) {
  10885. return _super.call(this, opts) || this;
  10886. }
  10887. Path.prototype.update = function () {
  10888. var _this = this;
  10889. _super.prototype.update.call(this);
  10890. var style = this.style;
  10891. if (style.decal) {
  10892. var decalEl = this._decalEl = this._decalEl || new Path();
  10893. if (decalEl.buildPath === Path.prototype.buildPath) {
  10894. decalEl.buildPath = function (ctx) {
  10895. _this.buildPath(ctx, _this.shape);
  10896. };
  10897. }
  10898. decalEl.silent = true;
  10899. var decalElStyle = decalEl.style;
  10900. for (var key in style) {
  10901. if (decalElStyle[key] !== style[key]) {
  10902. decalElStyle[key] = style[key];
  10903. }
  10904. }
  10905. decalElStyle.fill = style.fill ? style.decal : null;
  10906. decalElStyle.decal = null;
  10907. decalElStyle.shadowColor = null;
  10908. style.strokeFirst && (decalElStyle.stroke = null);
  10909. for (var i = 0; i < pathCopyParams.length; ++i) {
  10910. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10911. }
  10912. decalEl.__dirty |= REDRAW_BIT;
  10913. }
  10914. else if (this._decalEl) {
  10915. this._decalEl = null;
  10916. }
  10917. };
  10918. Path.prototype.getDecalElement = function () {
  10919. return this._decalEl;
  10920. };
  10921. Path.prototype._init = function (props) {
  10922. var keysArr = keys(props);
  10923. this.shape = this.getDefaultShape();
  10924. var defaultStyle = this.getDefaultStyle();
  10925. if (defaultStyle) {
  10926. this.useStyle(defaultStyle);
  10927. }
  10928. for (var i = 0; i < keysArr.length; i++) {
  10929. var key = keysArr[i];
  10930. var value = props[key];
  10931. if (key === 'style') {
  10932. if (!this.style) {
  10933. this.useStyle(value);
  10934. }
  10935. else {
  10936. extend(this.style, value);
  10937. }
  10938. }
  10939. else if (key === 'shape') {
  10940. extend(this.shape, value);
  10941. }
  10942. else {
  10943. _super.prototype.attrKV.call(this, key, value);
  10944. }
  10945. }
  10946. if (!this.style) {
  10947. this.useStyle({});
  10948. }
  10949. };
  10950. Path.prototype.getDefaultStyle = function () {
  10951. return null;
  10952. };
  10953. Path.prototype.getDefaultShape = function () {
  10954. return {};
  10955. };
  10956. Path.prototype.canBeInsideText = function () {
  10957. return this.hasFill();
  10958. };
  10959. Path.prototype.getInsideTextFill = function () {
  10960. var pathFill = this.style.fill;
  10961. if (pathFill !== 'none') {
  10962. if (isString(pathFill)) {
  10963. var fillLum = lum(pathFill, 0);
  10964. if (fillLum > 0.5) {
  10965. return DARK_LABEL_COLOR;
  10966. }
  10967. else if (fillLum > 0.2) {
  10968. return LIGHTER_LABEL_COLOR;
  10969. }
  10970. return LIGHT_LABEL_COLOR;
  10971. }
  10972. else if (pathFill) {
  10973. return LIGHT_LABEL_COLOR;
  10974. }
  10975. }
  10976. return DARK_LABEL_COLOR;
  10977. };
  10978. Path.prototype.getInsideTextStroke = function (textFill) {
  10979. var pathFill = this.style.fill;
  10980. if (isString(pathFill)) {
  10981. var zr = this.__zr;
  10982. var isDarkMode = !!(zr && zr.isDarkMode());
  10983. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10984. if (isDarkMode === isDarkLabel) {
  10985. return pathFill;
  10986. }
  10987. }
  10988. };
  10989. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10990. Path.prototype.pathUpdated = function () {
  10991. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10992. };
  10993. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10994. !this.path && this.createPathProxy();
  10995. this.path.beginPath();
  10996. this.buildPath(this.path, this.shape, inBatch);
  10997. return this.path;
  10998. };
  10999. Path.prototype.createPathProxy = function () {
  11000. this.path = new PathProxy(false);
  11001. };
  11002. Path.prototype.hasStroke = function () {
  11003. var style = this.style;
  11004. var stroke = style.stroke;
  11005. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  11006. };
  11007. Path.prototype.hasFill = function () {
  11008. var style = this.style;
  11009. var fill = style.fill;
  11010. return fill != null && fill !== 'none';
  11011. };
  11012. Path.prototype.getBoundingRect = function () {
  11013. var rect = this._rect;
  11014. var style = this.style;
  11015. var needsUpdateRect = !rect;
  11016. if (needsUpdateRect) {
  11017. var firstInvoke = false;
  11018. if (!this.path) {
  11019. firstInvoke = true;
  11020. this.createPathProxy();
  11021. }
  11022. var path = this.path;
  11023. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  11024. path.beginPath();
  11025. this.buildPath(path, this.shape, false);
  11026. this.pathUpdated();
  11027. }
  11028. rect = path.getBoundingRect();
  11029. }
  11030. this._rect = rect;
  11031. if (this.hasStroke() && this.path && this.path.len() > 0) {
  11032. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  11033. if (this.__dirty || needsUpdateRect) {
  11034. rectStroke.copy(rect);
  11035. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11036. var w = style.lineWidth;
  11037. if (!this.hasFill()) {
  11038. var strokeContainThreshold = this.strokeContainThreshold;
  11039. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  11040. }
  11041. if (lineScale > 1e-10) {
  11042. rectStroke.width += w / lineScale;
  11043. rectStroke.height += w / lineScale;
  11044. rectStroke.x -= w / lineScale / 2;
  11045. rectStroke.y -= w / lineScale / 2;
  11046. }
  11047. }
  11048. return rectStroke;
  11049. }
  11050. return rect;
  11051. };
  11052. Path.prototype.contain = function (x, y) {
  11053. var localPos = this.transformCoordToLocal(x, y);
  11054. var rect = this.getBoundingRect();
  11055. var style = this.style;
  11056. x = localPos[0];
  11057. y = localPos[1];
  11058. if (rect.contain(x, y)) {
  11059. var pathProxy = this.path;
  11060. if (this.hasStroke()) {
  11061. var lineWidth = style.lineWidth;
  11062. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11063. if (lineScale > 1e-10) {
  11064. if (!this.hasFill()) {
  11065. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11066. }
  11067. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  11068. return true;
  11069. }
  11070. }
  11071. }
  11072. if (this.hasFill()) {
  11073. return contain(pathProxy, x, y);
  11074. }
  11075. }
  11076. return false;
  11077. };
  11078. Path.prototype.dirtyShape = function () {
  11079. this.__dirty |= SHAPE_CHANGED_BIT;
  11080. if (this._rect) {
  11081. this._rect = null;
  11082. }
  11083. if (this._decalEl) {
  11084. this._decalEl.dirtyShape();
  11085. }
  11086. this.markRedraw();
  11087. };
  11088. Path.prototype.dirty = function () {
  11089. this.dirtyStyle();
  11090. this.dirtyShape();
  11091. };
  11092. Path.prototype.animateShape = function (loop) {
  11093. return this.animate('shape', loop);
  11094. };
  11095. Path.prototype.updateDuringAnimation = function (targetKey) {
  11096. if (targetKey === 'style') {
  11097. this.dirtyStyle();
  11098. }
  11099. else if (targetKey === 'shape') {
  11100. this.dirtyShape();
  11101. }
  11102. else {
  11103. this.markRedraw();
  11104. }
  11105. };
  11106. Path.prototype.attrKV = function (key, value) {
  11107. if (key === 'shape') {
  11108. this.setShape(value);
  11109. }
  11110. else {
  11111. _super.prototype.attrKV.call(this, key, value);
  11112. }
  11113. };
  11114. Path.prototype.setShape = function (keyOrObj, value) {
  11115. var shape = this.shape;
  11116. if (!shape) {
  11117. shape = this.shape = {};
  11118. }
  11119. if (typeof keyOrObj === 'string') {
  11120. shape[keyOrObj] = value;
  11121. }
  11122. else {
  11123. extend(shape, keyOrObj);
  11124. }
  11125. this.dirtyShape();
  11126. return this;
  11127. };
  11128. Path.prototype.shapeChanged = function () {
  11129. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  11130. };
  11131. Path.prototype.createStyle = function (obj) {
  11132. return createObject(DEFAULT_PATH_STYLE, obj);
  11133. };
  11134. Path.prototype._innerSaveToNormal = function (toState) {
  11135. _super.prototype._innerSaveToNormal.call(this, toState);
  11136. var normalState = this._normalState;
  11137. if (toState.shape && !normalState.shape) {
  11138. normalState.shape = extend({}, this.shape);
  11139. }
  11140. };
  11141. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  11142. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  11143. var needsRestoreToNormal = !(state && keepCurrentStates);
  11144. var targetShape;
  11145. if (state && state.shape) {
  11146. if (transition) {
  11147. if (keepCurrentStates) {
  11148. targetShape = state.shape;
  11149. }
  11150. else {
  11151. targetShape = extend({}, normalState.shape);
  11152. extend(targetShape, state.shape);
  11153. }
  11154. }
  11155. else {
  11156. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11157. extend(targetShape, state.shape);
  11158. }
  11159. }
  11160. else if (needsRestoreToNormal) {
  11161. targetShape = normalState.shape;
  11162. }
  11163. if (targetShape) {
  11164. if (transition) {
  11165. this.shape = extend({}, this.shape);
  11166. var targetShapePrimaryProps = {};
  11167. var shapeKeys = keys(targetShape);
  11168. for (var i = 0; i < shapeKeys.length; i++) {
  11169. var key = shapeKeys[i];
  11170. if (typeof targetShape[key] === 'object') {
  11171. this.shape[key] = targetShape[key];
  11172. }
  11173. else {
  11174. targetShapePrimaryProps[key] = targetShape[key];
  11175. }
  11176. }
  11177. this._transitionState(stateName, {
  11178. shape: targetShapePrimaryProps
  11179. }, animationCfg);
  11180. }
  11181. else {
  11182. this.shape = targetShape;
  11183. this.dirtyShape();
  11184. }
  11185. }
  11186. };
  11187. Path.prototype._mergeStates = function (states) {
  11188. var mergedState = _super.prototype._mergeStates.call(this, states);
  11189. var mergedShape;
  11190. for (var i = 0; i < states.length; i++) {
  11191. var state = states[i];
  11192. if (state.shape) {
  11193. mergedShape = mergedShape || {};
  11194. this._mergeStyle(mergedShape, state.shape);
  11195. }
  11196. }
  11197. if (mergedShape) {
  11198. mergedState.shape = mergedShape;
  11199. }
  11200. return mergedState;
  11201. };
  11202. Path.prototype.getAnimationStyleProps = function () {
  11203. return DEFAULT_PATH_ANIMATION_PROPS;
  11204. };
  11205. Path.prototype.isZeroArea = function () {
  11206. return false;
  11207. };
  11208. Path.extend = function (defaultProps) {
  11209. var Sub = (function (_super) {
  11210. __extends(Sub, _super);
  11211. function Sub(opts) {
  11212. var _this = _super.call(this, opts) || this;
  11213. defaultProps.init && defaultProps.init.call(_this, opts);
  11214. return _this;
  11215. }
  11216. Sub.prototype.getDefaultStyle = function () {
  11217. return clone(defaultProps.style);
  11218. };
  11219. Sub.prototype.getDefaultShape = function () {
  11220. return clone(defaultProps.shape);
  11221. };
  11222. return Sub;
  11223. }(Path));
  11224. for (var key in defaultProps) {
  11225. if (typeof defaultProps[key] === 'function') {
  11226. Sub.prototype[key] = defaultProps[key];
  11227. }
  11228. }
  11229. return Sub;
  11230. };
  11231. Path.initDefaultProps = (function () {
  11232. var pathProto = Path.prototype;
  11233. pathProto.type = 'path';
  11234. pathProto.strokeContainThreshold = 5;
  11235. pathProto.segmentIgnoreThreshold = 0;
  11236. pathProto.subPixelOptimize = false;
  11237. pathProto.autoBatch = false;
  11238. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11239. })();
  11240. return Path;
  11241. }(Displayable));
  11242. var DEFAULT_TSPAN_STYLE = defaults({
  11243. strokeFirst: true,
  11244. font: DEFAULT_FONT,
  11245. x: 0,
  11246. y: 0,
  11247. textAlign: 'left',
  11248. textBaseline: 'top',
  11249. miterLimit: 2
  11250. }, DEFAULT_PATH_STYLE);
  11251. var TSpan = (function (_super) {
  11252. __extends(TSpan, _super);
  11253. function TSpan() {
  11254. return _super !== null && _super.apply(this, arguments) || this;
  11255. }
  11256. TSpan.prototype.hasStroke = function () {
  11257. var style = this.style;
  11258. var stroke = style.stroke;
  11259. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11260. };
  11261. TSpan.prototype.hasFill = function () {
  11262. var style = this.style;
  11263. var fill = style.fill;
  11264. return fill != null && fill !== 'none';
  11265. };
  11266. TSpan.prototype.createStyle = function (obj) {
  11267. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11268. };
  11269. TSpan.prototype.setBoundingRect = function (rect) {
  11270. this._rect = rect;
  11271. };
  11272. TSpan.prototype.getBoundingRect = function () {
  11273. var style = this.style;
  11274. if (!this._rect) {
  11275. var text = style.text;
  11276. text != null ? (text += '') : (text = '');
  11277. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11278. rect.x += style.x || 0;
  11279. rect.y += style.y || 0;
  11280. if (this.hasStroke()) {
  11281. var w = style.lineWidth;
  11282. rect.x -= w / 2;
  11283. rect.y -= w / 2;
  11284. rect.width += w;
  11285. rect.height += w;
  11286. }
  11287. this._rect = rect;
  11288. }
  11289. return this._rect;
  11290. };
  11291. TSpan.initDefaultProps = (function () {
  11292. var tspanProto = TSpan.prototype;
  11293. tspanProto.dirtyRectTolerance = 10;
  11294. })();
  11295. return TSpan;
  11296. }(Displayable));
  11297. TSpan.prototype.type = 'tspan';
  11298. var DEFAULT_IMAGE_STYLE = defaults({
  11299. x: 0,
  11300. y: 0
  11301. }, DEFAULT_COMMON_STYLE);
  11302. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11303. style: defaults({
  11304. x: true,
  11305. y: true,
  11306. width: true,
  11307. height: true,
  11308. sx: true,
  11309. sy: true,
  11310. sWidth: true,
  11311. sHeight: true
  11312. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11313. };
  11314. function isImageLike(source) {
  11315. return !!(source
  11316. && typeof source !== 'string'
  11317. && source.width && source.height);
  11318. }
  11319. var ZRImage = (function (_super) {
  11320. __extends(ZRImage, _super);
  11321. function ZRImage() {
  11322. return _super !== null && _super.apply(this, arguments) || this;
  11323. }
  11324. ZRImage.prototype.createStyle = function (obj) {
  11325. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11326. };
  11327. ZRImage.prototype._getSize = function (dim) {
  11328. var style = this.style;
  11329. var size = style[dim];
  11330. if (size != null) {
  11331. return size;
  11332. }
  11333. var imageSource = isImageLike(style.image)
  11334. ? style.image : this.__image;
  11335. if (!imageSource) {
  11336. return 0;
  11337. }
  11338. var otherDim = dim === 'width' ? 'height' : 'width';
  11339. var otherDimSize = style[otherDim];
  11340. if (otherDimSize == null) {
  11341. return imageSource[dim];
  11342. }
  11343. else {
  11344. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11345. }
  11346. };
  11347. ZRImage.prototype.getWidth = function () {
  11348. return this._getSize('width');
  11349. };
  11350. ZRImage.prototype.getHeight = function () {
  11351. return this._getSize('height');
  11352. };
  11353. ZRImage.prototype.getAnimationStyleProps = function () {
  11354. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11355. };
  11356. ZRImage.prototype.getBoundingRect = function () {
  11357. var style = this.style;
  11358. if (!this._rect) {
  11359. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11360. }
  11361. return this._rect;
  11362. };
  11363. return ZRImage;
  11364. }(Displayable));
  11365. ZRImage.prototype.type = 'image';
  11366. function buildPath(ctx, shape) {
  11367. var x = shape.x;
  11368. var y = shape.y;
  11369. var width = shape.width;
  11370. var height = shape.height;
  11371. var r = shape.r;
  11372. var r1;
  11373. var r2;
  11374. var r3;
  11375. var r4;
  11376. if (width < 0) {
  11377. x = x + width;
  11378. width = -width;
  11379. }
  11380. if (height < 0) {
  11381. y = y + height;
  11382. height = -height;
  11383. }
  11384. if (typeof r === 'number') {
  11385. r1 = r2 = r3 = r4 = r;
  11386. }
  11387. else if (r instanceof Array) {
  11388. if (r.length === 1) {
  11389. r1 = r2 = r3 = r4 = r[0];
  11390. }
  11391. else if (r.length === 2) {
  11392. r1 = r3 = r[0];
  11393. r2 = r4 = r[1];
  11394. }
  11395. else if (r.length === 3) {
  11396. r1 = r[0];
  11397. r2 = r4 = r[1];
  11398. r3 = r[2];
  11399. }
  11400. else {
  11401. r1 = r[0];
  11402. r2 = r[1];
  11403. r3 = r[2];
  11404. r4 = r[3];
  11405. }
  11406. }
  11407. else {
  11408. r1 = r2 = r3 = r4 = 0;
  11409. }
  11410. var total;
  11411. if (r1 + r2 > width) {
  11412. total = r1 + r2;
  11413. r1 *= width / total;
  11414. r2 *= width / total;
  11415. }
  11416. if (r3 + r4 > width) {
  11417. total = r3 + r4;
  11418. r3 *= width / total;
  11419. r4 *= width / total;
  11420. }
  11421. if (r2 + r3 > height) {
  11422. total = r2 + r3;
  11423. r2 *= height / total;
  11424. r3 *= height / total;
  11425. }
  11426. if (r1 + r4 > height) {
  11427. total = r1 + r4;
  11428. r1 *= height / total;
  11429. r4 *= height / total;
  11430. }
  11431. ctx.moveTo(x + r1, y);
  11432. ctx.lineTo(x + width - r2, y);
  11433. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11434. ctx.lineTo(x + width, y + height - r3);
  11435. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11436. ctx.lineTo(x + r4, y + height);
  11437. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11438. ctx.lineTo(x, y + r1);
  11439. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11440. }
  11441. var round$1 = Math.round;
  11442. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11443. if (!inputShape) {
  11444. return;
  11445. }
  11446. var x1 = inputShape.x1;
  11447. var x2 = inputShape.x2;
  11448. var y1 = inputShape.y1;
  11449. var y2 = inputShape.y2;
  11450. outputShape.x1 = x1;
  11451. outputShape.x2 = x2;
  11452. outputShape.y1 = y1;
  11453. outputShape.y2 = y2;
  11454. var lineWidth = style && style.lineWidth;
  11455. if (!lineWidth) {
  11456. return outputShape;
  11457. }
  11458. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11459. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11460. }
  11461. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11462. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11463. }
  11464. return outputShape;
  11465. }
  11466. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11467. if (!inputShape) {
  11468. return;
  11469. }
  11470. var originX = inputShape.x;
  11471. var originY = inputShape.y;
  11472. var originWidth = inputShape.width;
  11473. var originHeight = inputShape.height;
  11474. outputShape.x = originX;
  11475. outputShape.y = originY;
  11476. outputShape.width = originWidth;
  11477. outputShape.height = originHeight;
  11478. var lineWidth = style && style.lineWidth;
  11479. if (!lineWidth) {
  11480. return outputShape;
  11481. }
  11482. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11483. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11484. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11485. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11486. return outputShape;
  11487. }
  11488. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11489. if (!lineWidth) {
  11490. return position;
  11491. }
  11492. var doubledPosition = round$1(position * 2);
  11493. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11494. ? doubledPosition / 2
  11495. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11496. }
  11497. var RectShape = (function () {
  11498. function RectShape() {
  11499. this.x = 0;
  11500. this.y = 0;
  11501. this.width = 0;
  11502. this.height = 0;
  11503. }
  11504. return RectShape;
  11505. }());
  11506. var subPixelOptimizeOutputShape = {};
  11507. var Rect = (function (_super) {
  11508. __extends(Rect, _super);
  11509. function Rect(opts) {
  11510. return _super.call(this, opts) || this;
  11511. }
  11512. Rect.prototype.getDefaultShape = function () {
  11513. return new RectShape();
  11514. };
  11515. Rect.prototype.buildPath = function (ctx, shape) {
  11516. var x;
  11517. var y;
  11518. var width;
  11519. var height;
  11520. if (this.subPixelOptimize) {
  11521. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11522. x = optimizedShape.x;
  11523. y = optimizedShape.y;
  11524. width = optimizedShape.width;
  11525. height = optimizedShape.height;
  11526. optimizedShape.r = shape.r;
  11527. shape = optimizedShape;
  11528. }
  11529. else {
  11530. x = shape.x;
  11531. y = shape.y;
  11532. width = shape.width;
  11533. height = shape.height;
  11534. }
  11535. if (!shape.r) {
  11536. ctx.rect(x, y, width, height);
  11537. }
  11538. else {
  11539. buildPath(ctx, shape);
  11540. }
  11541. };
  11542. Rect.prototype.isZeroArea = function () {
  11543. return !this.shape.width || !this.shape.height;
  11544. };
  11545. return Rect;
  11546. }(Path));
  11547. Rect.prototype.type = 'rect';
  11548. var DEFAULT_RICH_TEXT_COLOR = {
  11549. fill: '#000'
  11550. };
  11551. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11552. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11553. style: defaults({
  11554. fill: true,
  11555. stroke: true,
  11556. fillOpacity: true,
  11557. strokeOpacity: true,
  11558. lineWidth: true,
  11559. fontSize: true,
  11560. lineHeight: true,
  11561. width: true,
  11562. height: true,
  11563. textShadowColor: true,
  11564. textShadowBlur: true,
  11565. textShadowOffsetX: true,
  11566. textShadowOffsetY: true,
  11567. backgroundColor: true,
  11568. padding: true,
  11569. borderColor: true,
  11570. borderWidth: true,
  11571. borderRadius: true
  11572. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11573. };
  11574. var ZRText = (function (_super) {
  11575. __extends(ZRText, _super);
  11576. function ZRText(opts) {
  11577. var _this = _super.call(this) || this;
  11578. _this.type = 'text';
  11579. _this._children = [];
  11580. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11581. _this.attr(opts);
  11582. return _this;
  11583. }
  11584. ZRText.prototype.childrenRef = function () {
  11585. return this._children;
  11586. };
  11587. ZRText.prototype.update = function () {
  11588. _super.prototype.update.call(this);
  11589. if (this.styleChanged()) {
  11590. this._updateSubTexts();
  11591. }
  11592. for (var i = 0; i < this._children.length; i++) {
  11593. var child = this._children[i];
  11594. child.zlevel = this.zlevel;
  11595. child.z = this.z;
  11596. child.z2 = this.z2;
  11597. child.culling = this.culling;
  11598. child.cursor = this.cursor;
  11599. child.invisible = this.invisible;
  11600. }
  11601. };
  11602. ZRText.prototype.updateTransform = function () {
  11603. var innerTransformable = this.innerTransformable;
  11604. if (innerTransformable) {
  11605. innerTransformable.updateTransform();
  11606. if (innerTransformable.transform) {
  11607. this.transform = innerTransformable.transform;
  11608. }
  11609. }
  11610. else {
  11611. _super.prototype.updateTransform.call(this);
  11612. }
  11613. };
  11614. ZRText.prototype.getLocalTransform = function (m) {
  11615. var innerTransformable = this.innerTransformable;
  11616. return innerTransformable
  11617. ? innerTransformable.getLocalTransform(m)
  11618. : _super.prototype.getLocalTransform.call(this, m);
  11619. };
  11620. ZRText.prototype.getComputedTransform = function () {
  11621. if (this.__hostTarget) {
  11622. this.__hostTarget.getComputedTransform();
  11623. this.__hostTarget.updateInnerText(true);
  11624. }
  11625. return _super.prototype.getComputedTransform.call(this);
  11626. };
  11627. ZRText.prototype._updateSubTexts = function () {
  11628. this._childCursor = 0;
  11629. normalizeTextStyle(this.style);
  11630. this.style.rich
  11631. ? this._updateRichTexts()
  11632. : this._updatePlainTexts();
  11633. this._children.length = this._childCursor;
  11634. this.styleUpdated();
  11635. };
  11636. ZRText.prototype.addSelfToZr = function (zr) {
  11637. _super.prototype.addSelfToZr.call(this, zr);
  11638. for (var i = 0; i < this._children.length; i++) {
  11639. this._children[i].__zr = zr;
  11640. }
  11641. };
  11642. ZRText.prototype.removeSelfFromZr = function (zr) {
  11643. _super.prototype.removeSelfFromZr.call(this, zr);
  11644. for (var i = 0; i < this._children.length; i++) {
  11645. this._children[i].__zr = null;
  11646. }
  11647. };
  11648. ZRText.prototype.getBoundingRect = function () {
  11649. if (this.styleChanged()) {
  11650. this._updateSubTexts();
  11651. }
  11652. if (!this._rect) {
  11653. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11654. var children = this._children;
  11655. var tmpMat = [];
  11656. var rect = null;
  11657. for (var i = 0; i < children.length; i++) {
  11658. var child = children[i];
  11659. var childRect = child.getBoundingRect();
  11660. var transform = child.getLocalTransform(tmpMat);
  11661. if (transform) {
  11662. tmpRect.copy(childRect);
  11663. tmpRect.applyTransform(transform);
  11664. rect = rect || tmpRect.clone();
  11665. rect.union(tmpRect);
  11666. }
  11667. else {
  11668. rect = rect || childRect.clone();
  11669. rect.union(childRect);
  11670. }
  11671. }
  11672. this._rect = rect || tmpRect;
  11673. }
  11674. return this._rect;
  11675. };
  11676. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11677. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11678. };
  11679. ZRText.prototype.setTextContent = function (textContent) {
  11680. if ("development" !== 'production') {
  11681. throw new Error('Can\'t attach text on another text');
  11682. }
  11683. };
  11684. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11685. if (!sourceStyle) {
  11686. return targetStyle;
  11687. }
  11688. var sourceRich = sourceStyle.rich;
  11689. var targetRich = targetStyle.rich || (sourceRich && {});
  11690. extend(targetStyle, sourceStyle);
  11691. if (sourceRich && targetRich) {
  11692. this._mergeRich(targetRich, sourceRich);
  11693. targetStyle.rich = targetRich;
  11694. }
  11695. else if (targetRich) {
  11696. targetStyle.rich = targetRich;
  11697. }
  11698. return targetStyle;
  11699. };
  11700. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11701. var richNames = keys(sourceRich);
  11702. for (var i = 0; i < richNames.length; i++) {
  11703. var richName = richNames[i];
  11704. targetRich[richName] = targetRich[richName] || {};
  11705. extend(targetRich[richName], sourceRich[richName]);
  11706. }
  11707. };
  11708. ZRText.prototype.getAnimationStyleProps = function () {
  11709. return DEFAULT_TEXT_ANIMATION_PROPS;
  11710. };
  11711. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11712. var child = this._children[this._childCursor];
  11713. if (!child || !(child instanceof Ctor)) {
  11714. child = new Ctor();
  11715. }
  11716. this._children[this._childCursor++] = child;
  11717. child.__zr = this.__zr;
  11718. child.parent = this;
  11719. return child;
  11720. };
  11721. ZRText.prototype._updatePlainTexts = function () {
  11722. var style = this.style;
  11723. var textFont = style.font || DEFAULT_FONT;
  11724. var textPadding = style.padding;
  11725. var text = getStyleText(style);
  11726. var contentBlock = parsePlainText(text, style);
  11727. var needDrawBg = needDrawBackground(style);
  11728. var bgColorDrawn = !!(style.backgroundColor);
  11729. var outerHeight = contentBlock.outerHeight;
  11730. var outerWidth = contentBlock.outerWidth;
  11731. var contentWidth = contentBlock.contentWidth;
  11732. var textLines = contentBlock.lines;
  11733. var lineHeight = contentBlock.lineHeight;
  11734. var defaultStyle = this._defaultStyle;
  11735. var baseX = style.x || 0;
  11736. var baseY = style.y || 0;
  11737. var textAlign = style.align || defaultStyle.align || 'left';
  11738. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11739. var textX = baseX;
  11740. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11741. if (needDrawBg || textPadding) {
  11742. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11743. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11744. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11745. }
  11746. textY += lineHeight / 2;
  11747. if (textPadding) {
  11748. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11749. if (verticalAlign === 'top') {
  11750. textY += textPadding[0];
  11751. }
  11752. else if (verticalAlign === 'bottom') {
  11753. textY -= textPadding[2];
  11754. }
  11755. }
  11756. var defaultLineWidth = 0;
  11757. var useDefaultFill = false;
  11758. var textFill = getFill('fill' in style
  11759. ? style.fill
  11760. : (useDefaultFill = true, defaultStyle.fill));
  11761. var textStroke = getStroke('stroke' in style
  11762. ? style.stroke
  11763. : (!bgColorDrawn
  11764. && (!defaultStyle.autoStroke || useDefaultFill))
  11765. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11766. : null);
  11767. var hasShadow = style.textShadowBlur > 0;
  11768. var fixedBoundingRect = style.width != null
  11769. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11770. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11771. for (var i = 0; i < textLines.length; i++) {
  11772. var el = this._getOrCreateChild(TSpan);
  11773. var subElStyle = el.createStyle();
  11774. el.useStyle(subElStyle);
  11775. subElStyle.text = textLines[i];
  11776. subElStyle.x = textX;
  11777. subElStyle.y = textY;
  11778. if (textAlign) {
  11779. subElStyle.textAlign = textAlign;
  11780. }
  11781. subElStyle.textBaseline = 'middle';
  11782. subElStyle.opacity = style.opacity;
  11783. subElStyle.strokeFirst = true;
  11784. if (hasShadow) {
  11785. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11786. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11787. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11788. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11789. }
  11790. subElStyle.stroke = textStroke;
  11791. subElStyle.fill = textFill;
  11792. if (textStroke) {
  11793. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11794. subElStyle.lineDash = style.lineDash;
  11795. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11796. }
  11797. subElStyle.font = textFont;
  11798. setSeparateFont(subElStyle, style);
  11799. textY += lineHeight;
  11800. if (fixedBoundingRect) {
  11801. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11802. }
  11803. }
  11804. };
  11805. ZRText.prototype._updateRichTexts = function () {
  11806. var style = this.style;
  11807. var text = getStyleText(style);
  11808. var contentBlock = parseRichText(text, style);
  11809. var contentWidth = contentBlock.width;
  11810. var outerWidth = contentBlock.outerWidth;
  11811. var outerHeight = contentBlock.outerHeight;
  11812. var textPadding = style.padding;
  11813. var baseX = style.x || 0;
  11814. var baseY = style.y || 0;
  11815. var defaultStyle = this._defaultStyle;
  11816. var textAlign = style.align || defaultStyle.align;
  11817. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11818. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11819. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11820. var xLeft = boxX;
  11821. var lineTop = boxY;
  11822. if (textPadding) {
  11823. xLeft += textPadding[3];
  11824. lineTop += textPadding[0];
  11825. }
  11826. var xRight = xLeft + contentWidth;
  11827. if (needDrawBackground(style)) {
  11828. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11829. }
  11830. var bgColorDrawn = !!(style.backgroundColor);
  11831. for (var i = 0; i < contentBlock.lines.length; i++) {
  11832. var line = contentBlock.lines[i];
  11833. var tokens = line.tokens;
  11834. var tokenCount = tokens.length;
  11835. var lineHeight = line.lineHeight;
  11836. var remainedWidth = line.width;
  11837. var leftIndex = 0;
  11838. var lineXLeft = xLeft;
  11839. var lineXRight = xRight;
  11840. var rightIndex = tokenCount - 1;
  11841. var token = void 0;
  11842. while (leftIndex < tokenCount
  11843. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11844. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11845. remainedWidth -= token.width;
  11846. lineXLeft += token.width;
  11847. leftIndex++;
  11848. }
  11849. while (rightIndex >= 0
  11850. && (token = tokens[rightIndex], token.align === 'right')) {
  11851. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11852. remainedWidth -= token.width;
  11853. lineXRight -= token.width;
  11854. rightIndex--;
  11855. }
  11856. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11857. while (leftIndex <= rightIndex) {
  11858. token = tokens[leftIndex];
  11859. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11860. lineXLeft += token.width;
  11861. leftIndex++;
  11862. }
  11863. lineTop += lineHeight;
  11864. }
  11865. };
  11866. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11867. var tokenStyle = style.rich[token.styleName] || {};
  11868. tokenStyle.text = token.text;
  11869. var verticalAlign = token.verticalAlign;
  11870. var y = lineTop + lineHeight / 2;
  11871. if (verticalAlign === 'top') {
  11872. y = lineTop + token.height / 2;
  11873. }
  11874. else if (verticalAlign === 'bottom') {
  11875. y = lineTop + lineHeight - token.height / 2;
  11876. }
  11877. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11878. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11879. ? x - token.width
  11880. : textAlign === 'center'
  11881. ? x - token.width / 2
  11882. : x, y - token.height / 2, token.width, token.height);
  11883. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11884. var textPadding = token.textPadding;
  11885. if (textPadding) {
  11886. x = getTextXForPadding(x, textAlign, textPadding);
  11887. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11888. }
  11889. var el = this._getOrCreateChild(TSpan);
  11890. var subElStyle = el.createStyle();
  11891. el.useStyle(subElStyle);
  11892. var defaultStyle = this._defaultStyle;
  11893. var useDefaultFill = false;
  11894. var defaultLineWidth = 0;
  11895. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11896. : 'fill' in style ? style.fill
  11897. : (useDefaultFill = true, defaultStyle.fill));
  11898. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11899. : 'stroke' in style ? style.stroke
  11900. : (!bgColorDrawn
  11901. && !parentBgColorDrawn
  11902. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11903. : null);
  11904. var hasShadow = tokenStyle.textShadowBlur > 0
  11905. || style.textShadowBlur > 0;
  11906. subElStyle.text = token.text;
  11907. subElStyle.x = x;
  11908. subElStyle.y = y;
  11909. if (hasShadow) {
  11910. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11911. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11912. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11913. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11914. }
  11915. subElStyle.textAlign = textAlign;
  11916. subElStyle.textBaseline = 'middle';
  11917. subElStyle.font = token.font || DEFAULT_FONT;
  11918. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11919. setSeparateFont(subElStyle, tokenStyle);
  11920. if (textStroke) {
  11921. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11922. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11923. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11924. subElStyle.stroke = textStroke;
  11925. }
  11926. if (textFill) {
  11927. subElStyle.fill = textFill;
  11928. }
  11929. var textWidth = token.contentWidth;
  11930. var textHeight = token.contentHeight;
  11931. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11932. };
  11933. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11934. var textBackgroundColor = style.backgroundColor;
  11935. var textBorderWidth = style.borderWidth;
  11936. var textBorderColor = style.borderColor;
  11937. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11938. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11939. var textBorderRadius = style.borderRadius;
  11940. var self = this;
  11941. var rectEl;
  11942. var imgEl;
  11943. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11944. rectEl = this._getOrCreateChild(Rect);
  11945. rectEl.useStyle(rectEl.createStyle());
  11946. rectEl.style.fill = null;
  11947. var rectShape = rectEl.shape;
  11948. rectShape.x = x;
  11949. rectShape.y = y;
  11950. rectShape.width = width;
  11951. rectShape.height = height;
  11952. rectShape.r = textBorderRadius;
  11953. rectEl.dirtyShape();
  11954. }
  11955. if (isPlainOrGradientBg) {
  11956. var rectStyle = rectEl.style;
  11957. rectStyle.fill = textBackgroundColor || null;
  11958. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11959. }
  11960. else if (isImageBg) {
  11961. imgEl = this._getOrCreateChild(ZRImage);
  11962. imgEl.onload = function () {
  11963. self.dirtyStyle();
  11964. };
  11965. var imgStyle = imgEl.style;
  11966. imgStyle.image = textBackgroundColor.image;
  11967. imgStyle.x = x;
  11968. imgStyle.y = y;
  11969. imgStyle.width = width;
  11970. imgStyle.height = height;
  11971. }
  11972. if (textBorderWidth && textBorderColor) {
  11973. var rectStyle = rectEl.style;
  11974. rectStyle.lineWidth = textBorderWidth;
  11975. rectStyle.stroke = textBorderColor;
  11976. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11977. rectStyle.lineDash = style.borderDash;
  11978. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11979. rectEl.strokeContainThreshold = 0;
  11980. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11981. rectStyle.strokeFirst = true;
  11982. rectStyle.lineWidth *= 2;
  11983. }
  11984. }
  11985. var commonStyle = (rectEl || imgEl).style;
  11986. commonStyle.shadowBlur = style.shadowBlur || 0;
  11987. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11988. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11989. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11990. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11991. };
  11992. ZRText.makeFont = function (style) {
  11993. var font = '';
  11994. if (hasSeparateFont(style)) {
  11995. font = [
  11996. style.fontStyle,
  11997. style.fontWeight,
  11998. parseFontSize(style.fontSize),
  11999. style.fontFamily || 'sans-serif'
  12000. ].join(' ');
  12001. }
  12002. return font && trim(font) || style.textFont || style.font;
  12003. };
  12004. return ZRText;
  12005. }(Displayable));
  12006. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  12007. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  12008. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  12009. function parseFontSize(fontSize) {
  12010. if (typeof fontSize === 'string'
  12011. && (fontSize.indexOf('px') !== -1
  12012. || fontSize.indexOf('rem') !== -1
  12013. || fontSize.indexOf('em') !== -1)) {
  12014. return fontSize;
  12015. }
  12016. else if (!isNaN(+fontSize)) {
  12017. return fontSize + 'px';
  12018. }
  12019. else {
  12020. return DEFAULT_FONT_SIZE + 'px';
  12021. }
  12022. }
  12023. function setSeparateFont(targetStyle, sourceStyle) {
  12024. for (var i = 0; i < FONT_PARTS.length; i++) {
  12025. var fontProp = FONT_PARTS[i];
  12026. var val = sourceStyle[fontProp];
  12027. if (val != null) {
  12028. targetStyle[fontProp] = val;
  12029. }
  12030. }
  12031. }
  12032. function hasSeparateFont(style) {
  12033. return style.fontSize != null || style.fontFamily || style.fontWeight;
  12034. }
  12035. function normalizeTextStyle(style) {
  12036. normalizeStyle(style);
  12037. each(style.rich, normalizeStyle);
  12038. return style;
  12039. }
  12040. function normalizeStyle(style) {
  12041. if (style) {
  12042. style.font = ZRText.makeFont(style);
  12043. var textAlign = style.align;
  12044. textAlign === 'middle' && (textAlign = 'center');
  12045. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  12046. var verticalAlign = style.verticalAlign;
  12047. verticalAlign === 'center' && (verticalAlign = 'middle');
  12048. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  12049. var textPadding = style.padding;
  12050. if (textPadding) {
  12051. style.padding = normalizeCssArray(style.padding);
  12052. }
  12053. }
  12054. }
  12055. function getStroke(stroke, lineWidth) {
  12056. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  12057. ? null
  12058. : (stroke.image || stroke.colorStops)
  12059. ? '#000'
  12060. : stroke;
  12061. }
  12062. function getFill(fill) {
  12063. return (fill == null || fill === 'none')
  12064. ? null
  12065. : (fill.image || fill.colorStops)
  12066. ? '#000'
  12067. : fill;
  12068. }
  12069. function getTextXForPadding(x, textAlign, textPadding) {
  12070. return textAlign === 'right'
  12071. ? (x - textPadding[1])
  12072. : textAlign === 'center'
  12073. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  12074. : (x + textPadding[3]);
  12075. }
  12076. function getStyleText(style) {
  12077. var text = style.text;
  12078. text != null && (text += '');
  12079. return text;
  12080. }
  12081. function needDrawBackground(style) {
  12082. return !!(style.backgroundColor
  12083. || style.lineHeight
  12084. || (style.borderWidth && style.borderColor));
  12085. }
  12086. var getECData = makeInner();
  12087. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  12088. if (el) {
  12089. var ecData = getECData(el);
  12090. // Add data index and series index for indexing the data by element
  12091. // Useful in tooltip
  12092. ecData.dataIndex = dataIdx;
  12093. ecData.dataType = dataType;
  12094. ecData.seriesIndex = seriesIndex;
  12095. ecData.ssrType = 'chart';
  12096. // TODO: not store dataIndex on children.
  12097. if (el.type === 'group') {
  12098. el.traverse(function (child) {
  12099. var childECData = getECData(child);
  12100. childECData.seriesIndex = seriesIndex;
  12101. childECData.dataIndex = dataIdx;
  12102. childECData.dataType = dataType;
  12103. childECData.ssrType = 'chart';
  12104. });
  12105. }
  12106. }
  12107. };
  12108. // Reserve 0 as default.
  12109. var _highlightNextDigit = 1;
  12110. var _highlightKeyMap = {};
  12111. var getSavedStates = makeInner();
  12112. var getComponentStates = makeInner();
  12113. var HOVER_STATE_NORMAL = 0;
  12114. var HOVER_STATE_BLUR = 1;
  12115. var HOVER_STATE_EMPHASIS = 2;
  12116. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  12117. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  12118. var Z2_EMPHASIS_LIFT = 10;
  12119. var Z2_SELECT_LIFT = 9;
  12120. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  12121. var DOWNPLAY_ACTION_TYPE = 'downplay';
  12122. var SELECT_ACTION_TYPE = 'select';
  12123. var UNSELECT_ACTION_TYPE = 'unselect';
  12124. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  12125. function hasFillOrStroke(fillOrStroke) {
  12126. return fillOrStroke != null && fillOrStroke !== 'none';
  12127. }
  12128. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12129. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12130. el.onHoverStateChange(stateName);
  12131. }
  12132. el.hoverState = hoverStateEnum;
  12133. }
  12134. function singleEnterEmphasis(el) {
  12135. // Only mark the flag.
  12136. // States will be applied in the echarts.ts in next frame.
  12137. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12138. }
  12139. function singleLeaveEmphasis(el) {
  12140. // Only mark the flag.
  12141. // States will be applied in the echarts.ts in next frame.
  12142. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12143. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12144. }
  12145. }
  12146. function singleEnterBlur(el) {
  12147. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12148. }
  12149. function singleLeaveBlur(el) {
  12150. if (el.hoverState === HOVER_STATE_BLUR) {
  12151. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12152. }
  12153. }
  12154. function singleEnterSelect(el) {
  12155. el.selected = true;
  12156. }
  12157. function singleLeaveSelect(el) {
  12158. el.selected = false;
  12159. }
  12160. function updateElementState(el, updater, commonParam) {
  12161. updater(el, commonParam);
  12162. }
  12163. function traverseUpdateState(el, updater, commonParam) {
  12164. updateElementState(el, updater, commonParam);
  12165. el.isGroup && el.traverse(function (child) {
  12166. updateElementState(child, updater, commonParam);
  12167. });
  12168. }
  12169. function setStatesFlag(el, stateName) {
  12170. switch (stateName) {
  12171. case 'emphasis':
  12172. el.hoverState = HOVER_STATE_EMPHASIS;
  12173. break;
  12174. case 'normal':
  12175. el.hoverState = HOVER_STATE_NORMAL;
  12176. break;
  12177. case 'blur':
  12178. el.hoverState = HOVER_STATE_BLUR;
  12179. break;
  12180. case 'select':
  12181. el.selected = true;
  12182. }
  12183. }
  12184. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12185. var style = el.style;
  12186. var fromState = {};
  12187. for (var i = 0; i < props.length; i++) {
  12188. var propName = props[i];
  12189. var val = style[propName];
  12190. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12191. }
  12192. for (var i = 0; i < el.animators.length; i++) {
  12193. var animator = el.animators[i];
  12194. if (animator.__fromStateTransition
  12195. // Don't consider the animation to emphasis state.
  12196. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12197. animator.saveTo(fromState, props);
  12198. }
  12199. }
  12200. return fromState;
  12201. }
  12202. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12203. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12204. var cloned = false;
  12205. if (el instanceof Path) {
  12206. var store = getSavedStates(el);
  12207. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12208. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12209. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12210. state = state || {};
  12211. var emphasisStyle = state.style || {};
  12212. // inherit case
  12213. if (emphasisStyle.fill === 'inherit') {
  12214. cloned = true;
  12215. state = extend({}, state);
  12216. emphasisStyle = extend({}, emphasisStyle);
  12217. emphasisStyle.fill = fromFill;
  12218. }
  12219. // Apply default color lift
  12220. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12221. cloned = true;
  12222. // Not modify the original value.
  12223. state = extend({}, state);
  12224. emphasisStyle = extend({}, emphasisStyle);
  12225. // Already being applied 'emphasis'. DON'T lift color multiple times.
  12226. emphasisStyle.fill = liftColor(fromFill);
  12227. }
  12228. // Not highlight stroke if fill has been highlighted.
  12229. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12230. if (!cloned) {
  12231. state = extend({}, state);
  12232. emphasisStyle = extend({}, emphasisStyle);
  12233. }
  12234. emphasisStyle.stroke = liftColor(fromStroke);
  12235. }
  12236. state.style = emphasisStyle;
  12237. }
  12238. }
  12239. if (state) {
  12240. // TODO Share with textContent?
  12241. if (state.z2 == null) {
  12242. if (!cloned) {
  12243. state = extend({}, state);
  12244. }
  12245. var z2EmphasisLift = el.z2EmphasisLift;
  12246. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12247. }
  12248. }
  12249. return state;
  12250. }
  12251. function createSelectDefaultState(el, stateName, state) {
  12252. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12253. if (state) {
  12254. // TODO Share with textContent?
  12255. if (state.z2 == null) {
  12256. state = extend({}, state);
  12257. var z2SelectLift = el.z2SelectLift;
  12258. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12259. }
  12260. }
  12261. return state;
  12262. }
  12263. function createBlurDefaultState(el, stateName, state) {
  12264. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12265. var currentOpacity = el.style.opacity;
  12266. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12267. opacity: 1
  12268. }) : null;
  12269. state = state || {};
  12270. var blurStyle = state.style || {};
  12271. if (blurStyle.opacity == null) {
  12272. // clone state
  12273. state = extend({}, state);
  12274. blurStyle = extend({
  12275. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12276. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12277. }, blurStyle);
  12278. state.style = blurStyle;
  12279. }
  12280. return state;
  12281. }
  12282. function elementStateProxy(stateName, targetStates) {
  12283. var state = this.states[stateName];
  12284. if (this.style) {
  12285. if (stateName === 'emphasis') {
  12286. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12287. } else if (stateName === 'blur') {
  12288. return createBlurDefaultState(this, stateName, state);
  12289. } else if (stateName === 'select') {
  12290. return createSelectDefaultState(this, stateName, state);
  12291. }
  12292. }
  12293. return state;
  12294. }
  12295. /**
  12296. * Set hover style (namely "emphasis style") of element.
  12297. * @param el Should not be `zrender/graphic/Group`.
  12298. * @param focus 'self' | 'selfInSeries' | 'series'
  12299. */
  12300. function setDefaultStateProxy(el) {
  12301. el.stateProxy = elementStateProxy;
  12302. var textContent = el.getTextContent();
  12303. var textGuide = el.getTextGuideLine();
  12304. if (textContent) {
  12305. textContent.stateProxy = elementStateProxy;
  12306. }
  12307. if (textGuide) {
  12308. textGuide.stateProxy = elementStateProxy;
  12309. }
  12310. }
  12311. function enterEmphasisWhenMouseOver(el, e) {
  12312. !shouldSilent(el, e)
  12313. // "emphasis" event highlight has higher priority than mouse highlight.
  12314. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12315. }
  12316. function leaveEmphasisWhenMouseOut(el, e) {
  12317. !shouldSilent(el, e)
  12318. // "emphasis" event highlight has higher priority than mouse highlight.
  12319. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12320. }
  12321. function enterEmphasis(el, highlightDigit) {
  12322. el.__highByOuter |= 1 << (highlightDigit || 0);
  12323. traverseUpdateState(el, singleEnterEmphasis);
  12324. }
  12325. function leaveEmphasis(el, highlightDigit) {
  12326. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12327. }
  12328. function enterBlur(el) {
  12329. traverseUpdateState(el, singleEnterBlur);
  12330. }
  12331. function leaveBlur(el) {
  12332. traverseUpdateState(el, singleLeaveBlur);
  12333. }
  12334. function enterSelect(el) {
  12335. traverseUpdateState(el, singleEnterSelect);
  12336. }
  12337. function leaveSelect(el) {
  12338. traverseUpdateState(el, singleLeaveSelect);
  12339. }
  12340. function shouldSilent(el, e) {
  12341. return el.__highDownSilentOnTouch && e.zrByTouch;
  12342. }
  12343. function allLeaveBlur(api) {
  12344. var model = api.getModel();
  12345. var leaveBlurredSeries = [];
  12346. var allComponentViews = [];
  12347. model.eachComponent(function (componentType, componentModel) {
  12348. var componentStates = getComponentStates(componentModel);
  12349. var isSeries = componentType === 'series';
  12350. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12351. !isSeries && allComponentViews.push(view);
  12352. if (componentStates.isBlured) {
  12353. // Leave blur anyway
  12354. view.group.traverse(function (child) {
  12355. singleLeaveBlur(child);
  12356. });
  12357. isSeries && leaveBlurredSeries.push(componentModel);
  12358. }
  12359. componentStates.isBlured = false;
  12360. });
  12361. each(allComponentViews, function (view) {
  12362. if (view && view.toggleBlurSeries) {
  12363. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12364. }
  12365. });
  12366. }
  12367. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12368. var ecModel = api.getModel();
  12369. blurScope = blurScope || 'coordinateSystem';
  12370. function leaveBlurOfIndices(data, dataIndices) {
  12371. for (var i = 0; i < dataIndices.length; i++) {
  12372. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12373. itemEl && leaveBlur(itemEl);
  12374. }
  12375. }
  12376. if (targetSeriesIndex == null) {
  12377. return;
  12378. }
  12379. if (!focus || focus === 'none') {
  12380. return;
  12381. }
  12382. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12383. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12384. if (targetCoordSys && targetCoordSys.master) {
  12385. targetCoordSys = targetCoordSys.master;
  12386. }
  12387. var blurredSeries = [];
  12388. ecModel.eachSeries(function (seriesModel) {
  12389. var sameSeries = targetSeriesModel === seriesModel;
  12390. var coordSys = seriesModel.coordinateSystem;
  12391. if (coordSys && coordSys.master) {
  12392. coordSys = coordSys.master;
  12393. }
  12394. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12395. if (!(
  12396. // Not blur other series if blurScope series
  12397. blurScope === 'series' && !sameSeries
  12398. // Not blur other coordinate system if blurScope is coordinateSystem
  12399. || blurScope === 'coordinateSystem' && !sameCoordSys
  12400. // Not blur self series if focus is series.
  12401. || focus === 'series' && sameSeries
  12402. // TODO blurScope: coordinate system
  12403. )) {
  12404. var view = api.getViewOfSeriesModel(seriesModel);
  12405. view.group.traverse(function (child) {
  12406. // For the elements that have been triggered by other components,
  12407. // and are still required to be highlighted,
  12408. // because the current is directly forced to blur the element,
  12409. // it will cause the focus self to be unable to highlight, so skip the blur of this element.
  12410. if (child.__highByOuter && sameSeries && focus === 'self') {
  12411. return;
  12412. }
  12413. singleEnterBlur(child);
  12414. });
  12415. if (isArrayLike(focus)) {
  12416. leaveBlurOfIndices(seriesModel.getData(), focus);
  12417. } else if (isObject(focus)) {
  12418. var dataTypes = keys(focus);
  12419. for (var d = 0; d < dataTypes.length; d++) {
  12420. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12421. }
  12422. }
  12423. blurredSeries.push(seriesModel);
  12424. getComponentStates(seriesModel).isBlured = true;
  12425. }
  12426. });
  12427. ecModel.eachComponent(function (componentType, componentModel) {
  12428. if (componentType === 'series') {
  12429. return;
  12430. }
  12431. var view = api.getViewOfComponentModel(componentModel);
  12432. if (view && view.toggleBlurSeries) {
  12433. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12434. }
  12435. });
  12436. }
  12437. function blurComponent(componentMainType, componentIndex, api) {
  12438. if (componentMainType == null || componentIndex == null) {
  12439. return;
  12440. }
  12441. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12442. if (!componentModel) {
  12443. return;
  12444. }
  12445. getComponentStates(componentModel).isBlured = true;
  12446. var view = api.getViewOfComponentModel(componentModel);
  12447. if (!view || !view.focusBlurEnabled) {
  12448. return;
  12449. }
  12450. view.group.traverse(function (child) {
  12451. singleEnterBlur(child);
  12452. });
  12453. }
  12454. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12455. var seriesIndex = seriesModel.seriesIndex;
  12456. var data = seriesModel.getData(payload.dataType);
  12457. if (!data) {
  12458. if ("development" !== 'production') {
  12459. error("Unknown dataType " + payload.dataType);
  12460. }
  12461. return;
  12462. }
  12463. var dataIndex = queryDataIndex(data, payload);
  12464. // Pick the first one if there is multiple/none exists.
  12465. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12466. var el = data.getItemGraphicEl(dataIndex);
  12467. if (!el) {
  12468. var count = data.count();
  12469. var current = 0;
  12470. // If data on dataIndex is NaN.
  12471. while (!el && current < count) {
  12472. el = data.getItemGraphicEl(current++);
  12473. }
  12474. }
  12475. if (el) {
  12476. var ecData = getECData(el);
  12477. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12478. } else {
  12479. // If there is no element put on the data. Try getting it from raw option
  12480. // TODO Should put it on seriesModel?
  12481. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12482. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12483. if (focus_1 != null) {
  12484. blurSeries(seriesIndex, focus_1, blurScope, api);
  12485. }
  12486. }
  12487. }
  12488. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12489. var ret = {
  12490. focusSelf: false,
  12491. dispatchers: null
  12492. };
  12493. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12494. return ret;
  12495. }
  12496. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12497. if (!componentModel) {
  12498. return ret;
  12499. }
  12500. var view = api.getViewOfComponentModel(componentModel);
  12501. if (!view || !view.findHighDownDispatchers) {
  12502. return ret;
  12503. }
  12504. var dispatchers = view.findHighDownDispatchers(name);
  12505. // At presnet, the component (like Geo) only blur inside itself.
  12506. // So we do not use `blurScope` in component.
  12507. var focusSelf;
  12508. for (var i = 0; i < dispatchers.length; i++) {
  12509. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12510. error('param should be highDownDispatcher');
  12511. }
  12512. if (getECData(dispatchers[i]).focus === 'self') {
  12513. focusSelf = true;
  12514. break;
  12515. }
  12516. }
  12517. return {
  12518. focusSelf: focusSelf,
  12519. dispatchers: dispatchers
  12520. };
  12521. }
  12522. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12523. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12524. error('param should be highDownDispatcher');
  12525. }
  12526. var ecData = getECData(dispatcher);
  12527. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12528. dispatchers = _a.dispatchers,
  12529. focusSelf = _a.focusSelf;
  12530. // If `findHighDownDispatchers` is supported on the component,
  12531. // highlight/downplay elements with the same name.
  12532. if (dispatchers) {
  12533. if (focusSelf) {
  12534. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12535. }
  12536. each(dispatchers, function (dispatcher) {
  12537. return enterEmphasisWhenMouseOver(dispatcher, e);
  12538. });
  12539. } else {
  12540. // Try blur all in the related series. Then emphasis the hoverred.
  12541. // TODO. progressive mode.
  12542. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12543. if (ecData.focus === 'self') {
  12544. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12545. }
  12546. // Other than series, component that not support `findHighDownDispatcher` will
  12547. // also use it. But in this case, highlight/downplay are only supported in
  12548. // mouse hover but not in dispatchAction.
  12549. enterEmphasisWhenMouseOver(dispatcher, e);
  12550. }
  12551. }
  12552. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12553. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12554. error('param should be highDownDispatcher');
  12555. }
  12556. allLeaveBlur(api);
  12557. var ecData = getECData(dispatcher);
  12558. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12559. if (dispatchers) {
  12560. each(dispatchers, function (dispatcher) {
  12561. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12562. });
  12563. } else {
  12564. leaveEmphasisWhenMouseOut(dispatcher, e);
  12565. }
  12566. }
  12567. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12568. if (!isSelectChangePayload(payload)) {
  12569. return;
  12570. }
  12571. var dataType = payload.dataType;
  12572. var data = seriesModel.getData(dataType);
  12573. var dataIndex = queryDataIndex(data, payload);
  12574. if (!isArray(dataIndex)) {
  12575. dataIndex = [dataIndex];
  12576. }
  12577. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12578. }
  12579. function updateSeriesElementSelection(seriesModel) {
  12580. var allData = seriesModel.getAllData();
  12581. each(allData, function (_a) {
  12582. var data = _a.data,
  12583. type = _a.type;
  12584. data.eachItemGraphicEl(function (el, idx) {
  12585. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12586. });
  12587. });
  12588. }
  12589. function getAllSelectedIndices(ecModel) {
  12590. var ret = [];
  12591. ecModel.eachSeries(function (seriesModel) {
  12592. var allData = seriesModel.getAllData();
  12593. each(allData, function (_a) {
  12594. var data = _a.data,
  12595. type = _a.type;
  12596. var dataIndices = seriesModel.getSelectedDataIndices();
  12597. if (dataIndices.length > 0) {
  12598. var item = {
  12599. dataIndex: dataIndices,
  12600. seriesIndex: seriesModel.seriesIndex
  12601. };
  12602. if (type != null) {
  12603. item.dataType = type;
  12604. }
  12605. ret.push(item);
  12606. }
  12607. });
  12608. });
  12609. return ret;
  12610. }
  12611. /**
  12612. * Enable the function that mouseover will trigger the emphasis state.
  12613. *
  12614. * NOTE:
  12615. * This function should be used on the element with dataIndex, seriesIndex.
  12616. *
  12617. */
  12618. function enableHoverEmphasis(el, focus, blurScope) {
  12619. setAsHighDownDispatcher(el, true);
  12620. traverseUpdateState(el, setDefaultStateProxy);
  12621. enableHoverFocus(el, focus, blurScope);
  12622. }
  12623. function disableHoverEmphasis(el) {
  12624. setAsHighDownDispatcher(el, false);
  12625. }
  12626. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12627. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12628. }
  12629. function enableHoverFocus(el, focus, blurScope) {
  12630. var ecData = getECData(el);
  12631. if (focus != null) {
  12632. // TODO dataIndex may be set after this function. This check is not useful.
  12633. // if (ecData.dataIndex == null) {
  12634. // if (__DEV__) {
  12635. // console.warn('focus can only been set on element with dataIndex');
  12636. // }
  12637. // }
  12638. // else {
  12639. ecData.focus = focus;
  12640. ecData.blurScope = blurScope;
  12641. // }
  12642. } else if (ecData.focus) {
  12643. ecData.focus = null;
  12644. }
  12645. }
  12646. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12647. var defaultStyleGetterMap = {
  12648. itemStyle: 'getItemStyle',
  12649. lineStyle: 'getLineStyle',
  12650. areaStyle: 'getAreaStyle'
  12651. };
  12652. /**
  12653. * Set emphasis/blur/selected states of element.
  12654. */
  12655. function setStatesStylesFromModel(el, itemModel, styleType,
  12656. // default itemStyle
  12657. getter) {
  12658. styleType = styleType || 'itemStyle';
  12659. for (var i = 0; i < OTHER_STATES.length; i++) {
  12660. var stateName = OTHER_STATES[i];
  12661. var model = itemModel.getModel([stateName, styleType]);
  12662. var state = el.ensureState(stateName);
  12663. // Let it throw error if getterType is not found.
  12664. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12665. }
  12666. }
  12667. /**
  12668. *
  12669. * Set element as highlight / downplay dispatcher.
  12670. * It will be checked when element received mouseover event or from highlight action.
  12671. * It's in change of all highlight/downplay behavior of it's children.
  12672. *
  12673. * @param el
  12674. * @param el.highDownSilentOnTouch
  12675. * In touch device, mouseover event will be trigger on touchstart event
  12676. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12677. * conveniently use hoverStyle when tap on touch screen without additional
  12678. * code for compatibility.
  12679. * But if the chart/component has select feature, which usually also use
  12680. * hoverStyle, there might be conflict between 'select-highlight' and
  12681. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12682. * In this case, `highDownSilentOnTouch` should be used to disable
  12683. * hover-highlight on touch device.
  12684. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12685. */
  12686. function setAsHighDownDispatcher(el, asDispatcher) {
  12687. var disable = asDispatcher === false;
  12688. var extendedEl = el;
  12689. // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12690. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12691. if (el.highDownSilentOnTouch) {
  12692. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12693. }
  12694. // Simple optimize, since this method might be
  12695. // called for each elements of a group in some cases.
  12696. if (!disable || extendedEl.__highDownDispatcher) {
  12697. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12698. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12699. // Also keep previous record.
  12700. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12701. extendedEl.__highDownDispatcher = !disable;
  12702. }
  12703. }
  12704. function isHighDownDispatcher(el) {
  12705. return !!(el && el.__highDownDispatcher);
  12706. }
  12707. /**
  12708. * Support highlight/downplay record on each elements.
  12709. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12710. * user triggered highlight/downplay should not conflict.
  12711. * Only all of the highlightDigit cleared, return to normal.
  12712. * @param {string} highlightKey
  12713. * @return {number} highlightDigit
  12714. */
  12715. function getHighlightDigit(highlightKey) {
  12716. var highlightDigit = _highlightKeyMap[highlightKey];
  12717. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12718. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12719. }
  12720. return highlightDigit;
  12721. }
  12722. function isSelectChangePayload(payload) {
  12723. var payloadType = payload.type;
  12724. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12725. }
  12726. function isHighDownPayload(payload) {
  12727. var payloadType = payload.type;
  12728. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12729. }
  12730. function savePathStates(el) {
  12731. var store = getSavedStates(el);
  12732. store.normalFill = el.style.fill;
  12733. store.normalStroke = el.style.stroke;
  12734. var selectState = el.states.select || {};
  12735. store.selectFill = selectState.style && selectState.style.fill || null;
  12736. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12737. }
  12738. var CMD$2 = PathProxy.CMD;
  12739. var points = [[], [], []];
  12740. var mathSqrt$1 = Math.sqrt;
  12741. var mathAtan2 = Math.atan2;
  12742. function transformPath(path, m) {
  12743. if (!m) {
  12744. return;
  12745. }
  12746. var data = path.data;
  12747. var len = path.len();
  12748. var cmd;
  12749. var nPoint;
  12750. var i;
  12751. var j;
  12752. var k;
  12753. var p;
  12754. var M = CMD$2.M;
  12755. var C = CMD$2.C;
  12756. var L = CMD$2.L;
  12757. var R = CMD$2.R;
  12758. var A = CMD$2.A;
  12759. var Q = CMD$2.Q;
  12760. for (i = 0, j = 0; i < len;) {
  12761. cmd = data[i++];
  12762. j = i;
  12763. nPoint = 0;
  12764. switch (cmd) {
  12765. case M:
  12766. nPoint = 1;
  12767. break;
  12768. case L:
  12769. nPoint = 1;
  12770. break;
  12771. case C:
  12772. nPoint = 3;
  12773. break;
  12774. case Q:
  12775. nPoint = 2;
  12776. break;
  12777. case A:
  12778. var x = m[4];
  12779. var y = m[5];
  12780. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12781. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12782. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12783. data[i] *= sx;
  12784. data[i++] += x;
  12785. data[i] *= sy;
  12786. data[i++] += y;
  12787. data[i++] *= sx;
  12788. data[i++] *= sy;
  12789. data[i++] += angle;
  12790. data[i++] += angle;
  12791. i += 2;
  12792. j = i;
  12793. break;
  12794. case R:
  12795. p[0] = data[i++];
  12796. p[1] = data[i++];
  12797. applyTransform(p, p, m);
  12798. data[j++] = p[0];
  12799. data[j++] = p[1];
  12800. p[0] += data[i++];
  12801. p[1] += data[i++];
  12802. applyTransform(p, p, m);
  12803. data[j++] = p[0];
  12804. data[j++] = p[1];
  12805. }
  12806. for (k = 0; k < nPoint; k++) {
  12807. var p_1 = points[k];
  12808. p_1[0] = data[i++];
  12809. p_1[1] = data[i++];
  12810. applyTransform(p_1, p_1, m);
  12811. data[j++] = p_1[0];
  12812. data[j++] = p_1[1];
  12813. }
  12814. }
  12815. path.increaseVersion();
  12816. }
  12817. var mathSqrt$2 = Math.sqrt;
  12818. var mathSin$2 = Math.sin;
  12819. var mathCos$2 = Math.cos;
  12820. var PI$1 = Math.PI;
  12821. function vMag(v) {
  12822. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12823. }
  12824. function vRatio(u, v) {
  12825. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12826. }
  12827. function vAngle(u, v) {
  12828. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12829. * Math.acos(vRatio(u, v));
  12830. }
  12831. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12832. var psi = psiDeg * (PI$1 / 180.0);
  12833. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12834. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12835. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12836. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12837. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12838. if (lambda > 1) {
  12839. rx *= mathSqrt$2(lambda);
  12840. ry *= mathSqrt$2(lambda);
  12841. }
  12842. var f = (fa === fs ? -1 : 1)
  12843. * mathSqrt$2((((rx * rx) * (ry * ry))
  12844. - ((rx * rx) * (yp * yp))
  12845. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12846. + (ry * ry) * (xp * xp))) || 0;
  12847. var cxp = f * rx * yp / ry;
  12848. var cyp = f * -ry * xp / rx;
  12849. var cx = (x1 + x2) / 2.0
  12850. + mathCos$2(psi) * cxp
  12851. - mathSin$2(psi) * cyp;
  12852. var cy = (y1 + y2) / 2.0
  12853. + mathSin$2(psi) * cxp
  12854. + mathCos$2(psi) * cyp;
  12855. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12856. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12857. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12858. var dTheta = vAngle(u, v);
  12859. if (vRatio(u, v) <= -1) {
  12860. dTheta = PI$1;
  12861. }
  12862. if (vRatio(u, v) >= 1) {
  12863. dTheta = 0;
  12864. }
  12865. if (dTheta < 0) {
  12866. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12867. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12868. }
  12869. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12870. }
  12871. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12872. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12873. function createPathProxyFromString(data) {
  12874. var path = new PathProxy();
  12875. if (!data) {
  12876. return path;
  12877. }
  12878. var cpx = 0;
  12879. var cpy = 0;
  12880. var subpathX = cpx;
  12881. var subpathY = cpy;
  12882. var prevCmd;
  12883. var CMD = PathProxy.CMD;
  12884. var cmdList = data.match(commandReg);
  12885. if (!cmdList) {
  12886. return path;
  12887. }
  12888. for (var l = 0; l < cmdList.length; l++) {
  12889. var cmdText = cmdList[l];
  12890. var cmdStr = cmdText.charAt(0);
  12891. var cmd = void 0;
  12892. var p = cmdText.match(numberReg) || [];
  12893. var pLen = p.length;
  12894. for (var i = 0; i < pLen; i++) {
  12895. p[i] = parseFloat(p[i]);
  12896. }
  12897. var off = 0;
  12898. while (off < pLen) {
  12899. var ctlPtx = void 0;
  12900. var ctlPty = void 0;
  12901. var rx = void 0;
  12902. var ry = void 0;
  12903. var psi = void 0;
  12904. var fa = void 0;
  12905. var fs = void 0;
  12906. var x1 = cpx;
  12907. var y1 = cpy;
  12908. var len = void 0;
  12909. var pathData = void 0;
  12910. switch (cmdStr) {
  12911. case 'l':
  12912. cpx += p[off++];
  12913. cpy += p[off++];
  12914. cmd = CMD.L;
  12915. path.addData(cmd, cpx, cpy);
  12916. break;
  12917. case 'L':
  12918. cpx = p[off++];
  12919. cpy = p[off++];
  12920. cmd = CMD.L;
  12921. path.addData(cmd, cpx, cpy);
  12922. break;
  12923. case 'm':
  12924. cpx += p[off++];
  12925. cpy += p[off++];
  12926. cmd = CMD.M;
  12927. path.addData(cmd, cpx, cpy);
  12928. subpathX = cpx;
  12929. subpathY = cpy;
  12930. cmdStr = 'l';
  12931. break;
  12932. case 'M':
  12933. cpx = p[off++];
  12934. cpy = p[off++];
  12935. cmd = CMD.M;
  12936. path.addData(cmd, cpx, cpy);
  12937. subpathX = cpx;
  12938. subpathY = cpy;
  12939. cmdStr = 'L';
  12940. break;
  12941. case 'h':
  12942. cpx += p[off++];
  12943. cmd = CMD.L;
  12944. path.addData(cmd, cpx, cpy);
  12945. break;
  12946. case 'H':
  12947. cpx = p[off++];
  12948. cmd = CMD.L;
  12949. path.addData(cmd, cpx, cpy);
  12950. break;
  12951. case 'v':
  12952. cpy += p[off++];
  12953. cmd = CMD.L;
  12954. path.addData(cmd, cpx, cpy);
  12955. break;
  12956. case 'V':
  12957. cpy = p[off++];
  12958. cmd = CMD.L;
  12959. path.addData(cmd, cpx, cpy);
  12960. break;
  12961. case 'C':
  12962. cmd = CMD.C;
  12963. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12964. cpx = p[off - 2];
  12965. cpy = p[off - 1];
  12966. break;
  12967. case 'c':
  12968. cmd = CMD.C;
  12969. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12970. cpx += p[off - 2];
  12971. cpy += p[off - 1];
  12972. break;
  12973. case 'S':
  12974. ctlPtx = cpx;
  12975. ctlPty = cpy;
  12976. len = path.len();
  12977. pathData = path.data;
  12978. if (prevCmd === CMD.C) {
  12979. ctlPtx += cpx - pathData[len - 4];
  12980. ctlPty += cpy - pathData[len - 3];
  12981. }
  12982. cmd = CMD.C;
  12983. x1 = p[off++];
  12984. y1 = p[off++];
  12985. cpx = p[off++];
  12986. cpy = p[off++];
  12987. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12988. break;
  12989. case 's':
  12990. ctlPtx = cpx;
  12991. ctlPty = cpy;
  12992. len = path.len();
  12993. pathData = path.data;
  12994. if (prevCmd === CMD.C) {
  12995. ctlPtx += cpx - pathData[len - 4];
  12996. ctlPty += cpy - pathData[len - 3];
  12997. }
  12998. cmd = CMD.C;
  12999. x1 = cpx + p[off++];
  13000. y1 = cpy + p[off++];
  13001. cpx += p[off++];
  13002. cpy += p[off++];
  13003. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13004. break;
  13005. case 'Q':
  13006. x1 = p[off++];
  13007. y1 = p[off++];
  13008. cpx = p[off++];
  13009. cpy = p[off++];
  13010. cmd = CMD.Q;
  13011. path.addData(cmd, x1, y1, cpx, cpy);
  13012. break;
  13013. case 'q':
  13014. x1 = p[off++] + cpx;
  13015. y1 = p[off++] + cpy;
  13016. cpx += p[off++];
  13017. cpy += p[off++];
  13018. cmd = CMD.Q;
  13019. path.addData(cmd, x1, y1, cpx, cpy);
  13020. break;
  13021. case 'T':
  13022. ctlPtx = cpx;
  13023. ctlPty = cpy;
  13024. len = path.len();
  13025. pathData = path.data;
  13026. if (prevCmd === CMD.Q) {
  13027. ctlPtx += cpx - pathData[len - 4];
  13028. ctlPty += cpy - pathData[len - 3];
  13029. }
  13030. cpx = p[off++];
  13031. cpy = p[off++];
  13032. cmd = CMD.Q;
  13033. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13034. break;
  13035. case 't':
  13036. ctlPtx = cpx;
  13037. ctlPty = cpy;
  13038. len = path.len();
  13039. pathData = path.data;
  13040. if (prevCmd === CMD.Q) {
  13041. ctlPtx += cpx - pathData[len - 4];
  13042. ctlPty += cpy - pathData[len - 3];
  13043. }
  13044. cpx += p[off++];
  13045. cpy += p[off++];
  13046. cmd = CMD.Q;
  13047. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13048. break;
  13049. case 'A':
  13050. rx = p[off++];
  13051. ry = p[off++];
  13052. psi = p[off++];
  13053. fa = p[off++];
  13054. fs = p[off++];
  13055. x1 = cpx, y1 = cpy;
  13056. cpx = p[off++];
  13057. cpy = p[off++];
  13058. cmd = CMD.A;
  13059. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13060. break;
  13061. case 'a':
  13062. rx = p[off++];
  13063. ry = p[off++];
  13064. psi = p[off++];
  13065. fa = p[off++];
  13066. fs = p[off++];
  13067. x1 = cpx, y1 = cpy;
  13068. cpx += p[off++];
  13069. cpy += p[off++];
  13070. cmd = CMD.A;
  13071. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13072. break;
  13073. }
  13074. }
  13075. if (cmdStr === 'z' || cmdStr === 'Z') {
  13076. cmd = CMD.Z;
  13077. path.addData(cmd);
  13078. cpx = subpathX;
  13079. cpy = subpathY;
  13080. }
  13081. prevCmd = cmd;
  13082. }
  13083. path.toStatic();
  13084. return path;
  13085. }
  13086. var SVGPath = (function (_super) {
  13087. __extends(SVGPath, _super);
  13088. function SVGPath() {
  13089. return _super !== null && _super.apply(this, arguments) || this;
  13090. }
  13091. SVGPath.prototype.applyTransform = function (m) { };
  13092. return SVGPath;
  13093. }(Path));
  13094. function isPathProxy(path) {
  13095. return path.setData != null;
  13096. }
  13097. function createPathOptions(str, opts) {
  13098. var pathProxy = createPathProxyFromString(str);
  13099. var innerOpts = extend({}, opts);
  13100. innerOpts.buildPath = function (path) {
  13101. if (isPathProxy(path)) {
  13102. path.setData(pathProxy.data);
  13103. var ctx = path.getContext();
  13104. if (ctx) {
  13105. path.rebuildPath(ctx, 1);
  13106. }
  13107. }
  13108. else {
  13109. var ctx = path;
  13110. pathProxy.rebuildPath(ctx, 1);
  13111. }
  13112. };
  13113. innerOpts.applyTransform = function (m) {
  13114. transformPath(pathProxy, m);
  13115. this.dirtyShape();
  13116. };
  13117. return innerOpts;
  13118. }
  13119. function createFromString(str, opts) {
  13120. return new SVGPath(createPathOptions(str, opts));
  13121. }
  13122. function extendFromString(str, defaultOpts) {
  13123. var innerOpts = createPathOptions(str, defaultOpts);
  13124. var Sub = (function (_super) {
  13125. __extends(Sub, _super);
  13126. function Sub(opts) {
  13127. var _this = _super.call(this, opts) || this;
  13128. _this.applyTransform = innerOpts.applyTransform;
  13129. _this.buildPath = innerOpts.buildPath;
  13130. return _this;
  13131. }
  13132. return Sub;
  13133. }(SVGPath));
  13134. return Sub;
  13135. }
  13136. function mergePath(pathEls, opts) {
  13137. var pathList = [];
  13138. var len = pathEls.length;
  13139. for (var i = 0; i < len; i++) {
  13140. var pathEl = pathEls[i];
  13141. pathList.push(pathEl.getUpdatedPathProxy(true));
  13142. }
  13143. var pathBundle = new Path(opts);
  13144. pathBundle.createPathProxy();
  13145. pathBundle.buildPath = function (path) {
  13146. if (isPathProxy(path)) {
  13147. path.appendPath(pathList);
  13148. var ctx = path.getContext();
  13149. if (ctx) {
  13150. path.rebuildPath(ctx, 1);
  13151. }
  13152. }
  13153. };
  13154. return pathBundle;
  13155. }
  13156. var CircleShape = (function () {
  13157. function CircleShape() {
  13158. this.cx = 0;
  13159. this.cy = 0;
  13160. this.r = 0;
  13161. }
  13162. return CircleShape;
  13163. }());
  13164. var Circle = (function (_super) {
  13165. __extends(Circle, _super);
  13166. function Circle(opts) {
  13167. return _super.call(this, opts) || this;
  13168. }
  13169. Circle.prototype.getDefaultShape = function () {
  13170. return new CircleShape();
  13171. };
  13172. Circle.prototype.buildPath = function (ctx, shape) {
  13173. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13174. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13175. };
  13176. return Circle;
  13177. }(Path));
  13178. Circle.prototype.type = 'circle';
  13179. var EllipseShape = (function () {
  13180. function EllipseShape() {
  13181. this.cx = 0;
  13182. this.cy = 0;
  13183. this.rx = 0;
  13184. this.ry = 0;
  13185. }
  13186. return EllipseShape;
  13187. }());
  13188. var Ellipse = (function (_super) {
  13189. __extends(Ellipse, _super);
  13190. function Ellipse(opts) {
  13191. return _super.call(this, opts) || this;
  13192. }
  13193. Ellipse.prototype.getDefaultShape = function () {
  13194. return new EllipseShape();
  13195. };
  13196. Ellipse.prototype.buildPath = function (ctx, shape) {
  13197. var k = 0.5522848;
  13198. var x = shape.cx;
  13199. var y = shape.cy;
  13200. var a = shape.rx;
  13201. var b = shape.ry;
  13202. var ox = a * k;
  13203. var oy = b * k;
  13204. ctx.moveTo(x - a, y);
  13205. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13206. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13207. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13208. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13209. ctx.closePath();
  13210. };
  13211. return Ellipse;
  13212. }(Path));
  13213. Ellipse.prototype.type = 'ellipse';
  13214. var PI$2 = Math.PI;
  13215. var PI2$5 = PI$2 * 2;
  13216. var mathSin$3 = Math.sin;
  13217. var mathCos$3 = Math.cos;
  13218. var mathACos = Math.acos;
  13219. var mathATan2 = Math.atan2;
  13220. var mathAbs$1 = Math.abs;
  13221. var mathSqrt$3 = Math.sqrt;
  13222. var mathMax$3 = Math.max;
  13223. var mathMin$3 = Math.min;
  13224. var e = 1e-4;
  13225. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13226. var dx10 = x1 - x0;
  13227. var dy10 = y1 - y0;
  13228. var dx32 = x3 - x2;
  13229. var dy32 = y3 - y2;
  13230. var t = dy32 * dx10 - dx32 * dy10;
  13231. if (t * t < e) {
  13232. return;
  13233. }
  13234. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13235. return [x0 + t * dx10, y0 + t * dy10];
  13236. }
  13237. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13238. var x01 = x0 - x1;
  13239. var y01 = y0 - y1;
  13240. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13241. var ox = lo * y01;
  13242. var oy = -lo * x01;
  13243. var x11 = x0 + ox;
  13244. var y11 = y0 + oy;
  13245. var x10 = x1 + ox;
  13246. var y10 = y1 + oy;
  13247. var x00 = (x11 + x10) / 2;
  13248. var y00 = (y11 + y10) / 2;
  13249. var dx = x10 - x11;
  13250. var dy = y10 - y11;
  13251. var d2 = dx * dx + dy * dy;
  13252. var r = radius - cr;
  13253. var s = x11 * y10 - x10 * y11;
  13254. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13255. var cx0 = (s * dy - dx * d) / d2;
  13256. var cy0 = (-s * dx - dy * d) / d2;
  13257. var cx1 = (s * dy + dx * d) / d2;
  13258. var cy1 = (-s * dx + dy * d) / d2;
  13259. var dx0 = cx0 - x00;
  13260. var dy0 = cy0 - y00;
  13261. var dx1 = cx1 - x00;
  13262. var dy1 = cy1 - y00;
  13263. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13264. cx0 = cx1;
  13265. cy0 = cy1;
  13266. }
  13267. return {
  13268. cx: cx0,
  13269. cy: cy0,
  13270. x0: -ox,
  13271. y0: -oy,
  13272. x1: cx0 * (radius / r - 1),
  13273. y1: cy0 * (radius / r - 1)
  13274. };
  13275. }
  13276. function normalizeCornerRadius(cr) {
  13277. var arr;
  13278. if (isArray(cr)) {
  13279. var len = cr.length;
  13280. if (!len) {
  13281. return cr;
  13282. }
  13283. if (len === 1) {
  13284. arr = [cr[0], cr[0], 0, 0];
  13285. }
  13286. else if (len === 2) {
  13287. arr = [cr[0], cr[0], cr[1], cr[1]];
  13288. }
  13289. else if (len === 3) {
  13290. arr = cr.concat(cr[2]);
  13291. }
  13292. else {
  13293. arr = cr;
  13294. }
  13295. }
  13296. else {
  13297. arr = [cr, cr, cr, cr];
  13298. }
  13299. return arr;
  13300. }
  13301. function buildPath$1(ctx, shape) {
  13302. var _a;
  13303. var radius = mathMax$3(shape.r, 0);
  13304. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13305. var hasRadius = radius > 0;
  13306. var hasInnerRadius = innerRadius > 0;
  13307. if (!hasRadius && !hasInnerRadius) {
  13308. return;
  13309. }
  13310. if (!hasRadius) {
  13311. radius = innerRadius;
  13312. innerRadius = 0;
  13313. }
  13314. if (innerRadius > radius) {
  13315. var tmp = radius;
  13316. radius = innerRadius;
  13317. innerRadius = tmp;
  13318. }
  13319. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13320. if (isNaN(startAngle) || isNaN(endAngle)) {
  13321. return;
  13322. }
  13323. var cx = shape.cx, cy = shape.cy;
  13324. var clockwise = !!shape.clockwise;
  13325. var arc = mathAbs$1(endAngle - startAngle);
  13326. var mod = arc > PI2$5 && arc % PI2$5;
  13327. mod > e && (arc = mod);
  13328. if (!(radius > e)) {
  13329. ctx.moveTo(cx, cy);
  13330. }
  13331. else if (arc > PI2$5 - e) {
  13332. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13333. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13334. if (innerRadius > e) {
  13335. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13336. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13337. }
  13338. }
  13339. else {
  13340. var icrStart = void 0;
  13341. var icrEnd = void 0;
  13342. var ocrStart = void 0;
  13343. var ocrEnd = void 0;
  13344. var ocrs = void 0;
  13345. var ocre = void 0;
  13346. var icrs = void 0;
  13347. var icre = void 0;
  13348. var ocrMax = void 0;
  13349. var icrMax = void 0;
  13350. var limitedOcrMax = void 0;
  13351. var limitedIcrMax = void 0;
  13352. var xre = void 0;
  13353. var yre = void 0;
  13354. var xirs = void 0;
  13355. var yirs = void 0;
  13356. var xrs = radius * mathCos$3(startAngle);
  13357. var yrs = radius * mathSin$3(startAngle);
  13358. var xire = innerRadius * mathCos$3(endAngle);
  13359. var yire = innerRadius * mathSin$3(endAngle);
  13360. var hasArc = arc > e;
  13361. if (hasArc) {
  13362. var cornerRadius = shape.cornerRadius;
  13363. if (cornerRadius) {
  13364. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13365. }
  13366. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13367. ocrs = mathMin$3(halfRd, ocrStart);
  13368. ocre = mathMin$3(halfRd, ocrEnd);
  13369. icrs = mathMin$3(halfRd, icrStart);
  13370. icre = mathMin$3(halfRd, icrEnd);
  13371. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13372. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13373. if (ocrMax > e || icrMax > e) {
  13374. xre = radius * mathCos$3(endAngle);
  13375. yre = radius * mathSin$3(endAngle);
  13376. xirs = innerRadius * mathCos$3(startAngle);
  13377. yirs = innerRadius * mathSin$3(startAngle);
  13378. if (arc < PI$2) {
  13379. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13380. if (it_1) {
  13381. var x0 = xrs - it_1[0];
  13382. var y0 = yrs - it_1[1];
  13383. var x1 = xre - it_1[0];
  13384. var y1 = yre - it_1[1];
  13385. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13386. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13387. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13388. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13389. }
  13390. }
  13391. }
  13392. }
  13393. if (!hasArc) {
  13394. ctx.moveTo(cx + xrs, cy + yrs);
  13395. }
  13396. else if (limitedOcrMax > e) {
  13397. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13398. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13399. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13400. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13401. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13402. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13403. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13404. }
  13405. else {
  13406. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13407. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13408. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13409. }
  13410. }
  13411. else {
  13412. ctx.moveTo(cx + xrs, cy + yrs);
  13413. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13414. }
  13415. if (!(innerRadius > e) || !hasArc) {
  13416. ctx.lineTo(cx + xire, cy + yire);
  13417. }
  13418. else if (limitedIcrMax > e) {
  13419. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13420. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13421. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13422. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13423. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13424. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13425. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13426. }
  13427. else {
  13428. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13429. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13430. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13431. }
  13432. }
  13433. else {
  13434. ctx.lineTo(cx + xire, cy + yire);
  13435. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13436. }
  13437. }
  13438. ctx.closePath();
  13439. }
  13440. var SectorShape = (function () {
  13441. function SectorShape() {
  13442. this.cx = 0;
  13443. this.cy = 0;
  13444. this.r0 = 0;
  13445. this.r = 0;
  13446. this.startAngle = 0;
  13447. this.endAngle = Math.PI * 2;
  13448. this.clockwise = true;
  13449. this.cornerRadius = 0;
  13450. }
  13451. return SectorShape;
  13452. }());
  13453. var Sector = (function (_super) {
  13454. __extends(Sector, _super);
  13455. function Sector(opts) {
  13456. return _super.call(this, opts) || this;
  13457. }
  13458. Sector.prototype.getDefaultShape = function () {
  13459. return new SectorShape();
  13460. };
  13461. Sector.prototype.buildPath = function (ctx, shape) {
  13462. buildPath$1(ctx, shape);
  13463. };
  13464. Sector.prototype.isZeroArea = function () {
  13465. return this.shape.startAngle === this.shape.endAngle
  13466. || this.shape.r === this.shape.r0;
  13467. };
  13468. return Sector;
  13469. }(Path));
  13470. Sector.prototype.type = 'sector';
  13471. var RingShape = (function () {
  13472. function RingShape() {
  13473. this.cx = 0;
  13474. this.cy = 0;
  13475. this.r = 0;
  13476. this.r0 = 0;
  13477. }
  13478. return RingShape;
  13479. }());
  13480. var Ring = (function (_super) {
  13481. __extends(Ring, _super);
  13482. function Ring(opts) {
  13483. return _super.call(this, opts) || this;
  13484. }
  13485. Ring.prototype.getDefaultShape = function () {
  13486. return new RingShape();
  13487. };
  13488. Ring.prototype.buildPath = function (ctx, shape) {
  13489. var x = shape.cx;
  13490. var y = shape.cy;
  13491. var PI2 = Math.PI * 2;
  13492. ctx.moveTo(x + shape.r, y);
  13493. ctx.arc(x, y, shape.r, 0, PI2, false);
  13494. ctx.moveTo(x + shape.r0, y);
  13495. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13496. };
  13497. return Ring;
  13498. }(Path));
  13499. Ring.prototype.type = 'ring';
  13500. function smoothBezier(points, smooth, isLoop, constraint) {
  13501. var cps = [];
  13502. var v = [];
  13503. var v1 = [];
  13504. var v2 = [];
  13505. var prevPoint;
  13506. var nextPoint;
  13507. var min$1;
  13508. var max$1;
  13509. if (constraint) {
  13510. min$1 = [Infinity, Infinity];
  13511. max$1 = [-Infinity, -Infinity];
  13512. for (var i = 0, len = points.length; i < len; i++) {
  13513. min(min$1, min$1, points[i]);
  13514. max(max$1, max$1, points[i]);
  13515. }
  13516. min(min$1, min$1, constraint[0]);
  13517. max(max$1, max$1, constraint[1]);
  13518. }
  13519. for (var i = 0, len = points.length; i < len; i++) {
  13520. var point = points[i];
  13521. if (isLoop) {
  13522. prevPoint = points[i ? i - 1 : len - 1];
  13523. nextPoint = points[(i + 1) % len];
  13524. }
  13525. else {
  13526. if (i === 0 || i === len - 1) {
  13527. cps.push(clone$1(points[i]));
  13528. continue;
  13529. }
  13530. else {
  13531. prevPoint = points[i - 1];
  13532. nextPoint = points[i + 1];
  13533. }
  13534. }
  13535. sub(v, nextPoint, prevPoint);
  13536. scale(v, v, smooth);
  13537. var d0 = distance(point, prevPoint);
  13538. var d1 = distance(point, nextPoint);
  13539. var sum = d0 + d1;
  13540. if (sum !== 0) {
  13541. d0 /= sum;
  13542. d1 /= sum;
  13543. }
  13544. scale(v1, v, -d0);
  13545. scale(v2, v, d1);
  13546. var cp0 = add([], point, v1);
  13547. var cp1 = add([], point, v2);
  13548. if (constraint) {
  13549. max(cp0, cp0, min$1);
  13550. min(cp0, cp0, max$1);
  13551. max(cp1, cp1, min$1);
  13552. min(cp1, cp1, max$1);
  13553. }
  13554. cps.push(cp0);
  13555. cps.push(cp1);
  13556. }
  13557. if (isLoop) {
  13558. cps.push(cps.shift());
  13559. }
  13560. return cps;
  13561. }
  13562. function buildPath$2(ctx, shape, closePath) {
  13563. var smooth = shape.smooth;
  13564. var points = shape.points;
  13565. if (points && points.length >= 2) {
  13566. if (smooth) {
  13567. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13568. ctx.moveTo(points[0][0], points[0][1]);
  13569. var len = points.length;
  13570. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13571. var cp1 = controlPoints[i * 2];
  13572. var cp2 = controlPoints[i * 2 + 1];
  13573. var p = points[(i + 1) % len];
  13574. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13575. }
  13576. }
  13577. else {
  13578. ctx.moveTo(points[0][0], points[0][1]);
  13579. for (var i = 1, l = points.length; i < l; i++) {
  13580. ctx.lineTo(points[i][0], points[i][1]);
  13581. }
  13582. }
  13583. closePath && ctx.closePath();
  13584. }
  13585. }
  13586. var PolygonShape = (function () {
  13587. function PolygonShape() {
  13588. this.points = null;
  13589. this.smooth = 0;
  13590. this.smoothConstraint = null;
  13591. }
  13592. return PolygonShape;
  13593. }());
  13594. var Polygon = (function (_super) {
  13595. __extends(Polygon, _super);
  13596. function Polygon(opts) {
  13597. return _super.call(this, opts) || this;
  13598. }
  13599. Polygon.prototype.getDefaultShape = function () {
  13600. return new PolygonShape();
  13601. };
  13602. Polygon.prototype.buildPath = function (ctx, shape) {
  13603. buildPath$2(ctx, shape, true);
  13604. };
  13605. return Polygon;
  13606. }(Path));
  13607. Polygon.prototype.type = 'polygon';
  13608. var PolylineShape = (function () {
  13609. function PolylineShape() {
  13610. this.points = null;
  13611. this.percent = 1;
  13612. this.smooth = 0;
  13613. this.smoothConstraint = null;
  13614. }
  13615. return PolylineShape;
  13616. }());
  13617. var Polyline = (function (_super) {
  13618. __extends(Polyline, _super);
  13619. function Polyline(opts) {
  13620. return _super.call(this, opts) || this;
  13621. }
  13622. Polyline.prototype.getDefaultStyle = function () {
  13623. return {
  13624. stroke: '#000',
  13625. fill: null
  13626. };
  13627. };
  13628. Polyline.prototype.getDefaultShape = function () {
  13629. return new PolylineShape();
  13630. };
  13631. Polyline.prototype.buildPath = function (ctx, shape) {
  13632. buildPath$2(ctx, shape, false);
  13633. };
  13634. return Polyline;
  13635. }(Path));
  13636. Polyline.prototype.type = 'polyline';
  13637. var subPixelOptimizeOutputShape$1 = {};
  13638. var LineShape = (function () {
  13639. function LineShape() {
  13640. this.x1 = 0;
  13641. this.y1 = 0;
  13642. this.x2 = 0;
  13643. this.y2 = 0;
  13644. this.percent = 1;
  13645. }
  13646. return LineShape;
  13647. }());
  13648. var Line = (function (_super) {
  13649. __extends(Line, _super);
  13650. function Line(opts) {
  13651. return _super.call(this, opts) || this;
  13652. }
  13653. Line.prototype.getDefaultStyle = function () {
  13654. return {
  13655. stroke: '#000',
  13656. fill: null
  13657. };
  13658. };
  13659. Line.prototype.getDefaultShape = function () {
  13660. return new LineShape();
  13661. };
  13662. Line.prototype.buildPath = function (ctx, shape) {
  13663. var x1;
  13664. var y1;
  13665. var x2;
  13666. var y2;
  13667. if (this.subPixelOptimize) {
  13668. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13669. x1 = optimizedShape.x1;
  13670. y1 = optimizedShape.y1;
  13671. x2 = optimizedShape.x2;
  13672. y2 = optimizedShape.y2;
  13673. }
  13674. else {
  13675. x1 = shape.x1;
  13676. y1 = shape.y1;
  13677. x2 = shape.x2;
  13678. y2 = shape.y2;
  13679. }
  13680. var percent = shape.percent;
  13681. if (percent === 0) {
  13682. return;
  13683. }
  13684. ctx.moveTo(x1, y1);
  13685. if (percent < 1) {
  13686. x2 = x1 * (1 - percent) + x2 * percent;
  13687. y2 = y1 * (1 - percent) + y2 * percent;
  13688. }
  13689. ctx.lineTo(x2, y2);
  13690. };
  13691. Line.prototype.pointAt = function (p) {
  13692. var shape = this.shape;
  13693. return [
  13694. shape.x1 * (1 - p) + shape.x2 * p,
  13695. shape.y1 * (1 - p) + shape.y2 * p
  13696. ];
  13697. };
  13698. return Line;
  13699. }(Path));
  13700. Line.prototype.type = 'line';
  13701. var out = [];
  13702. var BezierCurveShape = (function () {
  13703. function BezierCurveShape() {
  13704. this.x1 = 0;
  13705. this.y1 = 0;
  13706. this.x2 = 0;
  13707. this.y2 = 0;
  13708. this.cpx1 = 0;
  13709. this.cpy1 = 0;
  13710. this.percent = 1;
  13711. }
  13712. return BezierCurveShape;
  13713. }());
  13714. function someVectorAt(shape, t, isTangent) {
  13715. var cpx2 = shape.cpx2;
  13716. var cpy2 = shape.cpy2;
  13717. if (cpx2 != null || cpy2 != null) {
  13718. return [
  13719. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13720. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13721. ];
  13722. }
  13723. else {
  13724. return [
  13725. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13726. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13727. ];
  13728. }
  13729. }
  13730. var BezierCurve = (function (_super) {
  13731. __extends(BezierCurve, _super);
  13732. function BezierCurve(opts) {
  13733. return _super.call(this, opts) || this;
  13734. }
  13735. BezierCurve.prototype.getDefaultStyle = function () {
  13736. return {
  13737. stroke: '#000',
  13738. fill: null
  13739. };
  13740. };
  13741. BezierCurve.prototype.getDefaultShape = function () {
  13742. return new BezierCurveShape();
  13743. };
  13744. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13745. var x1 = shape.x1;
  13746. var y1 = shape.y1;
  13747. var x2 = shape.x2;
  13748. var y2 = shape.y2;
  13749. var cpx1 = shape.cpx1;
  13750. var cpy1 = shape.cpy1;
  13751. var cpx2 = shape.cpx2;
  13752. var cpy2 = shape.cpy2;
  13753. var percent = shape.percent;
  13754. if (percent === 0) {
  13755. return;
  13756. }
  13757. ctx.moveTo(x1, y1);
  13758. if (cpx2 == null || cpy2 == null) {
  13759. if (percent < 1) {
  13760. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13761. cpx1 = out[1];
  13762. x2 = out[2];
  13763. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13764. cpy1 = out[1];
  13765. y2 = out[2];
  13766. }
  13767. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13768. }
  13769. else {
  13770. if (percent < 1) {
  13771. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13772. cpx1 = out[1];
  13773. cpx2 = out[2];
  13774. x2 = out[3];
  13775. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13776. cpy1 = out[1];
  13777. cpy2 = out[2];
  13778. y2 = out[3];
  13779. }
  13780. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13781. }
  13782. };
  13783. BezierCurve.prototype.pointAt = function (t) {
  13784. return someVectorAt(this.shape, t, false);
  13785. };
  13786. BezierCurve.prototype.tangentAt = function (t) {
  13787. var p = someVectorAt(this.shape, t, true);
  13788. return normalize(p, p);
  13789. };
  13790. return BezierCurve;
  13791. }(Path));
  13792. BezierCurve.prototype.type = 'bezier-curve';
  13793. var ArcShape = (function () {
  13794. function ArcShape() {
  13795. this.cx = 0;
  13796. this.cy = 0;
  13797. this.r = 0;
  13798. this.startAngle = 0;
  13799. this.endAngle = Math.PI * 2;
  13800. this.clockwise = true;
  13801. }
  13802. return ArcShape;
  13803. }());
  13804. var Arc = (function (_super) {
  13805. __extends(Arc, _super);
  13806. function Arc(opts) {
  13807. return _super.call(this, opts) || this;
  13808. }
  13809. Arc.prototype.getDefaultStyle = function () {
  13810. return {
  13811. stroke: '#000',
  13812. fill: null
  13813. };
  13814. };
  13815. Arc.prototype.getDefaultShape = function () {
  13816. return new ArcShape();
  13817. };
  13818. Arc.prototype.buildPath = function (ctx, shape) {
  13819. var x = shape.cx;
  13820. var y = shape.cy;
  13821. var r = Math.max(shape.r, 0);
  13822. var startAngle = shape.startAngle;
  13823. var endAngle = shape.endAngle;
  13824. var clockwise = shape.clockwise;
  13825. var unitX = Math.cos(startAngle);
  13826. var unitY = Math.sin(startAngle);
  13827. ctx.moveTo(unitX * r + x, unitY * r + y);
  13828. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13829. };
  13830. return Arc;
  13831. }(Path));
  13832. Arc.prototype.type = 'arc';
  13833. var CompoundPath = (function (_super) {
  13834. __extends(CompoundPath, _super);
  13835. function CompoundPath() {
  13836. var _this = _super !== null && _super.apply(this, arguments) || this;
  13837. _this.type = 'compound';
  13838. return _this;
  13839. }
  13840. CompoundPath.prototype._updatePathDirty = function () {
  13841. var paths = this.shape.paths;
  13842. var dirtyPath = this.shapeChanged();
  13843. for (var i = 0; i < paths.length; i++) {
  13844. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13845. }
  13846. if (dirtyPath) {
  13847. this.dirtyShape();
  13848. }
  13849. };
  13850. CompoundPath.prototype.beforeBrush = function () {
  13851. this._updatePathDirty();
  13852. var paths = this.shape.paths || [];
  13853. var scale = this.getGlobalScale();
  13854. for (var i = 0; i < paths.length; i++) {
  13855. if (!paths[i].path) {
  13856. paths[i].createPathProxy();
  13857. }
  13858. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13859. }
  13860. };
  13861. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13862. var paths = shape.paths || [];
  13863. for (var i = 0; i < paths.length; i++) {
  13864. paths[i].buildPath(ctx, paths[i].shape, true);
  13865. }
  13866. };
  13867. CompoundPath.prototype.afterBrush = function () {
  13868. var paths = this.shape.paths || [];
  13869. for (var i = 0; i < paths.length; i++) {
  13870. paths[i].pathUpdated();
  13871. }
  13872. };
  13873. CompoundPath.prototype.getBoundingRect = function () {
  13874. this._updatePathDirty.call(this);
  13875. return Path.prototype.getBoundingRect.call(this);
  13876. };
  13877. return CompoundPath;
  13878. }(Path));
  13879. var Gradient = (function () {
  13880. function Gradient(colorStops) {
  13881. this.colorStops = colorStops || [];
  13882. }
  13883. Gradient.prototype.addColorStop = function (offset, color) {
  13884. this.colorStops.push({
  13885. offset: offset,
  13886. color: color
  13887. });
  13888. };
  13889. return Gradient;
  13890. }());
  13891. var LinearGradient = (function (_super) {
  13892. __extends(LinearGradient, _super);
  13893. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13894. var _this = _super.call(this, colorStops) || this;
  13895. _this.x = x == null ? 0 : x;
  13896. _this.y = y == null ? 0 : y;
  13897. _this.x2 = x2 == null ? 1 : x2;
  13898. _this.y2 = y2 == null ? 0 : y2;
  13899. _this.type = 'linear';
  13900. _this.global = globalCoord || false;
  13901. return _this;
  13902. }
  13903. return LinearGradient;
  13904. }(Gradient));
  13905. var RadialGradient = (function (_super) {
  13906. __extends(RadialGradient, _super);
  13907. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13908. var _this = _super.call(this, colorStops) || this;
  13909. _this.x = x == null ? 0.5 : x;
  13910. _this.y = y == null ? 0.5 : y;
  13911. _this.r = r == null ? 0.5 : r;
  13912. _this.type = 'radial';
  13913. _this.global = globalCoord || false;
  13914. return _this;
  13915. }
  13916. return RadialGradient;
  13917. }(Gradient));
  13918. var extent = [0, 0];
  13919. var extent2 = [0, 0];
  13920. var minTv$1 = new Point();
  13921. var maxTv$1 = new Point();
  13922. var OrientedBoundingRect = (function () {
  13923. function OrientedBoundingRect(rect, transform) {
  13924. this._corners = [];
  13925. this._axes = [];
  13926. this._origin = [0, 0];
  13927. for (var i = 0; i < 4; i++) {
  13928. this._corners[i] = new Point();
  13929. }
  13930. for (var i = 0; i < 2; i++) {
  13931. this._axes[i] = new Point();
  13932. }
  13933. if (rect) {
  13934. this.fromBoundingRect(rect, transform);
  13935. }
  13936. }
  13937. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13938. var corners = this._corners;
  13939. var axes = this._axes;
  13940. var x = rect.x;
  13941. var y = rect.y;
  13942. var x2 = x + rect.width;
  13943. var y2 = y + rect.height;
  13944. corners[0].set(x, y);
  13945. corners[1].set(x2, y);
  13946. corners[2].set(x2, y2);
  13947. corners[3].set(x, y2);
  13948. if (transform) {
  13949. for (var i = 0; i < 4; i++) {
  13950. corners[i].transform(transform);
  13951. }
  13952. }
  13953. Point.sub(axes[0], corners[1], corners[0]);
  13954. Point.sub(axes[1], corners[3], corners[0]);
  13955. axes[0].normalize();
  13956. axes[1].normalize();
  13957. for (var i = 0; i < 2; i++) {
  13958. this._origin[i] = axes[i].dot(corners[0]);
  13959. }
  13960. };
  13961. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13962. var overlapped = true;
  13963. var noMtv = !mtv;
  13964. minTv$1.set(Infinity, Infinity);
  13965. maxTv$1.set(0, 0);
  13966. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13967. overlapped = false;
  13968. if (noMtv) {
  13969. return overlapped;
  13970. }
  13971. }
  13972. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13973. overlapped = false;
  13974. if (noMtv) {
  13975. return overlapped;
  13976. }
  13977. }
  13978. if (!noMtv) {
  13979. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13980. }
  13981. return overlapped;
  13982. };
  13983. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13984. var overlapped = true;
  13985. for (var i = 0; i < 2; i++) {
  13986. var axis = this._axes[i];
  13987. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13988. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13989. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13990. overlapped = false;
  13991. if (noMtv) {
  13992. return overlapped;
  13993. }
  13994. var dist0 = Math.abs(extent2[0] - extent[1]);
  13995. var dist1 = Math.abs(extent[0] - extent2[1]);
  13996. if (Math.min(dist0, dist1) > maxTv.len()) {
  13997. if (dist0 < dist1) {
  13998. Point.scale(maxTv, axis, -dist0 * inverse);
  13999. }
  14000. else {
  14001. Point.scale(maxTv, axis, dist1 * inverse);
  14002. }
  14003. }
  14004. }
  14005. else if (minTv) {
  14006. var dist0 = Math.abs(extent2[0] - extent[1]);
  14007. var dist1 = Math.abs(extent[0] - extent2[1]);
  14008. if (Math.min(dist0, dist1) < minTv.len()) {
  14009. if (dist0 < dist1) {
  14010. Point.scale(minTv, axis, dist0 * inverse);
  14011. }
  14012. else {
  14013. Point.scale(minTv, axis, -dist1 * inverse);
  14014. }
  14015. }
  14016. }
  14017. }
  14018. return overlapped;
  14019. };
  14020. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  14021. var axis = this._axes[dim];
  14022. var origin = this._origin;
  14023. var proj = corners[0].dot(axis) + origin[dim];
  14024. var min = proj;
  14025. var max = proj;
  14026. for (var i = 1; i < corners.length; i++) {
  14027. var proj_1 = corners[i].dot(axis) + origin[dim];
  14028. min = Math.min(proj_1, min);
  14029. max = Math.max(proj_1, max);
  14030. }
  14031. out[0] = min;
  14032. out[1] = max;
  14033. };
  14034. return OrientedBoundingRect;
  14035. }());
  14036. var m = [];
  14037. var IncrementalDisplayable = (function (_super) {
  14038. __extends(IncrementalDisplayable, _super);
  14039. function IncrementalDisplayable() {
  14040. var _this = _super !== null && _super.apply(this, arguments) || this;
  14041. _this.notClear = true;
  14042. _this.incremental = true;
  14043. _this._displayables = [];
  14044. _this._temporaryDisplayables = [];
  14045. _this._cursor = 0;
  14046. return _this;
  14047. }
  14048. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  14049. cb.call(context, this);
  14050. };
  14051. IncrementalDisplayable.prototype.useStyle = function () {
  14052. this.style = {};
  14053. };
  14054. IncrementalDisplayable.prototype.getCursor = function () {
  14055. return this._cursor;
  14056. };
  14057. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  14058. this._cursor = this._displayables.length;
  14059. };
  14060. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  14061. this._displayables = [];
  14062. this._temporaryDisplayables = [];
  14063. this._cursor = 0;
  14064. this.markRedraw();
  14065. this.notClear = false;
  14066. };
  14067. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  14068. this._temporaryDisplayables = [];
  14069. };
  14070. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  14071. if (notPersistent) {
  14072. this._temporaryDisplayables.push(displayable);
  14073. }
  14074. else {
  14075. this._displayables.push(displayable);
  14076. }
  14077. this.markRedraw();
  14078. };
  14079. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  14080. notPersistent = notPersistent || false;
  14081. for (var i = 0; i < displayables.length; i++) {
  14082. this.addDisplayable(displayables[i], notPersistent);
  14083. }
  14084. };
  14085. IncrementalDisplayable.prototype.getDisplayables = function () {
  14086. return this._displayables;
  14087. };
  14088. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  14089. return this._temporaryDisplayables;
  14090. };
  14091. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  14092. for (var i = this._cursor; i < this._displayables.length; i++) {
  14093. cb && cb(this._displayables[i]);
  14094. }
  14095. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14096. cb && cb(this._temporaryDisplayables[i]);
  14097. }
  14098. };
  14099. IncrementalDisplayable.prototype.update = function () {
  14100. this.updateTransform();
  14101. for (var i = this._cursor; i < this._displayables.length; i++) {
  14102. var displayable = this._displayables[i];
  14103. displayable.parent = this;
  14104. displayable.update();
  14105. displayable.parent = null;
  14106. }
  14107. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14108. var displayable = this._temporaryDisplayables[i];
  14109. displayable.parent = this;
  14110. displayable.update();
  14111. displayable.parent = null;
  14112. }
  14113. };
  14114. IncrementalDisplayable.prototype.getBoundingRect = function () {
  14115. if (!this._rect) {
  14116. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14117. for (var i = 0; i < this._displayables.length; i++) {
  14118. var displayable = this._displayables[i];
  14119. var childRect = displayable.getBoundingRect().clone();
  14120. if (displayable.needLocalTransform()) {
  14121. childRect.applyTransform(displayable.getLocalTransform(m));
  14122. }
  14123. rect.union(childRect);
  14124. }
  14125. this._rect = rect;
  14126. }
  14127. return this._rect;
  14128. };
  14129. IncrementalDisplayable.prototype.contain = function (x, y) {
  14130. var localPos = this.transformCoordToLocal(x, y);
  14131. var rect = this.getBoundingRect();
  14132. if (rect.contain(localPos[0], localPos[1])) {
  14133. for (var i = 0; i < this._displayables.length; i++) {
  14134. var displayable = this._displayables[i];
  14135. if (displayable.contain(x, y)) {
  14136. return true;
  14137. }
  14138. }
  14139. }
  14140. return false;
  14141. };
  14142. return IncrementalDisplayable;
  14143. }(Displayable));
  14144. // Stored properties for further transition.
  14145. var transitionStore = makeInner();
  14146. /**
  14147. * Return null if animation is disabled.
  14148. */
  14149. function getAnimationConfig(animationType, animatableModel, dataIndex,
  14150. // Extra opts can override the option in animatable model.
  14151. extraOpts,
  14152. // TODO It's only for pictorial bar now.
  14153. extraDelayParams) {
  14154. var animationPayload;
  14155. // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14156. // If animation is enabled. Will use this animation config in payload.
  14157. // If animation is disabled. Just ignore it.
  14158. if (animatableModel && animatableModel.ecModel) {
  14159. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14160. animationPayload = updatePayload && updatePayload.animation;
  14161. }
  14162. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14163. var isUpdate = animationType === 'update';
  14164. if (animationEnabled) {
  14165. var duration = void 0;
  14166. var easing = void 0;
  14167. var delay = void 0;
  14168. if (extraOpts) {
  14169. duration = retrieve2(extraOpts.duration, 200);
  14170. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14171. delay = 0;
  14172. } else {
  14173. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14174. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14175. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14176. }
  14177. // animation from payload has highest priority.
  14178. if (animationPayload) {
  14179. animationPayload.duration != null && (duration = animationPayload.duration);
  14180. animationPayload.easing != null && (easing = animationPayload.easing);
  14181. animationPayload.delay != null && (delay = animationPayload.delay);
  14182. }
  14183. if (isFunction(delay)) {
  14184. delay = delay(dataIndex, extraDelayParams);
  14185. }
  14186. if (isFunction(duration)) {
  14187. duration = duration(dataIndex);
  14188. }
  14189. var config = {
  14190. duration: duration || 0,
  14191. delay: delay,
  14192. easing: easing
  14193. };
  14194. return config;
  14195. } else {
  14196. return null;
  14197. }
  14198. }
  14199. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14200. var isFrom = false;
  14201. var removeOpt;
  14202. if (isFunction(dataIndex)) {
  14203. during = cb;
  14204. cb = dataIndex;
  14205. dataIndex = null;
  14206. } else if (isObject(dataIndex)) {
  14207. cb = dataIndex.cb;
  14208. during = dataIndex.during;
  14209. isFrom = dataIndex.isFrom;
  14210. removeOpt = dataIndex.removeOpt;
  14211. dataIndex = dataIndex.dataIndex;
  14212. }
  14213. var isRemove = animationType === 'leave';
  14214. if (!isRemove) {
  14215. // Must stop the remove animation.
  14216. el.stopAnimation('leave');
  14217. }
  14218. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14219. if (animationConfig && animationConfig.duration > 0) {
  14220. var duration = animationConfig.duration;
  14221. var animationDelay = animationConfig.delay;
  14222. var animationEasing = animationConfig.easing;
  14223. var animateConfig = {
  14224. duration: duration,
  14225. delay: animationDelay || 0,
  14226. easing: animationEasing,
  14227. done: cb,
  14228. force: !!cb || !!during,
  14229. // Set to final state in update/init animation.
  14230. // So the post processing based on the path shape can be done correctly.
  14231. setToFinal: !isRemove,
  14232. scope: animationType,
  14233. during: during
  14234. };
  14235. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14236. } else {
  14237. el.stopAnimation();
  14238. // If `isFrom`, the props is the "from" props.
  14239. !isFrom && el.attr(props);
  14240. // Call during at least once.
  14241. during && during(1);
  14242. cb && cb();
  14243. }
  14244. }
  14245. /**
  14246. * Update graphic element properties with or without animation according to the
  14247. * configuration in series.
  14248. *
  14249. * Caution: this method will stop previous animation.
  14250. * So do not use this method to one element twice before
  14251. * animation starts, unless you know what you are doing.
  14252. * @example
  14253. * graphic.updateProps(el, {
  14254. * position: [100, 100]
  14255. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14256. * // Or
  14257. * graphic.updateProps(el, {
  14258. * position: [100, 100]
  14259. * }, seriesModel, function () { console.log('Animation done!'); });
  14260. */
  14261. function updateProps(el, props,
  14262. // TODO: TYPE AnimatableModel
  14263. animatableModel, dataIndex, cb, during) {
  14264. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14265. }
  14266. /**
  14267. * Init graphic element properties with or without animation according to the
  14268. * configuration in series.
  14269. *
  14270. * Caution: this method will stop previous animation.
  14271. * So do not use this method to one element twice before
  14272. * animation starts, unless you know what you are doing.
  14273. */
  14274. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14275. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14276. }
  14277. /**
  14278. * If element is removed.
  14279. * It can determine if element is having remove animation.
  14280. */
  14281. function isElementRemoved(el) {
  14282. if (!el.__zr) {
  14283. return true;
  14284. }
  14285. for (var i = 0; i < el.animators.length; i++) {
  14286. var animator = el.animators[i];
  14287. if (animator.scope === 'leave') {
  14288. return true;
  14289. }
  14290. }
  14291. return false;
  14292. }
  14293. /**
  14294. * Remove graphic element
  14295. */
  14296. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14297. // Don't do remove animation twice.
  14298. if (isElementRemoved(el)) {
  14299. return;
  14300. }
  14301. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14302. }
  14303. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14304. el.removeTextContent();
  14305. el.removeTextGuideLine();
  14306. removeElement(el, {
  14307. style: {
  14308. opacity: 0
  14309. }
  14310. }, animatableModel, dataIndex, done);
  14311. }
  14312. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14313. function doRemove() {
  14314. el.parent && el.parent.remove(el);
  14315. }
  14316. // Hide label and labelLine first
  14317. // TODO Also use fade out animation?
  14318. if (!el.isGroup) {
  14319. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14320. } else {
  14321. el.traverse(function (disp) {
  14322. if (!disp.isGroup) {
  14323. // Can invoke doRemove multiple times.
  14324. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14325. }
  14326. });
  14327. }
  14328. }
  14329. /**
  14330. * Save old style for style transition in universalTransition module.
  14331. * It's used when element will be reused in each render.
  14332. * For chart like map, heatmap, which will always create new element.
  14333. * We don't need to save this because universalTransition can get old style from the old element
  14334. */
  14335. function saveOldStyle(el) {
  14336. transitionStore(el).oldStyle = el.style;
  14337. }
  14338. var mathMax$4 = Math.max;
  14339. var mathMin$4 = Math.min;
  14340. var _customShapeMap = {};
  14341. /**
  14342. * Extend shape with parameters
  14343. */
  14344. function extendShape(opts) {
  14345. return Path.extend(opts);
  14346. }
  14347. var extendPathFromString = extendFromString;
  14348. /**
  14349. * Extend path
  14350. */
  14351. function extendPath(pathData, opts) {
  14352. return extendPathFromString(pathData, opts);
  14353. }
  14354. /**
  14355. * Register a user defined shape.
  14356. * The shape class can be fetched by `getShapeClass`
  14357. * This method will overwrite the registered shapes, including
  14358. * the registered built-in shapes, if using the same `name`.
  14359. * The shape can be used in `custom series` and
  14360. * `graphic component` by declaring `{type: name}`.
  14361. *
  14362. * @param name
  14363. * @param ShapeClass Can be generated by `extendShape`.
  14364. */
  14365. function registerShape(name, ShapeClass) {
  14366. _customShapeMap[name] = ShapeClass;
  14367. }
  14368. /**
  14369. * Find shape class registered by `registerShape`. Usually used in
  14370. * fetching user defined shape.
  14371. *
  14372. * [Caution]:
  14373. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14374. * to use user registered shapes.
  14375. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14376. * `registerShape` by default. That enables users to get both built-in
  14377. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14378. * the built-in shapes by using names like 'circle', 'rect' via calling
  14379. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14380. * in case that it is overwritten by users, except that some features, like
  14381. * `custom series`, `graphic component`, do it deliberately.
  14382. *
  14383. * (2) In the features like `custom series`, `graphic component`, the user input
  14384. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14385. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14386. * are reserved names, that is, if some user registers a shape named `'image'`,
  14387. * the shape will not be used. If we intending to add some more reserved names
  14388. * in feature, that might bring break changes (disable some existing user shape
  14389. * names). But that case probably rarely happens. So we don't make more mechanism
  14390. * to resolve this issue here.
  14391. *
  14392. * @param name
  14393. * @return The shape class. If not found, return nothing.
  14394. */
  14395. function getShapeClass(name) {
  14396. if (_customShapeMap.hasOwnProperty(name)) {
  14397. return _customShapeMap[name];
  14398. }
  14399. }
  14400. /**
  14401. * Create a path element from path data string
  14402. * @param pathData
  14403. * @param opts
  14404. * @param rect
  14405. * @param layout 'center' or 'cover' default to be cover
  14406. */
  14407. function makePath(pathData, opts, rect, layout) {
  14408. var path = createFromString(pathData, opts);
  14409. if (rect) {
  14410. if (layout === 'center') {
  14411. rect = centerGraphic(rect, path.getBoundingRect());
  14412. }
  14413. resizePath(path, rect);
  14414. }
  14415. return path;
  14416. }
  14417. /**
  14418. * Create a image element from image url
  14419. * @param imageUrl image url
  14420. * @param opts options
  14421. * @param rect constrain rect
  14422. * @param layout 'center' or 'cover'. Default to be 'cover'
  14423. */
  14424. function makeImage(imageUrl, rect, layout) {
  14425. var zrImg = new ZRImage({
  14426. style: {
  14427. image: imageUrl,
  14428. x: rect.x,
  14429. y: rect.y,
  14430. width: rect.width,
  14431. height: rect.height
  14432. },
  14433. onload: function (img) {
  14434. if (layout === 'center') {
  14435. var boundingRect = {
  14436. width: img.width,
  14437. height: img.height
  14438. };
  14439. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14440. }
  14441. }
  14442. });
  14443. return zrImg;
  14444. }
  14445. /**
  14446. * Get position of centered element in bounding box.
  14447. *
  14448. * @param rect element local bounding box
  14449. * @param boundingRect constraint bounding box
  14450. * @return element position containing x, y, width, and height
  14451. */
  14452. function centerGraphic(rect, boundingRect) {
  14453. // Set rect to center, keep width / height ratio.
  14454. var aspect = boundingRect.width / boundingRect.height;
  14455. var width = rect.height * aspect;
  14456. var height;
  14457. if (width <= rect.width) {
  14458. height = rect.height;
  14459. } else {
  14460. width = rect.width;
  14461. height = width / aspect;
  14462. }
  14463. var cx = rect.x + rect.width / 2;
  14464. var cy = rect.y + rect.height / 2;
  14465. return {
  14466. x: cx - width / 2,
  14467. y: cy - height / 2,
  14468. width: width,
  14469. height: height
  14470. };
  14471. }
  14472. var mergePath$1 = mergePath;
  14473. /**
  14474. * Resize a path to fit the rect
  14475. * @param path
  14476. * @param rect
  14477. */
  14478. function resizePath(path, rect) {
  14479. if (!path.applyTransform) {
  14480. return;
  14481. }
  14482. var pathRect = path.getBoundingRect();
  14483. var m = pathRect.calculateTransform(rect);
  14484. path.applyTransform(m);
  14485. }
  14486. /**
  14487. * Sub pixel optimize line for canvas
  14488. */
  14489. function subPixelOptimizeLine$1(shape, lineWidth) {
  14490. subPixelOptimizeLine(shape, shape, {
  14491. lineWidth: lineWidth
  14492. });
  14493. return shape;
  14494. }
  14495. /**
  14496. * Sub pixel optimize rect for canvas
  14497. */
  14498. function subPixelOptimizeRect$1(param) {
  14499. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14500. return param;
  14501. }
  14502. /**
  14503. * Sub pixel optimize for canvas
  14504. *
  14505. * @param position Coordinate, such as x, y
  14506. * @param lineWidth Should be nonnegative integer.
  14507. * @param positiveOrNegative Default false (negative).
  14508. * @return Optimized position.
  14509. */
  14510. var subPixelOptimize$1 = subPixelOptimize;
  14511. /**
  14512. * Get transform matrix of target (param target),
  14513. * in coordinate of its ancestor (param ancestor)
  14514. *
  14515. * @param target
  14516. * @param [ancestor]
  14517. */
  14518. function getTransform(target, ancestor) {
  14519. var mat = identity([]);
  14520. while (target && target !== ancestor) {
  14521. mul$1(mat, target.getLocalTransform(), mat);
  14522. target = target.parent;
  14523. }
  14524. return mat;
  14525. }
  14526. /**
  14527. * Apply transform to an vertex.
  14528. * @param target [x, y]
  14529. * @param transform Can be:
  14530. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14531. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14532. * @param invert Whether use invert matrix.
  14533. * @return [x, y]
  14534. */
  14535. function applyTransform$1(target, transform, invert$1) {
  14536. if (transform && !isArrayLike(transform)) {
  14537. transform = Transformable.getLocalTransform(transform);
  14538. }
  14539. if (invert$1) {
  14540. transform = invert([], transform);
  14541. }
  14542. return applyTransform([], target, transform);
  14543. }
  14544. /**
  14545. * @param direction 'left' 'right' 'top' 'bottom'
  14546. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14547. * @param invert Whether use invert matrix.
  14548. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14549. */
  14550. function transformDirection(direction, transform, invert) {
  14551. // Pick a base, ensure that transform result will not be (0, 0).
  14552. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14553. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14554. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14555. vertex = applyTransform$1(vertex, transform, invert);
  14556. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14557. }
  14558. function isNotGroup(el) {
  14559. return !el.isGroup;
  14560. }
  14561. function isPath(el) {
  14562. return el.shape != null;
  14563. }
  14564. /**
  14565. * Apply group transition animation from g1 to g2.
  14566. * If no animatableModel, no animation.
  14567. */
  14568. function groupTransition(g1, g2, animatableModel) {
  14569. if (!g1 || !g2) {
  14570. return;
  14571. }
  14572. function getElMap(g) {
  14573. var elMap = {};
  14574. g.traverse(function (el) {
  14575. if (isNotGroup(el) && el.anid) {
  14576. elMap[el.anid] = el;
  14577. }
  14578. });
  14579. return elMap;
  14580. }
  14581. function getAnimatableProps(el) {
  14582. var obj = {
  14583. x: el.x,
  14584. y: el.y,
  14585. rotation: el.rotation
  14586. };
  14587. if (isPath(el)) {
  14588. obj.shape = extend({}, el.shape);
  14589. }
  14590. return obj;
  14591. }
  14592. var elMap1 = getElMap(g1);
  14593. g2.traverse(function (el) {
  14594. if (isNotGroup(el) && el.anid) {
  14595. var oldEl = elMap1[el.anid];
  14596. if (oldEl) {
  14597. var newProp = getAnimatableProps(el);
  14598. el.attr(getAnimatableProps(oldEl));
  14599. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14600. }
  14601. }
  14602. });
  14603. }
  14604. function clipPointsByRect(points, rect) {
  14605. // FIXME: This way might be incorrect when graphic clipped by a corner
  14606. // and when element has a border.
  14607. return map(points, function (point) {
  14608. var x = point[0];
  14609. x = mathMax$4(x, rect.x);
  14610. x = mathMin$4(x, rect.x + rect.width);
  14611. var y = point[1];
  14612. y = mathMax$4(y, rect.y);
  14613. y = mathMin$4(y, rect.y + rect.height);
  14614. return [x, y];
  14615. });
  14616. }
  14617. /**
  14618. * Return a new clipped rect. If rect size are negative, return undefined.
  14619. */
  14620. function clipRectByRect(targetRect, rect) {
  14621. var x = mathMax$4(targetRect.x, rect.x);
  14622. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14623. var y = mathMax$4(targetRect.y, rect.y);
  14624. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height);
  14625. // If the total rect is cliped, nothing, including the border,
  14626. // should be painted. So return undefined.
  14627. if (x2 >= x && y2 >= y) {
  14628. return {
  14629. x: x,
  14630. y: y,
  14631. width: x2 - x,
  14632. height: y2 - y
  14633. };
  14634. }
  14635. }
  14636. function createIcon(iconStr,
  14637. // Support 'image://' or 'path://' or direct svg path.
  14638. opt, rect) {
  14639. var innerOpts = extend({
  14640. rectHover: true
  14641. }, opt);
  14642. var style = innerOpts.style = {
  14643. strokeNoScale: true
  14644. };
  14645. rect = rect || {
  14646. x: -1,
  14647. y: -1,
  14648. width: 2,
  14649. height: 2
  14650. };
  14651. if (iconStr) {
  14652. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14653. }
  14654. }
  14655. /**
  14656. * Return `true` if the given line (line `a`) and the given polygon
  14657. * are intersect.
  14658. * Note that we do not count colinear as intersect here because no
  14659. * requirement for that. We could do that if required in future.
  14660. */
  14661. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14662. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14663. var p = points[i];
  14664. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14665. return true;
  14666. }
  14667. p2 = p;
  14668. }
  14669. }
  14670. /**
  14671. * Return `true` if the given two lines (line `a` and line `b`)
  14672. * are intersect.
  14673. * Note that we do not count colinear as intersect here because no
  14674. * requirement for that. We could do that if required in future.
  14675. */
  14676. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14677. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14678. var mx = a2x - a1x;
  14679. var my = a2y - a1y;
  14680. var nx = b2x - b1x;
  14681. var ny = b2y - b1y;
  14682. // `vec_m` and `vec_n` are parallel iff
  14683. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14684. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14685. if (nearZero(nmCrossProduct)) {
  14686. return false;
  14687. }
  14688. // `vec_m` and `vec_n` are intersect iff
  14689. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14690. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14691. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14692. var b1a1x = a1x - b1x;
  14693. var b1a1y = a1y - b1y;
  14694. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14695. if (q < 0 || q > 1) {
  14696. return false;
  14697. }
  14698. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14699. if (p < 0 || p > 1) {
  14700. return false;
  14701. }
  14702. return true;
  14703. }
  14704. /**
  14705. * Cross product of 2-dimension vector.
  14706. */
  14707. function crossProduct2d(x1, y1, x2, y2) {
  14708. return x1 * y2 - x2 * y1;
  14709. }
  14710. function nearZero(val) {
  14711. return val <= 1e-6 && val >= -1e-6;
  14712. }
  14713. function setTooltipConfig(opt) {
  14714. var itemTooltipOption = opt.itemTooltipOption;
  14715. var componentModel = opt.componentModel;
  14716. var itemName = opt.itemName;
  14717. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14718. formatter: itemTooltipOption
  14719. } : itemTooltipOption;
  14720. var mainType = componentModel.mainType;
  14721. var componentIndex = componentModel.componentIndex;
  14722. var formatterParams = {
  14723. componentType: mainType,
  14724. name: itemName,
  14725. $vars: ['name']
  14726. };
  14727. formatterParams[mainType + 'Index'] = componentIndex;
  14728. var formatterParamsExtra = opt.formatterParamsExtra;
  14729. if (formatterParamsExtra) {
  14730. each(keys(formatterParamsExtra), function (key) {
  14731. if (!hasOwn(formatterParams, key)) {
  14732. formatterParams[key] = formatterParamsExtra[key];
  14733. formatterParams.$vars.push(key);
  14734. }
  14735. });
  14736. }
  14737. var ecData = getECData(opt.el);
  14738. ecData.componentMainType = mainType;
  14739. ecData.componentIndex = componentIndex;
  14740. ecData.tooltipConfig = {
  14741. name: itemName,
  14742. option: defaults({
  14743. content: itemName,
  14744. encodeHTMLContent: true,
  14745. formatterParams: formatterParams
  14746. }, itemTooltipOptionObj)
  14747. };
  14748. }
  14749. function traverseElement(el, cb) {
  14750. var stopped;
  14751. // TODO
  14752. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14753. if (el.isGroup) {
  14754. stopped = cb(el);
  14755. }
  14756. if (!stopped) {
  14757. el.traverse(cb);
  14758. }
  14759. }
  14760. function traverseElements(els, cb) {
  14761. if (els) {
  14762. if (isArray(els)) {
  14763. for (var i = 0; i < els.length; i++) {
  14764. traverseElement(els[i], cb);
  14765. }
  14766. } else {
  14767. traverseElement(els, cb);
  14768. }
  14769. }
  14770. }
  14771. // Register built-in shapes. These shapes might be overwritten
  14772. // by users, although we do not recommend that.
  14773. registerShape('circle', Circle);
  14774. registerShape('ellipse', Ellipse);
  14775. registerShape('sector', Sector);
  14776. registerShape('ring', Ring);
  14777. registerShape('polygon', Polygon);
  14778. registerShape('polyline', Polyline);
  14779. registerShape('rect', Rect);
  14780. registerShape('line', Line);
  14781. registerShape('bezierCurve', BezierCurve);
  14782. registerShape('arc', Arc);
  14783. var graphic = /*#__PURE__*/Object.freeze({
  14784. __proto__: null,
  14785. updateProps: updateProps,
  14786. initProps: initProps,
  14787. removeElement: removeElement,
  14788. removeElementWithFadeOut: removeElementWithFadeOut,
  14789. isElementRemoved: isElementRemoved,
  14790. extendShape: extendShape,
  14791. extendPath: extendPath,
  14792. registerShape: registerShape,
  14793. getShapeClass: getShapeClass,
  14794. makePath: makePath,
  14795. makeImage: makeImage,
  14796. mergePath: mergePath$1,
  14797. resizePath: resizePath,
  14798. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14799. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14800. subPixelOptimize: subPixelOptimize$1,
  14801. getTransform: getTransform,
  14802. applyTransform: applyTransform$1,
  14803. transformDirection: transformDirection,
  14804. groupTransition: groupTransition,
  14805. clipPointsByRect: clipPointsByRect,
  14806. clipRectByRect: clipRectByRect,
  14807. createIcon: createIcon,
  14808. linePolygonIntersect: linePolygonIntersect,
  14809. lineLineIntersect: lineLineIntersect,
  14810. setTooltipConfig: setTooltipConfig,
  14811. traverseElements: traverseElements,
  14812. Group: Group,
  14813. Image: ZRImage,
  14814. Text: ZRText,
  14815. Circle: Circle,
  14816. Ellipse: Ellipse,
  14817. Sector: Sector,
  14818. Ring: Ring,
  14819. Polygon: Polygon,
  14820. Polyline: Polyline,
  14821. Rect: Rect,
  14822. Line: Line,
  14823. BezierCurve: BezierCurve,
  14824. Arc: Arc,
  14825. IncrementalDisplayable: IncrementalDisplayable,
  14826. CompoundPath: CompoundPath,
  14827. LinearGradient: LinearGradient,
  14828. RadialGradient: RadialGradient,
  14829. BoundingRect: BoundingRect,
  14830. OrientedBoundingRect: OrientedBoundingRect,
  14831. Point: Point,
  14832. Path: Path
  14833. });
  14834. var EMPTY_OBJ = {};
  14835. function setLabelText(label, labelTexts) {
  14836. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14837. var stateName = SPECIAL_STATES[i];
  14838. var text = labelTexts[stateName];
  14839. var state = label.ensureState(stateName);
  14840. state.style = state.style || {};
  14841. state.style.text = text;
  14842. }
  14843. var oldStates = label.currentStates.slice();
  14844. label.clearStates(true);
  14845. label.setStyle({
  14846. text: labelTexts.normal
  14847. });
  14848. label.useStates(oldStates, true);
  14849. }
  14850. function getLabelText(opt, stateModels, interpolatedValue) {
  14851. var labelFetcher = opt.labelFetcher;
  14852. var labelDataIndex = opt.labelDataIndex;
  14853. var labelDimIndex = opt.labelDimIndex;
  14854. var normalModel = stateModels.normal;
  14855. var baseText;
  14856. if (labelFetcher) {
  14857. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14858. interpolatedValue: interpolatedValue
  14859. } : null);
  14860. }
  14861. if (baseText == null) {
  14862. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14863. }
  14864. var statesText = {
  14865. normal: baseText
  14866. };
  14867. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14868. var stateName = SPECIAL_STATES[i];
  14869. var stateModel = stateModels[stateName];
  14870. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14871. }
  14872. return statesText;
  14873. }
  14874. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified
  14875. // TODO specified position?
  14876. ) {
  14877. opt = opt || EMPTY_OBJ;
  14878. var isSetOnText = targetEl instanceof ZRText;
  14879. var needsCreateText = false;
  14880. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14881. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14882. if (stateModel && stateModel.getShallow('show')) {
  14883. needsCreateText = true;
  14884. break;
  14885. }
  14886. }
  14887. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14888. if (needsCreateText) {
  14889. if (!isSetOnText) {
  14890. // Reuse the previous
  14891. if (!textContent) {
  14892. textContent = new ZRText();
  14893. targetEl.setTextContent(textContent);
  14894. }
  14895. // Use same state proxy
  14896. if (targetEl.stateProxy) {
  14897. textContent.stateProxy = targetEl.stateProxy;
  14898. }
  14899. }
  14900. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14901. var normalModel = labelStatesModels.normal;
  14902. var showNormal = !!normalModel.getShallow('show');
  14903. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14904. normalStyle.text = labelStatesTexts.normal;
  14905. if (!isSetOnText) {
  14906. // Always create new
  14907. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14908. }
  14909. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14910. var stateName = SPECIAL_STATES[i];
  14911. var stateModel = labelStatesModels[stateName];
  14912. if (stateModel) {
  14913. var stateObj = textContent.ensureState(stateName);
  14914. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14915. if (stateShow !== showNormal) {
  14916. stateObj.ignore = !stateShow;
  14917. }
  14918. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14919. stateObj.style.text = labelStatesTexts[stateName];
  14920. if (!isSetOnText) {
  14921. var targetElEmphasisState = targetEl.ensureState(stateName);
  14922. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14923. }
  14924. }
  14925. }
  14926. // PENDING: if there is many requirements that emphasis position
  14927. // need to be different from normal position, we might consider
  14928. // auto silent is those cases.
  14929. textContent.silent = !!normalModel.getShallow('silent');
  14930. // Keep x and y
  14931. if (textContent.style.x != null) {
  14932. normalStyle.x = textContent.style.x;
  14933. }
  14934. if (textContent.style.y != null) {
  14935. normalStyle.y = textContent.style.y;
  14936. }
  14937. textContent.ignore = !showNormal;
  14938. // Always create new style.
  14939. textContent.useStyle(normalStyle);
  14940. textContent.dirty();
  14941. if (opt.enableTextSetter) {
  14942. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14943. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14944. setLabelText(textContent, labelStatesTexts);
  14945. };
  14946. }
  14947. } else if (textContent) {
  14948. // Not display rich text.
  14949. textContent.ignore = true;
  14950. }
  14951. targetEl.dirty();
  14952. }
  14953. function getLabelStatesModels(itemModel, labelName) {
  14954. labelName = labelName || 'label';
  14955. var statesModels = {
  14956. normal: itemModel.getModel(labelName)
  14957. };
  14958. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14959. var stateName = SPECIAL_STATES[i];
  14960. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14961. }
  14962. return statesModels;
  14963. }
  14964. /**
  14965. * Set basic textStyle properties.
  14966. */
  14967. function createTextStyle(textStyleModel, specifiedTextStyle,
  14968. // Fixed style in the code. Can't be set by model.
  14969. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14970. ) {
  14971. var textStyle = {};
  14972. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14973. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14974. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14975. return textStyle;
  14976. }
  14977. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14978. opt = opt || {};
  14979. var textConfig = {};
  14980. var labelPosition;
  14981. var labelRotate = textStyleModel.getShallow('rotate');
  14982. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14983. var labelOffset = textStyleModel.getShallow('offset');
  14984. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside');
  14985. // 'outside' is not a valid zr textPostion value, but used
  14986. // in bar series, and magric type should be considered.
  14987. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14988. if (labelPosition != null) {
  14989. textConfig.position = labelPosition;
  14990. }
  14991. if (labelOffset != null) {
  14992. textConfig.offset = labelOffset;
  14993. }
  14994. if (labelRotate != null) {
  14995. labelRotate *= Math.PI / 180;
  14996. textConfig.rotation = labelRotate;
  14997. }
  14998. if (labelDistance != null) {
  14999. textConfig.distance = labelDistance;
  15000. }
  15001. // fill and auto is determined by the color of path fill if it's not specified by developers.
  15002. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  15003. return textConfig;
  15004. }
  15005. /**
  15006. * The uniform entry of set text style, that is, retrieve style definitions
  15007. * from `model` and set to `textStyle` object.
  15008. *
  15009. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15010. * properties will be set. (Consider the states of normal and emphasis and
  15011. * default value can be adopted, merge would make the logic too complicated
  15012. * to manage.)
  15013. */
  15014. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  15015. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15016. opt = opt || EMPTY_OBJ;
  15017. var ecModel = textStyleModel.ecModel;
  15018. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15019. // Consider case:
  15020. // {
  15021. // data: [{
  15022. // value: 12,
  15023. // label: {
  15024. // rich: {
  15025. // // no 'a' here but using parent 'a'.
  15026. // }
  15027. // }
  15028. // }],
  15029. // rich: {
  15030. // a: { ... }
  15031. // }
  15032. // }
  15033. var richItemNames = getRichItemNames(textStyleModel);
  15034. var richResult;
  15035. if (richItemNames) {
  15036. richResult = {};
  15037. for (var name_1 in richItemNames) {
  15038. if (richItemNames.hasOwnProperty(name_1)) {
  15039. // Cascade is supported in rich.
  15040. var richTextStyle = textStyleModel.getModel(['rich', name_1]);
  15041. // In rich, never `disableBox`.
  15042. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15043. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15044. // That might confuses users. So probably we should put `textStyleModel` as the
  15045. // root ancestor of the `richTextStyle`. But that would be a break change.
  15046. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  15047. }
  15048. }
  15049. }
  15050. if (richResult) {
  15051. textStyle.rich = richResult;
  15052. }
  15053. var overflow = textStyleModel.get('overflow');
  15054. if (overflow) {
  15055. textStyle.overflow = overflow;
  15056. }
  15057. var margin = textStyleModel.get('minMargin');
  15058. if (margin != null) {
  15059. textStyle.margin = margin;
  15060. }
  15061. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  15062. }
  15063. // Consider case:
  15064. // {
  15065. // data: [{
  15066. // value: 12,
  15067. // label: {
  15068. // rich: {
  15069. // // no 'a' here but using parent 'a'.
  15070. // }
  15071. // }
  15072. // }],
  15073. // rich: {
  15074. // a: { ... }
  15075. // }
  15076. // }
  15077. // TODO TextStyleModel
  15078. function getRichItemNames(textStyleModel) {
  15079. // Use object to remove duplicated names.
  15080. var richItemNameMap;
  15081. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15082. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15083. if (rich) {
  15084. richItemNameMap = richItemNameMap || {};
  15085. var richKeys = keys(rich);
  15086. for (var i = 0; i < richKeys.length; i++) {
  15087. var richKey = richKeys[i];
  15088. richItemNameMap[richKey] = 1;
  15089. }
  15090. }
  15091. textStyleModel = textStyleModel.parentModel;
  15092. }
  15093. return richItemNameMap;
  15094. }
  15095. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  15096. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign', 'ellipsis'];
  15097. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  15098. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  15099. // In merge mode, default value should not be given.
  15100. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  15101. var inheritColor = opt && opt.inheritColor;
  15102. var fillColor = textStyleModel.getShallow('color');
  15103. var strokeColor = textStyleModel.getShallow('textBorderColor');
  15104. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  15105. if (fillColor === 'inherit' || fillColor === 'auto') {
  15106. if ("development" !== 'production') {
  15107. if (fillColor === 'auto') {
  15108. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15109. }
  15110. }
  15111. if (inheritColor) {
  15112. fillColor = inheritColor;
  15113. } else {
  15114. fillColor = null;
  15115. }
  15116. }
  15117. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  15118. if ("development" !== 'production') {
  15119. if (strokeColor === 'auto') {
  15120. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15121. }
  15122. }
  15123. if (inheritColor) {
  15124. strokeColor = inheritColor;
  15125. } else {
  15126. strokeColor = null;
  15127. }
  15128. }
  15129. if (!isAttached) {
  15130. // Only use default global textStyle.color if text is individual.
  15131. // Otherwise it will use the strategy of attached text color because text may be on a path.
  15132. fillColor = fillColor || globalTextStyle.color;
  15133. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  15134. }
  15135. if (fillColor != null) {
  15136. textStyle.fill = fillColor;
  15137. }
  15138. if (strokeColor != null) {
  15139. textStyle.stroke = strokeColor;
  15140. }
  15141. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  15142. if (textBorderWidth != null) {
  15143. textStyle.lineWidth = textBorderWidth;
  15144. }
  15145. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  15146. if (textBorderType != null) {
  15147. textStyle.lineDash = textBorderType;
  15148. }
  15149. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  15150. if (textBorderDashOffset != null) {
  15151. textStyle.lineDashOffset = textBorderDashOffset;
  15152. }
  15153. if (!isNotNormal && opacity == null && !inRich) {
  15154. opacity = opt && opt.defaultOpacity;
  15155. }
  15156. if (opacity != null) {
  15157. textStyle.opacity = opacity;
  15158. }
  15159. // TODO
  15160. if (!isNotNormal && !isAttached) {
  15161. // Set default finally.
  15162. if (textStyle.fill == null && opt.inheritColor) {
  15163. textStyle.fill = opt.inheritColor;
  15164. }
  15165. }
  15166. // Do not use `getFont` here, because merge should be supported, where
  15167. // part of these properties may be changed in emphasis style, and the
  15168. // others should remain their original value got from normal style.
  15169. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  15170. var key = TEXT_PROPS_WITH_GLOBAL[i];
  15171. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  15172. if (val != null) {
  15173. textStyle[key] = val;
  15174. }
  15175. }
  15176. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  15177. var key = TEXT_PROPS_SELF[i];
  15178. var val = textStyleModel.getShallow(key);
  15179. if (val != null) {
  15180. textStyle[key] = val;
  15181. }
  15182. }
  15183. if (textStyle.verticalAlign == null) {
  15184. var baseline = textStyleModel.getShallow('baseline');
  15185. if (baseline != null) {
  15186. textStyle.verticalAlign = baseline;
  15187. }
  15188. }
  15189. if (!isBlock || !opt.disableBox) {
  15190. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15191. var key = TEXT_PROPS_BOX[i];
  15192. var val = textStyleModel.getShallow(key);
  15193. if (val != null) {
  15194. textStyle[key] = val;
  15195. }
  15196. }
  15197. var borderType = textStyleModel.getShallow('borderType');
  15198. if (borderType != null) {
  15199. textStyle.borderDash = borderType;
  15200. }
  15201. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15202. if ("development" !== 'production') {
  15203. if (textStyle.backgroundColor === 'auto') {
  15204. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15205. }
  15206. }
  15207. textStyle.backgroundColor = inheritColor;
  15208. }
  15209. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15210. if ("development" !== 'production') {
  15211. if (textStyle.borderColor === 'auto') {
  15212. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15213. }
  15214. }
  15215. textStyle.borderColor = inheritColor;
  15216. }
  15217. }
  15218. }
  15219. function getFont(opt, ecModel) {
  15220. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15221. return trim([
  15222. // FIXME in node-canvas fontWeight is before fontStyle
  15223. 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(' '));
  15224. }
  15225. var labelInner = makeInner();
  15226. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15227. if (!label) {
  15228. return;
  15229. }
  15230. var obj = labelInner(label);
  15231. obj.prevValue = obj.value;
  15232. obj.value = value;
  15233. var normalLabelModel = labelStatesModels.normal;
  15234. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15235. if (obj.valueAnimation) {
  15236. obj.precision = normalLabelModel.get('precision');
  15237. obj.defaultInterpolatedText = getDefaultText;
  15238. obj.statesModels = labelStatesModels;
  15239. }
  15240. }
  15241. var PATH_COLOR = ['textStyle', 'color'];
  15242. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow'];
  15243. // TODO Performance improvement?
  15244. var tmpText = new ZRText();
  15245. var TextStyleMixin = /** @class */function () {
  15246. function TextStyleMixin() {}
  15247. /**
  15248. * Get color property or get color from option.textStyle.color
  15249. */
  15250. // TODO Callback
  15251. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15252. var ecModel = this.ecModel;
  15253. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15254. };
  15255. /**
  15256. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15257. * @return {string}
  15258. */
  15259. TextStyleMixin.prototype.getFont = function () {
  15260. return getFont({
  15261. fontStyle: this.getShallow('fontStyle'),
  15262. fontWeight: this.getShallow('fontWeight'),
  15263. fontSize: this.getShallow('fontSize'),
  15264. fontFamily: this.getShallow('fontFamily')
  15265. }, this.ecModel);
  15266. };
  15267. TextStyleMixin.prototype.getTextRect = function (text) {
  15268. var style = {
  15269. text: text,
  15270. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15271. };
  15272. for (var i = 0; i < textStyleParams.length; i++) {
  15273. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15274. }
  15275. tmpText.useStyle(style);
  15276. tmpText.update();
  15277. return tmpText.getBoundingRect();
  15278. };
  15279. return TextStyleMixin;
  15280. }();
  15281. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit']
  15282. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15283. // So do not transfer decal directly.
  15284. ];
  15285. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15286. var LineStyleMixin = /** @class */function () {
  15287. function LineStyleMixin() {}
  15288. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15289. return getLineStyle(this, excludes);
  15290. };
  15291. return LineStyleMixin;
  15292. }();
  15293. 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']
  15294. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15295. // So do not transfer decal directly.
  15296. ];
  15297. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15298. var ItemStyleMixin = /** @class */function () {
  15299. function ItemStyleMixin() {}
  15300. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15301. return getItemStyle(this, excludes, includes);
  15302. };
  15303. return ItemStyleMixin;
  15304. }();
  15305. var Model = /** @class */function () {
  15306. function Model(option, parentModel, ecModel) {
  15307. this.parentModel = parentModel;
  15308. this.ecModel = ecModel;
  15309. this.option = option;
  15310. // Simple optimization
  15311. // if (this.init) {
  15312. // if (arguments.length <= 4) {
  15313. // this.init(option, parentModel, ecModel, extraOpt);
  15314. // }
  15315. // else {
  15316. // this.init.apply(this, arguments);
  15317. // }
  15318. // }
  15319. }
  15320. Model.prototype.init = function (option, parentModel, ecModel) {
  15321. var rest = [];
  15322. for (var _i = 3; _i < arguments.length; _i++) {
  15323. rest[_i - 3] = arguments[_i];
  15324. }
  15325. };
  15326. /**
  15327. * Merge the input option to me.
  15328. */
  15329. Model.prototype.mergeOption = function (option, ecModel) {
  15330. merge(this.option, option, true);
  15331. };
  15332. // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15333. // TODO: TYPE strict key check?
  15334. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15335. Model.prototype.get = function (path, ignoreParent) {
  15336. if (path == null) {
  15337. return this.option;
  15338. }
  15339. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15340. };
  15341. Model.prototype.getShallow = function (key, ignoreParent) {
  15342. var option = this.option;
  15343. var val = option == null ? option : option[key];
  15344. if (val == null && !ignoreParent) {
  15345. var parentModel = this.parentModel;
  15346. if (parentModel) {
  15347. // FIXME:TS do not know how to make it works
  15348. val = parentModel.getShallow(key);
  15349. }
  15350. }
  15351. return val;
  15352. };
  15353. // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15354. // getModel(path: string | string[], parentModel?: Model): Model;
  15355. // TODO 'a.b.c' is deprecated
  15356. Model.prototype.getModel = function (path, parentModel) {
  15357. var hasPath = path != null;
  15358. var pathFinal = hasPath ? this.parsePath(path) : null;
  15359. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15360. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15361. return new Model(obj, parentModel, this.ecModel);
  15362. };
  15363. /**
  15364. * If model has option
  15365. */
  15366. Model.prototype.isEmpty = function () {
  15367. return this.option == null;
  15368. };
  15369. Model.prototype.restoreData = function () {};
  15370. // Pending
  15371. Model.prototype.clone = function () {
  15372. var Ctor = this.constructor;
  15373. return new Ctor(clone(this.option));
  15374. };
  15375. // setReadOnly(properties): void {
  15376. // clazzUtil.setReadOnly(this, properties);
  15377. // }
  15378. // If path is null/undefined, return null/undefined.
  15379. Model.prototype.parsePath = function (path) {
  15380. if (typeof path === 'string') {
  15381. return path.split('.');
  15382. }
  15383. return path;
  15384. };
  15385. // Resolve path for parent. Perhaps useful when parent use a different property.
  15386. // Default to be a identity resolver.
  15387. // Can be modified to a different resolver.
  15388. Model.prototype.resolveParentPath = function (path) {
  15389. return path;
  15390. };
  15391. // FIXME:TS check whether put this method here
  15392. Model.prototype.isAnimationEnabled = function () {
  15393. if (!env.node && this.option) {
  15394. if (this.option.animation != null) {
  15395. return !!this.option.animation;
  15396. } else if (this.parentModel) {
  15397. return this.parentModel.isAnimationEnabled();
  15398. }
  15399. }
  15400. };
  15401. Model.prototype._doGet = function (pathArr, parentModel) {
  15402. var obj = this.option;
  15403. if (!pathArr) {
  15404. return obj;
  15405. }
  15406. for (var i = 0; i < pathArr.length; i++) {
  15407. // Ignore empty
  15408. if (!pathArr[i]) {
  15409. continue;
  15410. }
  15411. // obj could be number/string/... (like 0)
  15412. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15413. if (obj == null) {
  15414. break;
  15415. }
  15416. }
  15417. if (obj == null && parentModel) {
  15418. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15419. }
  15420. return obj;
  15421. };
  15422. return Model;
  15423. }();
  15424. // Enable Model.extend.
  15425. enableClassExtend(Model);
  15426. enableClassCheck(Model);
  15427. mixin(Model, LineStyleMixin);
  15428. mixin(Model, ItemStyleMixin);
  15429. mixin(Model, AreaStyleMixin);
  15430. mixin(Model, TextStyleMixin);
  15431. // A random offset
  15432. var base = Math.round(Math.random() * 10);
  15433. /**
  15434. * @public
  15435. * @param {string} type
  15436. * @return {string}
  15437. */
  15438. function getUID(type) {
  15439. // Considering the case of crossing js context,
  15440. // use Math.random to make id as unique as possible.
  15441. return [type || '', base++].join('_');
  15442. }
  15443. /**
  15444. * Implements `SubTypeDefaulterManager` for `target`.
  15445. */
  15446. function enableSubTypeDefaulter(target) {
  15447. var subTypeDefaulters = {};
  15448. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15449. var componentTypeInfo = parseClassType(componentType);
  15450. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15451. };
  15452. target.determineSubType = function (componentType, option) {
  15453. var type = option.type;
  15454. if (!type) {
  15455. var componentTypeMain = parseClassType(componentType).main;
  15456. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15457. type = subTypeDefaulters[componentTypeMain](option);
  15458. }
  15459. }
  15460. return type;
  15461. };
  15462. }
  15463. /**
  15464. * Implements `TopologicalTravelable<any>` for `entity`.
  15465. *
  15466. * Topological travel on Activity Network (Activity On Vertices).
  15467. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15468. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15469. * If there is circular dependencey, Error will be thrown.
  15470. */
  15471. function enableTopologicalTravel(entity, dependencyGetter) {
  15472. /**
  15473. * @param targetNameList Target Component type list.
  15474. * Can be ['aa', 'bb', 'aa.xx']
  15475. * @param fullNameList By which we can build dependency graph.
  15476. * @param callback Params: componentType, dependencies.
  15477. * @param context Scope of callback.
  15478. */
  15479. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15480. if (!targetNameList.length) {
  15481. return;
  15482. }
  15483. var result = makeDepndencyGraph(fullNameList);
  15484. var graph = result.graph;
  15485. var noEntryList = result.noEntryList;
  15486. var targetNameSet = {};
  15487. each(targetNameList, function (name) {
  15488. targetNameSet[name] = true;
  15489. });
  15490. while (noEntryList.length) {
  15491. var currComponentType = noEntryList.pop();
  15492. var currVertex = graph[currComponentType];
  15493. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15494. if (isInTargetNameSet) {
  15495. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15496. delete targetNameSet[currComponentType];
  15497. }
  15498. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15499. }
  15500. each(targetNameSet, function () {
  15501. var errMsg = '';
  15502. if ("development" !== 'production') {
  15503. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15504. }
  15505. throw new Error(errMsg);
  15506. });
  15507. function removeEdge(succComponentType) {
  15508. graph[succComponentType].entryCount--;
  15509. if (graph[succComponentType].entryCount === 0) {
  15510. noEntryList.push(succComponentType);
  15511. }
  15512. }
  15513. // Consider this case: legend depends on series, and we call
  15514. // chart.setOption({series: [...]}), where only series is in option.
  15515. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15516. // not be called, but only sereis.mergeOption is called. Thus legend
  15517. // have no chance to update its local record about series (like which
  15518. // name of series is available in legend).
  15519. function removeEdgeAndAdd(succComponentType) {
  15520. targetNameSet[succComponentType] = true;
  15521. removeEdge(succComponentType);
  15522. }
  15523. };
  15524. function makeDepndencyGraph(fullNameList) {
  15525. var graph = {};
  15526. var noEntryList = [];
  15527. each(fullNameList, function (name) {
  15528. var thisItem = createDependencyGraphItem(graph, name);
  15529. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15530. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15531. thisItem.entryCount = availableDeps.length;
  15532. if (thisItem.entryCount === 0) {
  15533. noEntryList.push(name);
  15534. }
  15535. each(availableDeps, function (dependentName) {
  15536. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15537. thisItem.predecessor.push(dependentName);
  15538. }
  15539. var thatItem = createDependencyGraphItem(graph, dependentName);
  15540. if (indexOf(thatItem.successor, dependentName) < 0) {
  15541. thatItem.successor.push(name);
  15542. }
  15543. });
  15544. });
  15545. return {
  15546. graph: graph,
  15547. noEntryList: noEntryList
  15548. };
  15549. }
  15550. function createDependencyGraphItem(graph, name) {
  15551. if (!graph[name]) {
  15552. graph[name] = {
  15553. predecessor: [],
  15554. successor: []
  15555. };
  15556. }
  15557. return graph[name];
  15558. }
  15559. function getAvailableDependencies(originalDeps, fullNameList) {
  15560. var availableDeps = [];
  15561. each(originalDeps, function (dep) {
  15562. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15563. });
  15564. return availableDeps;
  15565. }
  15566. }
  15567. function inheritDefaultOption(superOption, subOption) {
  15568. // See also `model/Component.ts#getDefaultOption`
  15569. return merge(merge({}, superOption, true), subOption, true);
  15570. }
  15571. /*
  15572. * Licensed to the Apache Software Foundation (ASF) under one
  15573. * or more contributor license agreements. See the NOTICE file
  15574. * distributed with this work for additional information
  15575. * regarding copyright ownership. The ASF licenses this file
  15576. * to you under the Apache License, Version 2.0 (the
  15577. * "License"); you may not use this file except in compliance
  15578. * with the License. You may obtain a copy of the License at
  15579. *
  15580. * http://www.apache.org/licenses/LICENSE-2.0
  15581. *
  15582. * Unless required by applicable law or agreed to in writing,
  15583. * software distributed under the License is distributed on an
  15584. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15585. * KIND, either express or implied. See the License for the
  15586. * specific language governing permissions and limitations
  15587. * under the License.
  15588. */
  15589. /**
  15590. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15591. */
  15592. /*
  15593. * Licensed to the Apache Software Foundation (ASF) under one
  15594. * or more contributor license agreements. See the NOTICE file
  15595. * distributed with this work for additional information
  15596. * regarding copyright ownership. The ASF licenses this file
  15597. * to you under the Apache License, Version 2.0 (the
  15598. * "License"); you may not use this file except in compliance
  15599. * with the License. You may obtain a copy of the License at
  15600. *
  15601. * http://www.apache.org/licenses/LICENSE-2.0
  15602. *
  15603. * Unless required by applicable law or agreed to in writing,
  15604. * software distributed under the License is distributed on an
  15605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15606. * KIND, either express or implied. See the License for the
  15607. * specific language governing permissions and limitations
  15608. * under the License.
  15609. */
  15610. /**
  15611. * Language: English.
  15612. */
  15613. var langEN = {
  15614. time: {
  15615. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15616. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15617. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15618. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15619. },
  15620. legend: {
  15621. selector: {
  15622. all: 'All',
  15623. inverse: 'Inv'
  15624. }
  15625. },
  15626. toolbox: {
  15627. brush: {
  15628. title: {
  15629. rect: 'Box Select',
  15630. polygon: 'Lasso Select',
  15631. lineX: 'Horizontally Select',
  15632. lineY: 'Vertically Select',
  15633. keep: 'Keep Selections',
  15634. clear: 'Clear Selections'
  15635. }
  15636. },
  15637. dataView: {
  15638. title: 'Data View',
  15639. lang: ['Data View', 'Close', 'Refresh']
  15640. },
  15641. dataZoom: {
  15642. title: {
  15643. zoom: 'Zoom',
  15644. back: 'Zoom Reset'
  15645. }
  15646. },
  15647. magicType: {
  15648. title: {
  15649. line: 'Switch to Line Chart',
  15650. bar: 'Switch to Bar Chart',
  15651. stack: 'Stack',
  15652. tiled: 'Tile'
  15653. }
  15654. },
  15655. restore: {
  15656. title: 'Restore'
  15657. },
  15658. saveAsImage: {
  15659. title: 'Save as Image',
  15660. lang: ['Right Click to Save Image']
  15661. }
  15662. },
  15663. series: {
  15664. typeNames: {
  15665. pie: 'Pie chart',
  15666. bar: 'Bar chart',
  15667. line: 'Line chart',
  15668. scatter: 'Scatter plot',
  15669. effectScatter: 'Ripple scatter plot',
  15670. radar: 'Radar chart',
  15671. tree: 'Tree',
  15672. treemap: 'Treemap',
  15673. boxplot: 'Boxplot',
  15674. candlestick: 'Candlestick',
  15675. k: 'K line chart',
  15676. heatmap: 'Heat map',
  15677. map: 'Map',
  15678. parallel: 'Parallel coordinate map',
  15679. lines: 'Line graph',
  15680. graph: 'Relationship graph',
  15681. sankey: 'Sankey diagram',
  15682. funnel: 'Funnel chart',
  15683. gauge: 'Gauge',
  15684. pictorialBar: 'Pictorial bar',
  15685. themeRiver: 'Theme River Map',
  15686. sunburst: 'Sunburst',
  15687. custom: 'Custom chart',
  15688. chart: 'Chart'
  15689. }
  15690. },
  15691. aria: {
  15692. general: {
  15693. withTitle: 'This is a chart about "{title}"',
  15694. withoutTitle: 'This is a chart'
  15695. },
  15696. series: {
  15697. single: {
  15698. prefix: '',
  15699. withName: ' with type {seriesType} named {seriesName}.',
  15700. withoutName: ' with type {seriesType}.'
  15701. },
  15702. multiple: {
  15703. prefix: '. It consists of {seriesCount} series count.',
  15704. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15705. withoutName: ' The {seriesId} series is a {seriesType}.',
  15706. separator: {
  15707. middle: '',
  15708. end: ''
  15709. }
  15710. }
  15711. },
  15712. data: {
  15713. allData: 'The data is as follows: ',
  15714. partialData: 'The first {displayCnt} items are: ',
  15715. withName: 'the data for {name} is {value}',
  15716. withoutName: '{value}',
  15717. separator: {
  15718. middle: ', ',
  15719. end: '. '
  15720. }
  15721. }
  15722. }
  15723. };
  15724. /*
  15725. * Licensed to the Apache Software Foundation (ASF) under one
  15726. * or more contributor license agreements. See the NOTICE file
  15727. * distributed with this work for additional information
  15728. * regarding copyright ownership. The ASF licenses this file
  15729. * to you under the Apache License, Version 2.0 (the
  15730. * "License"); you may not use this file except in compliance
  15731. * with the License. You may obtain a copy of the License at
  15732. *
  15733. * http://www.apache.org/licenses/LICENSE-2.0
  15734. *
  15735. * Unless required by applicable law or agreed to in writing,
  15736. * software distributed under the License is distributed on an
  15737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15738. * KIND, either express or implied. See the License for the
  15739. * specific language governing permissions and limitations
  15740. * under the License.
  15741. */
  15742. /**
  15743. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15744. */
  15745. /*
  15746. * Licensed to the Apache Software Foundation (ASF) under one
  15747. * or more contributor license agreements. See the NOTICE file
  15748. * distributed with this work for additional information
  15749. * regarding copyright ownership. The ASF licenses this file
  15750. * to you under the Apache License, Version 2.0 (the
  15751. * "License"); you may not use this file except in compliance
  15752. * with the License. You may obtain a copy of the License at
  15753. *
  15754. * http://www.apache.org/licenses/LICENSE-2.0
  15755. *
  15756. * Unless required by applicable law or agreed to in writing,
  15757. * software distributed under the License is distributed on an
  15758. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15759. * KIND, either express or implied. See the License for the
  15760. * specific language governing permissions and limitations
  15761. * under the License.
  15762. */
  15763. var langZH = {
  15764. time: {
  15765. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15766. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15767. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15768. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15769. },
  15770. legend: {
  15771. selector: {
  15772. all: '全选',
  15773. inverse: '反选'
  15774. }
  15775. },
  15776. toolbox: {
  15777. brush: {
  15778. title: {
  15779. rect: '矩形选择',
  15780. polygon: '圈选',
  15781. lineX: '横向选择',
  15782. lineY: '纵向选择',
  15783. keep: '保持选择',
  15784. clear: '清除选择'
  15785. }
  15786. },
  15787. dataView: {
  15788. title: '数据视图',
  15789. lang: ['数据视图', '关闭', '刷新']
  15790. },
  15791. dataZoom: {
  15792. title: {
  15793. zoom: '区域缩放',
  15794. back: '区域缩放还原'
  15795. }
  15796. },
  15797. magicType: {
  15798. title: {
  15799. line: '切换为折线图',
  15800. bar: '切换为柱状图',
  15801. stack: '切换为堆叠',
  15802. tiled: '切换为平铺'
  15803. }
  15804. },
  15805. restore: {
  15806. title: '还原'
  15807. },
  15808. saveAsImage: {
  15809. title: '保存为图片',
  15810. lang: ['右键另存为图片']
  15811. }
  15812. },
  15813. series: {
  15814. typeNames: {
  15815. pie: '饼图',
  15816. bar: '柱状图',
  15817. line: '折线图',
  15818. scatter: '散点图',
  15819. effectScatter: '涟漪散点图',
  15820. radar: '雷达图',
  15821. tree: '树图',
  15822. treemap: '矩形树图',
  15823. boxplot: '箱型图',
  15824. candlestick: 'K线图',
  15825. k: 'K线图',
  15826. heatmap: '热力图',
  15827. map: '地图',
  15828. parallel: '平行坐标图',
  15829. lines: '线图',
  15830. graph: '关系图',
  15831. sankey: '桑基图',
  15832. funnel: '漏斗图',
  15833. gauge: '仪表盘图',
  15834. pictorialBar: '象形柱图',
  15835. themeRiver: '主题河流图',
  15836. sunburst: '旭日图',
  15837. custom: '自定义图表',
  15838. chart: '图表'
  15839. }
  15840. },
  15841. aria: {
  15842. general: {
  15843. withTitle: '这是一个关于“{title}”的图表。',
  15844. withoutTitle: '这是一个图表,'
  15845. },
  15846. series: {
  15847. single: {
  15848. prefix: '',
  15849. withName: '图表类型是{seriesType},表示{seriesName}。',
  15850. withoutName: '图表类型是{seriesType}。'
  15851. },
  15852. multiple: {
  15853. prefix: '它由{seriesCount}个图表系列组成。',
  15854. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15855. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15856. separator: {
  15857. middle: ';',
  15858. end: '。'
  15859. }
  15860. }
  15861. },
  15862. data: {
  15863. allData: '其数据是——',
  15864. partialData: '其中,前{displayCnt}项是——',
  15865. withName: '{name}的数据是{value}',
  15866. withoutName: '{value}',
  15867. separator: {
  15868. middle: ',',
  15869. end: ''
  15870. }
  15871. }
  15872. }
  15873. };
  15874. var LOCALE_ZH = 'ZH';
  15875. var LOCALE_EN = 'EN';
  15876. var DEFAULT_LOCALE = LOCALE_EN;
  15877. var localeStorage = {};
  15878. var localeModels = {};
  15879. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15880. var langStr = ( /* eslint-disable-next-line */
  15881. document.documentElement.lang || navigator.language || navigator.browserLanguage || DEFAULT_LOCALE).toUpperCase();
  15882. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15883. }();
  15884. function registerLocale(locale, localeObj) {
  15885. locale = locale.toUpperCase();
  15886. localeModels[locale] = new Model(localeObj);
  15887. localeStorage[locale] = localeObj;
  15888. }
  15889. // export function getLocale(locale: string) {
  15890. // return localeStorage[locale];
  15891. // }
  15892. function createLocaleObject(locale) {
  15893. if (isString(locale)) {
  15894. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15895. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15896. return clone(localeObj);
  15897. } else {
  15898. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15899. }
  15900. } else {
  15901. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15902. }
  15903. }
  15904. function getLocaleModel(lang) {
  15905. return localeModels[lang];
  15906. }
  15907. function getDefaultLocaleModel() {
  15908. return localeModels[DEFAULT_LOCALE];
  15909. }
  15910. // Default locale
  15911. registerLocale(LOCALE_EN, langEN);
  15912. registerLocale(LOCALE_ZH, langZH);
  15913. var ONE_SECOND = 1000;
  15914. var ONE_MINUTE = ONE_SECOND * 60;
  15915. var ONE_HOUR = ONE_MINUTE * 60;
  15916. var ONE_DAY = ONE_HOUR * 24;
  15917. var ONE_YEAR = ONE_DAY * 365;
  15918. var defaultLeveledFormatter = {
  15919. year: '{yyyy}',
  15920. month: '{MMM}',
  15921. day: '{d}',
  15922. hour: '{HH}:{mm}',
  15923. minute: '{HH}:{mm}',
  15924. second: '{HH}:{mm}:{ss}',
  15925. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15926. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15927. };
  15928. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15929. var fullLeveledFormatter = {
  15930. year: '{yyyy}',
  15931. month: '{yyyy}-{MM}',
  15932. day: fullDayFormatter,
  15933. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15934. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15935. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15936. millisecond: defaultLeveledFormatter.none
  15937. };
  15938. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15939. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15940. function pad(str, len) {
  15941. str += '';
  15942. return '0000'.substr(0, len - str.length) + str;
  15943. }
  15944. function getPrimaryTimeUnit(timeUnit) {
  15945. switch (timeUnit) {
  15946. case 'half-year':
  15947. case 'quarter':
  15948. return 'month';
  15949. case 'week':
  15950. case 'half-week':
  15951. return 'day';
  15952. case 'half-day':
  15953. case 'quarter-day':
  15954. return 'hour';
  15955. default:
  15956. // year, minutes, second, milliseconds
  15957. return timeUnit;
  15958. }
  15959. }
  15960. function isPrimaryTimeUnit(timeUnit) {
  15961. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15962. }
  15963. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15964. switch (timeUnit) {
  15965. case 'year':
  15966. case 'month':
  15967. return 'day';
  15968. case 'millisecond':
  15969. return 'millisecond';
  15970. default:
  15971. // Also for day, hour, minute, second
  15972. return 'second';
  15973. }
  15974. }
  15975. function format(
  15976. // Note: The result based on `isUTC` are totally different, which can not be just simply
  15977. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15978. time, template, isUTC, lang) {
  15979. var date = parseDate(time);
  15980. var y = date[fullYearGetterName(isUTC)]();
  15981. var M = date[monthGetterName(isUTC)]() + 1;
  15982. var q = Math.floor((M - 1) / 3) + 1;
  15983. var d = date[dateGetterName(isUTC)]();
  15984. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15985. var H = date[hoursGetterName(isUTC)]();
  15986. var h = (H - 1) % 12 + 1;
  15987. var m = date[minutesGetterName(isUTC)]();
  15988. var s = date[secondsGetterName(isUTC)]();
  15989. var S = date[millisecondsGetterName(isUTC)]();
  15990. var a = H >= 12 ? 'pm' : 'am';
  15991. var A = a.toUpperCase();
  15992. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15993. var timeModel = localeModel.getModel('time');
  15994. var month = timeModel.get('month');
  15995. var monthAbbr = timeModel.get('monthAbbr');
  15996. var dayOfWeek = timeModel.get('dayOfWeek');
  15997. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15998. return (template || '').replace(/{a}/g, a + '').replace(/{A}/g, A + '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, pad(y % 100 + '', 2)).replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15999. }
  16000. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  16001. var template = null;
  16002. if (isString(formatter)) {
  16003. // Single formatter for all units at all levels
  16004. template = formatter;
  16005. } else if (isFunction(formatter)) {
  16006. // Callback formatter
  16007. template = formatter(tick.value, idx, {
  16008. level: tick.level
  16009. });
  16010. } else {
  16011. var defaults$1 = extend({}, defaultLeveledFormatter);
  16012. if (tick.level > 0) {
  16013. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  16014. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  16015. }
  16016. }
  16017. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  16018. : defaults(formatter, defaults$1) : defaults$1;
  16019. var unit = getUnitFromValue(tick.value, isUTC);
  16020. if (mergedFormatter[unit]) {
  16021. template = mergedFormatter[unit];
  16022. } else if (mergedFormatter.inherit) {
  16023. // Unit formatter is not defined and should inherit from bigger units
  16024. var targetId = timeUnits.indexOf(unit);
  16025. for (var i = targetId - 1; i >= 0; --i) {
  16026. if (mergedFormatter[unit]) {
  16027. template = mergedFormatter[unit];
  16028. break;
  16029. }
  16030. }
  16031. template = template || defaults$1.none;
  16032. }
  16033. if (isArray(template)) {
  16034. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  16035. levelId = Math.min(levelId, template.length - 1);
  16036. template = template[levelId];
  16037. }
  16038. }
  16039. return format(new Date(tick.value), template, isUTC, lang);
  16040. }
  16041. function getUnitFromValue(value, isUTC) {
  16042. var date = parseDate(value);
  16043. var M = date[monthGetterName(isUTC)]() + 1;
  16044. var d = date[dateGetterName(isUTC)]();
  16045. var h = date[hoursGetterName(isUTC)]();
  16046. var m = date[minutesGetterName(isUTC)]();
  16047. var s = date[secondsGetterName(isUTC)]();
  16048. var S = date[millisecondsGetterName(isUTC)]();
  16049. var isSecond = S === 0;
  16050. var isMinute = isSecond && s === 0;
  16051. var isHour = isMinute && m === 0;
  16052. var isDay = isHour && h === 0;
  16053. var isMonth = isDay && d === 1;
  16054. var isYear = isMonth && M === 1;
  16055. if (isYear) {
  16056. return 'year';
  16057. } else if (isMonth) {
  16058. return 'month';
  16059. } else if (isDay) {
  16060. return 'day';
  16061. } else if (isHour) {
  16062. return 'hour';
  16063. } else if (isMinute) {
  16064. return 'minute';
  16065. } else if (isSecond) {
  16066. return 'second';
  16067. } else {
  16068. return 'millisecond';
  16069. }
  16070. }
  16071. function getUnitValue(value, unit, isUTC) {
  16072. var date = isNumber(value) ? parseDate(value) : value;
  16073. unit = unit || getUnitFromValue(value, isUTC);
  16074. switch (unit) {
  16075. case 'year':
  16076. return date[fullYearGetterName(isUTC)]();
  16077. case 'half-year':
  16078. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  16079. case 'quarter':
  16080. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  16081. case 'month':
  16082. return date[monthGetterName(isUTC)]();
  16083. case 'day':
  16084. return date[dateGetterName(isUTC)]();
  16085. case 'half-day':
  16086. return date[hoursGetterName(isUTC)]() / 24;
  16087. case 'hour':
  16088. return date[hoursGetterName(isUTC)]();
  16089. case 'minute':
  16090. return date[minutesGetterName(isUTC)]();
  16091. case 'second':
  16092. return date[secondsGetterName(isUTC)]();
  16093. case 'millisecond':
  16094. return date[millisecondsGetterName(isUTC)]();
  16095. }
  16096. }
  16097. function fullYearGetterName(isUTC) {
  16098. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  16099. }
  16100. function monthGetterName(isUTC) {
  16101. return isUTC ? 'getUTCMonth' : 'getMonth';
  16102. }
  16103. function dateGetterName(isUTC) {
  16104. return isUTC ? 'getUTCDate' : 'getDate';
  16105. }
  16106. function hoursGetterName(isUTC) {
  16107. return isUTC ? 'getUTCHours' : 'getHours';
  16108. }
  16109. function minutesGetterName(isUTC) {
  16110. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  16111. }
  16112. function secondsGetterName(isUTC) {
  16113. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  16114. }
  16115. function millisecondsGetterName(isUTC) {
  16116. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  16117. }
  16118. function fullYearSetterName(isUTC) {
  16119. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  16120. }
  16121. function monthSetterName(isUTC) {
  16122. return isUTC ? 'setUTCMonth' : 'setMonth';
  16123. }
  16124. function dateSetterName(isUTC) {
  16125. return isUTC ? 'setUTCDate' : 'setDate';
  16126. }
  16127. function hoursSetterName(isUTC) {
  16128. return isUTC ? 'setUTCHours' : 'setHours';
  16129. }
  16130. function minutesSetterName(isUTC) {
  16131. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  16132. }
  16133. function secondsSetterName(isUTC) {
  16134. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  16135. }
  16136. function millisecondsSetterName(isUTC) {
  16137. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  16138. }
  16139. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  16140. var textEl = new ZRText({
  16141. style: {
  16142. text: text,
  16143. font: font,
  16144. align: align,
  16145. verticalAlign: verticalAlign,
  16146. padding: padding,
  16147. rich: rich,
  16148. overflow: truncate ? 'truncate' : null,
  16149. lineHeight: lineHeight
  16150. }
  16151. });
  16152. return textEl.getBoundingRect();
  16153. }
  16154. /**
  16155. * Add a comma each three digit.
  16156. */
  16157. function addCommas(x) {
  16158. if (!isNumeric(x)) {
  16159. return isString(x) ? x : '-';
  16160. }
  16161. var parts = (x + '').split('.');
  16162. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  16163. }
  16164. function toCamelCase(str, upperCaseFirst) {
  16165. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16166. return group1.toUpperCase();
  16167. });
  16168. if (upperCaseFirst && str) {
  16169. str = str.charAt(0).toUpperCase() + str.slice(1);
  16170. }
  16171. return str;
  16172. }
  16173. var normalizeCssArray$1 = normalizeCssArray;
  16174. /**
  16175. * Make value user readable for tooltip and label.
  16176. * "User readable":
  16177. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  16178. * Avoid to display an empty string, which users can not recognize there is
  16179. * a value and it might look like a bug.
  16180. */
  16181. function makeValueReadable(value, valueType, useUTC) {
  16182. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  16183. function stringToUserReadable(str) {
  16184. return str && trim(str) ? str : '-';
  16185. }
  16186. function isNumberUserReadable(num) {
  16187. return !!(num != null && !isNaN(num) && isFinite(num));
  16188. }
  16189. var isTypeTime = valueType === 'time';
  16190. var isValueDate = value instanceof Date;
  16191. if (isTypeTime || isValueDate) {
  16192. var date = isTypeTime ? parseDate(value) : value;
  16193. if (!isNaN(+date)) {
  16194. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  16195. } else if (isValueDate) {
  16196. return '-';
  16197. }
  16198. // In other cases, continue to try to display the value in the following code.
  16199. }
  16200. if (valueType === 'ordinal') {
  16201. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  16202. }
  16203. // By default.
  16204. var numericResult = numericToNumber(value);
  16205. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16206. }
  16207. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16208. var wrapVar = function (varName, seriesIdx) {
  16209. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16210. };
  16211. /**
  16212. * Template formatter
  16213. * @param {Array.<Object>|Object} paramsList
  16214. */
  16215. function formatTpl(tpl, paramsList, encode) {
  16216. if (!isArray(paramsList)) {
  16217. paramsList = [paramsList];
  16218. }
  16219. var seriesLen = paramsList.length;
  16220. if (!seriesLen) {
  16221. return '';
  16222. }
  16223. var $vars = paramsList[0].$vars || [];
  16224. for (var i = 0; i < $vars.length; i++) {
  16225. var alias = TPL_VAR_ALIAS[i];
  16226. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16227. }
  16228. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16229. for (var k = 0; k < $vars.length; k++) {
  16230. var val = paramsList[seriesIdx][$vars[k]];
  16231. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16232. }
  16233. }
  16234. return tpl;
  16235. }
  16236. function getTooltipMarker(inOpt, extraCssText) {
  16237. var opt = isString(inOpt) ? {
  16238. color: inOpt,
  16239. extraCssText: extraCssText
  16240. } : inOpt || {};
  16241. var color = opt.color;
  16242. var type = opt.type;
  16243. extraCssText = opt.extraCssText;
  16244. var renderMode = opt.renderMode || 'html';
  16245. if (!color) {
  16246. return '';
  16247. }
  16248. if (renderMode === 'html') {
  16249. 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:'
  16250. // Only support string
  16251. + 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>';
  16252. } else {
  16253. // Should better not to auto generate style name by auto-increment number here.
  16254. // Because this util is usually called in tooltip formatter, which is probably
  16255. // called repeatedly when mouse move and the auto-increment number increases fast.
  16256. // Users can make their own style name by theirselves, make it unique and readable.
  16257. var markerId = opt.markerId || 'markerX';
  16258. return {
  16259. renderMode: renderMode,
  16260. content: '{' + markerId + '|} ',
  16261. style: type === 'subItem' ? {
  16262. width: 4,
  16263. height: 4,
  16264. borderRadius: 2,
  16265. backgroundColor: color
  16266. } : {
  16267. width: 10,
  16268. height: 10,
  16269. borderRadius: 5,
  16270. backgroundColor: color
  16271. }
  16272. };
  16273. }
  16274. }
  16275. /**
  16276. * @deprecated Use `time/format` instead.
  16277. * ISO Date format
  16278. * @param {string} tpl
  16279. * @param {number} value
  16280. * @param {boolean} [isUTC=false] Default in local time.
  16281. * see `module:echarts/scale/Time`
  16282. * and `module:echarts/util/number#parseDate`.
  16283. * @inner
  16284. */
  16285. function formatTime(tpl, value, isUTC) {
  16286. if ("development" !== 'production') {
  16287. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16288. }
  16289. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16290. tpl = 'MM-dd\nyyyy';
  16291. }
  16292. var date = parseDate(value);
  16293. var getUTC = isUTC ? 'getUTC' : 'get';
  16294. var y = date[getUTC + 'FullYear']();
  16295. var M = date[getUTC + 'Month']() + 1;
  16296. var d = date[getUTC + 'Date']();
  16297. var h = date[getUTC + 'Hours']();
  16298. var m = date[getUTC + 'Minutes']();
  16299. var s = date[getUTC + 'Seconds']();
  16300. var S = date[getUTC + 'Milliseconds']();
  16301. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', pad(y % 100 + '', 2)).replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  16302. return tpl;
  16303. }
  16304. /**
  16305. * Capital first
  16306. * @param {string} str
  16307. * @return {string}
  16308. */
  16309. function capitalFirst(str) {
  16310. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16311. }
  16312. /**
  16313. * @return Never be null/undefined.
  16314. */
  16315. function convertToColorString(color, defaultColor) {
  16316. defaultColor = defaultColor || 'transparent';
  16317. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16318. }
  16319. /**
  16320. * open new tab
  16321. * @param link url
  16322. * @param target blank or self
  16323. */
  16324. function windowOpen(link, target) {
  16325. /* global window */
  16326. if (target === '_blank' || target === 'blank') {
  16327. var blank = window.open();
  16328. blank.opener = null;
  16329. blank.location.href = link;
  16330. } else {
  16331. window.open(link, target);
  16332. }
  16333. }
  16334. var each$1 = each;
  16335. /**
  16336. * @public
  16337. */
  16338. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16339. /**
  16340. * @public
  16341. */
  16342. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16343. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16344. var x = 0;
  16345. var y = 0;
  16346. if (maxWidth == null) {
  16347. maxWidth = Infinity;
  16348. }
  16349. if (maxHeight == null) {
  16350. maxHeight = Infinity;
  16351. }
  16352. var currentLineMaxSize = 0;
  16353. group.eachChild(function (child, idx) {
  16354. var rect = child.getBoundingRect();
  16355. var nextChild = group.childAt(idx + 1);
  16356. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16357. var nextX;
  16358. var nextY;
  16359. if (orient === 'horizontal') {
  16360. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16361. nextX = x + moveX;
  16362. // Wrap when width exceeds maxWidth or meet a `newline` group
  16363. // FIXME compare before adding gap?
  16364. if (nextX > maxWidth || child.newline) {
  16365. x = 0;
  16366. nextX = moveX;
  16367. y += currentLineMaxSize + gap;
  16368. currentLineMaxSize = rect.height;
  16369. } else {
  16370. // FIXME: consider rect.y is not `0`?
  16371. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16372. }
  16373. } else {
  16374. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16375. nextY = y + moveY;
  16376. // Wrap when width exceeds maxHeight or meet a `newline` group
  16377. if (nextY > maxHeight || child.newline) {
  16378. x += currentLineMaxSize + gap;
  16379. y = 0;
  16380. nextY = moveY;
  16381. currentLineMaxSize = rect.width;
  16382. } else {
  16383. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16384. }
  16385. }
  16386. if (child.newline) {
  16387. return;
  16388. }
  16389. child.x = x;
  16390. child.y = y;
  16391. child.markRedraw();
  16392. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16393. });
  16394. }
  16395. /**
  16396. * VBox or HBox layouting
  16397. * @param {string} orient
  16398. * @param {module:zrender/graphic/Group} group
  16399. * @param {number} gap
  16400. * @param {number} [width=Infinity]
  16401. * @param {number} [height=Infinity]
  16402. */
  16403. var box = boxLayout;
  16404. /**
  16405. * VBox layouting
  16406. * @param {module:zrender/graphic/Group} group
  16407. * @param {number} gap
  16408. * @param {number} [width=Infinity]
  16409. * @param {number} [height=Infinity]
  16410. */
  16411. var vbox = curry(boxLayout, 'vertical');
  16412. /**
  16413. * HBox layouting
  16414. * @param {module:zrender/graphic/Group} group
  16415. * @param {number} gap
  16416. * @param {number} [width=Infinity]
  16417. * @param {number} [height=Infinity]
  16418. */
  16419. var hbox = curry(boxLayout, 'horizontal');
  16420. /**
  16421. * Parse position info.
  16422. */
  16423. function getLayoutRect(positionInfo, containerRect, margin) {
  16424. margin = normalizeCssArray$1(margin || 0);
  16425. var containerWidth = containerRect.width;
  16426. var containerHeight = containerRect.height;
  16427. var left = parsePercent$1(positionInfo.left, containerWidth);
  16428. var top = parsePercent$1(positionInfo.top, containerHeight);
  16429. var right = parsePercent$1(positionInfo.right, containerWidth);
  16430. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16431. var width = parsePercent$1(positionInfo.width, containerWidth);
  16432. var height = parsePercent$1(positionInfo.height, containerHeight);
  16433. var verticalMargin = margin[2] + margin[0];
  16434. var horizontalMargin = margin[1] + margin[3];
  16435. var aspect = positionInfo.aspect;
  16436. // If width is not specified, calculate width from left and right
  16437. if (isNaN(width)) {
  16438. width = containerWidth - right - horizontalMargin - left;
  16439. }
  16440. if (isNaN(height)) {
  16441. height = containerHeight - bottom - verticalMargin - top;
  16442. }
  16443. if (aspect != null) {
  16444. // If width and height are not given
  16445. // 1. Graph should not exceeds the container
  16446. // 2. Aspect must be keeped
  16447. // 3. Graph should take the space as more as possible
  16448. // FIXME
  16449. // Margin is not considered, because there is no case that both
  16450. // using margin and aspect so far.
  16451. if (isNaN(width) && isNaN(height)) {
  16452. if (aspect > containerWidth / containerHeight) {
  16453. width = containerWidth * 0.8;
  16454. } else {
  16455. height = containerHeight * 0.8;
  16456. }
  16457. }
  16458. // Calculate width or height with given aspect
  16459. if (isNaN(width)) {
  16460. width = aspect * height;
  16461. }
  16462. if (isNaN(height)) {
  16463. height = width / aspect;
  16464. }
  16465. }
  16466. // If left is not specified, calculate left from right and width
  16467. if (isNaN(left)) {
  16468. left = containerWidth - right - width - horizontalMargin;
  16469. }
  16470. if (isNaN(top)) {
  16471. top = containerHeight - bottom - height - verticalMargin;
  16472. }
  16473. // Align left and top
  16474. switch (positionInfo.left || positionInfo.right) {
  16475. case 'center':
  16476. left = containerWidth / 2 - width / 2 - margin[3];
  16477. break;
  16478. case 'right':
  16479. left = containerWidth - width - horizontalMargin;
  16480. break;
  16481. }
  16482. switch (positionInfo.top || positionInfo.bottom) {
  16483. case 'middle':
  16484. case 'center':
  16485. top = containerHeight / 2 - height / 2 - margin[0];
  16486. break;
  16487. case 'bottom':
  16488. top = containerHeight - height - verticalMargin;
  16489. break;
  16490. }
  16491. // If something is wrong and left, top, width, height are calculated as NaN
  16492. left = left || 0;
  16493. top = top || 0;
  16494. if (isNaN(width)) {
  16495. // Width may be NaN if only one value is given except width
  16496. width = containerWidth - horizontalMargin - left - (right || 0);
  16497. }
  16498. if (isNaN(height)) {
  16499. // Height may be NaN if only one value is given except height
  16500. height = containerHeight - verticalMargin - top - (bottom || 0);
  16501. }
  16502. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16503. rect.margin = margin;
  16504. return rect;
  16505. }
  16506. /**
  16507. * Position a zr element in viewport
  16508. * Group position is specified by either
  16509. * {left, top}, {right, bottom}
  16510. * If all properties exists, right and bottom will be igonred.
  16511. *
  16512. * Logic:
  16513. * 1. Scale (against origin point in parent coord)
  16514. * 2. Rotate (against origin point in parent coord)
  16515. * 3. Translate (with el.position by this method)
  16516. * So this method only fixes the last step 'Translate', which does not affect
  16517. * scaling and rotating.
  16518. *
  16519. * If be called repeatedly with the same input el, the same result will be gotten.
  16520. *
  16521. * Return true if the layout happened.
  16522. *
  16523. * @param el Should have `getBoundingRect` method.
  16524. * @param positionInfo
  16525. * @param positionInfo.left
  16526. * @param positionInfo.top
  16527. * @param positionInfo.right
  16528. * @param positionInfo.bottom
  16529. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16530. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16531. * @param containerRect
  16532. * @param margin
  16533. * @param opt
  16534. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16535. * @param opt.boundingMode
  16536. * Specify how to calculate boundingRect when locating.
  16537. * 'all': Position the boundingRect that is transformed and uioned
  16538. * both itself and its descendants.
  16539. * This mode simplies confine the elements in the bounding
  16540. * of their container (e.g., using 'right: 0').
  16541. * 'raw': Position the boundingRect that is not transformed and only itself.
  16542. * This mode is useful when you want a element can overflow its
  16543. * container. (Consider a rotated circle needs to be located in a corner.)
  16544. * In this mode positionInfo.width/height can only be number.
  16545. */
  16546. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16547. var h = !opt || !opt.hv || opt.hv[0];
  16548. var v = !opt || !opt.hv || opt.hv[1];
  16549. var boundingMode = opt && opt.boundingMode || 'all';
  16550. out = out || el;
  16551. out.x = el.x;
  16552. out.y = el.y;
  16553. if (!h && !v) {
  16554. return false;
  16555. }
  16556. var rect;
  16557. if (boundingMode === 'raw') {
  16558. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16559. } else {
  16560. rect = el.getBoundingRect();
  16561. if (el.needLocalTransform()) {
  16562. var transform = el.getLocalTransform();
  16563. // Notice: raw rect may be inner object of el,
  16564. // which should not be modified.
  16565. rect = rect.clone();
  16566. rect.applyTransform(transform);
  16567. }
  16568. }
  16569. // The real width and height can not be specified but calculated by the given el.
  16570. var layoutRect = getLayoutRect(defaults({
  16571. width: rect.width,
  16572. height: rect.height
  16573. }, positionInfo), containerRect, margin);
  16574. // Because 'tranlate' is the last step in transform
  16575. // (see zrender/core/Transformable#getLocalTransform),
  16576. // we can just only modify el.position to get final result.
  16577. var dx = h ? layoutRect.x - rect.x : 0;
  16578. var dy = v ? layoutRect.y - rect.y : 0;
  16579. if (boundingMode === 'raw') {
  16580. out.x = dx;
  16581. out.y = dy;
  16582. } else {
  16583. out.x += dx;
  16584. out.y += dy;
  16585. }
  16586. if (out === el) {
  16587. el.markRedraw();
  16588. }
  16589. return true;
  16590. }
  16591. function fetchLayoutMode(ins) {
  16592. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16593. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16594. type: layoutMode
  16595. } : null;
  16596. }
  16597. /**
  16598. * Consider Case:
  16599. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16600. * through setOption or media query, using normal zrUtil.merge will cause
  16601. * {right: 0} does not take effect.
  16602. *
  16603. * @example
  16604. * ComponentModel.extend({
  16605. * init: function () {
  16606. * ...
  16607. * let inputPositionParams = layout.getLayoutParams(option);
  16608. * this.mergeOption(inputPositionParams);
  16609. * },
  16610. * mergeOption: function (newOption) {
  16611. * newOption && zrUtil.merge(thisOption, newOption, true);
  16612. * layout.mergeLayoutParam(thisOption, newOption);
  16613. * }
  16614. * });
  16615. *
  16616. * @param targetOption
  16617. * @param newOption
  16618. * @param opt
  16619. */
  16620. function mergeLayoutParam(targetOption, newOption, opt) {
  16621. var ignoreSize = opt && opt.ignoreSize;
  16622. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16623. var hResult = merge(HV_NAMES[0], 0);
  16624. var vResult = merge(HV_NAMES[1], 1);
  16625. copy(HV_NAMES[0], targetOption, hResult);
  16626. copy(HV_NAMES[1], targetOption, vResult);
  16627. function merge(names, hvIdx) {
  16628. var newParams = {};
  16629. var newValueCount = 0;
  16630. var merged = {};
  16631. var mergedValueCount = 0;
  16632. var enoughParamNumber = 2;
  16633. each$1(names, function (name) {
  16634. merged[name] = targetOption[name];
  16635. });
  16636. each$1(names, function (name) {
  16637. // Consider case: newOption.width is null, which is
  16638. // set by user for removing width setting.
  16639. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16640. hasValue(newParams, name) && newValueCount++;
  16641. hasValue(merged, name) && mergedValueCount++;
  16642. });
  16643. if (ignoreSize[hvIdx]) {
  16644. // Only one of left/right is premitted to exist.
  16645. if (hasValue(newOption, names[1])) {
  16646. merged[names[2]] = null;
  16647. } else if (hasValue(newOption, names[2])) {
  16648. merged[names[1]] = null;
  16649. }
  16650. return merged;
  16651. }
  16652. // Case: newOption: {width: ..., right: ...},
  16653. // or targetOption: {right: ...} and newOption: {width: ...},
  16654. // There is no conflict when merged only has params count
  16655. // little than enoughParamNumber.
  16656. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16657. return merged;
  16658. }
  16659. // Case: newOption: {width: ..., right: ...},
  16660. // Than we can make sure user only want those two, and ignore
  16661. // all origin params in targetOption.
  16662. else if (newValueCount >= enoughParamNumber) {
  16663. return newParams;
  16664. } else {
  16665. // Chose another param from targetOption by priority.
  16666. for (var i = 0; i < names.length; i++) {
  16667. var name_1 = names[i];
  16668. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16669. newParams[name_1] = targetOption[name_1];
  16670. break;
  16671. }
  16672. }
  16673. return newParams;
  16674. }
  16675. }
  16676. function hasProp(obj, name) {
  16677. return obj.hasOwnProperty(name);
  16678. }
  16679. function hasValue(obj, name) {
  16680. return obj[name] != null && obj[name] !== 'auto';
  16681. }
  16682. function copy(names, target, source) {
  16683. each$1(names, function (name) {
  16684. target[name] = source[name];
  16685. });
  16686. }
  16687. }
  16688. /**
  16689. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16690. */
  16691. function getLayoutParams(source) {
  16692. return copyLayoutParams({}, source);
  16693. }
  16694. /**
  16695. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16696. * @param {Object} source
  16697. * @return {Object} Result contains those props.
  16698. */
  16699. function copyLayoutParams(target, source) {
  16700. source && target && each$1(LOCATION_PARAMS, function (name) {
  16701. source.hasOwnProperty(name) && (target[name] = source[name]);
  16702. });
  16703. return target;
  16704. }
  16705. var inner = makeInner();
  16706. var ComponentModel = /** @class */function (_super) {
  16707. __extends(ComponentModel, _super);
  16708. function ComponentModel(option, parentModel, ecModel) {
  16709. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16710. _this.uid = getUID('ec_cpt_model');
  16711. return _this;
  16712. }
  16713. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16714. this.mergeDefaultAndTheme(option, ecModel);
  16715. };
  16716. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16717. var layoutMode = fetchLayoutMode(this);
  16718. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16719. var themeModel = ecModel.getTheme();
  16720. merge(option, themeModel.get(this.mainType));
  16721. merge(option, this.getDefaultOption());
  16722. if (layoutMode) {
  16723. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16724. }
  16725. };
  16726. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16727. merge(this.option, option, true);
  16728. var layoutMode = fetchLayoutMode(this);
  16729. if (layoutMode) {
  16730. mergeLayoutParam(this.option, option, layoutMode);
  16731. }
  16732. };
  16733. /**
  16734. * Called immediately after `init` or `mergeOption` of this instance called.
  16735. */
  16736. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16737. /**
  16738. * [How to declare defaultOption]:
  16739. *
  16740. * (A) If using class declaration in typescript (since echarts 5):
  16741. * ```ts
  16742. * import {ComponentOption} from '../model/option.js';
  16743. * export interface XxxOption extends ComponentOption {
  16744. * aaa: number
  16745. * }
  16746. * export class XxxModel extends Component {
  16747. * static type = 'xxx';
  16748. * static defaultOption: XxxOption = {
  16749. * aaa: 123
  16750. * }
  16751. * }
  16752. * Component.registerClass(XxxModel);
  16753. * ```
  16754. * ```ts
  16755. * import {inheritDefaultOption} from '../util/component.js';
  16756. * import {XxxModel, XxxOption} from './XxxModel.js';
  16757. * export interface XxxSubOption extends XxxOption {
  16758. * bbb: number
  16759. * }
  16760. * class XxxSubModel extends XxxModel {
  16761. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16762. * bbb: 456
  16763. * })
  16764. * fn() {
  16765. * let opt = this.getDefaultOption();
  16766. * // opt is {aaa: 123, bbb: 456}
  16767. * }
  16768. * }
  16769. * ```
  16770. *
  16771. * (B) If using class extend (previous approach in echarts 3 & 4):
  16772. * ```js
  16773. * let XxxComponent = Component.extend({
  16774. * defaultOption: {
  16775. * xx: 123
  16776. * }
  16777. * })
  16778. * ```
  16779. * ```js
  16780. * let XxxSubComponent = XxxComponent.extend({
  16781. * defaultOption: {
  16782. * yy: 456
  16783. * },
  16784. * fn: function () {
  16785. * let opt = this.getDefaultOption();
  16786. * // opt is {xx: 123, yy: 456}
  16787. * }
  16788. * })
  16789. * ```
  16790. */
  16791. ComponentModel.prototype.getDefaultOption = function () {
  16792. var ctor = this.constructor;
  16793. // If using class declaration, it is different to travel super class
  16794. // in legacy env and auto merge defaultOption. So if using class
  16795. // declaration, defaultOption should be merged manually.
  16796. if (!isExtendedClass(ctor)) {
  16797. // When using ts class, defaultOption must be declared as static.
  16798. return ctor.defaultOption;
  16799. }
  16800. // FIXME: remove this approach?
  16801. var fields = inner(this);
  16802. if (!fields.defaultOption) {
  16803. var optList = [];
  16804. var clz = ctor;
  16805. while (clz) {
  16806. var opt = clz.prototype.defaultOption;
  16807. opt && optList.push(opt);
  16808. clz = clz.superClass;
  16809. }
  16810. var defaultOption = {};
  16811. for (var i = optList.length - 1; i >= 0; i--) {
  16812. defaultOption = merge(defaultOption, optList[i], true);
  16813. }
  16814. fields.defaultOption = defaultOption;
  16815. }
  16816. return fields.defaultOption;
  16817. };
  16818. /**
  16819. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16820. * The same behavior as `modelUtil.parseFinder`.
  16821. *
  16822. * @param useDefault In many cases like series refer axis and axis refer grid,
  16823. * If axis index / axis id not specified, use the first target as default.
  16824. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16825. */
  16826. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16827. var indexKey = mainType + 'Index';
  16828. var idKey = mainType + 'Id';
  16829. return queryReferringComponents(this.ecModel, mainType, {
  16830. index: this.get(indexKey, true),
  16831. id: this.get(idKey, true)
  16832. }, opt);
  16833. };
  16834. ComponentModel.prototype.getBoxLayoutParams = function () {
  16835. // Consider itself having box layout configs.
  16836. var boxLayoutModel = this;
  16837. return {
  16838. left: boxLayoutModel.get('left'),
  16839. top: boxLayoutModel.get('top'),
  16840. right: boxLayoutModel.get('right'),
  16841. bottom: boxLayoutModel.get('bottom'),
  16842. width: boxLayoutModel.get('width'),
  16843. height: boxLayoutModel.get('height')
  16844. };
  16845. };
  16846. /**
  16847. * Get key for zlevel.
  16848. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16849. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16850. */
  16851. ComponentModel.prototype.getZLevelKey = function () {
  16852. return '';
  16853. };
  16854. ComponentModel.prototype.setZLevel = function (zlevel) {
  16855. this.option.zlevel = zlevel;
  16856. };
  16857. ComponentModel.protoInitialize = function () {
  16858. var proto = ComponentModel.prototype;
  16859. proto.type = 'component';
  16860. proto.id = '';
  16861. proto.name = '';
  16862. proto.mainType = '';
  16863. proto.subType = '';
  16864. proto.componentIndex = 0;
  16865. }();
  16866. return ComponentModel;
  16867. }(Model);
  16868. mountExtend(ComponentModel, Model);
  16869. enableClassManagement(ComponentModel);
  16870. enableSubTypeDefaulter(ComponentModel);
  16871. enableTopologicalTravel(ComponentModel, getDependencies);
  16872. function getDependencies(componentType) {
  16873. var deps = [];
  16874. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16875. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16876. });
  16877. // Ensure main type.
  16878. deps = map(deps, function (type) {
  16879. return parseClassType(type).main;
  16880. });
  16881. // Hack dataset for convenience.
  16882. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16883. deps.unshift('dataset');
  16884. }
  16885. return deps;
  16886. }
  16887. /*
  16888. * Licensed to the Apache Software Foundation (ASF) under one
  16889. * or more contributor license agreements. See the NOTICE file
  16890. * distributed with this work for additional information
  16891. * regarding copyright ownership. The ASF licenses this file
  16892. * to you under the Apache License, Version 2.0 (the
  16893. * "License"); you may not use this file except in compliance
  16894. * with the License. You may obtain a copy of the License at
  16895. *
  16896. * http://www.apache.org/licenses/LICENSE-2.0
  16897. *
  16898. * Unless required by applicable law or agreed to in writing,
  16899. * software distributed under the License is distributed on an
  16900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16901. * KIND, either express or implied. See the License for the
  16902. * specific language governing permissions and limitations
  16903. * under the License.
  16904. */
  16905. /**
  16906. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16907. */
  16908. /*
  16909. * Licensed to the Apache Software Foundation (ASF) under one
  16910. * or more contributor license agreements. See the NOTICE file
  16911. * distributed with this work for additional information
  16912. * regarding copyright ownership. The ASF licenses this file
  16913. * to you under the Apache License, Version 2.0 (the
  16914. * "License"); you may not use this file except in compliance
  16915. * with the License. You may obtain a copy of the License at
  16916. *
  16917. * http://www.apache.org/licenses/LICENSE-2.0
  16918. *
  16919. * Unless required by applicable law or agreed to in writing,
  16920. * software distributed under the License is distributed on an
  16921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16922. * KIND, either express or implied. See the License for the
  16923. * specific language governing permissions and limitations
  16924. * under the License.
  16925. */
  16926. var platform = '';
  16927. // Navigator not exists in node
  16928. if (typeof navigator !== 'undefined') {
  16929. /* global navigator */
  16930. platform = navigator.platform || '';
  16931. }
  16932. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16933. var globalDefault = {
  16934. darkMode: 'auto',
  16935. // backgroundColor: 'rgba(0,0,0,0)',
  16936. colorBy: 'series',
  16937. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16938. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16939. aria: {
  16940. decal: {
  16941. decals: [{
  16942. color: decalColor,
  16943. dashArrayX: [1, 0],
  16944. dashArrayY: [2, 5],
  16945. symbolSize: 1,
  16946. rotation: Math.PI / 6
  16947. }, {
  16948. color: decalColor,
  16949. symbol: 'circle',
  16950. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16951. dashArrayY: [6, 0],
  16952. symbolSize: 0.8
  16953. }, {
  16954. color: decalColor,
  16955. dashArrayX: [1, 0],
  16956. dashArrayY: [4, 3],
  16957. rotation: -Math.PI / 4
  16958. }, {
  16959. color: decalColor,
  16960. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16961. dashArrayY: [6, 0]
  16962. }, {
  16963. color: decalColor,
  16964. dashArrayX: [[1, 0], [1, 6]],
  16965. dashArrayY: [1, 0, 6, 0],
  16966. rotation: Math.PI / 4
  16967. }, {
  16968. color: decalColor,
  16969. symbol: 'triangle',
  16970. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16971. dashArrayY: [7, 2],
  16972. symbolSize: 0.75
  16973. }]
  16974. }
  16975. },
  16976. // If xAxis and yAxis declared, grid is created by default.
  16977. // grid: {},
  16978. textStyle: {
  16979. // color: '#000',
  16980. // decoration: 'none',
  16981. // PENDING
  16982. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16983. // fontFamily: 'Arial, Verdana, sans-serif',
  16984. fontSize: 12,
  16985. fontStyle: 'normal',
  16986. fontWeight: 'normal'
  16987. },
  16988. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16989. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16990. // Default is source-over
  16991. blendMode: null,
  16992. stateAnimation: {
  16993. duration: 300,
  16994. easing: 'cubicOut'
  16995. },
  16996. animation: 'auto',
  16997. animationDuration: 1000,
  16998. animationDurationUpdate: 500,
  16999. animationEasing: 'cubicInOut',
  17000. animationEasingUpdate: 'cubicInOut',
  17001. animationThreshold: 2000,
  17002. // Configuration for progressive/incremental rendering
  17003. progressiveThreshold: 3000,
  17004. progressive: 400,
  17005. // Threshold of if use single hover layer to optimize.
  17006. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17007. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17008. // which is unexpected.
  17009. // see example <echarts/test/heatmap-large.html>.
  17010. hoverLayerThreshold: 3000,
  17011. // See: module:echarts/scale/Time
  17012. useUTC: false
  17013. };
  17014. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'itemChildGroupId', 'seriesName']);
  17015. var SOURCE_FORMAT_ORIGINAL = 'original';
  17016. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17017. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17018. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17019. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17020. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17021. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17022. var SERIES_LAYOUT_BY_ROW = 'row';
  17023. // The result of `guessOrdinal`.
  17024. var BE_ORDINAL = {
  17025. Must: 1,
  17026. Might: 2,
  17027. Not: 3 // Other cases
  17028. };
  17029. var innerGlobalModel = makeInner();
  17030. /**
  17031. * MUST be called before mergeOption of all series.
  17032. */
  17033. function resetSourceDefaulter(ecModel) {
  17034. // `datasetMap` is used to make default encode.
  17035. innerGlobalModel(ecModel).datasetMap = createHashMap();
  17036. }
  17037. /**
  17038. * [The strategy of the arrengment of data dimensions for dataset]:
  17039. * "value way": all axes are non-category axes. So series one by one take
  17040. * several (the number is coordSysDims.length) dimensions from dataset.
  17041. * The result of data arrengment of data dimensions like:
  17042. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17043. * "category way": at least one axis is category axis. So the the first data
  17044. * dimension is always mapped to the first category axis and shared by
  17045. * all of the series. The other data dimensions are taken by series like
  17046. * "value way" does.
  17047. * The result of data arrengment of data dimensions like:
  17048. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17049. *
  17050. * @return encode Never be `null/undefined`.
  17051. */
  17052. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17053. var encode = {};
  17054. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  17055. // Currently only make default when using dataset, util more reqirements occur.
  17056. if (!datasetModel || !coordDimensions) {
  17057. return encode;
  17058. }
  17059. var encodeItemName = [];
  17060. var encodeSeriesName = [];
  17061. var ecModel = seriesModel.ecModel;
  17062. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  17063. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17064. var baseCategoryDimIndex;
  17065. var categoryWayValueDimStart;
  17066. coordDimensions = coordDimensions.slice();
  17067. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  17068. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  17069. name: coordDimInfoLoose
  17070. };
  17071. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17072. baseCategoryDimIndex = coordDimIdx;
  17073. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  17074. }
  17075. encode[coordDimInfo.name] = [];
  17076. });
  17077. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17078. categoryWayDim: categoryWayValueDimStart,
  17079. valueWayDim: 0
  17080. });
  17081. // TODO
  17082. // Auto detect first time axis and do arrangement.
  17083. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17084. var coordDimName = coordDimInfo.name;
  17085. var count = getDataDimCountOnCoordDim(coordDimInfo);
  17086. // In value way.
  17087. if (baseCategoryDimIndex == null) {
  17088. var start = datasetRecord.valueWayDim;
  17089. pushDim(encode[coordDimName], start, count);
  17090. pushDim(encodeSeriesName, start, count);
  17091. datasetRecord.valueWayDim += count;
  17092. // ??? TODO give a better default series name rule?
  17093. // especially when encode x y specified.
  17094. // consider: when multiple series share one dimension
  17095. // category axis, series name should better use
  17096. // the other dimension name. On the other hand, use
  17097. // both dimensions name.
  17098. }
  17099. // In category way, the first category axis.
  17100. else if (baseCategoryDimIndex === coordDimIdx) {
  17101. pushDim(encode[coordDimName], 0, count);
  17102. pushDim(encodeItemName, 0, count);
  17103. }
  17104. // In category way, the other axis.
  17105. else {
  17106. var start = datasetRecord.categoryWayDim;
  17107. pushDim(encode[coordDimName], start, count);
  17108. pushDim(encodeSeriesName, start, count);
  17109. datasetRecord.categoryWayDim += count;
  17110. }
  17111. });
  17112. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17113. for (var i = 0; i < idxCount; i++) {
  17114. dimIdxArr.push(idxFrom + i);
  17115. }
  17116. }
  17117. function getDataDimCountOnCoordDim(coordDimInfo) {
  17118. var dimsDef = coordDimInfo.dimsDef;
  17119. return dimsDef ? dimsDef.length : 1;
  17120. }
  17121. encodeItemName.length && (encode.itemName = encodeItemName);
  17122. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17123. return encode;
  17124. }
  17125. /**
  17126. * Work for data like [{name: ..., value: ...}, ...].
  17127. *
  17128. * @return encode Never be `null/undefined`.
  17129. */
  17130. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17131. var encode = {};
  17132. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  17133. // Currently only make default when using dataset, util more reqirements occur.
  17134. if (!datasetModel) {
  17135. return encode;
  17136. }
  17137. var sourceFormat = source.sourceFormat;
  17138. var dimensionsDefine = source.dimensionsDefine;
  17139. var potentialNameDimIndex;
  17140. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17141. each(dimensionsDefine, function (dim, idx) {
  17142. if ((isObject(dim) ? dim.name : dim) === 'name') {
  17143. potentialNameDimIndex = idx;
  17144. }
  17145. });
  17146. }
  17147. var idxResult = function () {
  17148. var idxRes0 = {};
  17149. var idxRes1 = {};
  17150. var guessRecords = [];
  17151. // 5 is an experience value.
  17152. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17153. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17154. guessRecords.push(guessResult);
  17155. var isPureNumber = guessResult === BE_ORDINAL.Not;
  17156. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17157. // and then find a name dim with the priority:
  17158. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17159. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17160. idxRes0.v = i;
  17161. }
  17162. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17163. idxRes0.n = i;
  17164. }
  17165. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17166. return idxRes0;
  17167. }
  17168. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17169. // find the first BE_ORDINAL.Might as the value dim,
  17170. // and then find a name dim with the priority:
  17171. // "other dim" > "the value dim itself".
  17172. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17173. // treated as number.
  17174. if (!isPureNumber) {
  17175. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17176. idxRes1.v = i;
  17177. }
  17178. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17179. idxRes1.n = i;
  17180. }
  17181. }
  17182. }
  17183. function fulfilled(idxResult) {
  17184. return idxResult.v != null && idxResult.n != null;
  17185. }
  17186. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17187. }();
  17188. if (idxResult) {
  17189. encode.value = [idxResult.v];
  17190. // `potentialNameDimIndex` has highest priority.
  17191. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  17192. // By default, label uses itemName in charts.
  17193. // So we don't set encodeLabel here.
  17194. encode.itemName = [nameDimIndex];
  17195. encode.seriesName = [nameDimIndex];
  17196. }
  17197. return encode;
  17198. }
  17199. /**
  17200. * @return If return null/undefined, indicate that should not use datasetModel.
  17201. */
  17202. function querySeriesUpstreamDatasetModel(seriesModel) {
  17203. // Caution: consider the scenario:
  17204. // A dataset is declared and a series is not expected to use the dataset,
  17205. // and at the beginning `setOption({series: { noData })` (just prepare other
  17206. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17207. // the user should set an empty array to avoid that dataset is used by default.
  17208. var thisData = seriesModel.get('data', true);
  17209. if (!thisData) {
  17210. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  17211. index: seriesModel.get('datasetIndex', true),
  17212. id: seriesModel.get('datasetId', true)
  17213. }, SINGLE_REFERRING).models[0];
  17214. }
  17215. }
  17216. /**
  17217. * @return Always return an array event empty.
  17218. */
  17219. function queryDatasetUpstreamDatasetModels(datasetModel) {
  17220. // Only these attributes declared, we by default reference to `datasetIndex: 0`.
  17221. // Otherwise, no reference.
  17222. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  17223. return [];
  17224. }
  17225. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  17226. index: datasetModel.get('fromDatasetIndex', true),
  17227. id: datasetModel.get('fromDatasetId', true)
  17228. }, SINGLE_REFERRING).models;
  17229. }
  17230. /**
  17231. * The rule should not be complex, otherwise user might not
  17232. * be able to known where the data is wrong.
  17233. * The code is ugly, but how to make it neat?
  17234. */
  17235. function guessOrdinal(source, dimIndex) {
  17236. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17237. }
  17238. // dimIndex may be overflow source data.
  17239. // return {BE_ORDINAL}
  17240. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17241. var result;
  17242. // Experience value.
  17243. var maxLoop = 5;
  17244. if (isTypedArray(data)) {
  17245. return BE_ORDINAL.Not;
  17246. }
  17247. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17248. // always exists in source.
  17249. var dimName;
  17250. var dimType;
  17251. if (dimensionsDefine) {
  17252. var dimDefItem = dimensionsDefine[dimIndex];
  17253. if (isObject(dimDefItem)) {
  17254. dimName = dimDefItem.name;
  17255. dimType = dimDefItem.type;
  17256. } else if (isString(dimDefItem)) {
  17257. dimName = dimDefItem;
  17258. }
  17259. }
  17260. if (dimType != null) {
  17261. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17262. }
  17263. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17264. var dataArrayRows = data;
  17265. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17266. var sample = dataArrayRows[dimIndex];
  17267. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17268. if ((result = detectValue(sample[startIndex + i])) != null) {
  17269. return result;
  17270. }
  17271. }
  17272. } else {
  17273. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  17274. var row = dataArrayRows[startIndex + i];
  17275. if (row && (result = detectValue(row[dimIndex])) != null) {
  17276. return result;
  17277. }
  17278. }
  17279. }
  17280. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17281. var dataObjectRows = data;
  17282. if (!dimName) {
  17283. return BE_ORDINAL.Not;
  17284. }
  17285. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  17286. var item = dataObjectRows[i];
  17287. if (item && (result = detectValue(item[dimName])) != null) {
  17288. return result;
  17289. }
  17290. }
  17291. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17292. var dataKeyedColumns = data;
  17293. if (!dimName) {
  17294. return BE_ORDINAL.Not;
  17295. }
  17296. var sample = dataKeyedColumns[dimName];
  17297. if (!sample || isTypedArray(sample)) {
  17298. return BE_ORDINAL.Not;
  17299. }
  17300. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17301. if ((result = detectValue(sample[i])) != null) {
  17302. return result;
  17303. }
  17304. }
  17305. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17306. var dataOriginal = data;
  17307. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17308. var item = dataOriginal[i];
  17309. var val = getDataItemValue(item);
  17310. if (!isArray(val)) {
  17311. return BE_ORDINAL.Not;
  17312. }
  17313. if ((result = detectValue(val[dimIndex])) != null) {
  17314. return result;
  17315. }
  17316. }
  17317. }
  17318. function detectValue(val) {
  17319. var beStr = isString(val);
  17320. // Consider usage convenience, '1', '2' will be treated as "number".
  17321. // `Number('')` (or any whitespace) is `0`.
  17322. if (val != null && Number.isFinite(Number(val)) && val !== '') {
  17323. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17324. } else if (beStr && val !== '-') {
  17325. return BE_ORDINAL.Must;
  17326. }
  17327. }
  17328. return BE_ORDINAL.Not;
  17329. }
  17330. var internalOptionCreatorMap = createHashMap();
  17331. function registerInternalOptionCreator(mainType, creator) {
  17332. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17333. internalOptionCreatorMap.set(mainType, creator);
  17334. }
  17335. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17336. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17337. if (!internalOptionCreator) {
  17338. return newCmptOptionList;
  17339. }
  17340. var internalOptions = internalOptionCreator(ecModel);
  17341. if (!internalOptions) {
  17342. return newCmptOptionList;
  17343. }
  17344. if ("development" !== 'production') {
  17345. for (var i = 0; i < internalOptions.length; i++) {
  17346. assert(isComponentIdInternal(internalOptions[i]));
  17347. }
  17348. }
  17349. return newCmptOptionList.concat(internalOptions);
  17350. }
  17351. var innerColor = makeInner();
  17352. var innerDecal = makeInner();
  17353. var PaletteMixin = /** @class */function () {
  17354. function PaletteMixin() {}
  17355. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17356. var defaultPalette = normalizeToArray(this.get('color', true));
  17357. var layeredPalette = this.get('colorLayer', true);
  17358. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17359. };
  17360. PaletteMixin.prototype.clearColorPalette = function () {
  17361. clearPalette(this, innerColor);
  17362. };
  17363. return PaletteMixin;
  17364. }();
  17365. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17366. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17367. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17368. }
  17369. function getNearestPalette(palettes, requestColorNum) {
  17370. var paletteNum = palettes.length;
  17371. // TODO palettes must be in order
  17372. for (var i = 0; i < paletteNum; i++) {
  17373. if (palettes[i].length > requestColorNum) {
  17374. return palettes[i];
  17375. }
  17376. }
  17377. return palettes[paletteNum - 1];
  17378. }
  17379. /**
  17380. * @param name MUST NOT be null/undefined. Otherwise call this function
  17381. * twise with the same parameters will get different result.
  17382. * @param scope default this.
  17383. * @return Can be null/undefined
  17384. */
  17385. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17386. scope = scope || that;
  17387. var scopeFields = inner(scope);
  17388. var paletteIdx = scopeFields.paletteIdx || 0;
  17389. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {};
  17390. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17391. if (paletteNameMap.hasOwnProperty(name)) {
  17392. return paletteNameMap[name];
  17393. }
  17394. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum);
  17395. // In case can't find in layered color palette.
  17396. palette = palette || defaultPalette;
  17397. if (!palette || !palette.length) {
  17398. return;
  17399. }
  17400. var pickedPaletteItem = palette[paletteIdx];
  17401. if (name) {
  17402. paletteNameMap[name] = pickedPaletteItem;
  17403. }
  17404. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17405. return pickedPaletteItem;
  17406. }
  17407. function clearPalette(that, inner) {
  17408. inner(that).paletteIdx = 0;
  17409. inner(that).paletteNameMap = {};
  17410. }
  17411. // -----------------------
  17412. // Internal method names:
  17413. // -----------------------
  17414. var reCreateSeriesIndices;
  17415. var assertSeriesInitialized;
  17416. var initBase;
  17417. var OPTION_INNER_KEY = '\0_ec_inner';
  17418. var OPTION_INNER_VALUE = 1;
  17419. var BUITIN_COMPONENTS_MAP = {
  17420. grid: 'GridComponent',
  17421. polar: 'PolarComponent',
  17422. geo: 'GeoComponent',
  17423. singleAxis: 'SingleAxisComponent',
  17424. parallel: 'ParallelComponent',
  17425. calendar: 'CalendarComponent',
  17426. graphic: 'GraphicComponent',
  17427. toolbox: 'ToolboxComponent',
  17428. tooltip: 'TooltipComponent',
  17429. axisPointer: 'AxisPointerComponent',
  17430. brush: 'BrushComponent',
  17431. title: 'TitleComponent',
  17432. timeline: 'TimelineComponent',
  17433. markPoint: 'MarkPointComponent',
  17434. markLine: 'MarkLineComponent',
  17435. markArea: 'MarkAreaComponent',
  17436. legend: 'LegendComponent',
  17437. dataZoom: 'DataZoomComponent',
  17438. visualMap: 'VisualMapComponent',
  17439. // aria: 'AriaComponent',
  17440. // dataset: 'DatasetComponent',
  17441. // Dependencies
  17442. xAxis: 'GridComponent',
  17443. yAxis: 'GridComponent',
  17444. angleAxis: 'PolarComponent',
  17445. radiusAxis: 'PolarComponent'
  17446. };
  17447. var BUILTIN_CHARTS_MAP = {
  17448. line: 'LineChart',
  17449. bar: 'BarChart',
  17450. pie: 'PieChart',
  17451. scatter: 'ScatterChart',
  17452. radar: 'RadarChart',
  17453. map: 'MapChart',
  17454. tree: 'TreeChart',
  17455. treemap: 'TreemapChart',
  17456. graph: 'GraphChart',
  17457. gauge: 'GaugeChart',
  17458. funnel: 'FunnelChart',
  17459. parallel: 'ParallelChart',
  17460. sankey: 'SankeyChart',
  17461. boxplot: 'BoxplotChart',
  17462. candlestick: 'CandlestickChart',
  17463. effectScatter: 'EffectScatterChart',
  17464. lines: 'LinesChart',
  17465. heatmap: 'HeatmapChart',
  17466. pictorialBar: 'PictorialBarChart',
  17467. themeRiver: 'ThemeRiverChart',
  17468. sunburst: 'SunburstChart',
  17469. custom: 'CustomChart'
  17470. };
  17471. var componetsMissingLogPrinted = {};
  17472. function checkMissingComponents(option) {
  17473. each(option, function (componentOption, mainType) {
  17474. if (!ComponentModel.hasClass(mainType)) {
  17475. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17476. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17477. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17478. componetsMissingLogPrinted[componentImportName] = true;
  17479. }
  17480. }
  17481. });
  17482. }
  17483. var GlobalModel = /** @class */function (_super) {
  17484. __extends(GlobalModel, _super);
  17485. function GlobalModel() {
  17486. return _super !== null && _super.apply(this, arguments) || this;
  17487. }
  17488. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17489. theme = theme || {};
  17490. this.option = null; // Mark as not initialized.
  17491. this._theme = new Model(theme);
  17492. this._locale = new Model(locale);
  17493. this._optionManager = optionManager;
  17494. };
  17495. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17496. if ("development" !== 'production') {
  17497. assert(option != null, 'option is null/undefined');
  17498. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17499. }
  17500. var innerOpt = normalizeSetOptionInput(opts);
  17501. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17502. this._resetOption(null, innerOpt);
  17503. };
  17504. /**
  17505. * @param type null/undefined: reset all.
  17506. * 'recreate': force recreate all.
  17507. * 'timeline': only reset timeline option
  17508. * 'media': only reset media query option
  17509. * @return Whether option changed.
  17510. */
  17511. GlobalModel.prototype.resetOption = function (type, opt) {
  17512. return this._resetOption(type, normalizeSetOptionInput(opt));
  17513. };
  17514. GlobalModel.prototype._resetOption = function (type, opt) {
  17515. var optionChanged = false;
  17516. var optionManager = this._optionManager;
  17517. if (!type || type === 'recreate') {
  17518. var baseOption = optionManager.mountOption(type === 'recreate');
  17519. if ("development" !== 'production') {
  17520. checkMissingComponents(baseOption);
  17521. }
  17522. if (!this.option || type === 'recreate') {
  17523. initBase(this, baseOption);
  17524. } else {
  17525. this.restoreData();
  17526. this._mergeOption(baseOption, opt);
  17527. }
  17528. optionChanged = true;
  17529. }
  17530. if (type === 'timeline' || type === 'media') {
  17531. this.restoreData();
  17532. }
  17533. // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17534. // it should better not have the same props with `MediaUnit['option']`.
  17535. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17536. // rather than original "baseOption". If they both override a prop, the result might be
  17537. // unexpected when media state changed after `setOption` called.
  17538. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17539. // (`{baseOption, media}`) in `setOption`.
  17540. // For `timeline`, the case is the same.
  17541. if (!type || type === 'recreate' || type === 'timeline') {
  17542. var timelineOption = optionManager.getTimelineOption(this);
  17543. if (timelineOption) {
  17544. optionChanged = true;
  17545. this._mergeOption(timelineOption, opt);
  17546. }
  17547. }
  17548. if (!type || type === 'recreate' || type === 'media') {
  17549. var mediaOptions = optionManager.getMediaOption(this);
  17550. if (mediaOptions.length) {
  17551. each(mediaOptions, function (mediaOption) {
  17552. optionChanged = true;
  17553. this._mergeOption(mediaOption, opt);
  17554. }, this);
  17555. }
  17556. }
  17557. return optionChanged;
  17558. };
  17559. GlobalModel.prototype.mergeOption = function (option) {
  17560. this._mergeOption(option, null);
  17561. };
  17562. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17563. var option = this.option;
  17564. var componentsMap = this._componentsMap;
  17565. var componentsCount = this._componentsCount;
  17566. var newCmptTypes = [];
  17567. var newCmptTypeMap = createHashMap();
  17568. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17569. resetSourceDefaulter(this);
  17570. // If no component class, merge directly.
  17571. // For example: color, animaiton options, etc.
  17572. each(newOption, function (componentOption, mainType) {
  17573. if (componentOption == null) {
  17574. return;
  17575. }
  17576. if (!ComponentModel.hasClass(mainType)) {
  17577. // globalSettingTask.dirty();
  17578. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17579. } else if (mainType) {
  17580. newCmptTypes.push(mainType);
  17581. newCmptTypeMap.set(mainType, true);
  17582. }
  17583. });
  17584. if (replaceMergeMainTypeMap) {
  17585. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17586. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17587. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17588. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17589. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17590. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17591. newCmptTypes.push(mainTypeInReplaceMerge);
  17592. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17593. }
  17594. });
  17595. }
  17596. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17597. function visitComponent(mainType) {
  17598. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17599. var oldCmptList = componentsMap.get(mainType);
  17600. var mergeMode =
  17601. // `!oldCmptList` means init. See the comment in `mappingToExists`
  17602. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17603. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode);
  17604. // Set mainType and complete subType.
  17605. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel);
  17606. // Empty it before the travel, in order to prevent `this._componentsMap`
  17607. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17608. // components, which is probably incorrect logic.
  17609. option[mainType] = null;
  17610. componentsMap.set(mainType, null);
  17611. componentsCount.set(mainType, 0);
  17612. var optionsByMainType = [];
  17613. var cmptsByMainType = [];
  17614. var cmptsCountByMainType = 0;
  17615. var tooltipExists;
  17616. var tooltipWarningLogged;
  17617. each(mappingResult, function (resultItem, index) {
  17618. var componentModel = resultItem.existing;
  17619. var newCmptOption = resultItem.newOption;
  17620. if (!newCmptOption) {
  17621. if (componentModel) {
  17622. // Consider where is no new option and should be merged using {},
  17623. // see removeEdgeAndAdd in topologicalTravel and
  17624. // ComponentModel.getAllClassMainTypes.
  17625. componentModel.mergeOption({}, this);
  17626. componentModel.optionUpdated({}, false);
  17627. }
  17628. // If no both `resultItem.exist` and `resultItem.option`,
  17629. // either it is in `replaceMerge` and not matched by any id,
  17630. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17631. } else {
  17632. var isSeriesType = mainType === 'series';
  17633. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17634. );
  17635. if (!ComponentModelClass) {
  17636. if ("development" !== 'production') {
  17637. var subType = resultItem.keyInfo.subType;
  17638. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17639. if (!componetsMissingLogPrinted[subType]) {
  17640. componetsMissingLogPrinted[subType] = true;
  17641. if (seriesImportName) {
  17642. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17643. } else {
  17644. error("Unknown series " + subType);
  17645. }
  17646. }
  17647. }
  17648. return;
  17649. }
  17650. // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17651. if (mainType === 'tooltip') {
  17652. if (tooltipExists) {
  17653. if ("development" !== 'production') {
  17654. if (!tooltipWarningLogged) {
  17655. warn('Currently only one tooltip component is allowed.');
  17656. tooltipWarningLogged = true;
  17657. }
  17658. }
  17659. return;
  17660. }
  17661. tooltipExists = true;
  17662. }
  17663. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17664. componentModel.name = resultItem.keyInfo.name;
  17665. // componentModel.settingTask && componentModel.settingTask.dirty();
  17666. componentModel.mergeOption(newCmptOption, this);
  17667. componentModel.optionUpdated(newCmptOption, false);
  17668. } else {
  17669. // PENDING Global as parent ?
  17670. var extraOpt = extend({
  17671. componentIndex: index
  17672. }, resultItem.keyInfo);
  17673. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt);
  17674. // Assign `keyInfo`
  17675. extend(componentModel, extraOpt);
  17676. if (resultItem.brandNew) {
  17677. componentModel.__requireNewView = true;
  17678. }
  17679. componentModel.init(newCmptOption, this, this);
  17680. // Call optionUpdated after init.
  17681. // newCmptOption has been used as componentModel.option
  17682. // and may be merged with theme and default, so pass null
  17683. // to avoid confusion.
  17684. componentModel.optionUpdated(null, true);
  17685. }
  17686. }
  17687. if (componentModel) {
  17688. optionsByMainType.push(componentModel.option);
  17689. cmptsByMainType.push(componentModel);
  17690. cmptsCountByMainType++;
  17691. } else {
  17692. // Always do assign to avoid elided item in array.
  17693. optionsByMainType.push(void 0);
  17694. cmptsByMainType.push(void 0);
  17695. }
  17696. }, this);
  17697. option[mainType] = optionsByMainType;
  17698. componentsMap.set(mainType, cmptsByMainType);
  17699. componentsCount.set(mainType, cmptsCountByMainType);
  17700. // Backup series for filtering.
  17701. if (mainType === 'series') {
  17702. reCreateSeriesIndices(this);
  17703. }
  17704. }
  17705. // If no series declared, ensure `_seriesIndices` initialized.
  17706. if (!this._seriesIndices) {
  17707. reCreateSeriesIndices(this);
  17708. }
  17709. };
  17710. /**
  17711. * Get option for output (cloned option and inner info removed)
  17712. */
  17713. GlobalModel.prototype.getOption = function () {
  17714. var option = clone(this.option);
  17715. each(option, function (optInMainType, mainType) {
  17716. if (ComponentModel.hasClass(mainType)) {
  17717. var opts = normalizeToArray(optInMainType);
  17718. // Inner cmpts need to be removed.
  17719. // Inner cmpts might not be at last since ec5.0, but still
  17720. // compatible for users: if inner cmpt at last, splice the returned array.
  17721. var realLen = opts.length;
  17722. var metNonInner = false;
  17723. for (var i = realLen - 1; i >= 0; i--) {
  17724. // Remove options with inner id.
  17725. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17726. metNonInner = true;
  17727. } else {
  17728. opts[i] = null;
  17729. !metNonInner && realLen--;
  17730. }
  17731. }
  17732. opts.length = realLen;
  17733. option[mainType] = opts;
  17734. }
  17735. });
  17736. delete option[OPTION_INNER_KEY];
  17737. return option;
  17738. };
  17739. GlobalModel.prototype.getTheme = function () {
  17740. return this._theme;
  17741. };
  17742. GlobalModel.prototype.getLocaleModel = function () {
  17743. return this._locale;
  17744. };
  17745. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17746. this._payload = payload;
  17747. };
  17748. GlobalModel.prototype.getUpdatePayload = function () {
  17749. return this._payload;
  17750. };
  17751. /**
  17752. * @param idx If not specified, return the first one.
  17753. */
  17754. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17755. var list = this._componentsMap.get(mainType);
  17756. if (list) {
  17757. var cmpt = list[idx || 0];
  17758. if (cmpt) {
  17759. return cmpt;
  17760. } else if (idx == null) {
  17761. for (var i = 0; i < list.length; i++) {
  17762. if (list[i]) {
  17763. return list[i];
  17764. }
  17765. }
  17766. }
  17767. }
  17768. };
  17769. /**
  17770. * @return Never be null/undefined.
  17771. */
  17772. GlobalModel.prototype.queryComponents = function (condition) {
  17773. var mainType = condition.mainType;
  17774. if (!mainType) {
  17775. return [];
  17776. }
  17777. var index = condition.index;
  17778. var id = condition.id;
  17779. var name = condition.name;
  17780. var cmpts = this._componentsMap.get(mainType);
  17781. if (!cmpts || !cmpts.length) {
  17782. return [];
  17783. }
  17784. var result;
  17785. if (index != null) {
  17786. result = [];
  17787. each(normalizeToArray(index), function (idx) {
  17788. cmpts[idx] && result.push(cmpts[idx]);
  17789. });
  17790. } else if (id != null) {
  17791. result = queryByIdOrName('id', id, cmpts);
  17792. } else if (name != null) {
  17793. result = queryByIdOrName('name', name, cmpts);
  17794. } else {
  17795. // Return all non-empty components in that mainType
  17796. result = filter(cmpts, function (cmpt) {
  17797. return !!cmpt;
  17798. });
  17799. }
  17800. return filterBySubType(result, condition);
  17801. };
  17802. /**
  17803. * The interface is different from queryComponents,
  17804. * which is convenient for inner usage.
  17805. *
  17806. * @usage
  17807. * let result = findComponents(
  17808. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17809. * );
  17810. * let result = findComponents(
  17811. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17812. * );
  17813. * let result = findComponents(
  17814. * {mainType: 'series',
  17815. * filter: function (model, index) {...}}
  17816. * );
  17817. * // result like [component0, componnet1, ...]
  17818. */
  17819. GlobalModel.prototype.findComponents = function (condition) {
  17820. var query = condition.query;
  17821. var mainType = condition.mainType;
  17822. var queryCond = getQueryCond(query);
  17823. var result = queryCond ? this.queryComponents(queryCond)
  17824. // Retrieve all non-empty components.
  17825. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17826. return !!cmpt;
  17827. });
  17828. return doFilter(filterBySubType(result, condition));
  17829. function getQueryCond(q) {
  17830. var indexAttr = mainType + 'Index';
  17831. var idAttr = mainType + 'Id';
  17832. var nameAttr = mainType + 'Name';
  17833. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17834. mainType: mainType,
  17835. // subType will be filtered finally.
  17836. index: q[indexAttr],
  17837. id: q[idAttr],
  17838. name: q[nameAttr]
  17839. } : null;
  17840. }
  17841. function doFilter(res) {
  17842. return condition.filter ? filter(res, condition.filter) : res;
  17843. }
  17844. };
  17845. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17846. var componentsMap = this._componentsMap;
  17847. if (isFunction(mainType)) {
  17848. var ctxForAll_1 = cb;
  17849. var cbForAll_1 = mainType;
  17850. componentsMap.each(function (cmpts, componentType) {
  17851. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17852. var cmpt = cmpts[i];
  17853. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17854. }
  17855. });
  17856. } else {
  17857. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17858. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17859. var cmpt = cmpts[i];
  17860. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17861. }
  17862. }
  17863. };
  17864. /**
  17865. * Get series list before filtered by name.
  17866. */
  17867. GlobalModel.prototype.getSeriesByName = function (name) {
  17868. var nameStr = convertOptionIdName(name, null);
  17869. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17870. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17871. });
  17872. };
  17873. /**
  17874. * Get series list before filtered by index.
  17875. */
  17876. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17877. return this._componentsMap.get('series')[seriesIndex];
  17878. };
  17879. /**
  17880. * Get series list before filtered by type.
  17881. * FIXME: rename to getRawSeriesByType?
  17882. */
  17883. GlobalModel.prototype.getSeriesByType = function (subType) {
  17884. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17885. return !!oneSeries && oneSeries.subType === subType;
  17886. });
  17887. };
  17888. /**
  17889. * Get all series before filtered.
  17890. */
  17891. GlobalModel.prototype.getSeries = function () {
  17892. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17893. return !!oneSeries;
  17894. });
  17895. };
  17896. /**
  17897. * Count series before filtered.
  17898. */
  17899. GlobalModel.prototype.getSeriesCount = function () {
  17900. return this._componentsCount.get('series');
  17901. };
  17902. /**
  17903. * After filtering, series may be different
  17904. * from raw series.
  17905. */
  17906. GlobalModel.prototype.eachSeries = function (cb, context) {
  17907. assertSeriesInitialized(this);
  17908. each(this._seriesIndices, function (rawSeriesIndex) {
  17909. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17910. cb.call(context, series, rawSeriesIndex);
  17911. }, this);
  17912. };
  17913. /**
  17914. * Iterate raw series before filtered.
  17915. *
  17916. * @param {Function} cb
  17917. * @param {*} context
  17918. */
  17919. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17920. each(this._componentsMap.get('series'), function (series) {
  17921. series && cb.call(context, series, series.componentIndex);
  17922. });
  17923. };
  17924. /**
  17925. * After filtering, series may be different.
  17926. * from raw series.
  17927. */
  17928. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17929. assertSeriesInitialized(this);
  17930. each(this._seriesIndices, function (rawSeriesIndex) {
  17931. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17932. if (series.subType === subType) {
  17933. cb.call(context, series, rawSeriesIndex);
  17934. }
  17935. }, this);
  17936. };
  17937. /**
  17938. * Iterate raw series before filtered of given type.
  17939. */
  17940. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17941. return each(this.getSeriesByType(subType), cb, context);
  17942. };
  17943. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17944. assertSeriesInitialized(this);
  17945. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17946. };
  17947. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17948. return (this._seriesIndices || []).slice();
  17949. };
  17950. GlobalModel.prototype.filterSeries = function (cb, context) {
  17951. assertSeriesInitialized(this);
  17952. var newSeriesIndices = [];
  17953. each(this._seriesIndices, function (seriesRawIdx) {
  17954. var series = this._componentsMap.get('series')[seriesRawIdx];
  17955. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17956. }, this);
  17957. this._seriesIndices = newSeriesIndices;
  17958. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17959. };
  17960. GlobalModel.prototype.restoreData = function (payload) {
  17961. reCreateSeriesIndices(this);
  17962. var componentsMap = this._componentsMap;
  17963. var componentTypes = [];
  17964. componentsMap.each(function (components, componentType) {
  17965. if (ComponentModel.hasClass(componentType)) {
  17966. componentTypes.push(componentType);
  17967. }
  17968. });
  17969. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17970. each(componentsMap.get(componentType), function (component) {
  17971. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17972. component.restoreData();
  17973. }
  17974. });
  17975. });
  17976. };
  17977. GlobalModel.internalField = function () {
  17978. reCreateSeriesIndices = function (ecModel) {
  17979. var seriesIndices = ecModel._seriesIndices = [];
  17980. each(ecModel._componentsMap.get('series'), function (series) {
  17981. // series may have been removed by `replaceMerge`.
  17982. series && seriesIndices.push(series.componentIndex);
  17983. });
  17984. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17985. };
  17986. assertSeriesInitialized = function (ecModel) {
  17987. // Components that use _seriesIndices should depends on series component,
  17988. // which make sure that their initialization is after series.
  17989. if ("development" !== 'production') {
  17990. if (!ecModel._seriesIndices) {
  17991. throw new Error('Option should contains series.');
  17992. }
  17993. }
  17994. };
  17995. initBase = function (ecModel, baseOption) {
  17996. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  17997. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  17998. ecModel.option = {};
  17999. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE;
  18000. // Init with series: [], in case of calling findSeries method
  18001. // before series initialized.
  18002. ecModel._componentsMap = createHashMap({
  18003. series: []
  18004. });
  18005. ecModel._componentsCount = createHashMap();
  18006. // If user spefied `option.aria`, aria will be enable. This detection should be
  18007. // performed before theme and globalDefault merge.
  18008. var airaOption = baseOption.aria;
  18009. if (isObject(airaOption) && airaOption.enabled == null) {
  18010. airaOption.enabled = true;
  18011. }
  18012. mergeTheme(baseOption, ecModel._theme.option);
  18013. // TODO Needs clone when merging to the unexisted property
  18014. merge(baseOption, globalDefault, false);
  18015. ecModel._mergeOption(baseOption, null);
  18016. };
  18017. }();
  18018. return GlobalModel;
  18019. }(Model);
  18020. function isNotTargetSeries(seriesModel, payload) {
  18021. if (payload) {
  18022. var index = payload.seriesIndex;
  18023. var id = payload.seriesId;
  18024. var name_1 = payload.seriesName;
  18025. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  18026. }
  18027. }
  18028. function mergeTheme(option, theme) {
  18029. // PENDING
  18030. // NOT use `colorLayer` in theme if option has `color`
  18031. var notMergeColorLayer = option.color && !option.colorLayer;
  18032. each(theme, function (themeItem, name) {
  18033. if (name === 'colorLayer' && notMergeColorLayer) {
  18034. return;
  18035. }
  18036. // If it is component model mainType, the model handles that merge later.
  18037. // otherwise, merge them here.
  18038. if (!ComponentModel.hasClass(name)) {
  18039. if (typeof themeItem === 'object') {
  18040. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  18041. } else {
  18042. if (option[name] == null) {
  18043. option[name] = themeItem;
  18044. }
  18045. }
  18046. }
  18047. });
  18048. }
  18049. function queryByIdOrName(attr, idOrName, cmpts) {
  18050. // Here is a break from echarts4: string and number are
  18051. // treated as equal.
  18052. if (isArray(idOrName)) {
  18053. var keyMap_1 = createHashMap();
  18054. each(idOrName, function (idOrNameItem) {
  18055. if (idOrNameItem != null) {
  18056. var idName = convertOptionIdName(idOrNameItem, null);
  18057. idName != null && keyMap_1.set(idOrNameItem, true);
  18058. }
  18059. });
  18060. return filter(cmpts, function (cmpt) {
  18061. return cmpt && keyMap_1.get(cmpt[attr]);
  18062. });
  18063. } else {
  18064. var idName_1 = convertOptionIdName(idOrName, null);
  18065. return filter(cmpts, function (cmpt) {
  18066. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  18067. });
  18068. }
  18069. }
  18070. function filterBySubType(components, condition) {
  18071. // Using hasOwnProperty for restrict. Consider
  18072. // subType is undefined in user payload.
  18073. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  18074. return cmpt && cmpt.subType === condition.subType;
  18075. }) : components;
  18076. }
  18077. function normalizeSetOptionInput(opts) {
  18078. var replaceMergeMainTypeMap = createHashMap();
  18079. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  18080. if ("development" !== 'production') {
  18081. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  18082. }
  18083. replaceMergeMainTypeMap.set(mainType, true);
  18084. });
  18085. return {
  18086. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  18087. };
  18088. }
  18089. mixin(GlobalModel, PaletteMixin);
  18090. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL',
  18091. // 'getModel',
  18092. 'getOption',
  18093. // 'getViewOfComponentModel',
  18094. // 'getViewOfSeriesModel',
  18095. 'getId', 'updateLabelLayout'];
  18096. var ExtensionAPI = /** @class */function () {
  18097. function ExtensionAPI(ecInstance) {
  18098. each(availableMethods, function (methodName) {
  18099. this[methodName] = bind(ecInstance[methodName], ecInstance);
  18100. }, this);
  18101. }
  18102. return ExtensionAPI;
  18103. }();
  18104. var coordinateSystemCreators = {};
  18105. var CoordinateSystemManager = /** @class */function () {
  18106. function CoordinateSystemManager() {
  18107. this._coordinateSystems = [];
  18108. }
  18109. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  18110. var coordinateSystems = [];
  18111. each(coordinateSystemCreators, function (creator, type) {
  18112. var list = creator.create(ecModel, api);
  18113. coordinateSystems = coordinateSystems.concat(list || []);
  18114. });
  18115. this._coordinateSystems = coordinateSystems;
  18116. };
  18117. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  18118. each(this._coordinateSystems, function (coordSys) {
  18119. coordSys.update && coordSys.update(ecModel, api);
  18120. });
  18121. };
  18122. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  18123. return this._coordinateSystems.slice();
  18124. };
  18125. CoordinateSystemManager.register = function (type, creator) {
  18126. coordinateSystemCreators[type] = creator;
  18127. };
  18128. CoordinateSystemManager.get = function (type) {
  18129. return coordinateSystemCreators[type];
  18130. };
  18131. return CoordinateSystemManager;
  18132. }();
  18133. var QUERY_REG = /^(min|max)?(.+)$/;
  18134. // Key: mainType
  18135. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  18136. /**
  18137. * TERM EXPLANATIONS:
  18138. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  18139. */
  18140. var OptionManager = /** @class */function () {
  18141. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18142. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18143. // rawOption cloned and backuped when timeline changed, which does no
  18144. // good to performance. What's more, that both timeline and setOption
  18145. // method supply 'notMerge' brings complex and some problems.
  18146. // Consider this case:
  18147. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18148. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18149. function OptionManager(api) {
  18150. this._timelineOptions = [];
  18151. this._mediaList = [];
  18152. /**
  18153. * -1, means default.
  18154. * empty means no media.
  18155. */
  18156. this._currentMediaIndices = [];
  18157. this._api = api;
  18158. }
  18159. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  18160. if (rawOption) {
  18161. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18162. each(normalizeToArray(rawOption.series), function (series) {
  18163. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18164. });
  18165. each(normalizeToArray(rawOption.dataset), function (dataset) {
  18166. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  18167. });
  18168. }
  18169. // Caution: some series modify option data, if do not clone,
  18170. // it should ensure that the repeat modify correctly
  18171. // (create a new object when modify itself).
  18172. rawOption = clone(rawOption);
  18173. // FIXME
  18174. // If some property is set in timeline options or media option but
  18175. // not set in baseOption, a warning should be given.
  18176. var optionBackup = this._optionBackup;
  18177. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  18178. this._newBaseOption = newParsedOption.baseOption;
  18179. // For setOption at second time (using merge mode);
  18180. if (optionBackup) {
  18181. // FIXME
  18182. // the restore merge solution is essentially incorrect.
  18183. // the mapping can not be 100% consistent with ecModel, which probably brings
  18184. // potential bug!
  18185. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  18186. // let fakeCmptsMap = this._fakeCmptsMap;
  18187. // if (!fakeCmptsMap) {
  18188. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  18189. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  18190. // }
  18191. // mergeToBackupOption(
  18192. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  18193. // );
  18194. // For simplicity, timeline options and media options do not support merge,
  18195. // that is, if you `setOption` twice and both has timeline options, the latter
  18196. // timeline options will not be merged to the former, but just substitute them.
  18197. if (newParsedOption.timelineOptions.length) {
  18198. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  18199. }
  18200. if (newParsedOption.mediaList.length) {
  18201. optionBackup.mediaList = newParsedOption.mediaList;
  18202. }
  18203. if (newParsedOption.mediaDefault) {
  18204. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  18205. }
  18206. } else {
  18207. this._optionBackup = newParsedOption;
  18208. }
  18209. };
  18210. OptionManager.prototype.mountOption = function (isRecreate) {
  18211. var optionBackup = this._optionBackup;
  18212. this._timelineOptions = optionBackup.timelineOptions;
  18213. this._mediaList = optionBackup.mediaList;
  18214. this._mediaDefault = optionBackup.mediaDefault;
  18215. this._currentMediaIndices = [];
  18216. return clone(isRecreate
  18217. // this._optionBackup.baseOption, which is created at the first `setOption`
  18218. // called, and is merged into every new option by inner method `mergeToBackupOption`
  18219. // each time `setOption` called, can be only used in `isRecreate`, because
  18220. // its reliability is under suspicion. In other cases option merge is
  18221. // performed by `model.mergeOption`.
  18222. ? optionBackup.baseOption : this._newBaseOption);
  18223. };
  18224. OptionManager.prototype.getTimelineOption = function (ecModel) {
  18225. var option;
  18226. var timelineOptions = this._timelineOptions;
  18227. if (timelineOptions.length) {
  18228. // getTimelineOption can only be called after ecModel inited,
  18229. // so we can get currentIndex from timelineModel.
  18230. var timelineModel = ecModel.getComponent('timeline');
  18231. if (timelineModel) {
  18232. option = clone(
  18233. // FIXME:TS as TimelineModel or quivlant interface
  18234. timelineOptions[timelineModel.getCurrentIndex()]);
  18235. }
  18236. }
  18237. return option;
  18238. };
  18239. OptionManager.prototype.getMediaOption = function (ecModel) {
  18240. var ecWidth = this._api.getWidth();
  18241. var ecHeight = this._api.getHeight();
  18242. var mediaList = this._mediaList;
  18243. var mediaDefault = this._mediaDefault;
  18244. var indices = [];
  18245. var result = [];
  18246. // No media defined.
  18247. if (!mediaList.length && !mediaDefault) {
  18248. return result;
  18249. }
  18250. // Multi media may be applied, the latter defined media has higher priority.
  18251. for (var i = 0, len = mediaList.length; i < len; i++) {
  18252. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18253. indices.push(i);
  18254. }
  18255. }
  18256. // FIXME
  18257. // Whether mediaDefault should force users to provide? Otherwise
  18258. // the change by media query can not be recorvered.
  18259. if (!indices.length && mediaDefault) {
  18260. indices = [-1];
  18261. }
  18262. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18263. result = map(indices, function (index) {
  18264. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  18265. });
  18266. }
  18267. // Otherwise return nothing.
  18268. this._currentMediaIndices = indices;
  18269. return result;
  18270. };
  18271. return OptionManager;
  18272. }();
  18273. /**
  18274. * [RAW_OPTION_PATTERNS]
  18275. * (Note: "series: []" represents all other props in `ECUnitOption`)
  18276. *
  18277. * (1) No prop "baseOption" declared:
  18278. * Root option is used as "baseOption" (except prop "options" and "media").
  18279. * ```js
  18280. * option = {
  18281. * series: [],
  18282. * timeline: {},
  18283. * options: [],
  18284. * };
  18285. * option = {
  18286. * series: [],
  18287. * media: {},
  18288. * };
  18289. * option = {
  18290. * series: [],
  18291. * timeline: {},
  18292. * options: [],
  18293. * media: {},
  18294. * }
  18295. * ```
  18296. *
  18297. * (2) Prop "baseOption" declared:
  18298. * If "baseOption" declared, `ECUnitOption` props can only be declared
  18299. * inside "baseOption" except prop "timeline" (compat ec2).
  18300. * ```js
  18301. * option = {
  18302. * baseOption: {
  18303. * timeline: {},
  18304. * series: [],
  18305. * },
  18306. * options: []
  18307. * };
  18308. * option = {
  18309. * baseOption: {
  18310. * series: [],
  18311. * },
  18312. * media: []
  18313. * };
  18314. * option = {
  18315. * baseOption: {
  18316. * timeline: {},
  18317. * series: [],
  18318. * },
  18319. * options: []
  18320. * media: []
  18321. * };
  18322. * option = {
  18323. * // ec3 compat ec2: allow (only) `timeline` declared
  18324. * // outside baseOption. Keep this setting for compat.
  18325. * timeline: {},
  18326. * baseOption: {
  18327. * series: [],
  18328. * },
  18329. * options: [],
  18330. * media: []
  18331. * };
  18332. * ```
  18333. */
  18334. function parseRawOption(
  18335. // `rawOption` May be modified
  18336. rawOption, optionPreprocessorFuncs, isNew) {
  18337. var mediaList = [];
  18338. var mediaDefault;
  18339. var baseOption;
  18340. var declaredBaseOption = rawOption.baseOption;
  18341. // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  18342. var timelineOnRoot = rawOption.timeline;
  18343. var timelineOptionsOnRoot = rawOption.options;
  18344. var mediaOnRoot = rawOption.media;
  18345. var hasMedia = !!rawOption.media;
  18346. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18347. if (declaredBaseOption) {
  18348. baseOption = declaredBaseOption;
  18349. // For merge option.
  18350. if (!baseOption.timeline) {
  18351. baseOption.timeline = timelineOnRoot;
  18352. }
  18353. }
  18354. // For convenience, enable to use the root option as the `baseOption`:
  18355. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18356. else {
  18357. if (hasTimeline || hasMedia) {
  18358. rawOption.options = rawOption.media = null;
  18359. }
  18360. baseOption = rawOption;
  18361. }
  18362. if (hasMedia) {
  18363. if (isArray(mediaOnRoot)) {
  18364. each(mediaOnRoot, function (singleMedia) {
  18365. if ("development" !== 'production') {
  18366. // Real case of wrong config.
  18367. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18368. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18369. }
  18370. }
  18371. if (singleMedia && singleMedia.option) {
  18372. if (singleMedia.query) {
  18373. mediaList.push(singleMedia);
  18374. } else if (!mediaDefault) {
  18375. // Use the first media default.
  18376. mediaDefault = singleMedia;
  18377. }
  18378. }
  18379. });
  18380. } else {
  18381. if ("development" !== 'production') {
  18382. // Real case of wrong config.
  18383. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18384. }
  18385. }
  18386. }
  18387. doPreprocess(baseOption);
  18388. each(timelineOptionsOnRoot, function (option) {
  18389. return doPreprocess(option);
  18390. });
  18391. each(mediaList, function (media) {
  18392. return doPreprocess(media.option);
  18393. });
  18394. function doPreprocess(option) {
  18395. each(optionPreprocessorFuncs, function (preProcess) {
  18396. preProcess(option, isNew);
  18397. });
  18398. }
  18399. return {
  18400. baseOption: baseOption,
  18401. timelineOptions: timelineOptionsOnRoot || [],
  18402. mediaDefault: mediaDefault,
  18403. mediaList: mediaList
  18404. };
  18405. }
  18406. /**
  18407. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18408. * Support: width, height, aspectRatio
  18409. * Can use max or min as prefix.
  18410. */
  18411. function applyMediaQuery(query, ecWidth, ecHeight) {
  18412. var realMap = {
  18413. width: ecWidth,
  18414. height: ecHeight,
  18415. aspectratio: ecWidth / ecHeight // lower case for convenience.
  18416. };
  18417. var applicable = true;
  18418. each(query, function (value, attr) {
  18419. var matched = attr.match(QUERY_REG);
  18420. if (!matched || !matched[1] || !matched[2]) {
  18421. return;
  18422. }
  18423. var operator = matched[1];
  18424. var realAttr = matched[2].toLowerCase();
  18425. if (!compare(realMap[realAttr], value, operator)) {
  18426. applicable = false;
  18427. }
  18428. });
  18429. return applicable;
  18430. }
  18431. function compare(real, expect, operator) {
  18432. if (operator === 'min') {
  18433. return real >= expect;
  18434. } else if (operator === 'max') {
  18435. return real <= expect;
  18436. } else {
  18437. // Equals
  18438. return real === expect;
  18439. }
  18440. }
  18441. function indicesEquals(indices1, indices2) {
  18442. // indices is always order by asc and has only finite number.
  18443. return indices1.join(',') === indices2.join(',');
  18444. }
  18445. var each$2 = each;
  18446. var isObject$1 = isObject;
  18447. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18448. function compatEC2ItemStyle(opt) {
  18449. var itemStyleOpt = opt && opt.itemStyle;
  18450. if (!itemStyleOpt) {
  18451. return;
  18452. }
  18453. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18454. var styleName = POSSIBLE_STYLES[i];
  18455. var normalItemStyleOpt = itemStyleOpt.normal;
  18456. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18457. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18458. if ("development" !== 'production') {
  18459. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18460. }
  18461. opt[styleName] = opt[styleName] || {};
  18462. if (!opt[styleName].normal) {
  18463. opt[styleName].normal = normalItemStyleOpt[styleName];
  18464. } else {
  18465. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18466. }
  18467. normalItemStyleOpt[styleName] = null;
  18468. }
  18469. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18470. if ("development" !== 'production') {
  18471. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18472. }
  18473. opt[styleName] = opt[styleName] || {};
  18474. if (!opt[styleName].emphasis) {
  18475. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18476. } else {
  18477. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18478. }
  18479. emphasisItemStyleOpt[styleName] = null;
  18480. }
  18481. }
  18482. }
  18483. function convertNormalEmphasis(opt, optType, useExtend) {
  18484. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18485. var normalOpt = opt[optType].normal;
  18486. var emphasisOpt = opt[optType].emphasis;
  18487. if (normalOpt) {
  18488. if ("development" !== 'production') {
  18489. // eslint-disable-next-line max-len
  18490. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18491. }
  18492. // Timeline controlStyle has other properties besides normal and emphasis
  18493. if (useExtend) {
  18494. opt[optType].normal = opt[optType].emphasis = null;
  18495. defaults(opt[optType], normalOpt);
  18496. } else {
  18497. opt[optType] = normalOpt;
  18498. }
  18499. }
  18500. if (emphasisOpt) {
  18501. if ("development" !== 'production') {
  18502. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18503. }
  18504. opt.emphasis = opt.emphasis || {};
  18505. opt.emphasis[optType] = emphasisOpt;
  18506. // Also compat the case user mix the style and focus together in ec3 style
  18507. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18508. if (emphasisOpt.focus) {
  18509. opt.emphasis.focus = emphasisOpt.focus;
  18510. }
  18511. if (emphasisOpt.blurScope) {
  18512. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18513. }
  18514. }
  18515. }
  18516. }
  18517. function removeEC3NormalStatus(opt) {
  18518. convertNormalEmphasis(opt, 'itemStyle');
  18519. convertNormalEmphasis(opt, 'lineStyle');
  18520. convertNormalEmphasis(opt, 'areaStyle');
  18521. convertNormalEmphasis(opt, 'label');
  18522. convertNormalEmphasis(opt, 'labelLine');
  18523. // treemap
  18524. convertNormalEmphasis(opt, 'upperLabel');
  18525. // graph
  18526. convertNormalEmphasis(opt, 'edgeLabel');
  18527. }
  18528. function compatTextStyle(opt, propName) {
  18529. // Check whether is not object (string\null\undefined ...)
  18530. var labelOptSingle = isObject$1(opt) && opt[propName];
  18531. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18532. if (textStyle) {
  18533. if ("development" !== 'production') {
  18534. // eslint-disable-next-line max-len
  18535. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18536. }
  18537. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18538. var textPropName = TEXT_STYLE_OPTIONS[i];
  18539. if (textStyle.hasOwnProperty(textPropName)) {
  18540. labelOptSingle[textPropName] = textStyle[textPropName];
  18541. }
  18542. }
  18543. }
  18544. }
  18545. function compatEC3CommonStyles(opt) {
  18546. if (opt) {
  18547. removeEC3NormalStatus(opt);
  18548. compatTextStyle(opt, 'label');
  18549. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18550. }
  18551. }
  18552. function processSeries(seriesOpt) {
  18553. if (!isObject$1(seriesOpt)) {
  18554. return;
  18555. }
  18556. compatEC2ItemStyle(seriesOpt);
  18557. removeEC3NormalStatus(seriesOpt);
  18558. compatTextStyle(seriesOpt, 'label');
  18559. // treemap
  18560. compatTextStyle(seriesOpt, 'upperLabel');
  18561. // graph
  18562. compatTextStyle(seriesOpt, 'edgeLabel');
  18563. if (seriesOpt.emphasis) {
  18564. compatTextStyle(seriesOpt.emphasis, 'label');
  18565. // treemap
  18566. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18567. // graph
  18568. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18569. }
  18570. var markPoint = seriesOpt.markPoint;
  18571. if (markPoint) {
  18572. compatEC2ItemStyle(markPoint);
  18573. compatEC3CommonStyles(markPoint);
  18574. }
  18575. var markLine = seriesOpt.markLine;
  18576. if (markLine) {
  18577. compatEC2ItemStyle(markLine);
  18578. compatEC3CommonStyles(markLine);
  18579. }
  18580. var markArea = seriesOpt.markArea;
  18581. if (markArea) {
  18582. compatEC3CommonStyles(markArea);
  18583. }
  18584. var data = seriesOpt.data;
  18585. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18586. // then the backward compat based on option type will not be performed.
  18587. if (seriesOpt.type === 'graph') {
  18588. data = data || seriesOpt.nodes;
  18589. var edgeData = seriesOpt.links || seriesOpt.edges;
  18590. if (edgeData && !isTypedArray(edgeData)) {
  18591. for (var i = 0; i < edgeData.length; i++) {
  18592. compatEC3CommonStyles(edgeData[i]);
  18593. }
  18594. }
  18595. each(seriesOpt.categories, function (opt) {
  18596. removeEC3NormalStatus(opt);
  18597. });
  18598. }
  18599. if (data && !isTypedArray(data)) {
  18600. for (var i = 0; i < data.length; i++) {
  18601. compatEC3CommonStyles(data[i]);
  18602. }
  18603. }
  18604. // mark point data
  18605. markPoint = seriesOpt.markPoint;
  18606. if (markPoint && markPoint.data) {
  18607. var mpData = markPoint.data;
  18608. for (var i = 0; i < mpData.length; i++) {
  18609. compatEC3CommonStyles(mpData[i]);
  18610. }
  18611. }
  18612. // mark line data
  18613. markLine = seriesOpt.markLine;
  18614. if (markLine && markLine.data) {
  18615. var mlData = markLine.data;
  18616. for (var i = 0; i < mlData.length; i++) {
  18617. if (isArray(mlData[i])) {
  18618. compatEC3CommonStyles(mlData[i][0]);
  18619. compatEC3CommonStyles(mlData[i][1]);
  18620. } else {
  18621. compatEC3CommonStyles(mlData[i]);
  18622. }
  18623. }
  18624. }
  18625. // Series
  18626. if (seriesOpt.type === 'gauge') {
  18627. compatTextStyle(seriesOpt, 'axisLabel');
  18628. compatTextStyle(seriesOpt, 'title');
  18629. compatTextStyle(seriesOpt, 'detail');
  18630. } else if (seriesOpt.type === 'treemap') {
  18631. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18632. each(seriesOpt.levels, function (opt) {
  18633. removeEC3NormalStatus(opt);
  18634. });
  18635. } else if (seriesOpt.type === 'tree') {
  18636. removeEC3NormalStatus(seriesOpt.leaves);
  18637. }
  18638. // sunburst starts from ec4, so it does not need to compat levels.
  18639. }
  18640. function toArr(o) {
  18641. return isArray(o) ? o : o ? [o] : [];
  18642. }
  18643. function toObj(o) {
  18644. return (isArray(o) ? o[0] : o) || {};
  18645. }
  18646. function globalCompatStyle(option, isTheme) {
  18647. each$2(toArr(option.series), function (seriesOpt) {
  18648. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18649. });
  18650. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18651. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18652. each$2(axes, function (axisName) {
  18653. each$2(toArr(option[axisName]), function (axisOpt) {
  18654. if (axisOpt) {
  18655. compatTextStyle(axisOpt, 'axisLabel');
  18656. compatTextStyle(axisOpt.axisPointer, 'label');
  18657. }
  18658. });
  18659. });
  18660. each$2(toArr(option.parallel), function (parallelOpt) {
  18661. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18662. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18663. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18664. });
  18665. each$2(toArr(option.calendar), function (calendarOpt) {
  18666. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18667. compatTextStyle(calendarOpt, 'dayLabel');
  18668. compatTextStyle(calendarOpt, 'monthLabel');
  18669. compatTextStyle(calendarOpt, 'yearLabel');
  18670. });
  18671. // radar.name.textStyle
  18672. each$2(toArr(option.radar), function (radarOpt) {
  18673. compatTextStyle(radarOpt, 'name');
  18674. // Use axisName instead of name because component has name property
  18675. if (radarOpt.name && radarOpt.axisName == null) {
  18676. radarOpt.axisName = radarOpt.name;
  18677. delete radarOpt.name;
  18678. if ("development" !== 'production') {
  18679. deprecateLog('name property in radar component has been changed to axisName');
  18680. }
  18681. }
  18682. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18683. radarOpt.axisNameGap = radarOpt.nameGap;
  18684. delete radarOpt.nameGap;
  18685. if ("development" !== 'production') {
  18686. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18687. }
  18688. }
  18689. if ("development" !== 'production') {
  18690. each$2(radarOpt.indicator, function (indicatorOpt) {
  18691. if (indicatorOpt.text) {
  18692. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18693. }
  18694. });
  18695. }
  18696. });
  18697. each$2(toArr(option.geo), function (geoOpt) {
  18698. if (isObject$1(geoOpt)) {
  18699. compatEC3CommonStyles(geoOpt);
  18700. each$2(toArr(geoOpt.regions), function (regionObj) {
  18701. compatEC3CommonStyles(regionObj);
  18702. });
  18703. }
  18704. });
  18705. each$2(toArr(option.timeline), function (timelineOpt) {
  18706. compatEC3CommonStyles(timelineOpt);
  18707. convertNormalEmphasis(timelineOpt, 'label');
  18708. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18709. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18710. var data = timelineOpt.data;
  18711. isArray(data) && each(data, function (item) {
  18712. if (isObject(item)) {
  18713. convertNormalEmphasis(item, 'label');
  18714. convertNormalEmphasis(item, 'itemStyle');
  18715. }
  18716. });
  18717. });
  18718. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18719. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18720. each$2(toolboxOpt.feature, function (featureOpt) {
  18721. convertNormalEmphasis(featureOpt, 'iconStyle');
  18722. });
  18723. });
  18724. compatTextStyle(toObj(option.axisPointer), 'label');
  18725. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18726. // Clean logs
  18727. // storedLogs = {};
  18728. }
  18729. function get(opt, path) {
  18730. var pathArr = path.split(',');
  18731. var obj = opt;
  18732. for (var i = 0; i < pathArr.length; i++) {
  18733. obj = obj && obj[pathArr[i]];
  18734. if (obj == null) {
  18735. break;
  18736. }
  18737. }
  18738. return obj;
  18739. }
  18740. function set$1(opt, path, val, overwrite) {
  18741. var pathArr = path.split(',');
  18742. var obj = opt;
  18743. var key;
  18744. var i = 0;
  18745. for (; i < pathArr.length - 1; i++) {
  18746. key = pathArr[i];
  18747. if (obj[key] == null) {
  18748. obj[key] = {};
  18749. }
  18750. obj = obj[key];
  18751. }
  18752. if (overwrite || obj[pathArr[i]] == null) {
  18753. obj[pathArr[i]] = val;
  18754. }
  18755. }
  18756. function compatLayoutProperties(option) {
  18757. option && each(LAYOUT_PROPERTIES, function (prop) {
  18758. if (prop[0] in option && !(prop[1] in option)) {
  18759. option[prop[1]] = option[prop[0]];
  18760. }
  18761. });
  18762. }
  18763. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18764. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18765. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18766. function compatBarItemStyle(option) {
  18767. var itemStyle = option && option.itemStyle;
  18768. if (itemStyle) {
  18769. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18770. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18771. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18772. if (itemStyle[oldName] != null) {
  18773. itemStyle[newName] = itemStyle[oldName];
  18774. if ("development" !== 'production') {
  18775. deprecateReplaceLog(oldName, newName);
  18776. }
  18777. }
  18778. }
  18779. }
  18780. }
  18781. function compatPieLabel(option) {
  18782. if (!option) {
  18783. return;
  18784. }
  18785. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18786. if ("development" !== 'production') {
  18787. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18788. }
  18789. option.edgeDistance = option.margin;
  18790. }
  18791. }
  18792. function compatSunburstState(option) {
  18793. if (!option) {
  18794. return;
  18795. }
  18796. if (option.downplay && !option.blur) {
  18797. option.blur = option.downplay;
  18798. if ("development" !== 'production') {
  18799. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18800. }
  18801. }
  18802. }
  18803. function compatGraphFocus(option) {
  18804. if (!option) {
  18805. return;
  18806. }
  18807. if (option.focusNodeAdjacency != null) {
  18808. option.emphasis = option.emphasis || {};
  18809. if (option.emphasis.focus == null) {
  18810. if ("development" !== 'production') {
  18811. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18812. }
  18813. option.emphasis.focus = 'adjacency';
  18814. }
  18815. }
  18816. }
  18817. function traverseTree(data, cb) {
  18818. if (data) {
  18819. for (var i = 0; i < data.length; i++) {
  18820. cb(data[i]);
  18821. data[i] && traverseTree(data[i].children, cb);
  18822. }
  18823. }
  18824. }
  18825. function globalBackwardCompat(option, isTheme) {
  18826. globalCompatStyle(option, isTheme);
  18827. // Make sure series array for model initialization.
  18828. option.series = normalizeToArray(option.series);
  18829. each(option.series, function (seriesOpt) {
  18830. if (!isObject(seriesOpt)) {
  18831. return;
  18832. }
  18833. var seriesType = seriesOpt.type;
  18834. if (seriesType === 'line') {
  18835. if (seriesOpt.clipOverflow != null) {
  18836. seriesOpt.clip = seriesOpt.clipOverflow;
  18837. if ("development" !== 'production') {
  18838. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18839. }
  18840. }
  18841. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18842. if (seriesOpt.clockWise != null) {
  18843. seriesOpt.clockwise = seriesOpt.clockWise;
  18844. if ("development" !== 'production') {
  18845. deprecateReplaceLog('clockWise', 'clockwise');
  18846. }
  18847. }
  18848. compatPieLabel(seriesOpt.label);
  18849. var data = seriesOpt.data;
  18850. if (data && !isTypedArray(data)) {
  18851. for (var i = 0; i < data.length; i++) {
  18852. compatPieLabel(data[i]);
  18853. }
  18854. }
  18855. if (seriesOpt.hoverOffset != null) {
  18856. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18857. if (seriesOpt.emphasis.scaleSize = null) {
  18858. if ("development" !== 'production') {
  18859. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18860. }
  18861. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18862. }
  18863. }
  18864. } else if (seriesType === 'gauge') {
  18865. var pointerColor = get(seriesOpt, 'pointer.color');
  18866. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18867. } else if (seriesType === 'bar') {
  18868. compatBarItemStyle(seriesOpt);
  18869. compatBarItemStyle(seriesOpt.backgroundStyle);
  18870. compatBarItemStyle(seriesOpt.emphasis);
  18871. var data = seriesOpt.data;
  18872. if (data && !isTypedArray(data)) {
  18873. for (var i = 0; i < data.length; i++) {
  18874. if (typeof data[i] === 'object') {
  18875. compatBarItemStyle(data[i]);
  18876. compatBarItemStyle(data[i] && data[i].emphasis);
  18877. }
  18878. }
  18879. }
  18880. } else if (seriesType === 'sunburst') {
  18881. var highlightPolicy = seriesOpt.highlightPolicy;
  18882. if (highlightPolicy) {
  18883. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18884. if (!seriesOpt.emphasis.focus) {
  18885. seriesOpt.emphasis.focus = highlightPolicy;
  18886. if ("development" !== 'production') {
  18887. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18888. }
  18889. }
  18890. }
  18891. compatSunburstState(seriesOpt);
  18892. traverseTree(seriesOpt.data, compatSunburstState);
  18893. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18894. compatGraphFocus(seriesOpt);
  18895. // TODO nodes, edges?
  18896. } else if (seriesType === 'map') {
  18897. if (seriesOpt.mapType && !seriesOpt.map) {
  18898. if ("development" !== 'production') {
  18899. deprecateReplaceLog('mapType', 'map', 'map');
  18900. }
  18901. seriesOpt.map = seriesOpt.mapType;
  18902. }
  18903. if (seriesOpt.mapLocation) {
  18904. if ("development" !== 'production') {
  18905. deprecateLog('`mapLocation` is not used anymore.');
  18906. }
  18907. defaults(seriesOpt, seriesOpt.mapLocation);
  18908. }
  18909. }
  18910. if (seriesOpt.hoverAnimation != null) {
  18911. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18912. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18913. if ("development" !== 'production') {
  18914. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18915. }
  18916. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18917. }
  18918. }
  18919. compatLayoutProperties(seriesOpt);
  18920. });
  18921. // dataRange has changed to visualMap
  18922. if (option.dataRange) {
  18923. option.visualMap = option.dataRange;
  18924. }
  18925. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18926. var options = option[componentName];
  18927. if (options) {
  18928. if (!isArray(options)) {
  18929. options = [options];
  18930. }
  18931. each(options, function (option) {
  18932. compatLayoutProperties(option);
  18933. });
  18934. }
  18935. });
  18936. }
  18937. // (1) [Caution]: the logic is correct based on the premises:
  18938. // data processing stage is blocked in stream.
  18939. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18940. // (2) Only register once when import repeatedly.
  18941. // Should be executed after series is filtered and before stack calculation.
  18942. function dataStack(ecModel) {
  18943. var stackInfoMap = createHashMap();
  18944. ecModel.eachSeries(function (seriesModel) {
  18945. var stack = seriesModel.get('stack');
  18946. // Compatible: when `stack` is set as '', do not stack.
  18947. if (stack) {
  18948. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18949. var data = seriesModel.getData();
  18950. var stackInfo = {
  18951. // Used for calculate axis extent automatically.
  18952. // TODO: Type getCalculationInfo return more specific type?
  18953. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18954. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18955. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18956. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18957. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18958. data: data,
  18959. seriesModel: seriesModel
  18960. };
  18961. // If stacked on axis that do not support data stack.
  18962. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18963. return;
  18964. }
  18965. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18966. stackInfoList.push(stackInfo);
  18967. }
  18968. });
  18969. stackInfoMap.each(calculateStack);
  18970. }
  18971. function calculateStack(stackInfoList) {
  18972. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18973. var resultVal = [];
  18974. var resultNaN = [NaN, NaN];
  18975. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18976. var targetData = targetStackInfo.data;
  18977. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18978. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign';
  18979. // Should not write on raw data, because stack series model list changes
  18980. // depending on legend selection.
  18981. targetData.modify(dims, function (v0, v1, dataIndex) {
  18982. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  18983. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18984. // should also be NaN, to draw a appropriate belt area.
  18985. if (isNaN(sum)) {
  18986. return resultNaN;
  18987. }
  18988. var byValue;
  18989. var stackedDataRawIndex;
  18990. if (isStackedByIndex) {
  18991. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18992. } else {
  18993. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18994. }
  18995. // If stackOver is NaN, chart view will render point on value start.
  18996. var stackedOver = NaN;
  18997. for (var j = idxInStack - 1; j >= 0; j--) {
  18998. var stackInfo = stackInfoList[j];
  18999. // Has been optimized by inverted indices on `stackedByDimension`.
  19000. if (!isStackedByIndex) {
  19001. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19002. }
  19003. if (stackedDataRawIndex >= 0) {
  19004. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19005. // Considering positive stack, negative stack and empty data
  19006. if (stackStrategy === 'all' // single stack group
  19007. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  19008. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  19009. ) {
  19010. // The sum has to be very small to be affected by the
  19011. // floating arithmetic problem. An incorrect result will probably
  19012. // cause axis min/max to be filtered incorrectly.
  19013. sum = addSafe(sum, val);
  19014. stackedOver = val;
  19015. break;
  19016. }
  19017. }
  19018. }
  19019. resultVal[0] = sum;
  19020. resultVal[1] = stackedOver;
  19021. return resultVal;
  19022. });
  19023. });
  19024. }
  19025. // @inner
  19026. var SourceImpl = /** @class */function () {
  19027. function SourceImpl(fields) {
  19028. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  19029. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  19030. // Visit config
  19031. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  19032. this.startIndex = fields.startIndex || 0;
  19033. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  19034. this.metaRawOption = fields.metaRawOption;
  19035. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  19036. if (dimensionsDefine) {
  19037. for (var i = 0; i < dimensionsDefine.length; i++) {
  19038. var dim = dimensionsDefine[i];
  19039. if (dim.type == null) {
  19040. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  19041. dim.type = 'ordinal';
  19042. }
  19043. }
  19044. }
  19045. }
  19046. }
  19047. return SourceImpl;
  19048. }();
  19049. function isSourceInstance(val) {
  19050. return val instanceof SourceImpl;
  19051. }
  19052. /**
  19053. * Create a source from option.
  19054. * NOTE: Created source is immutable. Don't change any properties in it.
  19055. */
  19056. function createSource(sourceData, thisMetaRawOption,
  19057. // can be null. If not provided, auto detect it from `sourceData`.
  19058. sourceFormat) {
  19059. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  19060. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  19061. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  19062. var source = new SourceImpl({
  19063. data: sourceData,
  19064. sourceFormat: sourceFormat,
  19065. seriesLayoutBy: seriesLayoutBy,
  19066. dimensionsDefine: determined.dimensionsDefine,
  19067. startIndex: determined.startIndex,
  19068. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  19069. metaRawOption: clone(thisMetaRawOption)
  19070. });
  19071. return source;
  19072. }
  19073. /**
  19074. * Wrap original series data for some compatibility cases.
  19075. */
  19076. function createSourceFromSeriesDataOption(data) {
  19077. return new SourceImpl({
  19078. data: data,
  19079. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  19080. });
  19081. }
  19082. /**
  19083. * Clone source but excludes source data.
  19084. */
  19085. function cloneSourceShallow(source) {
  19086. return new SourceImpl({
  19087. data: source.data,
  19088. sourceFormat: source.sourceFormat,
  19089. seriesLayoutBy: source.seriesLayoutBy,
  19090. dimensionsDefine: clone(source.dimensionsDefine),
  19091. startIndex: source.startIndex,
  19092. dimensionsDetectedCount: source.dimensionsDetectedCount
  19093. });
  19094. }
  19095. /**
  19096. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  19097. */
  19098. function detectSourceFormat(data) {
  19099. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  19100. if (isTypedArray(data)) {
  19101. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  19102. } else if (isArray(data)) {
  19103. // FIXME Whether tolerate null in top level array?
  19104. if (data.length === 0) {
  19105. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19106. }
  19107. for (var i = 0, len = data.length; i < len; i++) {
  19108. var item = data[i];
  19109. if (item == null) {
  19110. continue;
  19111. } else if (isArray(item) || isTypedArray(item)) {
  19112. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19113. break;
  19114. } else if (isObject(item)) {
  19115. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  19116. break;
  19117. }
  19118. }
  19119. } else if (isObject(data)) {
  19120. for (var key in data) {
  19121. if (hasOwn(data, key) && isArrayLike(data[key])) {
  19122. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  19123. break;
  19124. }
  19125. }
  19126. }
  19127. return sourceFormat;
  19128. }
  19129. /**
  19130. * Determine the source definitions from data standalone dimensions definitions
  19131. * are not specified.
  19132. */
  19133. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader,
  19134. // standalone raw dimensions definition, like:
  19135. // {
  19136. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  19137. // }
  19138. // in `dataset` or `series`
  19139. dimensionsDefine) {
  19140. var dimensionsDetectedCount;
  19141. var startIndex;
  19142. // PENDING: Could data be null/undefined here?
  19143. // currently, if `dataset.source` not specified, error thrown.
  19144. // if `series.data` not specified, nothing rendered without error thrown.
  19145. // Should test these cases.
  19146. if (!data) {
  19147. return {
  19148. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19149. startIndex: startIndex,
  19150. dimensionsDetectedCount: dimensionsDetectedCount
  19151. };
  19152. }
  19153. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19154. var dataArrayRows = data;
  19155. // Rule: Most of the first line are string: it is header.
  19156. // Caution: consider a line with 5 string and 1 number,
  19157. // it still can not be sure it is a head, because the
  19158. // 5 string may be 5 values of category columns.
  19159. if (sourceHeader === 'auto' || sourceHeader == null) {
  19160. arrayRowsTravelFirst(function (val) {
  19161. // '-' is regarded as null/undefined.
  19162. if (val != null && val !== '-') {
  19163. if (isString(val)) {
  19164. startIndex == null && (startIndex = 1);
  19165. } else {
  19166. startIndex = 0;
  19167. }
  19168. }
  19169. // 10 is an experience number, avoid long loop.
  19170. }, seriesLayoutBy, dataArrayRows, 10);
  19171. } else {
  19172. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  19173. }
  19174. if (!dimensionsDefine && startIndex === 1) {
  19175. dimensionsDefine = [];
  19176. arrayRowsTravelFirst(function (val, index) {
  19177. dimensionsDefine[index] = val != null ? val + '' : '';
  19178. }, seriesLayoutBy, dataArrayRows, Infinity);
  19179. }
  19180. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  19181. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19182. if (!dimensionsDefine) {
  19183. dimensionsDefine = objectRowsCollectDimensions(data);
  19184. }
  19185. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  19186. if (!dimensionsDefine) {
  19187. dimensionsDefine = [];
  19188. each(data, function (colArr, key) {
  19189. dimensionsDefine.push(key);
  19190. });
  19191. }
  19192. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19193. var value0 = getDataItemValue(data[0]);
  19194. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  19195. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19196. if ("development" !== 'production') {
  19197. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  19198. }
  19199. }
  19200. return {
  19201. startIndex: startIndex,
  19202. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19203. dimensionsDetectedCount: dimensionsDetectedCount
  19204. };
  19205. }
  19206. function objectRowsCollectDimensions(data) {
  19207. var firstIndex = 0;
  19208. var obj;
  19209. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  19210. if (obj) {
  19211. return keys(obj);
  19212. }
  19213. }
  19214. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  19215. // which is reasonable. But dimension name is duplicated.
  19216. // Returns undefined or an array contains only object without null/undefined or string.
  19217. function normalizeDimensionsOption(dimensionsDefine) {
  19218. if (!dimensionsDefine) {
  19219. // The meaning of null/undefined is different from empty array.
  19220. return;
  19221. }
  19222. var nameMap = createHashMap();
  19223. return map(dimensionsDefine, function (rawItem, index) {
  19224. rawItem = isObject(rawItem) ? rawItem : {
  19225. name: rawItem
  19226. };
  19227. // Other fields will be discarded.
  19228. var item = {
  19229. name: rawItem.name,
  19230. displayName: rawItem.displayName,
  19231. type: rawItem.type
  19232. };
  19233. // User can set null in dimensions.
  19234. // We don't auto specify name, otherwise a given name may
  19235. // cause it to be referred unexpectedly.
  19236. if (item.name == null) {
  19237. return item;
  19238. }
  19239. // Also consider number form like 2012.
  19240. item.name += '';
  19241. // User may also specify displayName.
  19242. // displayName will always exists except user not
  19243. // specified or dim name is not specified or detected.
  19244. // (A auto generated dim name will not be used as
  19245. // displayName).
  19246. if (item.displayName == null) {
  19247. item.displayName = item.name;
  19248. }
  19249. var exist = nameMap.get(item.name);
  19250. if (!exist) {
  19251. nameMap.set(item.name, {
  19252. count: 1
  19253. });
  19254. } else {
  19255. item.name += '-' + exist.count++;
  19256. }
  19257. return item;
  19258. });
  19259. }
  19260. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  19261. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  19262. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19263. cb(data[i] ? data[i][0] : null, i);
  19264. }
  19265. } else {
  19266. var value0 = data[0] || [];
  19267. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  19268. cb(value0[i], i);
  19269. }
  19270. }
  19271. }
  19272. function shouldRetrieveDataByName(source) {
  19273. var sourceFormat = source.sourceFormat;
  19274. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  19275. }
  19276. /*
  19277. * Licensed to the Apache Software Foundation (ASF) under one
  19278. * or more contributor license agreements. See the NOTICE file
  19279. * distributed with this work for additional information
  19280. * regarding copyright ownership. The ASF licenses this file
  19281. * to you under the Apache License, Version 2.0 (the
  19282. * "License"); you may not use this file except in compliance
  19283. * with the License. You may obtain a copy of the License at
  19284. *
  19285. * http://www.apache.org/licenses/LICENSE-2.0
  19286. *
  19287. * Unless required by applicable law or agreed to in writing,
  19288. * software distributed under the License is distributed on an
  19289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19290. * KIND, either express or implied. See the License for the
  19291. * specific language governing permissions and limitations
  19292. * under the License.
  19293. */
  19294. /**
  19295. * AUTO-GENERATED FILE. DO NOT MODIFY.
  19296. */
  19297. /*
  19298. * Licensed to the Apache Software Foundation (ASF) under one
  19299. * or more contributor license agreements. See the NOTICE file
  19300. * distributed with this work for additional information
  19301. * regarding copyright ownership. The ASF licenses this file
  19302. * to you under the Apache License, Version 2.0 (the
  19303. * "License"); you may not use this file except in compliance
  19304. * with the License. You may obtain a copy of the License at
  19305. *
  19306. * http://www.apache.org/licenses/LICENSE-2.0
  19307. *
  19308. * Unless required by applicable law or agreed to in writing,
  19309. * software distributed under the License is distributed on an
  19310. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19311. * KIND, either express or implied. See the License for the
  19312. * specific language governing permissions and limitations
  19313. * under the License.
  19314. */
  19315. var _a, _b, _c;
  19316. var providerMethods;
  19317. var mountMethods;
  19318. /**
  19319. * If normal array used, mutable chunk size is supported.
  19320. * If typed array used, chunk size must be fixed.
  19321. */
  19322. var DefaultDataProvider = /** @class */function () {
  19323. function DefaultDataProvider(sourceParam, dimSize) {
  19324. // let source: Source;
  19325. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam;
  19326. // declare source is Source;
  19327. this._source = source;
  19328. var data = this._data = source.data;
  19329. // Typed array. TODO IE10+?
  19330. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19331. if ("development" !== 'production') {
  19332. if (dimSize == null) {
  19333. throw new Error('Typed array data must specify dimension size');
  19334. }
  19335. }
  19336. this._offset = 0;
  19337. this._dimSize = dimSize;
  19338. this._data = data;
  19339. }
  19340. mountMethods(this, data, source);
  19341. }
  19342. DefaultDataProvider.prototype.getSource = function () {
  19343. return this._source;
  19344. };
  19345. DefaultDataProvider.prototype.count = function () {
  19346. return 0;
  19347. };
  19348. DefaultDataProvider.prototype.getItem = function (idx, out) {
  19349. return;
  19350. };
  19351. DefaultDataProvider.prototype.appendData = function (newData) {};
  19352. DefaultDataProvider.prototype.clean = function () {};
  19353. DefaultDataProvider.protoInitialize = function () {
  19354. // PENDING: To avoid potential incompat (e.g., prototype
  19355. // is visited somewhere), still init them on prototype.
  19356. var proto = DefaultDataProvider.prototype;
  19357. proto.pure = false;
  19358. proto.persistent = true;
  19359. }();
  19360. DefaultDataProvider.internalField = function () {
  19361. var _a;
  19362. mountMethods = function (provider, data, source) {
  19363. var sourceFormat = source.sourceFormat;
  19364. var seriesLayoutBy = source.seriesLayoutBy;
  19365. var startIndex = source.startIndex;
  19366. var dimsDef = source.dimensionsDefine;
  19367. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19368. if ("development" !== 'production') {
  19369. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19370. }
  19371. extend(provider, methods);
  19372. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19373. provider.getItem = getItemForTypedArray;
  19374. provider.count = countForTypedArray;
  19375. provider.fillStorage = fillStorageForTypedArray;
  19376. } else {
  19377. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  19378. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  19379. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  19380. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  19381. }
  19382. };
  19383. var getItemForTypedArray = function (idx, out) {
  19384. idx = idx - this._offset;
  19385. out = out || [];
  19386. var data = this._data;
  19387. var dimSize = this._dimSize;
  19388. var offset = dimSize * idx;
  19389. for (var i = 0; i < dimSize; i++) {
  19390. out[i] = data[offset + i];
  19391. }
  19392. return out;
  19393. };
  19394. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19395. var data = this._data;
  19396. var dimSize = this._dimSize;
  19397. for (var dim = 0; dim < dimSize; dim++) {
  19398. var dimExtent = extent[dim];
  19399. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19400. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19401. var count = end - start;
  19402. var arr = storage[dim];
  19403. for (var i = 0; i < count; i++) {
  19404. // appendData with TypedArray will always do replace in provider.
  19405. var val = data[i * dimSize + dim];
  19406. arr[start + i] = val;
  19407. val < min && (min = val);
  19408. val > max && (max = val);
  19409. }
  19410. dimExtent[0] = min;
  19411. dimExtent[1] = max;
  19412. }
  19413. };
  19414. var countForTypedArray = function () {
  19415. return this._data ? this._data.length / this._dimSize : 0;
  19416. };
  19417. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19418. pure: true,
  19419. appendData: appendDataSimply
  19420. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19421. pure: true,
  19422. appendData: function () {
  19423. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19424. }
  19425. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19426. pure: true,
  19427. appendData: appendDataSimply
  19428. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19429. pure: true,
  19430. appendData: function (newData) {
  19431. var data = this._data;
  19432. each(newData, function (newCol, key) {
  19433. var oldCol = data[key] || (data[key] = []);
  19434. for (var i = 0; i < (newCol || []).length; i++) {
  19435. oldCol.push(newCol[i]);
  19436. }
  19437. });
  19438. }
  19439. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19440. appendData: appendDataSimply
  19441. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19442. persistent: false,
  19443. pure: true,
  19444. appendData: function (newData) {
  19445. if ("development" !== 'production') {
  19446. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19447. }
  19448. this._data = newData;
  19449. },
  19450. // Clean self if data is already used.
  19451. clean: function () {
  19452. // PENDING
  19453. this._offset += this.count();
  19454. this._data = null;
  19455. }
  19456. }, _a);
  19457. function appendDataSimply(newData) {
  19458. for (var i = 0; i < newData.length; i++) {
  19459. this._data.push(newData[i]);
  19460. }
  19461. }
  19462. }();
  19463. return DefaultDataProvider;
  19464. }();
  19465. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19466. return rawData[idx];
  19467. };
  19468. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19469. return rawData[idx + startIndex];
  19470. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19471. idx += startIndex;
  19472. var item = out || [];
  19473. var data = rawData;
  19474. for (var i = 0; i < data.length; i++) {
  19475. var row = data[i];
  19476. item[i] = row ? row[idx] : null;
  19477. }
  19478. return item;
  19479. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19480. var item = out || [];
  19481. for (var i = 0; i < dimsDef.length; i++) {
  19482. var dimName = dimsDef[i].name;
  19483. if ("development" !== 'production') {
  19484. if (dimName == null) {
  19485. throw new Error();
  19486. }
  19487. }
  19488. var col = rawData[dimName];
  19489. item[i] = col ? col[idx] : null;
  19490. }
  19491. return item;
  19492. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19493. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19494. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19495. if ("development" !== 'production') {
  19496. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19497. }
  19498. return method;
  19499. }
  19500. var countSimply = function (rawData, startIndex, dimsDef) {
  19501. return rawData.length;
  19502. };
  19503. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19504. return Math.max(0, rawData.length - startIndex);
  19505. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19506. var row = rawData[0];
  19507. return row ? Math.max(0, row.length - startIndex) : 0;
  19508. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19509. var dimName = dimsDef[0].name;
  19510. if ("development" !== 'production') {
  19511. if (dimName == null) {
  19512. throw new Error();
  19513. }
  19514. }
  19515. var col = rawData[dimName];
  19516. return col ? col.length : 0;
  19517. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19518. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19519. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19520. if ("development" !== 'production') {
  19521. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19522. }
  19523. return method;
  19524. }
  19525. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19526. return dataItem[dimIndex];
  19527. };
  19528. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19529. return dataItem[property];
  19530. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19531. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19532. // dataItem is {coord: [...]}
  19533. var value = getDataItemValue(dataItem);
  19534. return !(value instanceof Array) ? value : value[dimIndex];
  19535. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19536. function getRawSourceValueGetter(sourceFormat) {
  19537. var method = rawSourceValueGetterMap[sourceFormat];
  19538. if ("development" !== 'production') {
  19539. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19540. }
  19541. return method;
  19542. }
  19543. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19544. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19545. }
  19546. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19547. // Consider persistent.
  19548. // Caution: why use raw value to display on label or tooltip?
  19549. // A reason is to avoid format. For example time value we do not know
  19550. // how to format is expected. More over, if stack is used, calculated
  19551. // value may be 0.91000000001, which have brings trouble to display.
  19552. // TODO: consider how to treat null/undefined/NaN when display?
  19553. function retrieveRawValue(data, dataIndex,
  19554. // If dimIndex is null/undefined, return OptionDataItem.
  19555. // Otherwise, return OptionDataValue.
  19556. dim) {
  19557. if (!data) {
  19558. return;
  19559. }
  19560. // Consider data may be not persistent.
  19561. var dataItem = data.getRawDataItem(dataIndex);
  19562. if (dataItem == null) {
  19563. return;
  19564. }
  19565. var store = data.getStore();
  19566. var sourceFormat = store.getSource().sourceFormat;
  19567. if (dim != null) {
  19568. var dimIndex = data.getDimensionIndex(dim);
  19569. var property = store.getDimensionProperty(dimIndex);
  19570. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19571. } else {
  19572. var result = dataItem;
  19573. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19574. result = getDataItemValue(dataItem);
  19575. }
  19576. return result;
  19577. }
  19578. }
  19579. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19580. var DataFormatMixin = /** @class */function () {
  19581. function DataFormatMixin() {}
  19582. /**
  19583. * Get params for formatter
  19584. */
  19585. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19586. var data = this.getData(dataType);
  19587. var rawValue = this.getRawValue(dataIndex, dataType);
  19588. var rawDataIndex = data.getRawIndex(dataIndex);
  19589. var name = data.getName(dataIndex);
  19590. var itemOpt = data.getRawDataItem(dataIndex);
  19591. var style = data.getItemVisual(dataIndex, 'style');
  19592. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19593. var borderColor = style && style.stroke;
  19594. var mainType = this.mainType;
  19595. var isSeries = mainType === 'series';
  19596. var userOutput = data.userOutput && data.userOutput.get();
  19597. return {
  19598. componentType: mainType,
  19599. componentSubType: this.subType,
  19600. componentIndex: this.componentIndex,
  19601. seriesType: isSeries ? this.subType : null,
  19602. seriesIndex: this.seriesIndex,
  19603. seriesId: isSeries ? this.id : null,
  19604. seriesName: isSeries ? this.name : null,
  19605. name: name,
  19606. dataIndex: rawDataIndex,
  19607. data: itemOpt,
  19608. dataType: dataType,
  19609. value: rawValue,
  19610. color: color,
  19611. borderColor: borderColor,
  19612. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19613. encode: userOutput ? userOutput.encode : null,
  19614. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19615. $vars: ['seriesName', 'name', 'value']
  19616. };
  19617. };
  19618. /**
  19619. * Format label
  19620. * @param dataIndex
  19621. * @param status 'normal' by default
  19622. * @param dataType
  19623. * @param labelDimIndex Only used in some chart that
  19624. * use formatter in different dimensions, like radar.
  19625. * @param formatter Formatter given outside.
  19626. * @return return null/undefined if no formatter
  19627. */
  19628. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19629. status = status || 'normal';
  19630. var data = this.getData(dataType);
  19631. var params = this.getDataParams(dataIndex, dataType);
  19632. if (extendParams) {
  19633. params.value = extendParams.interpolatedValue;
  19634. }
  19635. if (labelDimIndex != null && isArray(params.value)) {
  19636. params.value = params.value[labelDimIndex];
  19637. }
  19638. if (!formatter) {
  19639. var itemModel = data.getItemModel(dataIndex);
  19640. // @ts-ignore
  19641. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19642. }
  19643. if (isFunction(formatter)) {
  19644. params.status = status;
  19645. params.dimensionIndex = labelDimIndex;
  19646. return formatter(params);
  19647. } else if (isString(formatter)) {
  19648. var str = formatTpl(formatter, params);
  19649. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19650. // Do not support '}' in dim name util have to.
  19651. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19652. var len = dimStr.length;
  19653. var dimLoose = dimStr;
  19654. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19655. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19656. if ("development" !== 'production') {
  19657. if (isNaN(dimLoose)) {
  19658. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19659. }
  19660. }
  19661. }
  19662. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19663. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19664. var dimIndex = data.getDimensionIndex(dimLoose);
  19665. if (dimIndex >= 0) {
  19666. val = extendParams.interpolatedValue[dimIndex];
  19667. }
  19668. }
  19669. return val != null ? val + '' : '';
  19670. });
  19671. }
  19672. };
  19673. /**
  19674. * Get raw value in option
  19675. */
  19676. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19677. return retrieveRawValue(this.getData(dataType), idx);
  19678. };
  19679. /**
  19680. * Should be implemented.
  19681. * @param {number} dataIndex
  19682. * @param {boolean} [multipleSeries=false]
  19683. * @param {string} [dataType]
  19684. */
  19685. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19686. // Empty function
  19687. return;
  19688. };
  19689. return DataFormatMixin;
  19690. }();
  19691. // PENDING: previously we accept this type when calling `formatTooltip`,
  19692. // but guess little chance has been used outside. Do we need to backward
  19693. // compat it?
  19694. // type TooltipFormatResultLegacyObject = {
  19695. // // `html` means the markup language text, either in 'html' or 'richText'.
  19696. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  19697. // // string. But still support it for backward compatibility.
  19698. // html: string;
  19699. // markers: Dictionary<ColorString>;
  19700. // };
  19701. /**
  19702. * For backward compat, normalize the return from `formatTooltip`.
  19703. */
  19704. function normalizeTooltipFormatResult(result) {
  19705. var markupText;
  19706. // let markers: Dictionary<ColorString>;
  19707. var markupFragment;
  19708. if (isObject(result)) {
  19709. if (result.type) {
  19710. markupFragment = result;
  19711. } else {
  19712. if ("development" !== 'production') {
  19713. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19714. }
  19715. }
  19716. // else {
  19717. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19718. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19719. // if (markersExisting) {
  19720. // markers = zrUtil.merge(markersExisting, markers);
  19721. // }
  19722. // }
  19723. } else {
  19724. markupText = result;
  19725. }
  19726. return {
  19727. text: markupText,
  19728. // markers: markers || markersExisting,
  19729. frag: markupFragment
  19730. };
  19731. }
  19732. /**
  19733. * @param {Object} define
  19734. * @return See the return of `createTask`.
  19735. */
  19736. function createTask(define) {
  19737. return new Task(define);
  19738. }
  19739. var Task = /** @class */function () {
  19740. function Task(define) {
  19741. define = define || {};
  19742. this._reset = define.reset;
  19743. this._plan = define.plan;
  19744. this._count = define.count;
  19745. this._onDirty = define.onDirty;
  19746. this._dirty = true;
  19747. }
  19748. /**
  19749. * @param step Specified step.
  19750. * @param skip Skip customer perform call.
  19751. * @param modBy Sampling window size.
  19752. * @param modDataCount Sampling count.
  19753. * @return whether unfinished.
  19754. */
  19755. Task.prototype.perform = function (performArgs) {
  19756. var upTask = this._upstream;
  19757. var skip = performArgs && performArgs.skip;
  19758. // TODO some refactor.
  19759. // Pull data. Must pull data each time, because context.data
  19760. // may be updated by Series.setData.
  19761. if (this._dirty && upTask) {
  19762. var context = this.context;
  19763. context.data = context.outputData = upTask.context.outputData;
  19764. }
  19765. if (this.__pipeline) {
  19766. this.__pipeline.currentTask = this;
  19767. }
  19768. var planResult;
  19769. if (this._plan && !skip) {
  19770. planResult = this._plan(this.context);
  19771. }
  19772. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19773. // elements uniformed distributed when progress, especially when moving or zooming.
  19774. var lastModBy = normalizeModBy(this._modBy);
  19775. var lastModDataCount = this._modDataCount || 0;
  19776. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19777. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19778. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19779. planResult = 'reset';
  19780. }
  19781. function normalizeModBy(val) {
  19782. !(val >= 1) && (val = 1); // jshint ignore:line
  19783. return val;
  19784. }
  19785. var forceFirstProgress;
  19786. if (this._dirty || planResult === 'reset') {
  19787. this._dirty = false;
  19788. forceFirstProgress = this._doReset(skip);
  19789. }
  19790. this._modBy = modBy;
  19791. this._modDataCount = modDataCount;
  19792. var step = performArgs && performArgs.step;
  19793. if (upTask) {
  19794. if ("development" !== 'production') {
  19795. assert(upTask._outputDueEnd != null);
  19796. }
  19797. this._dueEnd = upTask._outputDueEnd;
  19798. }
  19799. // DataTask or overallTask
  19800. else {
  19801. if ("development" !== 'production') {
  19802. assert(!this._progress || this._count);
  19803. }
  19804. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19805. }
  19806. // Note: Stubs, that its host overall task let it has progress, has progress.
  19807. // If no progress, pass index from upstream to downstream each time plan called.
  19808. if (this._progress) {
  19809. var start = this._dueIndex;
  19810. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19811. if (!skip && (forceFirstProgress || start < end)) {
  19812. var progress = this._progress;
  19813. if (isArray(progress)) {
  19814. for (var i = 0; i < progress.length; i++) {
  19815. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19816. }
  19817. } else {
  19818. this._doProgress(progress, start, end, modBy, modDataCount);
  19819. }
  19820. }
  19821. this._dueIndex = end;
  19822. // If no `outputDueEnd`, assume that output data and
  19823. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19824. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19825. if ("development" !== 'production') {
  19826. // ??? Can not rollback.
  19827. assert(outputDueEnd >= this._outputDueEnd);
  19828. }
  19829. this._outputDueEnd = outputDueEnd;
  19830. } else {
  19831. // (1) Some overall task has no progress.
  19832. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19833. // This should always be performed so it can be passed to downstream.
  19834. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19835. }
  19836. return this.unfinished();
  19837. };
  19838. Task.prototype.dirty = function () {
  19839. this._dirty = true;
  19840. this._onDirty && this._onDirty(this.context);
  19841. };
  19842. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19843. iterator.reset(start, end, modBy, modDataCount);
  19844. this._callingProgress = progress;
  19845. this._callingProgress({
  19846. start: start,
  19847. end: end,
  19848. count: end - start,
  19849. next: iterator.next
  19850. }, this.context);
  19851. };
  19852. Task.prototype._doReset = function (skip) {
  19853. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19854. this._settedOutputEnd = null;
  19855. var progress;
  19856. var forceFirstProgress;
  19857. if (!skip && this._reset) {
  19858. progress = this._reset(this.context);
  19859. if (progress && progress.progress) {
  19860. forceFirstProgress = progress.forceFirstProgress;
  19861. progress = progress.progress;
  19862. }
  19863. // To simplify no progress checking, array must has item.
  19864. if (isArray(progress) && !progress.length) {
  19865. progress = null;
  19866. }
  19867. }
  19868. this._progress = progress;
  19869. this._modBy = this._modDataCount = null;
  19870. var downstream = this._downstream;
  19871. downstream && downstream.dirty();
  19872. return forceFirstProgress;
  19873. };
  19874. Task.prototype.unfinished = function () {
  19875. return this._progress && this._dueIndex < this._dueEnd;
  19876. };
  19877. /**
  19878. * @param downTask The downstream task.
  19879. * @return The downstream task.
  19880. */
  19881. Task.prototype.pipe = function (downTask) {
  19882. if ("development" !== 'production') {
  19883. assert(downTask && !downTask._disposed && downTask !== this);
  19884. }
  19885. // If already downstream, do not dirty downTask.
  19886. if (this._downstream !== downTask || this._dirty) {
  19887. this._downstream = downTask;
  19888. downTask._upstream = this;
  19889. downTask.dirty();
  19890. }
  19891. };
  19892. Task.prototype.dispose = function () {
  19893. if (this._disposed) {
  19894. return;
  19895. }
  19896. this._upstream && (this._upstream._downstream = null);
  19897. this._downstream && (this._downstream._upstream = null);
  19898. this._dirty = false;
  19899. this._disposed = true;
  19900. };
  19901. Task.prototype.getUpstream = function () {
  19902. return this._upstream;
  19903. };
  19904. Task.prototype.getDownstream = function () {
  19905. return this._downstream;
  19906. };
  19907. Task.prototype.setOutputEnd = function (end) {
  19908. // This only happens in dataTask, dataZoom, map, currently.
  19909. // where dataZoom do not set end each time, but only set
  19910. // when reset. So we should record the set end, in case
  19911. // that the stub of dataZoom perform again and earse the
  19912. // set end by upstream.
  19913. this._outputDueEnd = this._settedOutputEnd = end;
  19914. };
  19915. return Task;
  19916. }();
  19917. var iterator = function () {
  19918. var end;
  19919. var current;
  19920. var modBy;
  19921. var modDataCount;
  19922. var winCount;
  19923. var it = {
  19924. reset: function (s, e, sStep, sCount) {
  19925. current = s;
  19926. end = e;
  19927. modBy = sStep;
  19928. modDataCount = sCount;
  19929. winCount = Math.ceil(modDataCount / modBy);
  19930. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19931. }
  19932. };
  19933. return it;
  19934. function sequentialNext() {
  19935. return current < end ? current++ : null;
  19936. }
  19937. function modNext() {
  19938. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19939. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex
  19940. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19941. // Use normal linear rendering mode.
  19942. : current;
  19943. current++;
  19944. return result;
  19945. }
  19946. }();
  19947. // -----------------------------------------------------------------------------
  19948. // For stream debug (Should be commented out after used!)
  19949. // @usage: printTask(this, 'begin');
  19950. // @usage: printTask(this, null, {someExtraProp});
  19951. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19952. //
  19953. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19954. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19955. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19956. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19957. // let props = [];
  19958. // if (task.__pipeline) {
  19959. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19960. // props.push({text: '__idxInPipeline/total', value: val});
  19961. // } else {
  19962. // let stubCount = 0;
  19963. // task.agentStubMap.each(() => stubCount++);
  19964. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19965. // }
  19966. // props.push({text: 'uid', value: task.uidDebug});
  19967. // if (task.__pipeline) {
  19968. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19969. // task.agent && props.push(
  19970. // {text: 'stubFor', value: task.agent.uidDebug}
  19971. // );
  19972. // }
  19973. // props.push(
  19974. // {text: 'dirty', value: task._dirty},
  19975. // {text: 'dueIndex', value: task._dueIndex},
  19976. // {text: 'dueEnd', value: task._dueEnd},
  19977. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19978. // );
  19979. // if (extra) {
  19980. // Object.keys(extra).forEach(key => {
  19981. // props.push({text: key, value: extra[key]});
  19982. // });
  19983. // }
  19984. // let args = ['color: blue'];
  19985. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19986. // args.push('color: green', 'color: red'),
  19987. // `${item.text}: %c${item.value}`
  19988. // )).join('%c, ');
  19989. // console.log.apply(console, [msg].concat(args));
  19990. // // console.log(this);
  19991. // };
  19992. // window.printPipeline = function (task: any, prefix: string) {
  19993. // const pipeline = task.__pipeline;
  19994. // let currTask = pipeline.head;
  19995. // while (currTask) {
  19996. // window.printTask(currTask, prefix);
  19997. // currTask = currTask._downstream;
  19998. // }
  19999. // };
  20000. // window.showChain = function (chainHeadTask) {
  20001. // var chain = [];
  20002. // var task = chainHeadTask;
  20003. // while (task) {
  20004. // chain.push({
  20005. // task: task,
  20006. // up: task._upstream,
  20007. // down: task._downstream,
  20008. // idxInPipeline: task.__idxInPipeline
  20009. // });
  20010. // task = task._downstream;
  20011. // }
  20012. // return chain;
  20013. // };
  20014. // window.findTaskInChain = function (task, chainHeadTask) {
  20015. // let chain = window.showChain(chainHeadTask);
  20016. // let result = [];
  20017. // for (let i = 0; i < chain.length; i++) {
  20018. // let chainItem = chain[i];
  20019. // if (chainItem.task === task) {
  20020. // result.push(i);
  20021. // }
  20022. // }
  20023. // return result;
  20024. // };
  20025. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  20026. // let chainA = window.showChain(chainHeadTaskA);
  20027. // for (let i = 0; i < chainA.length; i++) {
  20028. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  20029. // }
  20030. // };
  20031. /**
  20032. * Convert raw the value in to inner value in List.
  20033. *
  20034. * [Performance sensitive]
  20035. *
  20036. * [Caution]: this is the key logic of user value parser.
  20037. * For backward compatibility, do not modify it until you have to!
  20038. */
  20039. function parseDataValue(value,
  20040. // For high performance, do not omit the second param.
  20041. opt) {
  20042. // Performance sensitive.
  20043. var dimType = opt && opt.type;
  20044. if (dimType === 'ordinal') {
  20045. // If given value is a category string
  20046. return value;
  20047. }
  20048. if (dimType === 'time'
  20049. // spead up when using timestamp
  20050. && !isNumber(value) && value != null && value !== '-') {
  20051. value = +parseDate(value);
  20052. }
  20053. // dimType defaults 'number'.
  20054. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20055. // parse to NaN.
  20056. // number-like string (like ' 123 ') can be converted to a number.
  20057. // where null/undefined or other string will be converted to NaN.
  20058. return value == null || value === '' ? NaN
  20059. // If string (like '-'), using '+' parse to NaN
  20060. // If object, also parse to NaN
  20061. : Number(value);
  20062. }
  20063. var valueParserMap = createHashMap({
  20064. 'number': function (val) {
  20065. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  20066. // Here the number parser can have loose rule:
  20067. // enable to cut suffix: "120px" => 120, "14%" => 14.
  20068. return parseFloat(val);
  20069. },
  20070. 'time': function (val) {
  20071. // return timestamp.
  20072. return +parseDate(val);
  20073. },
  20074. 'trim': function (val) {
  20075. return isString(val) ? trim(val) : val;
  20076. }
  20077. });
  20078. var SortOrderComparator = /** @class */function () {
  20079. /**
  20080. * @param order by default: 'asc'
  20081. * @param incomparable by default: Always on the tail.
  20082. * That is, if 'asc' => 'max', if 'desc' => 'min'
  20083. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  20084. */
  20085. function SortOrderComparator(order, incomparable) {
  20086. var isDesc = order === 'desc';
  20087. this._resultLT = isDesc ? 1 : -1;
  20088. if (incomparable == null) {
  20089. incomparable = isDesc ? 'min' : 'max';
  20090. }
  20091. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  20092. }
  20093. // See [SORT_COMPARISON_RULE].
  20094. // Performance sensitive.
  20095. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  20096. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  20097. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  20098. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  20099. var lvalNotNumeric = isNaN(lvalFloat);
  20100. var rvalNotNumeric = isNaN(rvalFloat);
  20101. if (lvalNotNumeric) {
  20102. lvalFloat = this._incomparable;
  20103. }
  20104. if (rvalNotNumeric) {
  20105. rvalFloat = this._incomparable;
  20106. }
  20107. if (lvalNotNumeric && rvalNotNumeric) {
  20108. var lvalIsStr = isString(lval);
  20109. var rvalIsStr = isString(rval);
  20110. if (lvalIsStr) {
  20111. lvalFloat = rvalIsStr ? lval : 0;
  20112. }
  20113. if (rvalIsStr) {
  20114. rvalFloat = lvalIsStr ? rval : 0;
  20115. }
  20116. }
  20117. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  20118. };
  20119. return SortOrderComparator;
  20120. }();
  20121. /**
  20122. * TODO: disable writable.
  20123. * This structure will be exposed to users.
  20124. */
  20125. var ExternalSource = /** @class */function () {
  20126. function ExternalSource() {}
  20127. ExternalSource.prototype.getRawData = function () {
  20128. // Only built-in transform available.
  20129. throw new Error('not supported');
  20130. };
  20131. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  20132. // Only built-in transform available.
  20133. throw new Error('not supported');
  20134. };
  20135. ExternalSource.prototype.cloneRawData = function () {
  20136. return;
  20137. };
  20138. /**
  20139. * @return If dimension not found, return null/undefined.
  20140. */
  20141. ExternalSource.prototype.getDimensionInfo = function (dim) {
  20142. return;
  20143. };
  20144. /**
  20145. * dimensions defined if and only if either:
  20146. * (a) dataset.dimensions are declared.
  20147. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  20148. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  20149. * the defined dimensions.
  20150. * Otherwise, `dimensionInfoAll` is determined by data columns.
  20151. * @return Always return an array (even empty array).
  20152. */
  20153. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  20154. return;
  20155. };
  20156. ExternalSource.prototype.count = function () {
  20157. return;
  20158. };
  20159. /**
  20160. * Only support by dimension index.
  20161. * No need to support by dimension name in transform function,
  20162. * because transform function is not case-specific, no need to use name literally.
  20163. */
  20164. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  20165. return;
  20166. };
  20167. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  20168. return;
  20169. };
  20170. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  20171. return parseDataValue(rawVal, dimInfo);
  20172. };
  20173. return ExternalSource;
  20174. }();
  20175. function createExternalSource(internalSource, externalTransform) {
  20176. var extSource = new ExternalSource();
  20177. var data = internalSource.data;
  20178. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  20179. var sourceHeaderCount = internalSource.startIndex;
  20180. var errMsg = '';
  20181. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  20182. // For the logic simplicity in transformer, only 'culumn' is
  20183. // supported in data transform. Otherwise, the `dimensionsDefine`
  20184. // might be detected by 'row', which probably confuses users.
  20185. if ("development" !== 'production') {
  20186. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  20187. }
  20188. throwError(errMsg);
  20189. }
  20190. // [MEMO]
  20191. // Create a new dimensions structure for exposing.
  20192. // Do not expose all dimension info to users directly.
  20193. // Because the dimension is probably auto detected from data and not might reliable.
  20194. // Should not lead the transformers to think that is reliable and return it.
  20195. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20196. var dimensions = [];
  20197. var dimsByName = {};
  20198. var dimsDef = internalSource.dimensionsDefine;
  20199. if (dimsDef) {
  20200. each(dimsDef, function (dimDef, idx) {
  20201. var name = dimDef.name;
  20202. var dimDefExt = {
  20203. index: idx,
  20204. name: name,
  20205. displayName: dimDef.displayName
  20206. };
  20207. dimensions.push(dimDefExt);
  20208. // Users probably do not specify dimension name. For simplicity, data transform
  20209. // does not generate dimension name.
  20210. if (name != null) {
  20211. // Dimension name should not be duplicated.
  20212. // For simplicity, data transform forbids name duplication, do not generate
  20213. // new name like module `completeDimensions.ts` did, but just tell users.
  20214. var errMsg_1 = '';
  20215. if (hasOwn(dimsByName, name)) {
  20216. if ("development" !== 'production') {
  20217. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  20218. }
  20219. throwError(errMsg_1);
  20220. }
  20221. dimsByName[name] = dimDefExt;
  20222. }
  20223. });
  20224. }
  20225. // If dimension definitions are not defined and can not be detected.
  20226. // e.g., pure data `[[11, 22], ...]`.
  20227. else {
  20228. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  20229. // Do not generete name or anything others. The consequence process in
  20230. // `transform` or `series` probably have there own name generation strategry.
  20231. dimensions.push({
  20232. index: i
  20233. });
  20234. }
  20235. }
  20236. // Implement public methods:
  20237. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20238. if (externalTransform.__isBuiltIn) {
  20239. extSource.getRawDataItem = function (dataIndex) {
  20240. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20241. };
  20242. extSource.getRawData = bind(getRawData, null, internalSource);
  20243. }
  20244. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  20245. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20246. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  20247. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  20248. extSource.retrieveValue = function (dataIndex, dimIndex) {
  20249. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20250. return retrieveValueFromItem(rawItem, dimIndex);
  20251. };
  20252. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  20253. if (dataItem == null) {
  20254. return;
  20255. }
  20256. var dimDef = dimensions[dimIndex];
  20257. // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  20258. if (dimDef) {
  20259. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  20260. }
  20261. };
  20262. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  20263. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  20264. return extSource;
  20265. }
  20266. function getRawData(upstream) {
  20267. var sourceFormat = upstream.sourceFormat;
  20268. if (!isSupportedSourceFormat(sourceFormat)) {
  20269. var errMsg = '';
  20270. if ("development" !== 'production') {
  20271. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  20272. }
  20273. throwError(errMsg);
  20274. }
  20275. return upstream.data;
  20276. }
  20277. function cloneRawData(upstream) {
  20278. var sourceFormat = upstream.sourceFormat;
  20279. var data = upstream.data;
  20280. if (!isSupportedSourceFormat(sourceFormat)) {
  20281. var errMsg = '';
  20282. if ("development" !== 'production') {
  20283. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  20284. }
  20285. throwError(errMsg);
  20286. }
  20287. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  20288. var result = [];
  20289. for (var i = 0, len = data.length; i < len; i++) {
  20290. // Not strictly clone for performance
  20291. result.push(data[i].slice());
  20292. }
  20293. return result;
  20294. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  20295. var result = [];
  20296. for (var i = 0, len = data.length; i < len; i++) {
  20297. // Not strictly clone for performance
  20298. result.push(extend({}, data[i]));
  20299. }
  20300. return result;
  20301. }
  20302. }
  20303. function getDimensionInfo(dimensions, dimsByName, dim) {
  20304. if (dim == null) {
  20305. return;
  20306. }
  20307. // Keep the same logic as `List::getDimension` did.
  20308. if (isNumber(dim)
  20309. // If being a number-like string but not being defined a dimension name.
  20310. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  20311. return dimensions[dim];
  20312. } else if (hasOwn(dimsByName, dim)) {
  20313. return dimsByName[dim];
  20314. }
  20315. }
  20316. function cloneAllDimensionInfo(dimensions) {
  20317. return clone(dimensions);
  20318. }
  20319. var externalTransformMap = createHashMap();
  20320. function registerExternalTransform(externalTransform) {
  20321. externalTransform = clone(externalTransform);
  20322. var type = externalTransform.type;
  20323. var errMsg = '';
  20324. if (!type) {
  20325. if ("development" !== 'production') {
  20326. errMsg = 'Must have a `type` when `registerTransform`.';
  20327. }
  20328. throwError(errMsg);
  20329. }
  20330. var typeParsed = type.split(':');
  20331. if (typeParsed.length !== 2) {
  20332. if ("development" !== 'production') {
  20333. errMsg = 'Name must include namespace like "ns:regression".';
  20334. }
  20335. throwError(errMsg);
  20336. }
  20337. // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20338. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20339. var isBuiltIn = false;
  20340. if (typeParsed[0] === 'echarts') {
  20341. type = typeParsed[1];
  20342. isBuiltIn = true;
  20343. }
  20344. externalTransform.__isBuiltIn = isBuiltIn;
  20345. externalTransformMap.set(type, externalTransform);
  20346. }
  20347. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20348. var pipedTransOption = normalizeToArray(rawTransOption);
  20349. var pipeLen = pipedTransOption.length;
  20350. var errMsg = '';
  20351. if (!pipeLen) {
  20352. if ("development" !== 'production') {
  20353. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20354. }
  20355. throwError(errMsg);
  20356. }
  20357. for (var i = 0, len = pipeLen; i < len; i++) {
  20358. var transOption = pipedTransOption[i];
  20359. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i);
  20360. // piped transform only support single input, except the fist one.
  20361. // piped transform only support single output, except the last one.
  20362. if (i !== len - 1) {
  20363. sourceList.length = Math.max(sourceList.length, 1);
  20364. }
  20365. }
  20366. return sourceList;
  20367. }
  20368. function applySingleDataTransform(transOption, upSourceList, infoForPrint,
  20369. // If `pipeIndex` is null/undefined, no piped transform.
  20370. pipeIndex) {
  20371. var errMsg = '';
  20372. if (!upSourceList.length) {
  20373. if ("development" !== 'production') {
  20374. errMsg = 'Must have at least one upstream dataset.';
  20375. }
  20376. throwError(errMsg);
  20377. }
  20378. if (!isObject(transOption)) {
  20379. if ("development" !== 'production') {
  20380. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20381. }
  20382. throwError(errMsg);
  20383. }
  20384. var transType = transOption.type;
  20385. var externalTransform = externalTransformMap.get(transType);
  20386. if (!externalTransform) {
  20387. if ("development" !== 'production') {
  20388. errMsg = 'Can not find transform on type "' + transType + '".';
  20389. }
  20390. throwError(errMsg);
  20391. }
  20392. // Prepare source
  20393. var extUpSourceList = map(upSourceList, function (upSource) {
  20394. return createExternalSource(upSource, externalTransform);
  20395. });
  20396. var resultList = normalizeToArray(externalTransform.transform({
  20397. upstream: extUpSourceList[0],
  20398. upstreamList: extUpSourceList,
  20399. config: clone(transOption.config)
  20400. }));
  20401. if ("development" !== 'production') {
  20402. if (transOption.print) {
  20403. var printStrArr = map(resultList, function (extSource) {
  20404. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20405. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20406. }).join('\n');
  20407. log(printStrArr);
  20408. }
  20409. }
  20410. return map(resultList, function (result, resultIndex) {
  20411. var errMsg = '';
  20412. if (!isObject(result)) {
  20413. if ("development" !== 'production') {
  20414. errMsg = 'A transform should not return some empty results.';
  20415. }
  20416. throwError(errMsg);
  20417. }
  20418. if (!result.data) {
  20419. if ("development" !== 'production') {
  20420. errMsg = 'Transform result data should be not be null or undefined';
  20421. }
  20422. throwError(errMsg);
  20423. }
  20424. var sourceFormat = detectSourceFormat(result.data);
  20425. if (!isSupportedSourceFormat(sourceFormat)) {
  20426. if ("development" !== 'production') {
  20427. errMsg = 'Transform result data should be array rows or object rows.';
  20428. }
  20429. throwError(errMsg);
  20430. }
  20431. var resultMetaRawOption;
  20432. var firstUpSource = upSourceList[0];
  20433. /**
  20434. * Intuitively, the end users known the content of the original `dataset.source`,
  20435. * calucating the transform result in mind.
  20436. * Suppose the original `dataset.source` is:
  20437. * ```js
  20438. * [
  20439. * ['product', '2012', '2013', '2014', '2015'],
  20440. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20441. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20442. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20443. * ]
  20444. * ```
  20445. * The dimension info have to be detected from the source data.
  20446. * Some of the transformers (like filter, sort) will follow the dimension info
  20447. * of upstream, while others use new dimensions (like aggregate).
  20448. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20449. * We also allow transformers to ignore the output `dimensions` field, and
  20450. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20451. * dimensions in transformers.
  20452. *
  20453. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20454. */
  20455. if (firstUpSource && resultIndex === 0
  20456. // If transformer returns `dimensions`, it means that the transformer has different
  20457. // dimensions definitions. We do not inherit anything from upstream.
  20458. && !result.dimensions) {
  20459. var startIndex = firstUpSource.startIndex;
  20460. // We copy the header of upstream to the result, because:
  20461. // (1) The returned data always does not contain header line and can not be used
  20462. // as dimension-detection. In this case we can not use "detected dimensions" of
  20463. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20464. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20465. // So the original detected header should be add to the result, otherwise they can not be read.
  20466. if (startIndex) {
  20467. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20468. }
  20469. resultMetaRawOption = {
  20470. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20471. sourceHeader: startIndex,
  20472. dimensions: firstUpSource.metaRawOption.dimensions
  20473. };
  20474. } else {
  20475. resultMetaRawOption = {
  20476. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20477. sourceHeader: 0,
  20478. dimensions: result.dimensions
  20479. };
  20480. }
  20481. return createSource(result.data, resultMetaRawOption, null);
  20482. });
  20483. }
  20484. function isSupportedSourceFormat(sourceFormat) {
  20485. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20486. }
  20487. var UNDEFINED = 'undefined';
  20488. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20489. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20490. // different from the Ctor of typed array.
  20491. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20492. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20493. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20494. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20495. /**
  20496. * Multi dimensional data store
  20497. */
  20498. var dataCtors = {
  20499. 'float': CtorFloat64Array,
  20500. 'int': CtorInt32Array,
  20501. // Ordinal data type can be string or int
  20502. 'ordinal': Array,
  20503. 'number': Array,
  20504. 'time': CtorFloat64Array
  20505. };
  20506. var defaultDimValueGetters;
  20507. function getIndicesCtor(rawCount) {
  20508. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20509. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20510. }
  20511. function getInitialExtent() {
  20512. return [Infinity, -Infinity];
  20513. }
  20514. function cloneChunk(originalChunk) {
  20515. var Ctor = originalChunk.constructor;
  20516. // Only shallow clone is enough when Array.
  20517. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20518. }
  20519. function prepareStore(store, dimIdx, dimType, end, append) {
  20520. var DataCtor = dataCtors[dimType || 'float'];
  20521. if (append) {
  20522. var oldStore = store[dimIdx];
  20523. var oldLen = oldStore && oldStore.length;
  20524. if (!(oldLen === end)) {
  20525. var newStore = new DataCtor(end);
  20526. // The cost of the copy is probably inconsiderable
  20527. // within the initial chunkSize.
  20528. for (var j = 0; j < oldLen; j++) {
  20529. newStore[j] = oldStore[j];
  20530. }
  20531. store[dimIdx] = newStore;
  20532. }
  20533. } else {
  20534. store[dimIdx] = new DataCtor(end);
  20535. }
  20536. }
  20537. /**
  20538. * Basically, DataStore API keep immutable.
  20539. */
  20540. var DataStore = /** @class */function () {
  20541. function DataStore() {
  20542. this._chunks = [];
  20543. // It will not be calculated until needed.
  20544. this._rawExtent = [];
  20545. this._extent = [];
  20546. this._count = 0;
  20547. this._rawCount = 0;
  20548. this._calcDimNameToIdx = createHashMap();
  20549. }
  20550. /**
  20551. * Initialize from data
  20552. */
  20553. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20554. if ("development" !== 'production') {
  20555. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20556. }
  20557. this._provider = provider;
  20558. // Clear
  20559. this._chunks = [];
  20560. this._indices = null;
  20561. this.getRawIndex = this._getRawIdxIdentity;
  20562. var source = provider.getSource();
  20563. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat];
  20564. // Default dim value getter
  20565. this._dimValueGetter = dimValueGetter || defaultGetter;
  20566. // Reset raw extent.
  20567. this._rawExtent = [];
  20568. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20569. this._dimensions = map(inputDimensions, function (dim) {
  20570. if ("development" !== 'production') {
  20571. if (willRetrieveDataByName) {
  20572. assert(dim.property != null);
  20573. }
  20574. }
  20575. return {
  20576. // Only pick these two props. Not leak other properties like orderMeta.
  20577. type: dim.type,
  20578. property: dim.property
  20579. };
  20580. });
  20581. this._initDataFromProvider(0, provider.count());
  20582. };
  20583. DataStore.prototype.getProvider = function () {
  20584. return this._provider;
  20585. };
  20586. /**
  20587. * Caution: even when a `source` instance owned by a series, the created data store
  20588. * may still be shared by different sereis (the source hash does not use all `source`
  20589. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20590. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20591. * thus should not be fetch here.
  20592. */
  20593. DataStore.prototype.getSource = function () {
  20594. return this._provider.getSource();
  20595. };
  20596. /**
  20597. * @caution Only used in dataStack.
  20598. */
  20599. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20600. var calcDimNameToIdx = this._calcDimNameToIdx;
  20601. var dimensions = this._dimensions;
  20602. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20603. if (calcDimIdx != null) {
  20604. if (dimensions[calcDimIdx].type === type) {
  20605. return calcDimIdx;
  20606. }
  20607. } else {
  20608. calcDimIdx = dimensions.length;
  20609. }
  20610. dimensions[calcDimIdx] = {
  20611. type: type
  20612. };
  20613. calcDimNameToIdx.set(dimName, calcDimIdx);
  20614. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20615. this._rawExtent[calcDimIdx] = getInitialExtent();
  20616. return calcDimIdx;
  20617. };
  20618. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20619. var chunk = this._chunks[dimIdx];
  20620. var dim = this._dimensions[dimIdx];
  20621. var rawExtents = this._rawExtent;
  20622. var offset = dim.ordinalOffset || 0;
  20623. var len = chunk.length;
  20624. if (offset === 0) {
  20625. // We need to reset the rawExtent if collect is from start.
  20626. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20627. rawExtents[dimIdx] = getInitialExtent();
  20628. }
  20629. var dimRawExtent = rawExtents[dimIdx];
  20630. // Parse from previous data offset. len may be changed after appendData
  20631. for (var i = offset; i < len; i++) {
  20632. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20633. if (!isNaN(val)) {
  20634. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20635. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20636. }
  20637. }
  20638. dim.ordinalMeta = ordinalMeta;
  20639. dim.ordinalOffset = len;
  20640. dim.type = 'ordinal'; // Force to be ordinal
  20641. };
  20642. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20643. var dimInfo = this._dimensions[dimIdx];
  20644. var ordinalMeta = dimInfo.ordinalMeta;
  20645. return ordinalMeta;
  20646. };
  20647. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20648. var item = this._dimensions[dimIndex];
  20649. return item && item.property;
  20650. };
  20651. /**
  20652. * Caution: Can be only called on raw data (before `this._indices` created).
  20653. */
  20654. DataStore.prototype.appendData = function (data) {
  20655. if ("development" !== 'production') {
  20656. assert(!this._indices, 'appendData can only be called on raw data.');
  20657. }
  20658. var provider = this._provider;
  20659. var start = this.count();
  20660. provider.appendData(data);
  20661. var end = provider.count();
  20662. if (!provider.persistent) {
  20663. end += start;
  20664. }
  20665. if (start < end) {
  20666. this._initDataFromProvider(start, end, true);
  20667. }
  20668. return [start, end];
  20669. };
  20670. DataStore.prototype.appendValues = function (values, minFillLen) {
  20671. var chunks = this._chunks;
  20672. var dimensions = this._dimensions;
  20673. var dimLen = dimensions.length;
  20674. var rawExtent = this._rawExtent;
  20675. var start = this.count();
  20676. var end = start + Math.max(values.length, minFillLen || 0);
  20677. for (var i = 0; i < dimLen; i++) {
  20678. var dim = dimensions[i];
  20679. prepareStore(chunks, i, dim.type, end, true);
  20680. }
  20681. var emptyDataItem = [];
  20682. for (var idx = start; idx < end; idx++) {
  20683. var sourceIdx = idx - start;
  20684. // Store the data by dimensions
  20685. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20686. var dim = dimensions[dimIdx];
  20687. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20688. chunks[dimIdx][idx] = val;
  20689. var dimRawExtent = rawExtent[dimIdx];
  20690. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20691. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20692. }
  20693. }
  20694. this._rawCount = this._count = end;
  20695. return {
  20696. start: start,
  20697. end: end
  20698. };
  20699. };
  20700. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20701. var provider = this._provider;
  20702. var chunks = this._chunks;
  20703. var dimensions = this._dimensions;
  20704. var dimLen = dimensions.length;
  20705. var rawExtent = this._rawExtent;
  20706. var dimNames = map(dimensions, function (dim) {
  20707. return dim.property;
  20708. });
  20709. for (var i = 0; i < dimLen; i++) {
  20710. var dim = dimensions[i];
  20711. if (!rawExtent[i]) {
  20712. rawExtent[i] = getInitialExtent();
  20713. }
  20714. prepareStore(chunks, i, dim.type, end, append);
  20715. }
  20716. if (provider.fillStorage) {
  20717. provider.fillStorage(start, end, chunks, rawExtent);
  20718. } else {
  20719. var dataItem = [];
  20720. for (var idx = start; idx < end; idx++) {
  20721. // NOTICE: Try not to write things into dataItem
  20722. dataItem = provider.getItem(idx, dataItem);
  20723. // Each data item is value
  20724. // [1, 2]
  20725. // 2
  20726. // Bar chart, line chart which uses category axis
  20727. // only gives the 'y' value. 'x' value is the indices of category
  20728. // Use a tempValue to normalize the value to be a (x, y) value
  20729. // Store the data by dimensions
  20730. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20731. var dimStorage = chunks[dimIdx];
  20732. // PENDING NULL is empty or zero
  20733. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20734. dimStorage[idx] = val;
  20735. var dimRawExtent = rawExtent[dimIdx];
  20736. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20737. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20738. }
  20739. }
  20740. }
  20741. if (!provider.persistent && provider.clean) {
  20742. // Clean unused data if data source is typed array.
  20743. provider.clean();
  20744. }
  20745. this._rawCount = this._count = end;
  20746. // Reset data extent
  20747. this._extent = [];
  20748. };
  20749. DataStore.prototype.count = function () {
  20750. return this._count;
  20751. };
  20752. /**
  20753. * Get value. Return NaN if idx is out of range.
  20754. */
  20755. DataStore.prototype.get = function (dim, idx) {
  20756. if (!(idx >= 0 && idx < this._count)) {
  20757. return NaN;
  20758. }
  20759. var dimStore = this._chunks[dim];
  20760. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20761. };
  20762. DataStore.prototype.getValues = function (dimensions, idx) {
  20763. var values = [];
  20764. var dimArr = [];
  20765. if (idx == null) {
  20766. idx = dimensions;
  20767. // TODO get all from store?
  20768. dimensions = [];
  20769. // All dimensions
  20770. for (var i = 0; i < this._dimensions.length; i++) {
  20771. dimArr.push(i);
  20772. }
  20773. } else {
  20774. dimArr = dimensions;
  20775. }
  20776. for (var i = 0, len = dimArr.length; i < len; i++) {
  20777. values.push(this.get(dimArr[i], idx));
  20778. }
  20779. return values;
  20780. };
  20781. /**
  20782. * @param dim concrete dim
  20783. */
  20784. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20785. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20786. return NaN;
  20787. }
  20788. var dimStore = this._chunks[dim];
  20789. return dimStore ? dimStore[rawIdx] : NaN;
  20790. };
  20791. /**
  20792. * Get sum of data in one dimension
  20793. */
  20794. DataStore.prototype.getSum = function (dim) {
  20795. var dimData = this._chunks[dim];
  20796. var sum = 0;
  20797. if (dimData) {
  20798. for (var i = 0, len = this.count(); i < len; i++) {
  20799. var value = this.get(dim, i);
  20800. if (!isNaN(value)) {
  20801. sum += value;
  20802. }
  20803. }
  20804. }
  20805. return sum;
  20806. };
  20807. /**
  20808. * Get median of data in one dimension
  20809. */
  20810. DataStore.prototype.getMedian = function (dim) {
  20811. var dimDataArray = [];
  20812. // map all data of one dimension
  20813. this.each([dim], function (val) {
  20814. if (!isNaN(val)) {
  20815. dimDataArray.push(val);
  20816. }
  20817. });
  20818. // TODO
  20819. // Use quick select?
  20820. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20821. return a - b;
  20822. });
  20823. var len = this.count();
  20824. // calculate median
  20825. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20826. };
  20827. /**
  20828. * Retrieve the index with given raw data index.
  20829. */
  20830. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20831. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20832. return -1;
  20833. }
  20834. if (!this._indices) {
  20835. return rawIndex;
  20836. }
  20837. // Indices are ascending
  20838. var indices = this._indices;
  20839. // If rawIndex === dataIndex
  20840. var rawDataIndex = indices[rawIndex];
  20841. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20842. return rawIndex;
  20843. }
  20844. var left = 0;
  20845. var right = this._count - 1;
  20846. while (left <= right) {
  20847. var mid = (left + right) / 2 | 0;
  20848. if (indices[mid] < rawIndex) {
  20849. left = mid + 1;
  20850. } else if (indices[mid] > rawIndex) {
  20851. right = mid - 1;
  20852. } else {
  20853. return mid;
  20854. }
  20855. }
  20856. return -1;
  20857. };
  20858. /**
  20859. * Retrieve the index of nearest value.
  20860. * @param dim
  20861. * @param value
  20862. * @param [maxDistance=Infinity]
  20863. * @return If and only if multiple indices have
  20864. * the same value, they are put to the result.
  20865. */
  20866. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20867. var chunks = this._chunks;
  20868. var dimData = chunks[dim];
  20869. var nearestIndices = [];
  20870. if (!dimData) {
  20871. return nearestIndices;
  20872. }
  20873. if (maxDistance == null) {
  20874. maxDistance = Infinity;
  20875. }
  20876. var minDist = Infinity;
  20877. var minDiff = -1;
  20878. var nearestIndicesLen = 0;
  20879. // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20880. for (var i = 0, len = this.count(); i < len; i++) {
  20881. var dataIndex = this.getRawIndex(i);
  20882. var diff = value - dimData[dataIndex];
  20883. var dist = Math.abs(diff);
  20884. if (dist <= maxDistance) {
  20885. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20886. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20887. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20888. // So we choose the one that `diff >= 0` in this case.
  20889. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20890. // should be push to `nearestIndices`.
  20891. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20892. minDist = dist;
  20893. minDiff = diff;
  20894. nearestIndicesLen = 0;
  20895. }
  20896. if (diff === minDiff) {
  20897. nearestIndices[nearestIndicesLen++] = i;
  20898. }
  20899. }
  20900. }
  20901. nearestIndices.length = nearestIndicesLen;
  20902. return nearestIndices;
  20903. };
  20904. DataStore.prototype.getIndices = function () {
  20905. var newIndices;
  20906. var indices = this._indices;
  20907. if (indices) {
  20908. var Ctor = indices.constructor;
  20909. var thisCount = this._count;
  20910. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20911. if (Ctor === Array) {
  20912. newIndices = new Ctor(thisCount);
  20913. for (var i = 0; i < thisCount; i++) {
  20914. newIndices[i] = indices[i];
  20915. }
  20916. } else {
  20917. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20918. }
  20919. } else {
  20920. var Ctor = getIndicesCtor(this._rawCount);
  20921. newIndices = new Ctor(this.count());
  20922. for (var i = 0; i < newIndices.length; i++) {
  20923. newIndices[i] = i;
  20924. }
  20925. }
  20926. return newIndices;
  20927. };
  20928. /**
  20929. * Data filter.
  20930. */
  20931. DataStore.prototype.filter = function (dims, cb) {
  20932. if (!this._count) {
  20933. return this;
  20934. }
  20935. var newStore = this.clone();
  20936. var count = newStore.count();
  20937. var Ctor = getIndicesCtor(newStore._rawCount);
  20938. var newIndices = new Ctor(count);
  20939. var value = [];
  20940. var dimSize = dims.length;
  20941. var offset = 0;
  20942. var dim0 = dims[0];
  20943. var chunks = newStore._chunks;
  20944. for (var i = 0; i < count; i++) {
  20945. var keep = void 0;
  20946. var rawIdx = newStore.getRawIndex(i);
  20947. // Simple optimization
  20948. if (dimSize === 0) {
  20949. keep = cb(i);
  20950. } else if (dimSize === 1) {
  20951. var val = chunks[dim0][rawIdx];
  20952. keep = cb(val, i);
  20953. } else {
  20954. var k = 0;
  20955. for (; k < dimSize; k++) {
  20956. value[k] = chunks[dims[k]][rawIdx];
  20957. }
  20958. value[k] = i;
  20959. keep = cb.apply(null, value);
  20960. }
  20961. if (keep) {
  20962. newIndices[offset++] = rawIdx;
  20963. }
  20964. }
  20965. // Set indices after filtered.
  20966. if (offset < count) {
  20967. newStore._indices = newIndices;
  20968. }
  20969. newStore._count = offset;
  20970. // Reset data extent
  20971. newStore._extent = [];
  20972. newStore._updateGetRawIdx();
  20973. return newStore;
  20974. };
  20975. /**
  20976. * Select data in range. (For optimization of filter)
  20977. * (Manually inline code, support 5 million data filtering in data zoom.)
  20978. */
  20979. DataStore.prototype.selectRange = function (range) {
  20980. var newStore = this.clone();
  20981. var len = newStore._count;
  20982. if (!len) {
  20983. return this;
  20984. }
  20985. var dims = keys(range);
  20986. var dimSize = dims.length;
  20987. if (!dimSize) {
  20988. return this;
  20989. }
  20990. var originalCount = newStore.count();
  20991. var Ctor = getIndicesCtor(newStore._rawCount);
  20992. var newIndices = new Ctor(originalCount);
  20993. var offset = 0;
  20994. var dim0 = dims[0];
  20995. var min = range[dim0][0];
  20996. var max = range[dim0][1];
  20997. var storeArr = newStore._chunks;
  20998. var quickFinished = false;
  20999. if (!newStore._indices) {
  21000. // Extreme optimization for common case. About 2x faster in chrome.
  21001. var idx = 0;
  21002. if (dimSize === 1) {
  21003. var dimStorage = storeArr[dims[0]];
  21004. for (var i = 0; i < len; i++) {
  21005. var val = dimStorage[i];
  21006. // NaN will not be filtered. Consider the case, in line chart, empty
  21007. // value indicates the line should be broken. But for the case like
  21008. // scatter plot, a data item with empty value will not be rendered,
  21009. // but the axis extent may be effected if some other dim of the data
  21010. // item has value. Fortunately it is not a significant negative effect.
  21011. if (val >= min && val <= max || isNaN(val)) {
  21012. newIndices[offset++] = idx;
  21013. }
  21014. idx++;
  21015. }
  21016. quickFinished = true;
  21017. } else if (dimSize === 2) {
  21018. var dimStorage = storeArr[dims[0]];
  21019. var dimStorage2 = storeArr[dims[1]];
  21020. var min2 = range[dims[1]][0];
  21021. var max2 = range[dims[1]][1];
  21022. for (var i = 0; i < len; i++) {
  21023. var val = dimStorage[i];
  21024. var val2 = dimStorage2[i];
  21025. // Do not filter NaN, see comment above.
  21026. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  21027. newIndices[offset++] = idx;
  21028. }
  21029. idx++;
  21030. }
  21031. quickFinished = true;
  21032. }
  21033. }
  21034. if (!quickFinished) {
  21035. if (dimSize === 1) {
  21036. for (var i = 0; i < originalCount; i++) {
  21037. var rawIndex = newStore.getRawIndex(i);
  21038. var val = storeArr[dims[0]][rawIndex];
  21039. // Do not filter NaN, see comment above.
  21040. if (val >= min && val <= max || isNaN(val)) {
  21041. newIndices[offset++] = rawIndex;
  21042. }
  21043. }
  21044. } else {
  21045. for (var i = 0; i < originalCount; i++) {
  21046. var keep = true;
  21047. var rawIndex = newStore.getRawIndex(i);
  21048. for (var k = 0; k < dimSize; k++) {
  21049. var dimk = dims[k];
  21050. var val = storeArr[dimk][rawIndex];
  21051. // Do not filter NaN, see comment above.
  21052. if (val < range[dimk][0] || val > range[dimk][1]) {
  21053. keep = false;
  21054. }
  21055. }
  21056. if (keep) {
  21057. newIndices[offset++] = newStore.getRawIndex(i);
  21058. }
  21059. }
  21060. }
  21061. }
  21062. // Set indices after filtered.
  21063. if (offset < originalCount) {
  21064. newStore._indices = newIndices;
  21065. }
  21066. newStore._count = offset;
  21067. // Reset data extent
  21068. newStore._extent = [];
  21069. newStore._updateGetRawIdx();
  21070. return newStore;
  21071. };
  21072. // /**
  21073. // * Data mapping to a plain array
  21074. // */
  21075. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  21076. // const result: any[] = [];
  21077. // this.each(dims, function () {
  21078. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  21079. // });
  21080. // return result;
  21081. // }
  21082. /**
  21083. * Data mapping to a new List with given dimensions
  21084. */
  21085. DataStore.prototype.map = function (dims, cb) {
  21086. // TODO only clone picked chunks.
  21087. var target = this.clone(dims);
  21088. this._updateDims(target, dims, cb);
  21089. return target;
  21090. };
  21091. /**
  21092. * @caution Danger!! Only used in dataStack.
  21093. */
  21094. DataStore.prototype.modify = function (dims, cb) {
  21095. this._updateDims(this, dims, cb);
  21096. };
  21097. DataStore.prototype._updateDims = function (target, dims, cb) {
  21098. var targetChunks = target._chunks;
  21099. var tmpRetValue = [];
  21100. var dimSize = dims.length;
  21101. var dataCount = target.count();
  21102. var values = [];
  21103. var rawExtent = target._rawExtent;
  21104. for (var i = 0; i < dims.length; i++) {
  21105. rawExtent[dims[i]] = getInitialExtent();
  21106. }
  21107. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  21108. var rawIndex = target.getRawIndex(dataIndex);
  21109. for (var k = 0; k < dimSize; k++) {
  21110. values[k] = targetChunks[dims[k]][rawIndex];
  21111. }
  21112. values[dimSize] = dataIndex;
  21113. var retValue = cb && cb.apply(null, values);
  21114. if (retValue != null) {
  21115. // a number or string (in oridinal dimension)?
  21116. if (typeof retValue !== 'object') {
  21117. tmpRetValue[0] = retValue;
  21118. retValue = tmpRetValue;
  21119. }
  21120. for (var i = 0; i < retValue.length; i++) {
  21121. var dim = dims[i];
  21122. var val = retValue[i];
  21123. var rawExtentOnDim = rawExtent[dim];
  21124. var dimStore = targetChunks[dim];
  21125. if (dimStore) {
  21126. dimStore[rawIndex] = val;
  21127. }
  21128. if (val < rawExtentOnDim[0]) {
  21129. rawExtentOnDim[0] = val;
  21130. }
  21131. if (val > rawExtentOnDim[1]) {
  21132. rawExtentOnDim[1] = val;
  21133. }
  21134. }
  21135. }
  21136. }
  21137. };
  21138. /**
  21139. * Large data down sampling using largest-triangle-three-buckets
  21140. * @param {string} valueDimension
  21141. * @param {number} targetCount
  21142. */
  21143. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  21144. var target = this.clone([valueDimension], true);
  21145. var targetStorage = target._chunks;
  21146. var dimStore = targetStorage[valueDimension];
  21147. var len = this.count();
  21148. var sampledIndex = 0;
  21149. var frameSize = Math.floor(1 / rate);
  21150. var currentRawIndex = this.getRawIndex(0);
  21151. var maxArea;
  21152. var area;
  21153. var nextRawIndex;
  21154. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len));
  21155. // First frame use the first data.
  21156. newIndices[sampledIndex++] = currentRawIndex;
  21157. for (var i = 1; i < len - 1; i += frameSize) {
  21158. var nextFrameStart = Math.min(i + frameSize, len - 1);
  21159. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  21160. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  21161. var avgY = 0;
  21162. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  21163. var rawIndex = this.getRawIndex(idx);
  21164. var y = dimStore[rawIndex];
  21165. if (isNaN(y)) {
  21166. continue;
  21167. }
  21168. avgY += y;
  21169. }
  21170. avgY /= nextFrameEnd - nextFrameStart;
  21171. var frameStart = i;
  21172. var frameEnd = Math.min(i + frameSize, len);
  21173. var pointAX = i - 1;
  21174. var pointAY = dimStore[currentRawIndex];
  21175. maxArea = -1;
  21176. nextRawIndex = frameStart;
  21177. var firstNaNIndex = -1;
  21178. var countNaN = 0;
  21179. // Find a point from current frame that construct a triangle with largest area with previous selected point
  21180. // And the average of next frame.
  21181. for (var idx = frameStart; idx < frameEnd; idx++) {
  21182. var rawIndex = this.getRawIndex(idx);
  21183. var y = dimStore[rawIndex];
  21184. if (isNaN(y)) {
  21185. countNaN++;
  21186. if (firstNaNIndex < 0) {
  21187. firstNaNIndex = rawIndex;
  21188. }
  21189. continue;
  21190. }
  21191. // Calculate triangle area over three buckets
  21192. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  21193. if (area > maxArea) {
  21194. maxArea = area;
  21195. nextRawIndex = rawIndex; // Next a is this b
  21196. }
  21197. }
  21198. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  21199. // Append first NaN point in every bucket.
  21200. // It is necessary to ensure the correct order of indices.
  21201. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  21202. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  21203. }
  21204. newIndices[sampledIndex++] = nextRawIndex;
  21205. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  21206. }
  21207. // First frame use the last data.
  21208. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  21209. target._count = sampledIndex;
  21210. target._indices = newIndices;
  21211. target.getRawIndex = this._getRawIdx;
  21212. return target;
  21213. };
  21214. /**
  21215. * Large data down sampling on given dimension
  21216. * @param sampleIndex Sample index for name and id
  21217. */
  21218. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  21219. var target = this.clone([dimension], true);
  21220. var targetStorage = target._chunks;
  21221. var frameValues = [];
  21222. var frameSize = Math.floor(1 / rate);
  21223. var dimStore = targetStorage[dimension];
  21224. var len = this.count();
  21225. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  21226. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  21227. var offset = 0;
  21228. for (var i = 0; i < len; i += frameSize) {
  21229. // Last frame
  21230. if (frameSize > len - i) {
  21231. frameSize = len - i;
  21232. frameValues.length = frameSize;
  21233. }
  21234. for (var k = 0; k < frameSize; k++) {
  21235. var dataIdx = this.getRawIndex(i + k);
  21236. frameValues[k] = dimStore[dataIdx];
  21237. }
  21238. var value = sampleValue(frameValues);
  21239. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1));
  21240. // Only write value on the filtered data
  21241. dimStore[sampleFrameIdx] = value;
  21242. if (value < rawExtentOnDim[0]) {
  21243. rawExtentOnDim[0] = value;
  21244. }
  21245. if (value > rawExtentOnDim[1]) {
  21246. rawExtentOnDim[1] = value;
  21247. }
  21248. newIndices[offset++] = sampleFrameIdx;
  21249. }
  21250. target._count = offset;
  21251. target._indices = newIndices;
  21252. target._updateGetRawIdx();
  21253. return target;
  21254. };
  21255. /**
  21256. * Data iteration
  21257. * @param ctx default this
  21258. * @example
  21259. * list.each('x', function (x, idx) {});
  21260. * list.each(['x', 'y'], function (x, y, idx) {});
  21261. * list.each(function (idx) {})
  21262. */
  21263. DataStore.prototype.each = function (dims, cb) {
  21264. if (!this._count) {
  21265. return;
  21266. }
  21267. var dimSize = dims.length;
  21268. var chunks = this._chunks;
  21269. for (var i = 0, len = this.count(); i < len; i++) {
  21270. var rawIdx = this.getRawIndex(i);
  21271. // Simple optimization
  21272. switch (dimSize) {
  21273. case 0:
  21274. cb(i);
  21275. break;
  21276. case 1:
  21277. cb(chunks[dims[0]][rawIdx], i);
  21278. break;
  21279. case 2:
  21280. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  21281. break;
  21282. default:
  21283. var k = 0;
  21284. var value = [];
  21285. for (; k < dimSize; k++) {
  21286. value[k] = chunks[dims[k]][rawIdx];
  21287. }
  21288. // Index
  21289. value[k] = i;
  21290. cb.apply(null, value);
  21291. }
  21292. }
  21293. };
  21294. /**
  21295. * Get extent of data in one dimension
  21296. */
  21297. DataStore.prototype.getDataExtent = function (dim) {
  21298. // Make sure use concrete dim as cache name.
  21299. var dimData = this._chunks[dim];
  21300. var initialExtent = getInitialExtent();
  21301. if (!dimData) {
  21302. return initialExtent;
  21303. }
  21304. // Make more strict checkings to ensure hitting cache.
  21305. var currEnd = this.count();
  21306. // Consider the most cases when using data zoom, `getDataExtent`
  21307. // happened before filtering. We cache raw extent, which is not
  21308. // necessary to be cleared and recalculated when restore data.
  21309. var useRaw = !this._indices;
  21310. var dimExtent;
  21311. if (useRaw) {
  21312. return this._rawExtent[dim].slice();
  21313. }
  21314. dimExtent = this._extent[dim];
  21315. if (dimExtent) {
  21316. return dimExtent.slice();
  21317. }
  21318. dimExtent = initialExtent;
  21319. var min = dimExtent[0];
  21320. var max = dimExtent[1];
  21321. for (var i = 0; i < currEnd; i++) {
  21322. var rawIdx = this.getRawIndex(i);
  21323. var value = dimData[rawIdx];
  21324. value < min && (min = value);
  21325. value > max && (max = value);
  21326. }
  21327. dimExtent = [min, max];
  21328. this._extent[dim] = dimExtent;
  21329. return dimExtent;
  21330. };
  21331. /**
  21332. * Get raw data item
  21333. */
  21334. DataStore.prototype.getRawDataItem = function (idx) {
  21335. var rawIdx = this.getRawIndex(idx);
  21336. if (!this._provider.persistent) {
  21337. var val = [];
  21338. var chunks = this._chunks;
  21339. for (var i = 0; i < chunks.length; i++) {
  21340. val.push(chunks[i][rawIdx]);
  21341. }
  21342. return val;
  21343. } else {
  21344. return this._provider.getItem(rawIdx);
  21345. }
  21346. };
  21347. /**
  21348. * Clone shallow.
  21349. *
  21350. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  21351. */
  21352. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  21353. var target = new DataStore();
  21354. var chunks = this._chunks;
  21355. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  21356. obj[dimIdx] = true;
  21357. return obj;
  21358. }, {});
  21359. if (clonedDimsMap) {
  21360. for (var i = 0; i < chunks.length; i++) {
  21361. // Not clone if dim is not picked.
  21362. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  21363. }
  21364. } else {
  21365. target._chunks = chunks;
  21366. }
  21367. this._copyCommonProps(target);
  21368. if (!ignoreIndices) {
  21369. target._indices = this._cloneIndices();
  21370. }
  21371. target._updateGetRawIdx();
  21372. return target;
  21373. };
  21374. DataStore.prototype._copyCommonProps = function (target) {
  21375. target._count = this._count;
  21376. target._rawCount = this._rawCount;
  21377. target._provider = this._provider;
  21378. target._dimensions = this._dimensions;
  21379. target._extent = clone(this._extent);
  21380. target._rawExtent = clone(this._rawExtent);
  21381. };
  21382. DataStore.prototype._cloneIndices = function () {
  21383. if (this._indices) {
  21384. var Ctor = this._indices.constructor;
  21385. var indices = void 0;
  21386. if (Ctor === Array) {
  21387. var thisCount = this._indices.length;
  21388. indices = new Ctor(thisCount);
  21389. for (var i = 0; i < thisCount; i++) {
  21390. indices[i] = this._indices[i];
  21391. }
  21392. } else {
  21393. indices = new Ctor(this._indices);
  21394. }
  21395. return indices;
  21396. }
  21397. return null;
  21398. };
  21399. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21400. return idx;
  21401. };
  21402. DataStore.prototype._getRawIdx = function (idx) {
  21403. if (idx < this._count && idx >= 0) {
  21404. return this._indices[idx];
  21405. }
  21406. return -1;
  21407. };
  21408. DataStore.prototype._updateGetRawIdx = function () {
  21409. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21410. };
  21411. DataStore.internalField = function () {
  21412. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21413. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21414. }
  21415. defaultDimValueGetters = {
  21416. arrayRows: getDimValueSimply,
  21417. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21418. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21419. },
  21420. keyedColumns: getDimValueSimply,
  21421. original: function (dataItem, property, dataIndex, dimIndex) {
  21422. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21423. // If dataItem is an plain object with no value field, the let `value`
  21424. // will be assigned with the object, but it will be tread correctly
  21425. // in the `convertValue`.
  21426. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21427. return parseDataValue(value instanceof Array ? value[dimIndex]
  21428. // If value is a single number or something else not array.
  21429. : value, this._dimensions[dimIndex]);
  21430. },
  21431. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21432. return dataItem[dimIndex];
  21433. }
  21434. };
  21435. }();
  21436. return DataStore;
  21437. }();
  21438. /**
  21439. * [REQUIREMENT_MEMO]:
  21440. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21441. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21442. * `root-dataset`. Them on `series` has higher priority.
  21443. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21444. * confuse users: whether those props indicate how to visit the upstream source or visit
  21445. * the transform result source, and some transforms has nothing to do with these props,
  21446. * and some transforms might have multiple upstream.
  21447. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21448. * declared in `root-dataset`.
  21449. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21450. * That is for reducing complexity in transforms.
  21451. * PENDING: Whether to provide transposition transform?
  21452. *
  21453. * [IMPLEMENTAION_MEMO]:
  21454. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21455. * They will not be calculated until `source` is about to be visited (to prevent from
  21456. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21457. *
  21458. * [DIMENSION_INHERIT_RULE]:
  21459. * By default the dimensions are inherited from ancestors, unless a transform return
  21460. * a new dimensions definition.
  21461. * Consider the case:
  21462. * ```js
  21463. * dataset: [{
  21464. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21465. * }, {
  21466. * transform: { type: 'filter', ... }
  21467. * }]
  21468. * dataset: [{
  21469. * dimension: ['Product', 'Sales', 'Prise'],
  21470. * source: [ ['Cookies', 321, 44.21], ...]
  21471. * }, {
  21472. * transform: { type: 'filter', ... }
  21473. * }]
  21474. * ```
  21475. * The two types of option should have the same behavior after transform.
  21476. *
  21477. *
  21478. * [SCENARIO]:
  21479. * (1) Provide source data directly:
  21480. * ```js
  21481. * series: {
  21482. * encode: {...},
  21483. * dimensions: [...]
  21484. * seriesLayoutBy: 'row',
  21485. * data: [[...]]
  21486. * }
  21487. * ```
  21488. * (2) Series refer to dataset.
  21489. * ```js
  21490. * series: [{
  21491. * encode: {...}
  21492. * // Ignore datasetIndex means `datasetIndex: 0`
  21493. * // and the dimensions defination in dataset is used
  21494. * }, {
  21495. * encode: {...},
  21496. * seriesLayoutBy: 'column',
  21497. * datasetIndex: 1
  21498. * }]
  21499. * ```
  21500. * (3) dataset transform
  21501. * ```js
  21502. * dataset: [{
  21503. * source: [...]
  21504. * }, {
  21505. * source: [...]
  21506. * }, {
  21507. * // By default from 0.
  21508. * transform: { type: 'filter', config: {...} }
  21509. * }, {
  21510. * // Piped.
  21511. * transform: [
  21512. * { type: 'filter', config: {...} },
  21513. * { type: 'sort', config: {...} }
  21514. * ]
  21515. * }, {
  21516. * id: 'regressionData',
  21517. * fromDatasetIndex: 1,
  21518. * // Third-party transform
  21519. * transform: { type: 'ecStat:regression', config: {...} }
  21520. * }, {
  21521. * // retrieve the extra result.
  21522. * id: 'regressionFormula',
  21523. * fromDatasetId: 'regressionData',
  21524. * fromTransformResult: 1
  21525. * }]
  21526. * ```
  21527. */
  21528. var SourceManager = /** @class */function () {
  21529. function SourceManager(sourceHost) {
  21530. // Cached source. Do not repeat calculating if not dirty.
  21531. this._sourceList = [];
  21532. this._storeList = [];
  21533. // version sign of each upstream source manager.
  21534. this._upstreamSignList = [];
  21535. this._versionSignBase = 0;
  21536. this._dirty = true;
  21537. this._sourceHost = sourceHost;
  21538. }
  21539. /**
  21540. * Mark dirty.
  21541. */
  21542. SourceManager.prototype.dirty = function () {
  21543. this._setLocalSource([], []);
  21544. this._storeList = [];
  21545. this._dirty = true;
  21546. };
  21547. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21548. this._sourceList = sourceList;
  21549. this._upstreamSignList = upstreamSignList;
  21550. this._versionSignBase++;
  21551. if (this._versionSignBase > 9e10) {
  21552. this._versionSignBase = 0;
  21553. }
  21554. };
  21555. /**
  21556. * For detecting whether the upstream source is dirty, so that
  21557. * the local cached source (in `_sourceList`) should be discarded.
  21558. */
  21559. SourceManager.prototype._getVersionSign = function () {
  21560. return this._sourceHost.uid + '_' + this._versionSignBase;
  21561. };
  21562. /**
  21563. * Always return a source instance. Otherwise throw error.
  21564. */
  21565. SourceManager.prototype.prepareSource = function () {
  21566. // For the case that call `setOption` multiple time but no data changed,
  21567. // cache the result source to prevent from repeating transform.
  21568. if (this._isDirty()) {
  21569. this._createSource();
  21570. this._dirty = false;
  21571. }
  21572. };
  21573. SourceManager.prototype._createSource = function () {
  21574. this._setLocalSource([], []);
  21575. var sourceHost = this._sourceHost;
  21576. var upSourceMgrList = this._getUpstreamSourceManagers();
  21577. var hasUpstream = !!upSourceMgrList.length;
  21578. var resultSourceList;
  21579. var upstreamSignList;
  21580. if (isSeries(sourceHost)) {
  21581. var seriesModel = sourceHost;
  21582. var data = void 0;
  21583. var sourceFormat = void 0;
  21584. var upSource = void 0;
  21585. // Has upstream dataset
  21586. if (hasUpstream) {
  21587. var upSourceMgr = upSourceMgrList[0];
  21588. upSourceMgr.prepareSource();
  21589. upSource = upSourceMgr.getSource();
  21590. data = upSource.data;
  21591. sourceFormat = upSource.sourceFormat;
  21592. upstreamSignList = [upSourceMgr._getVersionSign()];
  21593. }
  21594. // Series data is from own.
  21595. else {
  21596. data = seriesModel.get('data', true);
  21597. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21598. upstreamSignList = [];
  21599. }
  21600. // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21601. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21602. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21603. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21604. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader);
  21605. // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21606. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21607. // but series need `seriesLayoutBy: 'row'`.
  21608. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions);
  21609. // We share source with dataset as much as possible
  21610. // to avoid extra memory cost of high dimensional data.
  21611. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21612. resultSourceList = needsCreateSource ? [createSource(data, {
  21613. seriesLayoutBy: seriesLayoutBy,
  21614. sourceHeader: sourceHeader,
  21615. dimensions: dimensions
  21616. }, sourceFormat)] : [];
  21617. } else {
  21618. var datasetModel = sourceHost;
  21619. // Has upstream dataset.
  21620. if (hasUpstream) {
  21621. var result = this._applyTransform(upSourceMgrList);
  21622. resultSourceList = result.sourceList;
  21623. upstreamSignList = result.upstreamSignList;
  21624. }
  21625. // Is root dataset.
  21626. else {
  21627. var sourceData = datasetModel.get('source', true);
  21628. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21629. upstreamSignList = [];
  21630. }
  21631. }
  21632. if ("development" !== 'production') {
  21633. assert(resultSourceList && upstreamSignList);
  21634. }
  21635. this._setLocalSource(resultSourceList, upstreamSignList);
  21636. };
  21637. SourceManager.prototype._applyTransform = function (upMgrList) {
  21638. var datasetModel = this._sourceHost;
  21639. var transformOption = datasetModel.get('transform', true);
  21640. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21641. if ("development" !== 'production') {
  21642. assert(fromTransformResult != null || transformOption != null);
  21643. }
  21644. if (fromTransformResult != null) {
  21645. var errMsg = '';
  21646. if (upMgrList.length !== 1) {
  21647. if ("development" !== 'production') {
  21648. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21649. }
  21650. doThrow(errMsg);
  21651. }
  21652. }
  21653. var sourceList;
  21654. var upSourceList = [];
  21655. var upstreamSignList = [];
  21656. each(upMgrList, function (upMgr) {
  21657. upMgr.prepareSource();
  21658. var upSource = upMgr.getSource(fromTransformResult || 0);
  21659. var errMsg = '';
  21660. if (fromTransformResult != null && !upSource) {
  21661. if ("development" !== 'production') {
  21662. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21663. }
  21664. doThrow(errMsg);
  21665. }
  21666. upSourceList.push(upSource);
  21667. upstreamSignList.push(upMgr._getVersionSign());
  21668. });
  21669. if (transformOption) {
  21670. sourceList = applyDataTransform(transformOption, upSourceList, {
  21671. datasetIndex: datasetModel.componentIndex
  21672. });
  21673. } else if (fromTransformResult != null) {
  21674. sourceList = [cloneSourceShallow(upSourceList[0])];
  21675. }
  21676. return {
  21677. sourceList: sourceList,
  21678. upstreamSignList: upstreamSignList
  21679. };
  21680. };
  21681. SourceManager.prototype._isDirty = function () {
  21682. if (this._dirty) {
  21683. return true;
  21684. }
  21685. // All sourceList is from the some upstream.
  21686. var upSourceMgrList = this._getUpstreamSourceManagers();
  21687. for (var i = 0; i < upSourceMgrList.length; i++) {
  21688. var upSrcMgr = upSourceMgrList[i];
  21689. if (
  21690. // Consider the case that there is ancestor diry, call it recursively.
  21691. // The performance is probably not an issue because usually the chain is not long.
  21692. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21693. return true;
  21694. }
  21695. }
  21696. };
  21697. /**
  21698. * @param sourceIndex By default 0, means "main source".
  21699. * In most cases there is only one source.
  21700. */
  21701. SourceManager.prototype.getSource = function (sourceIndex) {
  21702. sourceIndex = sourceIndex || 0;
  21703. var source = this._sourceList[sourceIndex];
  21704. if (!source) {
  21705. // Series may share source instance with dataset.
  21706. var upSourceMgrList = this._getUpstreamSourceManagers();
  21707. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21708. }
  21709. return source;
  21710. };
  21711. /**
  21712. *
  21713. * Get a data store which can be shared across series.
  21714. * Only available for series.
  21715. *
  21716. * @param seriesDimRequest Dimensions that are generated in series.
  21717. * Should have been sorted by `storeDimIndex` asc.
  21718. */
  21719. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21720. if ("development" !== 'production') {
  21721. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21722. }
  21723. var schema = seriesDimRequest.makeStoreSchema();
  21724. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21725. };
  21726. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21727. // TODO Can use other sourceIndex?
  21728. var sourceIndex = 0;
  21729. var storeList = this._storeList;
  21730. var cachedStoreMap = storeList[sourceIndex];
  21731. if (!cachedStoreMap) {
  21732. cachedStoreMap = storeList[sourceIndex] = {};
  21733. }
  21734. var cachedStore = cachedStoreMap[sourceReadKey];
  21735. if (!cachedStore) {
  21736. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21737. if (isSeries(this._sourceHost) && upSourceMgr) {
  21738. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21739. } else {
  21740. cachedStore = new DataStore();
  21741. // Always create store from source of series.
  21742. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21743. }
  21744. cachedStoreMap[sourceReadKey] = cachedStore;
  21745. }
  21746. return cachedStore;
  21747. };
  21748. /**
  21749. * PENDING: Is it fast enough?
  21750. * If no upstream, return empty array.
  21751. */
  21752. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21753. // Always get the relationship from the raw option.
  21754. // Do not cache the link of the dependency graph, so that
  21755. // there is no need to update them when change happens.
  21756. var sourceHost = this._sourceHost;
  21757. if (isSeries(sourceHost)) {
  21758. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21759. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21760. } else {
  21761. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21762. return datasetModel.getSourceManager();
  21763. });
  21764. }
  21765. };
  21766. SourceManager.prototype._getSourceMetaRawOption = function () {
  21767. var sourceHost = this._sourceHost;
  21768. var seriesLayoutBy;
  21769. var sourceHeader;
  21770. var dimensions;
  21771. if (isSeries(sourceHost)) {
  21772. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21773. sourceHeader = sourceHost.get('sourceHeader', true);
  21774. dimensions = sourceHost.get('dimensions', true);
  21775. }
  21776. // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21777. else if (!this._getUpstreamSourceManagers().length) {
  21778. var model = sourceHost;
  21779. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21780. sourceHeader = model.get('sourceHeader', true);
  21781. dimensions = model.get('dimensions', true);
  21782. }
  21783. return {
  21784. seriesLayoutBy: seriesLayoutBy,
  21785. sourceHeader: sourceHeader,
  21786. dimensions: dimensions
  21787. };
  21788. };
  21789. return SourceManager;
  21790. }();
  21791. // Call this method after `super.init` and `super.mergeOption` to
  21792. // disable the transform merge, but do not disable transform clone from rawOption.
  21793. function disableTransformOptionMerge(datasetModel) {
  21794. var transformOption = datasetModel.option.transform;
  21795. transformOption && setAsPrimitive(datasetModel.option.transform);
  21796. }
  21797. function isSeries(sourceHost) {
  21798. // Avoid circular dependency with Series.ts
  21799. return sourceHost.mainType === 'series';
  21800. }
  21801. function doThrow(errMsg) {
  21802. throw new Error(errMsg);
  21803. }
  21804. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1';
  21805. // TODO: more textStyle option
  21806. function getTooltipTextStyle(textStyle, renderMode) {
  21807. var nameFontColor = textStyle.color || '#6e7079';
  21808. var nameFontSize = textStyle.fontSize || 12;
  21809. var nameFontWeight = textStyle.fontWeight || '400';
  21810. var valueFontColor = textStyle.color || '#464646';
  21811. var valueFontSize = textStyle.fontSize || 14;
  21812. var valueFontWeight = textStyle.fontWeight || '900';
  21813. if (renderMode === 'html') {
  21814. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21815. return {
  21816. // eslint-disable-next-line max-len
  21817. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21818. // eslint-disable-next-line max-len
  21819. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21820. };
  21821. } else {
  21822. return {
  21823. nameStyle: {
  21824. fontSize: nameFontSize,
  21825. fill: nameFontColor,
  21826. fontWeight: nameFontWeight
  21827. },
  21828. valueStyle: {
  21829. fontSize: valueFontSize,
  21830. fill: valueFontColor,
  21831. fontWeight: valueFontWeight
  21832. }
  21833. };
  21834. }
  21835. }
  21836. // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21837. // (value from UI design)
  21838. var HTML_GAPS = [0, 10, 20, 30];
  21839. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n'];
  21840. // eslint-disable-next-line max-len
  21841. function createTooltipMarkup(type, option) {
  21842. option.type = type;
  21843. return option;
  21844. }
  21845. function isSectionFragment(frag) {
  21846. return frag.type === 'section';
  21847. }
  21848. function getBuilder(frag) {
  21849. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21850. }
  21851. function getBlockGapLevel(frag) {
  21852. if (isSectionFragment(frag)) {
  21853. var gapLevel_1 = 0;
  21854. var subBlockLen = frag.blocks.length;
  21855. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21856. each(frag.blocks, function (subBlock) {
  21857. var subGapLevel = getBlockGapLevel(subBlock);
  21858. // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21859. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21860. if (subGapLevel >= gapLevel_1) {
  21861. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && (
  21862. // 0 always can not be readable gap level.
  21863. !subGapLevel
  21864. // If no header, always keep the sub gap level. Otherwise
  21865. // look weird in case `multipleSeries`.
  21866. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21867. }
  21868. });
  21869. return gapLevel_1;
  21870. }
  21871. return 0;
  21872. }
  21873. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21874. var noHeader = fragment.noHeader;
  21875. var gaps = getGap(getBlockGapLevel(fragment));
  21876. var subMarkupTextList = [];
  21877. var subBlocks = fragment.blocks || [];
  21878. assert(!subBlocks || isArray(subBlocks));
  21879. subBlocks = subBlocks || [];
  21880. var orderMode = ctx.orderMode;
  21881. if (fragment.sortBlocks && orderMode) {
  21882. subBlocks = subBlocks.slice();
  21883. var orderMap = {
  21884. valueAsc: 'asc',
  21885. valueDesc: 'desc'
  21886. };
  21887. if (hasOwn(orderMap, orderMode)) {
  21888. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21889. subBlocks.sort(function (a, b) {
  21890. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21891. });
  21892. }
  21893. // FIXME 'seriesDesc' necessary?
  21894. else if (orderMode === 'seriesDesc') {
  21895. subBlocks.reverse();
  21896. }
  21897. }
  21898. each(subBlocks, function (subBlock, idx) {
  21899. var valueFormatter = fragment.valueFormatter;
  21900. var subMarkupText = getBuilder(subBlock)(
  21901. // Inherit valueFormatter
  21902. valueFormatter ? extend(extend({}, ctx), {
  21903. valueFormatter: valueFormatter
  21904. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21905. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21906. });
  21907. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21908. if (noHeader) {
  21909. return subMarkupText;
  21910. }
  21911. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21912. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21913. if (ctx.renderMode === 'richText') {
  21914. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21915. } else {
  21916. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21917. }
  21918. }
  21919. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21920. var renderMode = ctx.renderMode;
  21921. var noName = fragment.noName;
  21922. var noValue = fragment.noValue;
  21923. var noMarker = !fragment.markerType;
  21924. var name = fragment.name;
  21925. var useUTC = ctx.useUTC;
  21926. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  21927. value = isArray(value) ? value : [value];
  21928. return map(value, function (val, idx) {
  21929. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21930. });
  21931. };
  21932. if (noName && noValue) {
  21933. return;
  21934. }
  21935. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21936. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21937. var valueTypeOption = fragment.valueType;
  21938. var readableValueList = noValue ? [] : valueFormatter(fragment.value, fragment.dataIndex);
  21939. var valueAlignRight = !noMarker || !noName;
  21940. // It little weird if only value next to marker but far from marker.
  21941. var valueCloseToMarker = !noMarker && noName;
  21942. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21943. nameStyle = _a.nameStyle,
  21944. valueStyle = _a.valueStyle;
  21945. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle))
  21946. // Value has commas inside, so use ' ' as delimiter for multiple values.
  21947. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21948. }
  21949. /**
  21950. * @return markupText. null/undefined means no content.
  21951. */
  21952. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21953. if (!fragment) {
  21954. return;
  21955. }
  21956. var builder = getBuilder(fragment);
  21957. var ctx = {
  21958. useUTC: useUTC,
  21959. renderMode: renderMode,
  21960. orderMode: orderMode,
  21961. markupStyleCreator: markupStyleCreator,
  21962. valueFormatter: fragment.valueFormatter
  21963. };
  21964. return builder(ctx, fragment, 0, toolTipTextStyle);
  21965. }
  21966. function getGap(gapLevel) {
  21967. return {
  21968. html: HTML_GAPS[gapLevel],
  21969. richText: RICH_TEXT_GAPS[gapLevel]
  21970. };
  21971. }
  21972. function wrapBlockHTML(encodedContent, topGap) {
  21973. var clearfix = '<div style="clear:both"></div>';
  21974. var marginCSS = "margin: " + topGap + "px 0 0";
  21975. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21976. }
  21977. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21978. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21979. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21980. }
  21981. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21982. // Do not too close to marker, considering there are multiple values separated by spaces.
  21983. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21984. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21985. valueList = isArray(valueList) ? valueList : [valueList];
  21986. return "<span style=\"" + alignCSS + ";" + style + "\">"
  21987. // Value has commas inside, so use ' ' as delimiter for multiple values.
  21988. + map(valueList, function (value) {
  21989. return encodeHTML(value);
  21990. }).join('&nbsp;&nbsp;') + '</span>';
  21991. }
  21992. function wrapInlineNameRichText(ctx, name, style) {
  21993. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21994. }
  21995. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  21996. var styles = [style];
  21997. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21998. alignRight && styles.push({
  21999. padding: [0, 0, 0, paddingLeft],
  22000. align: 'right'
  22001. });
  22002. // Value has commas inside, so use ' ' as delimiter for multiple values.
  22003. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  22004. }
  22005. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  22006. var style = series.getData().getItemVisual(dataIndex, 'style');
  22007. var color = style[series.visualDrawType];
  22008. return convertToColorString(color);
  22009. }
  22010. function getPaddingFromTooltipModel(model, renderMode) {
  22011. var padding = model.get('padding');
  22012. return padding != null ? padding
  22013. // We give slightly different to look pretty.
  22014. : renderMode === 'richText' ? [8, 10] : 10;
  22015. }
  22016. /**
  22017. * The major feature is generate styles for `renderMode: 'richText'`.
  22018. * But it also serves `renderMode: 'html'` to provide
  22019. * "renderMode-independent" API.
  22020. */
  22021. var TooltipMarkupStyleCreator = /** @class */function () {
  22022. function TooltipMarkupStyleCreator() {
  22023. this.richTextStyles = {};
  22024. // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  22025. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  22026. // rather than static shared by all creators (which will cause it increase to fast).
  22027. this._nextStyleNameId = getRandomIdBase();
  22028. }
  22029. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  22030. return '__EC_aUTo_' + this._nextStyleNameId++;
  22031. };
  22032. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  22033. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  22034. var marker = getTooltipMarker({
  22035. color: colorStr,
  22036. type: markerType,
  22037. renderMode: renderMode,
  22038. markerId: markerId
  22039. });
  22040. if (isString(marker)) {
  22041. return marker;
  22042. } else {
  22043. if ("development" !== 'production') {
  22044. assert(markerId);
  22045. }
  22046. this.richTextStyles[markerId] = marker.style;
  22047. return marker.content;
  22048. }
  22049. };
  22050. /**
  22051. * @usage
  22052. * ```ts
  22053. * const styledText = markupStyleCreator.wrapRichTextStyle([
  22054. * // The styles will be auto merged.
  22055. * {
  22056. * fontSize: 12,
  22057. * color: 'blue'
  22058. * },
  22059. * {
  22060. * padding: 20
  22061. * }
  22062. * ]);
  22063. * ```
  22064. */
  22065. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  22066. var finalStl = {};
  22067. if (isArray(styles)) {
  22068. each(styles, function (stl) {
  22069. return extend(finalStl, stl);
  22070. });
  22071. } else {
  22072. extend(finalStl, styles);
  22073. }
  22074. var styleName = this._generateStyleName();
  22075. this.richTextStyles[styleName] = finalStl;
  22076. return "{" + styleName + "|" + text + "}";
  22077. };
  22078. return TooltipMarkupStyleCreator;
  22079. }();
  22080. function defaultSeriesFormatTooltip(opt) {
  22081. var series = opt.series;
  22082. var dataIndex = opt.dataIndex;
  22083. var multipleSeries = opt.multipleSeries;
  22084. var data = series.getData();
  22085. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  22086. var tooltipDimLen = tooltipDims.length;
  22087. var value = series.getRawValue(dataIndex);
  22088. var isValueArr = isArray(value);
  22089. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex);
  22090. // Complicated rule for pretty tooltip.
  22091. var inlineValue;
  22092. var inlineValueType;
  22093. var subBlocks;
  22094. var sortParam;
  22095. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  22096. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  22097. inlineValue = formatArrResult.inlineValues;
  22098. inlineValueType = formatArrResult.inlineValueTypes;
  22099. subBlocks = formatArrResult.blocks;
  22100. // Only support tooltip sort by the first inline value. It's enough in most cases.
  22101. sortParam = formatArrResult.inlineValues[0];
  22102. } else if (tooltipDimLen) {
  22103. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  22104. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  22105. inlineValueType = dimInfo.type;
  22106. } else {
  22107. sortParam = inlineValue = isValueArr ? value[0] : value;
  22108. }
  22109. // Do not show generated series name. It might not be readable.
  22110. var seriesNameSpecified = isNameSpecified(series);
  22111. var seriesName = seriesNameSpecified && series.name || '';
  22112. var itemName = data.getName(dataIndex);
  22113. var inlineName = multipleSeries ? seriesName : itemName;
  22114. return createTooltipMarkup('section', {
  22115. header: seriesName,
  22116. // When series name is not specified, do not show a header line with only '-'.
  22117. // This case always happens in tooltip.trigger: 'item'.
  22118. noHeader: multipleSeries || !seriesNameSpecified,
  22119. sortParam: sortParam,
  22120. blocks: [createTooltipMarkup('nameValue', {
  22121. markerType: 'item',
  22122. markerColor: markerColor,
  22123. // Do not mix display seriesName and itemName in one tooltip,
  22124. // which might confuses users.
  22125. name: inlineName,
  22126. // name dimension might be auto assigned, where the name might
  22127. // be not readable. So we check trim here.
  22128. noName: !trim(inlineName),
  22129. value: inlineValue,
  22130. valueType: inlineValueType,
  22131. dataIndex: dataIndex
  22132. })].concat(subBlocks || [])
  22133. });
  22134. }
  22135. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  22136. // check: category-no-encode-has-axis-data in dataset.html
  22137. var data = series.getData();
  22138. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  22139. var dimItem = data.getDimensionInfo(idx);
  22140. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  22141. }, false);
  22142. var inlineValues = [];
  22143. var inlineValueTypes = [];
  22144. var blocks = [];
  22145. tooltipDims.length ? each(tooltipDims, function (dim) {
  22146. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  22147. })
  22148. // By default, all dims is used on tooltip.
  22149. : each(value, setEachItem);
  22150. function setEachItem(val, dim) {
  22151. var dimInfo = data.getDimensionInfo(dim);
  22152. // If `dimInfo.tooltip` is not set, show tooltip.
  22153. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  22154. return;
  22155. }
  22156. if (isValueMultipleLine) {
  22157. blocks.push(createTooltipMarkup('nameValue', {
  22158. markerType: 'subItem',
  22159. markerColor: colorStr,
  22160. name: dimInfo.displayName,
  22161. value: val,
  22162. valueType: dimInfo.type
  22163. }));
  22164. } else {
  22165. inlineValues.push(val);
  22166. inlineValueTypes.push(dimInfo.type);
  22167. }
  22168. }
  22169. return {
  22170. inlineValues: inlineValues,
  22171. inlineValueTypes: inlineValueTypes,
  22172. blocks: blocks
  22173. };
  22174. }
  22175. var inner$1 = makeInner();
  22176. function getSelectionKey(data, dataIndex) {
  22177. return data.getName(dataIndex) || data.getId(dataIndex);
  22178. }
  22179. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  22180. var SeriesModel = /** @class */function (_super) {
  22181. __extends(SeriesModel, _super);
  22182. function SeriesModel() {
  22183. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  22184. // the class members must not be initialized in constructor or declaration place.
  22185. // Otherwise there is bad case:
  22186. // class A {xxx = 1;}
  22187. // enableClassExtend(A);
  22188. // class B extends A {}
  22189. // var C = B.extend({xxx: 5});
  22190. // var c = new C();
  22191. // console.log(c.xxx); // expect 5 but always 1.
  22192. var _this = _super !== null && _super.apply(this, arguments) || this;
  22193. // ---------------------------------------
  22194. // Props about data selection
  22195. // ---------------------------------------
  22196. _this._selectedDataIndicesMap = {};
  22197. return _this;
  22198. }
  22199. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  22200. this.seriesIndex = this.componentIndex;
  22201. this.dataTask = createTask({
  22202. count: dataTaskCount,
  22203. reset: dataTaskReset
  22204. });
  22205. this.dataTask.context = {
  22206. model: this
  22207. };
  22208. this.mergeDefaultAndTheme(option, ecModel);
  22209. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  22210. sourceManager.prepareSource();
  22211. var data = this.getInitialData(option, ecModel);
  22212. wrapData(data, this);
  22213. this.dataTask.context.data = data;
  22214. if ("development" !== 'production') {
  22215. assert(data, 'getInitialData returned invalid data.');
  22216. }
  22217. inner$1(this).dataBeforeProcessed = data;
  22218. // If we reverse the order (make data firstly, and then make
  22219. // dataBeforeProcessed by cloneShallow), cloneShallow will
  22220. // cause data.graph.data !== data when using
  22221. // module:echarts/data/Graph or module:echarts/data/Tree.
  22222. // See module:echarts/data/helper/linkSeriesData
  22223. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  22224. // init or merge stage, because the data can be restored. So we do not `restoreData`
  22225. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  22226. // Call `seriesModel.getRawData()` instead.
  22227. // this.restoreData();
  22228. autoSeriesName(this);
  22229. this._initSelectedMapFromData(data);
  22230. };
  22231. /**
  22232. * Util for merge default and theme to option
  22233. */
  22234. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  22235. var layoutMode = fetchLayoutMode(this);
  22236. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  22237. // Backward compat: using subType on theme.
  22238. // But if name duplicate between series subType
  22239. // (for example: parallel) add component mainType,
  22240. // add suffix 'Series'.
  22241. var themeSubType = this.subType;
  22242. if (ComponentModel.hasClass(themeSubType)) {
  22243. themeSubType += 'Series';
  22244. }
  22245. merge(option, ecModel.getTheme().get(this.subType));
  22246. merge(option, this.getDefaultOption());
  22247. // Default label emphasis `show`
  22248. defaultEmphasis(option, 'label', ['show']);
  22249. this.fillDataTextStyle(option.data);
  22250. if (layoutMode) {
  22251. mergeLayoutParam(option, inputPositionParams, layoutMode);
  22252. }
  22253. };
  22254. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  22255. // this.settingTask.dirty();
  22256. newSeriesOption = merge(this.option, newSeriesOption, true);
  22257. this.fillDataTextStyle(newSeriesOption.data);
  22258. var layoutMode = fetchLayoutMode(this);
  22259. if (layoutMode) {
  22260. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  22261. }
  22262. var sourceManager = inner$1(this).sourceManager;
  22263. sourceManager.dirty();
  22264. sourceManager.prepareSource();
  22265. var data = this.getInitialData(newSeriesOption, ecModel);
  22266. wrapData(data, this);
  22267. this.dataTask.dirty();
  22268. this.dataTask.context.data = data;
  22269. inner$1(this).dataBeforeProcessed = data;
  22270. autoSeriesName(this);
  22271. this._initSelectedMapFromData(data);
  22272. };
  22273. SeriesModel.prototype.fillDataTextStyle = function (data) {
  22274. // Default data label emphasis `show`
  22275. // FIXME Tree structure data ?
  22276. // FIXME Performance ?
  22277. if (data && !isTypedArray(data)) {
  22278. var props = ['show'];
  22279. for (var i = 0; i < data.length; i++) {
  22280. if (data[i] && data[i].label) {
  22281. defaultEmphasis(data[i], 'label', props);
  22282. }
  22283. }
  22284. }
  22285. };
  22286. /**
  22287. * Init a data structure from data related option in series
  22288. * Must be overridden.
  22289. */
  22290. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  22291. return;
  22292. };
  22293. /**
  22294. * Append data to list
  22295. */
  22296. SeriesModel.prototype.appendData = function (params) {
  22297. // FIXME ???
  22298. // (1) If data from dataset, forbidden append.
  22299. // (2) support append data of dataset.
  22300. var data = this.getRawData();
  22301. data.appendData(params.data);
  22302. };
  22303. /**
  22304. * Consider some method like `filter`, `map` need make new data,
  22305. * We should make sure that `seriesModel.getData()` get correct
  22306. * data in the stream procedure. So we fetch data from upstream
  22307. * each time `task.perform` called.
  22308. */
  22309. SeriesModel.prototype.getData = function (dataType) {
  22310. var task = getCurrentTask(this);
  22311. if (task) {
  22312. var data = task.context.data;
  22313. return dataType == null || !data.getLinkedData ? data : data.getLinkedData(dataType);
  22314. } else {
  22315. // When series is not alive (that may happen when click toolbox
  22316. // restore or setOption with not merge mode), series data may
  22317. // be still need to judge animation or something when graphic
  22318. // elements want to know whether fade out.
  22319. return inner$1(this).data;
  22320. }
  22321. };
  22322. SeriesModel.prototype.getAllData = function () {
  22323. var mainData = this.getData();
  22324. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  22325. data: mainData
  22326. }];
  22327. };
  22328. SeriesModel.prototype.setData = function (data) {
  22329. var task = getCurrentTask(this);
  22330. if (task) {
  22331. var context = task.context;
  22332. // Consider case: filter, data sample.
  22333. // FIXME:TS never used, so comment it
  22334. // if (context.data !== data && task.modifyOutputEnd) {
  22335. // task.setOutputEnd(data.count());
  22336. // }
  22337. context.outputData = data;
  22338. // Caution: setData should update context.data,
  22339. // Because getData may be called multiply in a
  22340. // single stage and expect to get the data just
  22341. // set. (For example, AxisProxy, x y both call
  22342. // getData and setDate sequentially).
  22343. // So the context.data should be fetched from
  22344. // upstream each time when a stage starts to be
  22345. // performed.
  22346. if (task !== this.dataTask) {
  22347. context.data = data;
  22348. }
  22349. }
  22350. inner$1(this).data = data;
  22351. };
  22352. SeriesModel.prototype.getEncode = function () {
  22353. var encode = this.get('encode', true);
  22354. if (encode) {
  22355. return createHashMap(encode);
  22356. }
  22357. };
  22358. SeriesModel.prototype.getSourceManager = function () {
  22359. return inner$1(this).sourceManager;
  22360. };
  22361. SeriesModel.prototype.getSource = function () {
  22362. return this.getSourceManager().getSource();
  22363. };
  22364. /**
  22365. * Get data before processed
  22366. */
  22367. SeriesModel.prototype.getRawData = function () {
  22368. return inner$1(this).dataBeforeProcessed;
  22369. };
  22370. SeriesModel.prototype.getColorBy = function () {
  22371. var colorBy = this.get('colorBy');
  22372. return colorBy || 'series';
  22373. };
  22374. SeriesModel.prototype.isColorBySeries = function () {
  22375. return this.getColorBy() === 'series';
  22376. };
  22377. /**
  22378. * Get base axis if has coordinate system and has axis.
  22379. * By default use coordSys.getBaseAxis();
  22380. * Can be overridden for some chart.
  22381. * @return {type} description
  22382. */
  22383. SeriesModel.prototype.getBaseAxis = function () {
  22384. var coordSys = this.coordinateSystem;
  22385. // @ts-ignore
  22386. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  22387. };
  22388. /**
  22389. * Default tooltip formatter
  22390. *
  22391. * @param dataIndex
  22392. * @param multipleSeries
  22393. * @param dataType
  22394. * @param renderMode valid values: 'html'(by default) and 'richText'.
  22395. * 'html' is used for rendering tooltip in extra DOM form, and the result
  22396. * string is used as DOM HTML content.
  22397. * 'richText' is used for rendering tooltip in rich text form, for those where
  22398. * DOM operation is not supported.
  22399. * @return formatted tooltip with `html` and `markers`
  22400. * Notice: The override method can also return string
  22401. */
  22402. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22403. return defaultSeriesFormatTooltip({
  22404. series: this,
  22405. dataIndex: dataIndex,
  22406. multipleSeries: multipleSeries
  22407. });
  22408. };
  22409. SeriesModel.prototype.isAnimationEnabled = function () {
  22410. var ecModel = this.ecModel;
  22411. // Disable animation if using echarts in node but not give ssr flag.
  22412. // In ssr mode, renderToString will generate svg with css animation.
  22413. if (env.node && !(ecModel && ecModel.ssr)) {
  22414. return false;
  22415. }
  22416. var animationEnabled = this.getShallow('animation');
  22417. if (animationEnabled) {
  22418. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22419. animationEnabled = false;
  22420. }
  22421. }
  22422. return !!animationEnabled;
  22423. };
  22424. SeriesModel.prototype.restoreData = function () {
  22425. this.dataTask.dirty();
  22426. };
  22427. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22428. var ecModel = this.ecModel;
  22429. // PENDING
  22430. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22431. if (!color) {
  22432. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22433. }
  22434. return color;
  22435. };
  22436. /**
  22437. * Use `data.mapDimensionsAll(coordDim)` instead.
  22438. * @deprecated
  22439. */
  22440. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22441. return this.getRawData().mapDimensionsAll(coordDim);
  22442. };
  22443. /**
  22444. * Get progressive rendering count each step
  22445. */
  22446. SeriesModel.prototype.getProgressive = function () {
  22447. return this.get('progressive');
  22448. };
  22449. /**
  22450. * Get progressive rendering count each step
  22451. */
  22452. SeriesModel.prototype.getProgressiveThreshold = function () {
  22453. return this.get('progressiveThreshold');
  22454. };
  22455. // PENGING If selectedMode is null ?
  22456. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22457. this._innerSelect(this.getData(dataType), innerDataIndices);
  22458. };
  22459. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22460. var selectedMap = this.option.selectedMap;
  22461. if (!selectedMap) {
  22462. return;
  22463. }
  22464. var selectedMode = this.option.selectedMode;
  22465. var data = this.getData(dataType);
  22466. if (selectedMode === 'series' || selectedMap === 'all') {
  22467. this.option.selectedMap = {};
  22468. this._selectedDataIndicesMap = {};
  22469. return;
  22470. }
  22471. for (var i = 0; i < innerDataIndices.length; i++) {
  22472. var dataIndex = innerDataIndices[i];
  22473. var nameOrId = getSelectionKey(data, dataIndex);
  22474. selectedMap[nameOrId] = false;
  22475. this._selectedDataIndicesMap[nameOrId] = -1;
  22476. }
  22477. };
  22478. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22479. var tmpArr = [];
  22480. for (var i = 0; i < innerDataIndices.length; i++) {
  22481. tmpArr[0] = innerDataIndices[i];
  22482. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22483. }
  22484. };
  22485. SeriesModel.prototype.getSelectedDataIndices = function () {
  22486. if (this.option.selectedMap === 'all') {
  22487. return [].slice.call(this.getData().getIndices());
  22488. }
  22489. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22490. var nameOrIds = keys(selectedDataIndicesMap);
  22491. var dataIndices = [];
  22492. for (var i = 0; i < nameOrIds.length; i++) {
  22493. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22494. if (dataIndex >= 0) {
  22495. dataIndices.push(dataIndex);
  22496. }
  22497. }
  22498. return dataIndices;
  22499. };
  22500. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22501. var selectedMap = this.option.selectedMap;
  22502. if (!selectedMap) {
  22503. return false;
  22504. }
  22505. var data = this.getData(dataType);
  22506. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  22507. };
  22508. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22509. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22510. return true;
  22511. }
  22512. var universalTransitionOpt = this.option.universalTransition;
  22513. // Quick reject
  22514. if (!universalTransitionOpt) {
  22515. return false;
  22516. }
  22517. if (universalTransitionOpt === true) {
  22518. return true;
  22519. }
  22520. // Can be simply 'universalTransition: true'
  22521. return universalTransitionOpt && universalTransitionOpt.enabled;
  22522. };
  22523. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22524. var _a, _b;
  22525. var option = this.option;
  22526. var selectedMode = option.selectedMode;
  22527. var len = innerDataIndices.length;
  22528. if (!selectedMode || !len) {
  22529. return;
  22530. }
  22531. if (selectedMode === 'series') {
  22532. option.selectedMap = 'all';
  22533. } else if (selectedMode === 'multiple') {
  22534. if (!isObject(option.selectedMap)) {
  22535. option.selectedMap = {};
  22536. }
  22537. var selectedMap = option.selectedMap;
  22538. for (var i = 0; i < len; i++) {
  22539. var dataIndex = innerDataIndices[i];
  22540. // TODO different types of data share same object.
  22541. var nameOrId = getSelectionKey(data, dataIndex);
  22542. selectedMap[nameOrId] = true;
  22543. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22544. }
  22545. } else if (selectedMode === 'single' || selectedMode === true) {
  22546. var lastDataIndex = innerDataIndices[len - 1];
  22547. var nameOrId = getSelectionKey(data, lastDataIndex);
  22548. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22549. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22550. }
  22551. };
  22552. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22553. // Ignore select info in data if selectedMap exists.
  22554. // NOTE It's only for legacy usage. edge data is not supported.
  22555. if (this.option.selectedMap) {
  22556. return;
  22557. }
  22558. var dataIndices = [];
  22559. if (data.hasItemOption) {
  22560. data.each(function (idx) {
  22561. var rawItem = data.getRawDataItem(idx);
  22562. if (rawItem && rawItem.selected) {
  22563. dataIndices.push(idx);
  22564. }
  22565. });
  22566. }
  22567. if (dataIndices.length > 0) {
  22568. this._innerSelect(data, dataIndices);
  22569. }
  22570. };
  22571. // /**
  22572. // * @see {module:echarts/stream/Scheduler}
  22573. // */
  22574. // abstract pipeTask: null
  22575. SeriesModel.registerClass = function (clz) {
  22576. return ComponentModel.registerClass(clz);
  22577. };
  22578. SeriesModel.protoInitialize = function () {
  22579. var proto = SeriesModel.prototype;
  22580. proto.type = 'series.__base__';
  22581. proto.seriesIndex = 0;
  22582. proto.ignoreStyleOnData = false;
  22583. proto.hasSymbolVisual = false;
  22584. proto.defaultSymbol = 'circle';
  22585. // Make sure the values can be accessed!
  22586. proto.visualStyleAccessPath = 'itemStyle';
  22587. proto.visualDrawType = 'fill';
  22588. }();
  22589. return SeriesModel;
  22590. }(ComponentModel);
  22591. mixin(SeriesModel, DataFormatMixin);
  22592. mixin(SeriesModel, PaletteMixin);
  22593. mountExtend(SeriesModel, ComponentModel);
  22594. /**
  22595. * MUST be called after `prepareSource` called
  22596. * Here we need to make auto series, especially for auto legend. But we
  22597. * do not modify series.name in option to avoid side effects.
  22598. */
  22599. function autoSeriesName(seriesModel) {
  22600. // User specified name has higher priority, otherwise it may cause
  22601. // series can not be queried unexpectedly.
  22602. var name = seriesModel.name;
  22603. if (!isNameSpecified(seriesModel)) {
  22604. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22605. }
  22606. }
  22607. function getSeriesAutoName(seriesModel) {
  22608. var data = seriesModel.getRawData();
  22609. var dataDims = data.mapDimensionsAll('seriesName');
  22610. var nameArr = [];
  22611. each(dataDims, function (dataDim) {
  22612. var dimInfo = data.getDimensionInfo(dataDim);
  22613. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22614. });
  22615. return nameArr.join(' ');
  22616. }
  22617. function dataTaskCount(context) {
  22618. return context.model.getRawData().count();
  22619. }
  22620. function dataTaskReset(context) {
  22621. var seriesModel = context.model;
  22622. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22623. return dataTaskProgress;
  22624. }
  22625. function dataTaskProgress(param, context) {
  22626. // Avoid repeat cloneShallow when data just created in reset.
  22627. if (context.outputData && param.end > context.outputData.count()) {
  22628. context.model.getRawData().cloneShallow(context.outputData);
  22629. }
  22630. }
  22631. // TODO refactor
  22632. function wrapData(data, seriesModel) {
  22633. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22634. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22635. });
  22636. }
  22637. function onDataChange(seriesModel, newList) {
  22638. var task = getCurrentTask(seriesModel);
  22639. if (task) {
  22640. // Consider case: filter, selectRange
  22641. task.setOutputEnd((newList || this).count());
  22642. }
  22643. return newList;
  22644. }
  22645. function getCurrentTask(seriesModel) {
  22646. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22647. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22648. if (pipeline) {
  22649. // When pipline finished, the currrentTask keep the last
  22650. // task (renderTask).
  22651. var task = pipeline.currentTask;
  22652. if (task) {
  22653. var agentStubMap = task.agentStubMap;
  22654. if (agentStubMap) {
  22655. task = agentStubMap.get(seriesModel.uid);
  22656. }
  22657. }
  22658. return task;
  22659. }
  22660. }
  22661. var ComponentView = /** @class */function () {
  22662. function ComponentView() {
  22663. this.group = new Group();
  22664. this.uid = getUID('viewComponent');
  22665. }
  22666. ComponentView.prototype.init = function (ecModel, api) {};
  22667. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22668. ComponentView.prototype.dispose = function (ecModel, api) {};
  22669. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {
  22670. // Do nothing;
  22671. };
  22672. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {
  22673. // Do nothing;
  22674. };
  22675. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {
  22676. // Do nothing;
  22677. };
  22678. /**
  22679. * Hook for toggle blur target series.
  22680. * Can be used in marker for blur or leave blur the markers
  22681. */
  22682. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {
  22683. // Do nothing;
  22684. };
  22685. /**
  22686. * Traverse the new rendered elements.
  22687. *
  22688. * It will traverse the new added element in progressive rendering.
  22689. * And traverse all in normal rendering.
  22690. */
  22691. ComponentView.prototype.eachRendered = function (cb) {
  22692. var group = this.group;
  22693. if (group) {
  22694. group.traverse(cb);
  22695. }
  22696. };
  22697. return ComponentView;
  22698. }();
  22699. enableClassExtend(ComponentView);
  22700. enableClassManagement(ComponentView);
  22701. /**
  22702. * @return {string} If large mode changed, return string 'reset';
  22703. */
  22704. function createRenderPlanner() {
  22705. var inner = makeInner();
  22706. return function (seriesModel) {
  22707. var fields = inner(seriesModel);
  22708. var pipelineContext = seriesModel.pipelineContext;
  22709. var originalLarge = !!fields.large;
  22710. var originalProgressive = !!fields.progressiveRender;
  22711. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22712. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22713. // on `performRawSeries` in `Schedular.js`.
  22714. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22715. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22716. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22717. };
  22718. }
  22719. var inner$2 = makeInner();
  22720. var renderPlanner = createRenderPlanner();
  22721. var ChartView = /** @class */function () {
  22722. function ChartView() {
  22723. this.group = new Group();
  22724. this.uid = getUID('viewChart');
  22725. this.renderTask = createTask({
  22726. plan: renderTaskPlan,
  22727. reset: renderTaskReset
  22728. });
  22729. this.renderTask.context = {
  22730. view: this
  22731. };
  22732. }
  22733. ChartView.prototype.init = function (ecModel, api) {};
  22734. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22735. if ("development" !== 'production') {
  22736. throw new Error('render method must been implemented');
  22737. }
  22738. };
  22739. /**
  22740. * Highlight series or specified data item.
  22741. */
  22742. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22743. var data = seriesModel.getData(payload && payload.dataType);
  22744. if (!data) {
  22745. if ("development" !== 'production') {
  22746. error("Unknown dataType " + payload.dataType);
  22747. }
  22748. return;
  22749. }
  22750. toggleHighlight(data, payload, 'emphasis');
  22751. };
  22752. /**
  22753. * Downplay series or specified data item.
  22754. */
  22755. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22756. var data = seriesModel.getData(payload && payload.dataType);
  22757. if (!data) {
  22758. if ("development" !== 'production') {
  22759. error("Unknown dataType " + payload.dataType);
  22760. }
  22761. return;
  22762. }
  22763. toggleHighlight(data, payload, 'normal');
  22764. };
  22765. /**
  22766. * Remove self.
  22767. */
  22768. ChartView.prototype.remove = function (ecModel, api) {
  22769. this.group.removeAll();
  22770. };
  22771. /**
  22772. * Dispose self.
  22773. */
  22774. ChartView.prototype.dispose = function (ecModel, api) {};
  22775. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22776. this.render(seriesModel, ecModel, api, payload);
  22777. };
  22778. // FIXME never used?
  22779. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22780. this.render(seriesModel, ecModel, api, payload);
  22781. };
  22782. // FIXME never used?
  22783. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22784. this.render(seriesModel, ecModel, api, payload);
  22785. };
  22786. /**
  22787. * Traverse the new rendered elements.
  22788. *
  22789. * It will traverse the new added element in progressive rendering.
  22790. * And traverse all in normal rendering.
  22791. */
  22792. ChartView.prototype.eachRendered = function (cb) {
  22793. traverseElements(this.group, cb);
  22794. };
  22795. ChartView.markUpdateMethod = function (payload, methodName) {
  22796. inner$2(payload).updateMethod = methodName;
  22797. };
  22798. ChartView.protoInitialize = function () {
  22799. var proto = ChartView.prototype;
  22800. proto.type = 'chart';
  22801. }();
  22802. return ChartView;
  22803. }();
  22804. /**
  22805. * Set state of single element
  22806. */
  22807. function elSetState(el, state, highlightDigit) {
  22808. if (el && isHighDownDispatcher(el)) {
  22809. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22810. }
  22811. }
  22812. function toggleHighlight(data, payload, state) {
  22813. var dataIndex = queryDataIndex(data, payload);
  22814. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22815. if (dataIndex != null) {
  22816. each(normalizeToArray(dataIndex), function (dataIdx) {
  22817. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22818. });
  22819. } else {
  22820. data.eachItemGraphicEl(function (el) {
  22821. elSetState(el, state, highlightDigit);
  22822. });
  22823. }
  22824. }
  22825. enableClassExtend(ChartView, ['dispose']);
  22826. enableClassManagement(ChartView);
  22827. function renderTaskPlan(context) {
  22828. return renderPlanner(context.model);
  22829. }
  22830. function renderTaskReset(context) {
  22831. var seriesModel = context.model;
  22832. var ecModel = context.ecModel;
  22833. var api = context.api;
  22834. var payload = context.payload;
  22835. // FIXME: remove updateView updateVisual
  22836. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22837. var view = context.view;
  22838. var updateMethod = payload && inner$2(payload).updateMethod;
  22839. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod
  22840. // `appendData` is also supported when data amount
  22841. // is less than progressive threshold.
  22842. : 'render';
  22843. if (methodName !== 'render') {
  22844. view[methodName](seriesModel, ecModel, api, payload);
  22845. }
  22846. return progressMethodMap[methodName];
  22847. }
  22848. var progressMethodMap = {
  22849. incrementalPrepareRender: {
  22850. progress: function (params, context) {
  22851. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22852. }
  22853. },
  22854. render: {
  22855. // Put view.render in `progress` to support appendData. But in this case
  22856. // view.render should not be called in reset, otherwise it will be called
  22857. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22858. // in any cases.
  22859. forceFirstProgress: true,
  22860. progress: function (params, context) {
  22861. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22862. }
  22863. }
  22864. };
  22865. /*
  22866. * Licensed to the Apache Software Foundation (ASF) under one
  22867. * or more contributor license agreements. See the NOTICE file
  22868. * distributed with this work for additional information
  22869. * regarding copyright ownership. The ASF licenses this file
  22870. * to you under the Apache License, Version 2.0 (the
  22871. * "License"); you may not use this file except in compliance
  22872. * with the License. You may obtain a copy of the License at
  22873. *
  22874. * http://www.apache.org/licenses/LICENSE-2.0
  22875. *
  22876. * Unless required by applicable law or agreed to in writing,
  22877. * software distributed under the License is distributed on an
  22878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22879. * KIND, either express or implied. See the License for the
  22880. * specific language governing permissions and limitations
  22881. * under the License.
  22882. */
  22883. /**
  22884. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22885. */
  22886. /*
  22887. * Licensed to the Apache Software Foundation (ASF) under one
  22888. * or more contributor license agreements. See the NOTICE file
  22889. * distributed with this work for additional information
  22890. * regarding copyright ownership. The ASF licenses this file
  22891. * to you under the Apache License, Version 2.0 (the
  22892. * "License"); you may not use this file except in compliance
  22893. * with the License. You may obtain a copy of the License at
  22894. *
  22895. * http://www.apache.org/licenses/LICENSE-2.0
  22896. *
  22897. * Unless required by applicable law or agreed to in writing,
  22898. * software distributed under the License is distributed on an
  22899. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22900. * KIND, either express or implied. See the License for the
  22901. * specific language governing permissions and limitations
  22902. * under the License.
  22903. */
  22904. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22905. var RATE = '\0__throttleRate';
  22906. var THROTTLE_TYPE = '\0__throttleType';
  22907. /**
  22908. * @public
  22909. * @param {(Function)} fn
  22910. * @param {number} [delay=0] Unit: ms.
  22911. * @param {boolean} [debounce=false]
  22912. * true: If call interval less than `delay`, only the last call works.
  22913. * false: If call interval less than `delay, call works on fixed rate.
  22914. * @return {(Function)} throttled fn.
  22915. */
  22916. function throttle(fn, delay, debounce) {
  22917. var currCall;
  22918. var lastCall = 0;
  22919. var lastExec = 0;
  22920. var timer = null;
  22921. var diff;
  22922. var scope;
  22923. var args;
  22924. var debounceNextCall;
  22925. delay = delay || 0;
  22926. function exec() {
  22927. lastExec = new Date().getTime();
  22928. timer = null;
  22929. fn.apply(scope, args || []);
  22930. }
  22931. var cb = function () {
  22932. var cbArgs = [];
  22933. for (var _i = 0; _i < arguments.length; _i++) {
  22934. cbArgs[_i] = arguments[_i];
  22935. }
  22936. currCall = new Date().getTime();
  22937. scope = this;
  22938. args = cbArgs;
  22939. var thisDelay = debounceNextCall || delay;
  22940. var thisDebounce = debounceNextCall || debounce;
  22941. debounceNextCall = null;
  22942. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22943. clearTimeout(timer);
  22944. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22945. // than a new call of `cb`, that is, preserving the command order. Consider
  22946. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22947. // happens, either the `exec` is called dierectly, or the call is delayed.
  22948. // But the delayed call should never be later than next call of `cb`. Under
  22949. // this assurance, we can simply update view state each time `dispatchAction`
  22950. // triggered by user roaming, but not need to add extra code to avoid the
  22951. // state being "rolled-back".
  22952. if (thisDebounce) {
  22953. timer = setTimeout(exec, thisDelay);
  22954. } else {
  22955. if (diff >= 0) {
  22956. exec();
  22957. } else {
  22958. timer = setTimeout(exec, -diff);
  22959. }
  22960. }
  22961. lastCall = currCall;
  22962. };
  22963. /**
  22964. * Clear throttle.
  22965. * @public
  22966. */
  22967. cb.clear = function () {
  22968. if (timer) {
  22969. clearTimeout(timer);
  22970. timer = null;
  22971. }
  22972. };
  22973. /**
  22974. * Enable debounce once.
  22975. */
  22976. cb.debounceNextCall = function (debounceDelay) {
  22977. debounceNextCall = debounceDelay;
  22978. };
  22979. return cb;
  22980. }
  22981. /**
  22982. * Create throttle method or update throttle rate.
  22983. *
  22984. * @example
  22985. * ComponentView.prototype.render = function () {
  22986. * ...
  22987. * throttle.createOrUpdate(
  22988. * this,
  22989. * '_dispatchAction',
  22990. * this.model.get('throttle'),
  22991. * 'fixRate'
  22992. * );
  22993. * };
  22994. * ComponentView.prototype.remove = function () {
  22995. * throttle.clear(this, '_dispatchAction');
  22996. * };
  22997. * ComponentView.prototype.dispose = function () {
  22998. * throttle.clear(this, '_dispatchAction');
  22999. * };
  23000. *
  23001. */
  23002. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  23003. var fn = obj[fnAttr];
  23004. if (!fn) {
  23005. return;
  23006. }
  23007. var originFn = fn[ORIGIN_METHOD] || fn;
  23008. var lastThrottleType = fn[THROTTLE_TYPE];
  23009. var lastRate = fn[RATE];
  23010. if (lastRate !== rate || lastThrottleType !== throttleType) {
  23011. if (rate == null || !throttleType) {
  23012. return obj[fnAttr] = originFn;
  23013. }
  23014. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  23015. fn[ORIGIN_METHOD] = originFn;
  23016. fn[THROTTLE_TYPE] = throttleType;
  23017. fn[RATE] = rate;
  23018. }
  23019. return fn;
  23020. }
  23021. /**
  23022. * Clear throttle. Example see throttle.createOrUpdate.
  23023. */
  23024. function clear(obj, fnAttr) {
  23025. var fn = obj[fnAttr];
  23026. if (fn && fn[ORIGIN_METHOD]) {
  23027. // Clear throttle
  23028. fn.clear && fn.clear();
  23029. obj[fnAttr] = fn[ORIGIN_METHOD];
  23030. }
  23031. }
  23032. var inner$3 = makeInner();
  23033. var defaultStyleMappers = {
  23034. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  23035. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  23036. };
  23037. var defaultColorKey = {
  23038. lineStyle: 'stroke',
  23039. itemStyle: 'fill'
  23040. };
  23041. function getStyleMapper(seriesModel, stylePath) {
  23042. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  23043. if (!styleMapper) {
  23044. console.warn("Unknown style type '" + stylePath + "'.");
  23045. return defaultStyleMappers.itemStyle;
  23046. }
  23047. return styleMapper;
  23048. }
  23049. function getDefaultColorKey(seriesModel, stylePath) {
  23050. // return defaultColorKey[stylePath] ||
  23051. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  23052. if (!colorKey) {
  23053. console.warn("Unknown style type '" + stylePath + "'.");
  23054. return 'fill';
  23055. }
  23056. return colorKey;
  23057. }
  23058. var seriesStyleTask = {
  23059. createOnAllSeries: true,
  23060. performRawSeries: true,
  23061. reset: function (seriesModel, ecModel) {
  23062. var data = seriesModel.getData();
  23063. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23064. // Set in itemStyle
  23065. var styleModel = seriesModel.getModel(stylePath);
  23066. var getStyle = getStyleMapper(seriesModel, stylePath);
  23067. var globalStyle = getStyle(styleModel);
  23068. var decalOption = styleModel.getShallow('decal');
  23069. if (decalOption) {
  23070. data.setVisual('decal', decalOption);
  23071. decalOption.dirty = true;
  23072. }
  23073. // TODO
  23074. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23075. var color = globalStyle[colorKey];
  23076. // TODO style callback
  23077. var colorCallback = isFunction(color) ? color : null;
  23078. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto';
  23079. // Get from color palette by default.
  23080. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  23081. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  23082. // make it effect palette. Because some scenarios users need to make some series
  23083. // transparent or as background, which should better not effect the palette.
  23084. var colorPalette = seriesModel.getColorFromPalette(
  23085. // TODO series count changed.
  23086. seriesModel.name, null, ecModel.getSeriesCount());
  23087. if (!globalStyle[colorKey]) {
  23088. globalStyle[colorKey] = colorPalette;
  23089. data.setVisual('colorFromPalette', true);
  23090. }
  23091. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  23092. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  23093. }
  23094. data.setVisual('style', globalStyle);
  23095. data.setVisual('drawType', colorKey);
  23096. // Only visible series has each data be visual encoded
  23097. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  23098. data.setVisual('colorFromPalette', false);
  23099. return {
  23100. dataEach: function (data, idx) {
  23101. var dataParams = seriesModel.getDataParams(idx);
  23102. var itemStyle = extend({}, globalStyle);
  23103. itemStyle[colorKey] = colorCallback(dataParams);
  23104. data.setItemVisual(idx, 'style', itemStyle);
  23105. }
  23106. };
  23107. }
  23108. }
  23109. };
  23110. var sharedModel = new Model();
  23111. var dataStyleTask = {
  23112. createOnAllSeries: true,
  23113. performRawSeries: true,
  23114. reset: function (seriesModel, ecModel) {
  23115. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  23116. return;
  23117. }
  23118. var data = seriesModel.getData();
  23119. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23120. // Set in itemStyle
  23121. var getStyle = getStyleMapper(seriesModel, stylePath);
  23122. var colorKey = data.getVisual('drawType');
  23123. return {
  23124. dataEach: data.hasItemOption ? function (data, idx) {
  23125. // Not use getItemModel for performance considuration
  23126. var rawItem = data.getRawDataItem(idx);
  23127. if (rawItem && rawItem[stylePath]) {
  23128. sharedModel.option = rawItem[stylePath];
  23129. var style = getStyle(sharedModel);
  23130. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  23131. extend(existsStyle, style);
  23132. if (sharedModel.option.decal) {
  23133. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  23134. sharedModel.option.decal.dirty = true;
  23135. }
  23136. if (colorKey in style) {
  23137. data.setItemVisual(idx, 'colorFromPalette', false);
  23138. }
  23139. }
  23140. } : null
  23141. };
  23142. }
  23143. };
  23144. // Pick color from palette for the data which has not been set with color yet.
  23145. // Note: do not support stream rendering. No such cases yet.
  23146. var dataColorPaletteTask = {
  23147. performRawSeries: true,
  23148. overallReset: function (ecModel) {
  23149. // Each type of series uses one scope.
  23150. // Pie and funnel are using different scopes.
  23151. var paletteScopeGroupByType = createHashMap();
  23152. ecModel.eachSeries(function (seriesModel) {
  23153. var colorBy = seriesModel.getColorBy();
  23154. if (seriesModel.isColorBySeries()) {
  23155. return;
  23156. }
  23157. var key = seriesModel.type + '-' + colorBy;
  23158. var colorScope = paletteScopeGroupByType.get(key);
  23159. if (!colorScope) {
  23160. colorScope = {};
  23161. paletteScopeGroupByType.set(key, colorScope);
  23162. }
  23163. inner$3(seriesModel).scope = colorScope;
  23164. });
  23165. ecModel.eachSeries(function (seriesModel) {
  23166. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  23167. return;
  23168. }
  23169. var dataAll = seriesModel.getRawData();
  23170. var idxMap = {};
  23171. var data = seriesModel.getData();
  23172. var colorScope = inner$3(seriesModel).scope;
  23173. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23174. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23175. data.each(function (idx) {
  23176. var rawIdx = data.getRawIndex(idx);
  23177. idxMap[rawIdx] = idx;
  23178. });
  23179. // Iterate on data before filtered. To make sure color from palette can be
  23180. // Consistent when toggling legend.
  23181. dataAll.each(function (rawIdx) {
  23182. var idx = idxMap[rawIdx];
  23183. var fromPalette = data.getItemVisual(idx, 'colorFromPalette');
  23184. // Get color from palette for each data only when the color is inherited from series color, which is
  23185. // also picked from color palette. So following situation is not in the case:
  23186. // 1. series.itemStyle.color is set
  23187. // 2. color is encoded by visualMap
  23188. if (fromPalette) {
  23189. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  23190. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  23191. var dataCount = dataAll.count();
  23192. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  23193. }
  23194. });
  23195. });
  23196. }
  23197. };
  23198. var PI$3 = Math.PI;
  23199. /**
  23200. * @param {module:echarts/ExtensionAPI} api
  23201. * @param {Object} [opts]
  23202. * @param {string} [opts.text]
  23203. * @param {string} [opts.color]
  23204. * @param {string} [opts.textColor]
  23205. * @return {module:zrender/Element}
  23206. */
  23207. function defaultLoading(api, opts) {
  23208. opts = opts || {};
  23209. defaults(opts, {
  23210. text: 'loading',
  23211. textColor: '#000',
  23212. fontSize: 12,
  23213. fontWeight: 'normal',
  23214. fontStyle: 'normal',
  23215. fontFamily: 'sans-serif',
  23216. maskColor: 'rgba(255, 255, 255, 0.8)',
  23217. showSpinner: true,
  23218. color: '#5470c6',
  23219. spinnerRadius: 10,
  23220. lineWidth: 5,
  23221. zlevel: 0
  23222. });
  23223. var group = new Group();
  23224. var mask = new Rect({
  23225. style: {
  23226. fill: opts.maskColor
  23227. },
  23228. zlevel: opts.zlevel,
  23229. z: 10000
  23230. });
  23231. group.add(mask);
  23232. var textContent = new ZRText({
  23233. style: {
  23234. text: opts.text,
  23235. fill: opts.textColor,
  23236. fontSize: opts.fontSize,
  23237. fontWeight: opts.fontWeight,
  23238. fontStyle: opts.fontStyle,
  23239. fontFamily: opts.fontFamily
  23240. },
  23241. zlevel: opts.zlevel,
  23242. z: 10001
  23243. });
  23244. var labelRect = new Rect({
  23245. style: {
  23246. fill: 'none'
  23247. },
  23248. textContent: textContent,
  23249. textConfig: {
  23250. position: 'right',
  23251. distance: 10
  23252. },
  23253. zlevel: opts.zlevel,
  23254. z: 10001
  23255. });
  23256. group.add(labelRect);
  23257. var arc;
  23258. if (opts.showSpinner) {
  23259. arc = new Arc({
  23260. shape: {
  23261. startAngle: -PI$3 / 2,
  23262. endAngle: -PI$3 / 2 + 0.1,
  23263. r: opts.spinnerRadius
  23264. },
  23265. style: {
  23266. stroke: opts.color,
  23267. lineCap: 'round',
  23268. lineWidth: opts.lineWidth
  23269. },
  23270. zlevel: opts.zlevel,
  23271. z: 10001
  23272. });
  23273. arc.animateShape(true).when(1000, {
  23274. endAngle: PI$3 * 3 / 2
  23275. }).start('circularInOut');
  23276. arc.animateShape(true).when(1000, {
  23277. startAngle: PI$3 * 3 / 2
  23278. }).delay(300).start('circularInOut');
  23279. group.add(arc);
  23280. }
  23281. // Inject resize
  23282. group.resize = function () {
  23283. var textWidth = textContent.getBoundingRect().width;
  23284. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  23285. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  23286. // textDistance needs to be calculated when both animation and text exist
  23287. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2)
  23288. // only show the text
  23289. + (opts.showSpinner ? 0 : textWidth / 2)
  23290. // only show the spinner
  23291. + (textWidth ? 0 : r);
  23292. var cy = api.getHeight() / 2;
  23293. opts.showSpinner && arc.setShape({
  23294. cx: cx,
  23295. cy: cy
  23296. });
  23297. labelRect.setShape({
  23298. x: cx - r,
  23299. y: cy - r,
  23300. width: r * 2,
  23301. height: r * 2
  23302. });
  23303. mask.setShape({
  23304. x: 0,
  23305. y: 0,
  23306. width: api.getWidth(),
  23307. height: api.getHeight()
  23308. });
  23309. };
  23310. group.resize();
  23311. return group;
  23312. }
  23313. var Scheduler = /** @class */function () {
  23314. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  23315. // key: handlerUID
  23316. this._stageTaskMap = createHashMap();
  23317. this.ecInstance = ecInstance;
  23318. this.api = api;
  23319. // Fix current processors in case that in some rear cases that
  23320. // processors might be registered after echarts instance created.
  23321. // Register processors incrementally for a echarts instance is
  23322. // not supported by this stream architecture.
  23323. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  23324. visualHandlers = this._visualHandlers = visualHandlers.slice();
  23325. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  23326. }
  23327. Scheduler.prototype.restoreData = function (ecModel, payload) {
  23328. // TODO: Only restore needed series and components, but not all components.
  23329. // Currently `restoreData` of all of the series and component will be called.
  23330. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  23331. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  23332. // and some components like coordinate system, axes, dataZoom, visualMap only
  23333. // need their target series refresh.
  23334. // (1) If we are implementing this feature some day, we should consider these cases:
  23335. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  23336. // on the settings of `dataZoom`), it should be re-performed if the component
  23337. // is modified by `setOption`.
  23338. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  23339. // it should be re-performed when the result array of `getTargetSeries` changed.
  23340. // We use `dependencies` to cover these issues.
  23341. // (3) How to update target series when coordinate system related components modified.
  23342. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  23343. // and this case all of the tasks will be set as dirty.
  23344. ecModel.restoreData(payload);
  23345. // Theoretically an overall task not only depends on each of its target series, but also
  23346. // depends on all of the series.
  23347. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  23348. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  23349. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  23350. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  23351. // probably cause state chaos (consider `dataZoomProcessor`).
  23352. this._stageTaskMap.each(function (taskRecord) {
  23353. var overallTask = taskRecord.overallTask;
  23354. overallTask && overallTask.dirty();
  23355. });
  23356. };
  23357. // If seriesModel provided, incremental threshold is check by series data.
  23358. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  23359. // For overall task
  23360. if (!task.__pipeline) {
  23361. return;
  23362. }
  23363. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  23364. var pCtx = pipeline.context;
  23365. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  23366. var step = incremental ? pipeline.step : null;
  23367. var modDataCount = pCtx && pCtx.modDataCount;
  23368. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  23369. return {
  23370. step: step,
  23371. modBy: modBy,
  23372. modDataCount: modDataCount
  23373. };
  23374. };
  23375. Scheduler.prototype.getPipeline = function (pipelineId) {
  23376. return this._pipelineMap.get(pipelineId);
  23377. };
  23378. /**
  23379. * Current, progressive rendering starts from visual and layout.
  23380. * Always detect render mode in the same stage, avoiding that incorrect
  23381. * detection caused by data filtering.
  23382. * Caution:
  23383. * `updateStreamModes` use `seriesModel.getData()`.
  23384. */
  23385. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  23386. var pipeline = this._pipelineMap.get(seriesModel.uid);
  23387. var data = seriesModel.getData();
  23388. var dataLen = data.count();
  23389. // `progressiveRender` means that can render progressively in each
  23390. // animation frame. Note that some types of series do not provide
  23391. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  23392. // use the term `incremental` but not `progressive` to describe the
  23393. // case that `chart.appendData`.
  23394. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  23395. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  23396. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  23397. // see `test/candlestick-large3.html`
  23398. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  23399. seriesModel.pipelineContext = pipeline.context = {
  23400. progressiveRender: progressiveRender,
  23401. modDataCount: modDataCount,
  23402. large: large
  23403. };
  23404. };
  23405. Scheduler.prototype.restorePipelines = function (ecModel) {
  23406. var scheduler = this;
  23407. var pipelineMap = scheduler._pipelineMap = createHashMap();
  23408. ecModel.eachSeries(function (seriesModel) {
  23409. var progressive = seriesModel.getProgressive();
  23410. var pipelineId = seriesModel.uid;
  23411. pipelineMap.set(pipelineId, {
  23412. id: pipelineId,
  23413. head: null,
  23414. tail: null,
  23415. threshold: seriesModel.getProgressiveThreshold(),
  23416. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  23417. blockIndex: -1,
  23418. step: Math.round(progressive || 700),
  23419. count: 0
  23420. });
  23421. scheduler._pipe(seriesModel, seriesModel.dataTask);
  23422. });
  23423. };
  23424. Scheduler.prototype.prepareStageTasks = function () {
  23425. var stageTaskMap = this._stageTaskMap;
  23426. var ecModel = this.api.getModel();
  23427. var api = this.api;
  23428. each(this._allHandlers, function (handler) {
  23429. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  23430. var errMsg = '';
  23431. if ("development" !== 'production') {
  23432. // Currently do not need to support to sepecify them both.
  23433. errMsg = '"reset" and "overallReset" must not be both specified.';
  23434. }
  23435. assert(!(handler.reset && handler.overallReset), errMsg);
  23436. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  23437. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  23438. }, this);
  23439. };
  23440. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  23441. var renderTask = view.renderTask;
  23442. var context = renderTask.context;
  23443. context.model = model;
  23444. context.ecModel = ecModel;
  23445. context.api = api;
  23446. renderTask.__block = !view.incrementalPrepareRender;
  23447. this._pipe(model, renderTask);
  23448. };
  23449. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  23450. // If we do not use `block` here, it should be considered when to update modes.
  23451. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  23452. block: true
  23453. });
  23454. };
  23455. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  23456. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  23457. };
  23458. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  23459. opt = opt || {};
  23460. var unfinished = false;
  23461. var scheduler = this;
  23462. each(stageHandlers, function (stageHandler, idx) {
  23463. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23464. return;
  23465. }
  23466. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23467. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23468. var overallTask = stageHandlerRecord.overallTask;
  23469. if (overallTask) {
  23470. var overallNeedDirty_1;
  23471. var agentStubMap = overallTask.agentStubMap;
  23472. agentStubMap.each(function (stub) {
  23473. if (needSetDirty(opt, stub)) {
  23474. stub.dirty();
  23475. overallNeedDirty_1 = true;
  23476. }
  23477. });
  23478. overallNeedDirty_1 && overallTask.dirty();
  23479. scheduler.updatePayload(overallTask, payload);
  23480. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block);
  23481. // Execute stubs firstly, which may set the overall task dirty,
  23482. // then execute the overall task. And stub will call seriesModel.setData,
  23483. // which ensures that in the overallTask seriesModel.getData() will not
  23484. // return incorrect data.
  23485. agentStubMap.each(function (stub) {
  23486. stub.perform(performArgs_1);
  23487. });
  23488. if (overallTask.perform(performArgs_1)) {
  23489. unfinished = true;
  23490. }
  23491. } else if (seriesTaskMap) {
  23492. seriesTaskMap.each(function (task, pipelineId) {
  23493. if (needSetDirty(opt, task)) {
  23494. task.dirty();
  23495. }
  23496. var performArgs = scheduler.getPerformArgs(task, opt.block);
  23497. // FIXME
  23498. // if intending to declare `performRawSeries` in handlers, only
  23499. // stream-independent (specifically, data item independent) operations can be
  23500. // performed. Because if a series is filtered, most of the tasks will not
  23501. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23502. // Perhaps we should not provide a separate callback for this case instead
  23503. // of providing the config `performRawSeries`. The stream-dependent operations
  23504. // and stream-independent operations should better not be mixed.
  23505. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23506. scheduler.updatePayload(task, payload);
  23507. if (task.perform(performArgs)) {
  23508. unfinished = true;
  23509. }
  23510. });
  23511. }
  23512. });
  23513. function needSetDirty(opt, task) {
  23514. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23515. }
  23516. this.unfinished = unfinished || this.unfinished;
  23517. };
  23518. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23519. var unfinished;
  23520. ecModel.eachSeries(function (seriesModel) {
  23521. // Progress to the end for dataInit and dataRestore.
  23522. unfinished = seriesModel.dataTask.perform() || unfinished;
  23523. });
  23524. this.unfinished = unfinished || this.unfinished;
  23525. };
  23526. Scheduler.prototype.plan = function () {
  23527. // Travel pipelines, check block.
  23528. this._pipelineMap.each(function (pipeline) {
  23529. var task = pipeline.tail;
  23530. do {
  23531. if (task.__block) {
  23532. pipeline.blockIndex = task.__idxInPipeline;
  23533. break;
  23534. }
  23535. task = task.getUpstream();
  23536. } while (task);
  23537. });
  23538. };
  23539. Scheduler.prototype.updatePayload = function (task, payload) {
  23540. payload !== 'remain' && (task.context.payload = payload);
  23541. };
  23542. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23543. var scheduler = this;
  23544. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23545. // The count of stages are totally about only several dozen, so
  23546. // do not need to reuse the map.
  23547. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23548. var seriesType = stageHandler.seriesType;
  23549. var getTargetSeries = stageHandler.getTargetSeries;
  23550. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23551. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23552. // it works but it may cause other irrelevant charts blocked.
  23553. if (stageHandler.createOnAllSeries) {
  23554. ecModel.eachRawSeries(create);
  23555. } else if (seriesType) {
  23556. ecModel.eachRawSeriesByType(seriesType, create);
  23557. } else if (getTargetSeries) {
  23558. getTargetSeries(ecModel, api).each(create);
  23559. }
  23560. function create(seriesModel) {
  23561. var pipelineId = seriesModel.uid;
  23562. // Init tasks for each seriesModel only once.
  23563. // Reuse original task instance.
  23564. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23565. plan: seriesTaskPlan,
  23566. reset: seriesTaskReset,
  23567. count: seriesTaskCount
  23568. }));
  23569. task.context = {
  23570. model: seriesModel,
  23571. ecModel: ecModel,
  23572. api: api,
  23573. // PENDING: `useClearVisual` not used?
  23574. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23575. plan: stageHandler.plan,
  23576. reset: stageHandler.reset,
  23577. scheduler: scheduler
  23578. };
  23579. scheduler._pipe(seriesModel, task);
  23580. }
  23581. };
  23582. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23583. var scheduler = this;
  23584. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23585. // For overall task, the function only be called on reset stage.
  23586. || createTask({
  23587. reset: overallTaskReset
  23588. });
  23589. overallTask.context = {
  23590. ecModel: ecModel,
  23591. api: api,
  23592. overallReset: stageHandler.overallReset,
  23593. scheduler: scheduler
  23594. };
  23595. var oldAgentStubMap = overallTask.agentStubMap;
  23596. // The count of stages are totally about only several dozen, so
  23597. // do not need to reuse the map.
  23598. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23599. var seriesType = stageHandler.seriesType;
  23600. var getTargetSeries = stageHandler.getTargetSeries;
  23601. var overallProgress = true;
  23602. var shouldOverallTaskDirty = false;
  23603. // FIXME:TS never used, so comment it
  23604. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23605. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23606. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23607. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23608. // we set the pipeline block.
  23609. var errMsg = '';
  23610. if ("development" !== 'production') {
  23611. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  23612. }
  23613. assert(!stageHandler.createOnAllSeries, errMsg);
  23614. if (seriesType) {
  23615. ecModel.eachRawSeriesByType(seriesType, createStub);
  23616. } else if (getTargetSeries) {
  23617. getTargetSeries(ecModel, api).each(createStub);
  23618. }
  23619. // Otherwise, (usually it is legacy case), the overall task will only be
  23620. // executed when upstream is dirty. Otherwise the progressive rendering of all
  23621. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23622. // dirty info from upstream.
  23623. else {
  23624. overallProgress = false;
  23625. each(ecModel.getSeries(), createStub);
  23626. }
  23627. function createStub(seriesModel) {
  23628. var pipelineId = seriesModel.uid;
  23629. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || (
  23630. // When the result of `getTargetSeries` changed, the overallTask
  23631. // should be set as dirty and re-performed.
  23632. shouldOverallTaskDirty = true, createTask({
  23633. reset: stubReset,
  23634. onDirty: stubOnDirty
  23635. })));
  23636. stub.context = {
  23637. model: seriesModel,
  23638. overallProgress: overallProgress
  23639. // FIXME:TS never used, so comment it
  23640. // modifyOutputEnd: modifyOutputEnd
  23641. };
  23642. stub.agent = overallTask;
  23643. stub.__block = overallProgress;
  23644. scheduler._pipe(seriesModel, stub);
  23645. }
  23646. if (shouldOverallTaskDirty) {
  23647. overallTask.dirty();
  23648. }
  23649. };
  23650. Scheduler.prototype._pipe = function (seriesModel, task) {
  23651. var pipelineId = seriesModel.uid;
  23652. var pipeline = this._pipelineMap.get(pipelineId);
  23653. !pipeline.head && (pipeline.head = task);
  23654. pipeline.tail && pipeline.tail.pipe(task);
  23655. pipeline.tail = task;
  23656. task.__idxInPipeline = pipeline.count++;
  23657. task.__pipeline = pipeline;
  23658. };
  23659. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23660. if (isFunction(stageHandler)) {
  23661. stageHandler = {
  23662. overallReset: stageHandler,
  23663. seriesType: detectSeriseType(stageHandler)
  23664. };
  23665. }
  23666. stageHandler.uid = getUID('stageHandler');
  23667. visualType && (stageHandler.visualType = visualType);
  23668. return stageHandler;
  23669. };
  23670. return Scheduler;
  23671. }();
  23672. function overallTaskReset(context) {
  23673. context.overallReset(context.ecModel, context.api, context.payload);
  23674. }
  23675. function stubReset(context) {
  23676. return context.overallProgress && stubProgress;
  23677. }
  23678. function stubProgress() {
  23679. this.agent.dirty();
  23680. this.getDownstream().dirty();
  23681. }
  23682. function stubOnDirty() {
  23683. this.agent && this.agent.dirty();
  23684. }
  23685. function seriesTaskPlan(context) {
  23686. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23687. }
  23688. function seriesTaskReset(context) {
  23689. if (context.useClearVisual) {
  23690. context.data.clearAllVisual();
  23691. }
  23692. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23693. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23694. return makeSeriesTaskProgress(idx);
  23695. }) : singleSeriesTaskProgress;
  23696. }
  23697. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23698. function makeSeriesTaskProgress(resetDefineIdx) {
  23699. return function (params, context) {
  23700. var data = context.data;
  23701. var resetDefine = context.resetDefines[resetDefineIdx];
  23702. if (resetDefine && resetDefine.dataEach) {
  23703. for (var i = params.start; i < params.end; i++) {
  23704. resetDefine.dataEach(data, i);
  23705. }
  23706. } else if (resetDefine && resetDefine.progress) {
  23707. resetDefine.progress(params, data);
  23708. }
  23709. };
  23710. }
  23711. function seriesTaskCount(context) {
  23712. return context.data.count();
  23713. }
  23714. /**
  23715. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23716. * To ensure that they can work normally, they should work in block mode, that is,
  23717. * they should not be started util the previous tasks finished. So they cause the
  23718. * progressive rendering disabled. We try to detect the series type, to narrow down
  23719. * the block range to only the series type they concern, but not all series.
  23720. */
  23721. function detectSeriseType(legacyFunc) {
  23722. seriesType = null;
  23723. try {
  23724. // Assume there is no async when calling `eachSeriesByType`.
  23725. legacyFunc(ecModelMock, apiMock);
  23726. } catch (e) {}
  23727. return seriesType;
  23728. }
  23729. var ecModelMock = {};
  23730. var apiMock = {};
  23731. var seriesType;
  23732. mockMethods(ecModelMock, GlobalModel);
  23733. mockMethods(apiMock, ExtensionAPI);
  23734. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23735. seriesType = type;
  23736. };
  23737. ecModelMock.eachComponent = function (cond) {
  23738. if (cond.mainType === 'series' && cond.subType) {
  23739. seriesType = cond.subType;
  23740. }
  23741. };
  23742. function mockMethods(target, Clz) {
  23743. /* eslint-disable */
  23744. for (var name_1 in Clz.prototype) {
  23745. // Do not use hasOwnProperty
  23746. target[name_1] = noop;
  23747. }
  23748. /* eslint-enable */
  23749. }
  23750. /*
  23751. * Licensed to the Apache Software Foundation (ASF) under one
  23752. * or more contributor license agreements. See the NOTICE file
  23753. * distributed with this work for additional information
  23754. * regarding copyright ownership. The ASF licenses this file
  23755. * to you under the Apache License, Version 2.0 (the
  23756. * "License"); you may not use this file except in compliance
  23757. * with the License. You may obtain a copy of the License at
  23758. *
  23759. * http://www.apache.org/licenses/LICENSE-2.0
  23760. *
  23761. * Unless required by applicable law or agreed to in writing,
  23762. * software distributed under the License is distributed on an
  23763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23764. * KIND, either express or implied. See the License for the
  23765. * specific language governing permissions and limitations
  23766. * under the License.
  23767. */
  23768. /**
  23769. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23770. */
  23771. /*
  23772. * Licensed to the Apache Software Foundation (ASF) under one
  23773. * or more contributor license agreements. See the NOTICE file
  23774. * distributed with this work for additional information
  23775. * regarding copyright ownership. The ASF licenses this file
  23776. * to you under the Apache License, Version 2.0 (the
  23777. * "License"); you may not use this file except in compliance
  23778. * with the License. You may obtain a copy of the License at
  23779. *
  23780. * http://www.apache.org/licenses/LICENSE-2.0
  23781. *
  23782. * Unless required by applicable law or agreed to in writing,
  23783. * software distributed under the License is distributed on an
  23784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23785. * KIND, either express or implied. See the License for the
  23786. * specific language governing permissions and limitations
  23787. * under the License.
  23788. */
  23789. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23790. var lightTheme = {
  23791. color: colorAll,
  23792. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23793. };
  23794. /*
  23795. * Licensed to the Apache Software Foundation (ASF) under one
  23796. * or more contributor license agreements. See the NOTICE file
  23797. * distributed with this work for additional information
  23798. * regarding copyright ownership. The ASF licenses this file
  23799. * to you under the Apache License, Version 2.0 (the
  23800. * "License"); you may not use this file except in compliance
  23801. * with the License. You may obtain a copy of the License at
  23802. *
  23803. * http://www.apache.org/licenses/LICENSE-2.0
  23804. *
  23805. * Unless required by applicable law or agreed to in writing,
  23806. * software distributed under the License is distributed on an
  23807. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23808. * KIND, either express or implied. See the License for the
  23809. * specific language governing permissions and limitations
  23810. * under the License.
  23811. */
  23812. /**
  23813. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23814. */
  23815. /*
  23816. * Licensed to the Apache Software Foundation (ASF) under one
  23817. * or more contributor license agreements. See the NOTICE file
  23818. * distributed with this work for additional information
  23819. * regarding copyright ownership. The ASF licenses this file
  23820. * to you under the Apache License, Version 2.0 (the
  23821. * "License"); you may not use this file except in compliance
  23822. * with the License. You may obtain a copy of the License at
  23823. *
  23824. * http://www.apache.org/licenses/LICENSE-2.0
  23825. *
  23826. * Unless required by applicable law or agreed to in writing,
  23827. * software distributed under the License is distributed on an
  23828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23829. * KIND, either express or implied. See the License for the
  23830. * specific language governing permissions and limitations
  23831. * under the License.
  23832. */
  23833. var contrastColor = '#B9B8CE';
  23834. var backgroundColor = '#100C2A';
  23835. var axisCommon = function () {
  23836. return {
  23837. axisLine: {
  23838. lineStyle: {
  23839. color: contrastColor
  23840. }
  23841. },
  23842. splitLine: {
  23843. lineStyle: {
  23844. color: '#484753'
  23845. }
  23846. },
  23847. splitArea: {
  23848. areaStyle: {
  23849. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23850. }
  23851. },
  23852. minorSplitLine: {
  23853. lineStyle: {
  23854. color: '#20203B'
  23855. }
  23856. }
  23857. };
  23858. };
  23859. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23860. var theme = {
  23861. darkMode: true,
  23862. color: colorPalette,
  23863. backgroundColor: backgroundColor,
  23864. axisPointer: {
  23865. lineStyle: {
  23866. color: '#817f91'
  23867. },
  23868. crossStyle: {
  23869. color: '#817f91'
  23870. },
  23871. label: {
  23872. // TODO Contrast of label backgorundColor
  23873. color: '#fff'
  23874. }
  23875. },
  23876. legend: {
  23877. textStyle: {
  23878. color: contrastColor
  23879. }
  23880. },
  23881. textStyle: {
  23882. color: contrastColor
  23883. },
  23884. title: {
  23885. textStyle: {
  23886. color: '#EEF1FA'
  23887. },
  23888. subtextStyle: {
  23889. color: '#B9B8CE'
  23890. }
  23891. },
  23892. toolbox: {
  23893. iconStyle: {
  23894. borderColor: contrastColor
  23895. }
  23896. },
  23897. dataZoom: {
  23898. borderColor: '#71708A',
  23899. textStyle: {
  23900. color: contrastColor
  23901. },
  23902. brushStyle: {
  23903. color: 'rgba(135,163,206,0.3)'
  23904. },
  23905. handleStyle: {
  23906. color: '#353450',
  23907. borderColor: '#C5CBE3'
  23908. },
  23909. moveHandleStyle: {
  23910. color: '#B0B6C3',
  23911. opacity: 0.3
  23912. },
  23913. fillerColor: 'rgba(135,163,206,0.2)',
  23914. emphasis: {
  23915. handleStyle: {
  23916. borderColor: '#91B7F2',
  23917. color: '#4D587D'
  23918. },
  23919. moveHandleStyle: {
  23920. color: '#636D9A',
  23921. opacity: 0.7
  23922. }
  23923. },
  23924. dataBackground: {
  23925. lineStyle: {
  23926. color: '#71708A',
  23927. width: 1
  23928. },
  23929. areaStyle: {
  23930. color: '#71708A'
  23931. }
  23932. },
  23933. selectedDataBackground: {
  23934. lineStyle: {
  23935. color: '#87A3CE'
  23936. },
  23937. areaStyle: {
  23938. color: '#87A3CE'
  23939. }
  23940. }
  23941. },
  23942. visualMap: {
  23943. textStyle: {
  23944. color: contrastColor
  23945. }
  23946. },
  23947. timeline: {
  23948. lineStyle: {
  23949. color: contrastColor
  23950. },
  23951. label: {
  23952. color: contrastColor
  23953. },
  23954. controlStyle: {
  23955. color: contrastColor,
  23956. borderColor: contrastColor
  23957. }
  23958. },
  23959. calendar: {
  23960. itemStyle: {
  23961. color: backgroundColor
  23962. },
  23963. dayLabel: {
  23964. color: contrastColor
  23965. },
  23966. monthLabel: {
  23967. color: contrastColor
  23968. },
  23969. yearLabel: {
  23970. color: contrastColor
  23971. }
  23972. },
  23973. timeAxis: axisCommon(),
  23974. logAxis: axisCommon(),
  23975. valueAxis: axisCommon(),
  23976. categoryAxis: axisCommon(),
  23977. line: {
  23978. symbol: 'circle'
  23979. },
  23980. graph: {
  23981. color: colorPalette
  23982. },
  23983. gauge: {
  23984. title: {
  23985. color: contrastColor
  23986. },
  23987. axisLine: {
  23988. lineStyle: {
  23989. color: [[1, 'rgba(207,212,219,0.2)']]
  23990. }
  23991. },
  23992. axisLabel: {
  23993. color: contrastColor
  23994. },
  23995. detail: {
  23996. color: '#EEF1FA'
  23997. }
  23998. },
  23999. candlestick: {
  24000. itemStyle: {
  24001. color: '#f64e56',
  24002. color0: '#54ea92',
  24003. borderColor: '#f64e56',
  24004. borderColor0: '#54ea92'
  24005. // borderColor: '#ca2824',
  24006. // borderColor0: '#09a443'
  24007. }
  24008. }
  24009. };
  24010. theme.categoryAxis.splitLine.show = false;
  24011. /**
  24012. * Usage of query:
  24013. * `chart.on('click', query, handler);`
  24014. * The `query` can be:
  24015. * + The component type query string, only `mainType` or `mainType.subType`,
  24016. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24017. * + The component query object, like:
  24018. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24019. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24020. * + The data query object, like:
  24021. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24022. * + The other query object (cmponent customized query), like:
  24023. * `{element: 'some'}` (only available in custom series).
  24024. *
  24025. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24026. * same as there is no such prop in the `query` object.
  24027. */
  24028. var ECEventProcessor = /** @class */function () {
  24029. function ECEventProcessor() {}
  24030. ECEventProcessor.prototype.normalizeQuery = function (query) {
  24031. var cptQuery = {};
  24032. var dataQuery = {};
  24033. var otherQuery = {};
  24034. // `query` is `mainType` or `mainType.subType` of component.
  24035. if (isString(query)) {
  24036. var condCptType = parseClassType(query);
  24037. // `.main` and `.sub` may be ''.
  24038. cptQuery.mainType = condCptType.main || null;
  24039. cptQuery.subType = condCptType.sub || null;
  24040. }
  24041. // `query` is an object, convert to {mainType, index, name, id}.
  24042. else {
  24043. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24044. // can not be used in `compomentModel.filterForExposedEvent`.
  24045. var suffixes_1 = ['Index', 'Name', 'Id'];
  24046. var dataKeys_1 = {
  24047. name: 1,
  24048. dataIndex: 1,
  24049. dataType: 1
  24050. };
  24051. each(query, function (val, key) {
  24052. var reserved = false;
  24053. for (var i = 0; i < suffixes_1.length; i++) {
  24054. var propSuffix = suffixes_1[i];
  24055. var suffixPos = key.lastIndexOf(propSuffix);
  24056. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24057. var mainType = key.slice(0, suffixPos);
  24058. // Consider `dataIndex`.
  24059. if (mainType !== 'data') {
  24060. cptQuery.mainType = mainType;
  24061. cptQuery[propSuffix.toLowerCase()] = val;
  24062. reserved = true;
  24063. }
  24064. }
  24065. }
  24066. if (dataKeys_1.hasOwnProperty(key)) {
  24067. dataQuery[key] = val;
  24068. reserved = true;
  24069. }
  24070. if (!reserved) {
  24071. otherQuery[key] = val;
  24072. }
  24073. });
  24074. }
  24075. return {
  24076. cptQuery: cptQuery,
  24077. dataQuery: dataQuery,
  24078. otherQuery: otherQuery
  24079. };
  24080. };
  24081. ECEventProcessor.prototype.filter = function (eventType, query) {
  24082. // They should be assigned before each trigger call.
  24083. var eventInfo = this.eventInfo;
  24084. if (!eventInfo) {
  24085. return true;
  24086. }
  24087. var targetEl = eventInfo.targetEl;
  24088. var packedEvent = eventInfo.packedEvent;
  24089. var model = eventInfo.model;
  24090. var view = eventInfo.view;
  24091. // For event like 'globalout'.
  24092. if (!model || !view) {
  24093. return true;
  24094. }
  24095. var cptQuery = query.cptQuery;
  24096. var dataQuery = query.dataQuery;
  24097. 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));
  24098. function check(query, host, prop, propOnHost) {
  24099. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24100. }
  24101. };
  24102. ECEventProcessor.prototype.afterTrigger = function () {
  24103. // Make sure the eventInfo won't be used in next trigger.
  24104. this.eventInfo = null;
  24105. };
  24106. return ECEventProcessor;
  24107. }();
  24108. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  24109. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']);
  24110. // Encoding visual for all series include which is filtered for legend drawing
  24111. var seriesSymbolTask = {
  24112. createOnAllSeries: true,
  24113. // For legend.
  24114. performRawSeries: true,
  24115. reset: function (seriesModel, ecModel) {
  24116. var data = seriesModel.getData();
  24117. if (seriesModel.legendIcon) {
  24118. data.setVisual('legendIcon', seriesModel.legendIcon);
  24119. }
  24120. if (!seriesModel.hasSymbolVisual) {
  24121. return;
  24122. }
  24123. var symbolOptions = {};
  24124. var symbolOptionsCb = {};
  24125. var hasCallback = false;
  24126. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  24127. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  24128. var val = seriesModel.get(symbolPropName);
  24129. if (isFunction(val)) {
  24130. hasCallback = true;
  24131. symbolOptionsCb[symbolPropName] = val;
  24132. } else {
  24133. symbolOptions[symbolPropName] = val;
  24134. }
  24135. }
  24136. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  24137. data.setVisual(extend({
  24138. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  24139. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  24140. }, symbolOptions));
  24141. // Only visible series has each data be visual encoded
  24142. if (ecModel.isSeriesFiltered(seriesModel)) {
  24143. return;
  24144. }
  24145. var symbolPropsCb = keys(symbolOptionsCb);
  24146. function dataEach(data, idx) {
  24147. var rawValue = seriesModel.getRawValue(idx);
  24148. var params = seriesModel.getDataParams(idx);
  24149. for (var i = 0; i < symbolPropsCb.length; i++) {
  24150. var symbolPropName = symbolPropsCb[i];
  24151. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  24152. }
  24153. }
  24154. return {
  24155. dataEach: hasCallback ? dataEach : null
  24156. };
  24157. }
  24158. };
  24159. var dataSymbolTask = {
  24160. createOnAllSeries: true,
  24161. // For legend.
  24162. performRawSeries: true,
  24163. reset: function (seriesModel, ecModel) {
  24164. if (!seriesModel.hasSymbolVisual) {
  24165. return;
  24166. }
  24167. // Only visible series has each data be visual encoded
  24168. if (ecModel.isSeriesFiltered(seriesModel)) {
  24169. return;
  24170. }
  24171. var data = seriesModel.getData();
  24172. function dataEach(data, idx) {
  24173. var itemModel = data.getItemModel(idx);
  24174. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  24175. var symbolPropName = SYMBOL_PROPS[i];
  24176. var val = itemModel.getShallow(symbolPropName, true);
  24177. if (val != null) {
  24178. data.setItemVisual(idx, symbolPropName, val);
  24179. }
  24180. }
  24181. }
  24182. return {
  24183. dataEach: data.hasItemOption ? dataEach : null
  24184. };
  24185. }
  24186. };
  24187. /*
  24188. * Licensed to the Apache Software Foundation (ASF) under one
  24189. * or more contributor license agreements. See the NOTICE file
  24190. * distributed with this work for additional information
  24191. * regarding copyright ownership. The ASF licenses this file
  24192. * to you under the Apache License, Version 2.0 (the
  24193. * "License"); you may not use this file except in compliance
  24194. * with the License. You may obtain a copy of the License at
  24195. *
  24196. * http://www.apache.org/licenses/LICENSE-2.0
  24197. *
  24198. * Unless required by applicable law or agreed to in writing,
  24199. * software distributed under the License is distributed on an
  24200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24201. * KIND, either express or implied. See the License for the
  24202. * specific language governing permissions and limitations
  24203. * under the License.
  24204. */
  24205. /**
  24206. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24207. */
  24208. /*
  24209. * Licensed to the Apache Software Foundation (ASF) under one
  24210. * or more contributor license agreements. See the NOTICE file
  24211. * distributed with this work for additional information
  24212. * regarding copyright ownership. The ASF licenses this file
  24213. * to you under the Apache License, Version 2.0 (the
  24214. * "License"); you may not use this file except in compliance
  24215. * with the License. You may obtain a copy of the License at
  24216. *
  24217. * http://www.apache.org/licenses/LICENSE-2.0
  24218. *
  24219. * Unless required by applicable law or agreed to in writing,
  24220. * software distributed under the License is distributed on an
  24221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24222. * KIND, either express or implied. See the License for the
  24223. * specific language governing permissions and limitations
  24224. * under the License.
  24225. */
  24226. function getItemVisualFromData(data, dataIndex, key) {
  24227. switch (key) {
  24228. case 'color':
  24229. var style = data.getItemVisual(dataIndex, 'style');
  24230. return style[data.getVisual('drawType')];
  24231. case 'opacity':
  24232. return data.getItemVisual(dataIndex, 'style').opacity;
  24233. case 'symbol':
  24234. case 'symbolSize':
  24235. case 'liftZ':
  24236. return data.getItemVisual(dataIndex, key);
  24237. default:
  24238. if ("development" !== 'production') {
  24239. console.warn("Unknown visual type " + key);
  24240. }
  24241. }
  24242. }
  24243. function getVisualFromData(data, key) {
  24244. switch (key) {
  24245. case 'color':
  24246. var style = data.getVisual('style');
  24247. return style[data.getVisual('drawType')];
  24248. case 'opacity':
  24249. return data.getVisual('style').opacity;
  24250. case 'symbol':
  24251. case 'symbolSize':
  24252. case 'liftZ':
  24253. return data.getVisual(key);
  24254. default:
  24255. if ("development" !== 'production') {
  24256. console.warn("Unknown visual type " + key);
  24257. }
  24258. }
  24259. }
  24260. // Legacy data selection action.
  24261. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  24262. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  24263. function getSeriesIndices(ecModel, payload) {
  24264. var seriesIndices = [];
  24265. ecModel.eachComponent({
  24266. mainType: 'series',
  24267. subType: seriesType,
  24268. query: payload
  24269. }, function (seriesModel) {
  24270. seriesIndices.push(seriesModel.seriesIndex);
  24271. });
  24272. return seriesIndices;
  24273. }
  24274. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  24275. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  24276. payload = extend({}, payload);
  24277. if ("development" !== 'production') {
  24278. deprecateReplaceLog(payload.type, eventsMap[1]);
  24279. }
  24280. api.dispatchAction(extend(payload, {
  24281. type: eventsMap[1],
  24282. seriesIndex: getSeriesIndices(ecModel, payload)
  24283. }));
  24284. });
  24285. });
  24286. }
  24287. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  24288. var legacyEventName = type + eventPostfix;
  24289. if (!ecIns.isSilent(legacyEventName)) {
  24290. if ("development" !== 'production') {
  24291. deprecateLog("event " + legacyEventName + " is deprecated.");
  24292. }
  24293. ecModel.eachComponent({
  24294. mainType: 'series',
  24295. subType: 'pie'
  24296. }, function (seriesModel) {
  24297. var seriesIndex = seriesModel.seriesIndex;
  24298. var selectedMap = seriesModel.option.selectedMap;
  24299. var selected = payload.selected;
  24300. for (var i = 0; i < selected.length; i++) {
  24301. if (selected[i].seriesIndex === seriesIndex) {
  24302. var data = seriesModel.getData();
  24303. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  24304. ecIns.trigger(legacyEventName, {
  24305. type: legacyEventName,
  24306. seriesId: seriesModel.id,
  24307. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  24308. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  24309. });
  24310. }
  24311. }
  24312. });
  24313. }
  24314. }
  24315. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  24316. messageCenter.on('selectchanged', function (params) {
  24317. var ecModel = api.getModel();
  24318. if (params.isFromClick) {
  24319. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  24320. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  24321. } else if (params.fromAction === 'select') {
  24322. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  24323. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  24324. } else if (params.fromAction === 'unselect') {
  24325. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  24326. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  24327. }
  24328. });
  24329. }
  24330. /*
  24331. * Licensed to the Apache Software Foundation (ASF) under one
  24332. * or more contributor license agreements. See the NOTICE file
  24333. * distributed with this work for additional information
  24334. * regarding copyright ownership. The ASF licenses this file
  24335. * to you under the Apache License, Version 2.0 (the
  24336. * "License"); you may not use this file except in compliance
  24337. * with the License. You may obtain a copy of the License at
  24338. *
  24339. * http://www.apache.org/licenses/LICENSE-2.0
  24340. *
  24341. * Unless required by applicable law or agreed to in writing,
  24342. * software distributed under the License is distributed on an
  24343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24344. * KIND, either express or implied. See the License for the
  24345. * specific language governing permissions and limitations
  24346. * under the License.
  24347. */
  24348. /**
  24349. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24350. */
  24351. /*
  24352. * Licensed to the Apache Software Foundation (ASF) under one
  24353. * or more contributor license agreements. See the NOTICE file
  24354. * distributed with this work for additional information
  24355. * regarding copyright ownership. The ASF licenses this file
  24356. * to you under the Apache License, Version 2.0 (the
  24357. * "License"); you may not use this file except in compliance
  24358. * with the License. You may obtain a copy of the License at
  24359. *
  24360. * http://www.apache.org/licenses/LICENSE-2.0
  24361. *
  24362. * Unless required by applicable law or agreed to in writing,
  24363. * software distributed under the License is distributed on an
  24364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24365. * KIND, either express or implied. See the License for the
  24366. * specific language governing permissions and limitations
  24367. * under the License.
  24368. */
  24369. function findEventDispatcher(target, det, returnFirstMatch) {
  24370. var found;
  24371. while (target) {
  24372. if (det(target)) {
  24373. found = target;
  24374. if (returnFirstMatch) {
  24375. break;
  24376. }
  24377. }
  24378. target = target.__hostTarget || target.parent;
  24379. }
  24380. return found;
  24381. }
  24382. var wmUniqueIndex = Math.round(Math.random() * 9);
  24383. var supportDefineProperty = typeof Object.defineProperty === 'function';
  24384. var WeakMap = (function () {
  24385. function WeakMap() {
  24386. this._id = '__ec_inner_' + wmUniqueIndex++;
  24387. }
  24388. WeakMap.prototype.get = function (key) {
  24389. return this._guard(key)[this._id];
  24390. };
  24391. WeakMap.prototype.set = function (key, value) {
  24392. var target = this._guard(key);
  24393. if (supportDefineProperty) {
  24394. Object.defineProperty(target, this._id, {
  24395. value: value,
  24396. enumerable: false,
  24397. configurable: true
  24398. });
  24399. }
  24400. else {
  24401. target[this._id] = value;
  24402. }
  24403. return this;
  24404. };
  24405. WeakMap.prototype["delete"] = function (key) {
  24406. if (this.has(key)) {
  24407. delete this._guard(key)[this._id];
  24408. return true;
  24409. }
  24410. return false;
  24411. };
  24412. WeakMap.prototype.has = function (key) {
  24413. return !!this._guard(key)[this._id];
  24414. };
  24415. WeakMap.prototype._guard = function (key) {
  24416. if (key !== Object(key)) {
  24417. throw TypeError('Value of WeakMap is not a non-null object.');
  24418. }
  24419. return key;
  24420. };
  24421. return WeakMap;
  24422. }());
  24423. /**
  24424. * Triangle shape
  24425. * @inner
  24426. */
  24427. var Triangle = Path.extend({
  24428. type: 'triangle',
  24429. shape: {
  24430. cx: 0,
  24431. cy: 0,
  24432. width: 0,
  24433. height: 0
  24434. },
  24435. buildPath: function (path, shape) {
  24436. var cx = shape.cx;
  24437. var cy = shape.cy;
  24438. var width = shape.width / 2;
  24439. var height = shape.height / 2;
  24440. path.moveTo(cx, cy - height);
  24441. path.lineTo(cx + width, cy + height);
  24442. path.lineTo(cx - width, cy + height);
  24443. path.closePath();
  24444. }
  24445. });
  24446. /**
  24447. * Diamond shape
  24448. * @inner
  24449. */
  24450. var Diamond = Path.extend({
  24451. type: 'diamond',
  24452. shape: {
  24453. cx: 0,
  24454. cy: 0,
  24455. width: 0,
  24456. height: 0
  24457. },
  24458. buildPath: function (path, shape) {
  24459. var cx = shape.cx;
  24460. var cy = shape.cy;
  24461. var width = shape.width / 2;
  24462. var height = shape.height / 2;
  24463. path.moveTo(cx, cy - height);
  24464. path.lineTo(cx + width, cy);
  24465. path.lineTo(cx, cy + height);
  24466. path.lineTo(cx - width, cy);
  24467. path.closePath();
  24468. }
  24469. });
  24470. /**
  24471. * Pin shape
  24472. * @inner
  24473. */
  24474. var Pin = Path.extend({
  24475. type: 'pin',
  24476. shape: {
  24477. // x, y on the cusp
  24478. x: 0,
  24479. y: 0,
  24480. width: 0,
  24481. height: 0
  24482. },
  24483. buildPath: function (path, shape) {
  24484. var x = shape.x;
  24485. var y = shape.y;
  24486. var w = shape.width / 5 * 3;
  24487. // Height must be larger than width
  24488. var h = Math.max(w, shape.height);
  24489. var r = w / 2;
  24490. // Dist on y with tangent point and circle center
  24491. var dy = r * r / (h - r);
  24492. var cy = y - h + r + dy;
  24493. var angle = Math.asin(dy / r);
  24494. // Dist on x with tangent point and circle center
  24495. var dx = Math.cos(angle) * r;
  24496. var tanX = Math.sin(angle);
  24497. var tanY = Math.cos(angle);
  24498. var cpLen = r * 0.6;
  24499. var cpLen2 = r * 0.7;
  24500. path.moveTo(x - dx, cy + dy);
  24501. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24502. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24503. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24504. path.closePath();
  24505. }
  24506. });
  24507. /**
  24508. * Arrow shape
  24509. * @inner
  24510. */
  24511. var Arrow = Path.extend({
  24512. type: 'arrow',
  24513. shape: {
  24514. x: 0,
  24515. y: 0,
  24516. width: 0,
  24517. height: 0
  24518. },
  24519. buildPath: function (ctx, shape) {
  24520. var height = shape.height;
  24521. var width = shape.width;
  24522. var x = shape.x;
  24523. var y = shape.y;
  24524. var dx = width / 3 * 2;
  24525. ctx.moveTo(x, y);
  24526. ctx.lineTo(x + dx, y + height);
  24527. ctx.lineTo(x, y + height / 4 * 3);
  24528. ctx.lineTo(x - dx, y + height);
  24529. ctx.lineTo(x, y);
  24530. ctx.closePath();
  24531. }
  24532. });
  24533. /**
  24534. * Map of path constructors
  24535. */
  24536. // TODO Use function to build symbol path.
  24537. var symbolCtors = {
  24538. line: Line,
  24539. rect: Rect,
  24540. roundRect: Rect,
  24541. square: Rect,
  24542. circle: Circle,
  24543. diamond: Diamond,
  24544. pin: Pin,
  24545. arrow: Arrow,
  24546. triangle: Triangle
  24547. };
  24548. var symbolShapeMakers = {
  24549. line: function (x, y, w, h, shape) {
  24550. shape.x1 = x;
  24551. shape.y1 = y + h / 2;
  24552. shape.x2 = x + w;
  24553. shape.y2 = y + h / 2;
  24554. },
  24555. rect: function (x, y, w, h, shape) {
  24556. shape.x = x;
  24557. shape.y = y;
  24558. shape.width = w;
  24559. shape.height = h;
  24560. },
  24561. roundRect: function (x, y, w, h, shape) {
  24562. shape.x = x;
  24563. shape.y = y;
  24564. shape.width = w;
  24565. shape.height = h;
  24566. shape.r = Math.min(w, h) / 4;
  24567. },
  24568. square: function (x, y, w, h, shape) {
  24569. var size = Math.min(w, h);
  24570. shape.x = x;
  24571. shape.y = y;
  24572. shape.width = size;
  24573. shape.height = size;
  24574. },
  24575. circle: function (x, y, w, h, shape) {
  24576. // Put circle in the center of square
  24577. shape.cx = x + w / 2;
  24578. shape.cy = y + h / 2;
  24579. shape.r = Math.min(w, h) / 2;
  24580. },
  24581. diamond: function (x, y, w, h, shape) {
  24582. shape.cx = x + w / 2;
  24583. shape.cy = y + h / 2;
  24584. shape.width = w;
  24585. shape.height = h;
  24586. },
  24587. pin: function (x, y, w, h, shape) {
  24588. shape.x = x + w / 2;
  24589. shape.y = y + h / 2;
  24590. shape.width = w;
  24591. shape.height = h;
  24592. },
  24593. arrow: function (x, y, w, h, shape) {
  24594. shape.x = x + w / 2;
  24595. shape.y = y + h / 2;
  24596. shape.width = w;
  24597. shape.height = h;
  24598. },
  24599. triangle: function (x, y, w, h, shape) {
  24600. shape.cx = x + w / 2;
  24601. shape.cy = y + h / 2;
  24602. shape.width = w;
  24603. shape.height = h;
  24604. }
  24605. };
  24606. var symbolBuildProxies = {};
  24607. each(symbolCtors, function (Ctor, name) {
  24608. symbolBuildProxies[name] = new Ctor();
  24609. });
  24610. var SymbolClz = Path.extend({
  24611. type: 'symbol',
  24612. shape: {
  24613. symbolType: '',
  24614. x: 0,
  24615. y: 0,
  24616. width: 0,
  24617. height: 0
  24618. },
  24619. calculateTextPosition: function (out, config, rect) {
  24620. var res = calculateTextPosition(out, config, rect);
  24621. var shape = this.shape;
  24622. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24623. res.y = rect.y + rect.height * 0.4;
  24624. }
  24625. return res;
  24626. },
  24627. buildPath: function (ctx, shape, inBundle) {
  24628. var symbolType = shape.symbolType;
  24629. if (symbolType !== 'none') {
  24630. var proxySymbol = symbolBuildProxies[symbolType];
  24631. if (!proxySymbol) {
  24632. // Default rect
  24633. symbolType = 'rect';
  24634. proxySymbol = symbolBuildProxies[symbolType];
  24635. }
  24636. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24637. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24638. }
  24639. }
  24640. });
  24641. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24642. function symbolPathSetColor(color, innerColor) {
  24643. if (this.type !== 'image') {
  24644. var symbolStyle = this.style;
  24645. if (this.__isEmptyBrush) {
  24646. symbolStyle.stroke = color;
  24647. symbolStyle.fill = innerColor || '#fff';
  24648. // TODO Same width with lineStyle in LineView
  24649. symbolStyle.lineWidth = 2;
  24650. } else if (this.shape.symbolType === 'line') {
  24651. symbolStyle.stroke = color;
  24652. } else {
  24653. symbolStyle.fill = color;
  24654. }
  24655. this.markRedraw();
  24656. }
  24657. }
  24658. /**
  24659. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24660. */
  24661. function createSymbol(symbolType, x, y, w, h, color,
  24662. // whether to keep the ratio of w/h,
  24663. keepAspect) {
  24664. // TODO Support image object, DynamicImage.
  24665. var isEmpty = symbolType.indexOf('empty') === 0;
  24666. if (isEmpty) {
  24667. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24668. }
  24669. var symbolPath;
  24670. if (symbolType.indexOf('image://') === 0) {
  24671. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24672. } else if (symbolType.indexOf('path://') === 0) {
  24673. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24674. } else {
  24675. symbolPath = new SymbolClz({
  24676. shape: {
  24677. symbolType: symbolType,
  24678. x: x,
  24679. y: y,
  24680. width: w,
  24681. height: h
  24682. }
  24683. });
  24684. }
  24685. symbolPath.__isEmptyBrush = isEmpty;
  24686. // TODO Should deprecate setColor
  24687. symbolPath.setColor = symbolPathSetColor;
  24688. if (color) {
  24689. symbolPath.setColor(color);
  24690. }
  24691. return symbolPath;
  24692. }
  24693. function normalizeSymbolSize(symbolSize) {
  24694. if (!isArray(symbolSize)) {
  24695. symbolSize = [+symbolSize, +symbolSize];
  24696. }
  24697. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24698. }
  24699. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24700. if (symbolOffset == null) {
  24701. return;
  24702. }
  24703. if (!isArray(symbolOffset)) {
  24704. symbolOffset = [symbolOffset, symbolOffset];
  24705. }
  24706. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24707. }
  24708. function isSafeNum(num) {
  24709. return isFinite(num);
  24710. }
  24711. function createLinearGradient(ctx, obj, rect) {
  24712. var x = obj.x == null ? 0 : obj.x;
  24713. var x2 = obj.x2 == null ? 1 : obj.x2;
  24714. var y = obj.y == null ? 0 : obj.y;
  24715. var y2 = obj.y2 == null ? 0 : obj.y2;
  24716. if (!obj.global) {
  24717. x = x * rect.width + rect.x;
  24718. x2 = x2 * rect.width + rect.x;
  24719. y = y * rect.height + rect.y;
  24720. y2 = y2 * rect.height + rect.y;
  24721. }
  24722. x = isSafeNum(x) ? x : 0;
  24723. x2 = isSafeNum(x2) ? x2 : 1;
  24724. y = isSafeNum(y) ? y : 0;
  24725. y2 = isSafeNum(y2) ? y2 : 0;
  24726. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24727. return canvasGradient;
  24728. }
  24729. function createRadialGradient(ctx, obj, rect) {
  24730. var width = rect.width;
  24731. var height = rect.height;
  24732. var min = Math.min(width, height);
  24733. var x = obj.x == null ? 0.5 : obj.x;
  24734. var y = obj.y == null ? 0.5 : obj.y;
  24735. var r = obj.r == null ? 0.5 : obj.r;
  24736. if (!obj.global) {
  24737. x = x * width + rect.x;
  24738. y = y * height + rect.y;
  24739. r = r * min;
  24740. }
  24741. x = isSafeNum(x) ? x : 0.5;
  24742. y = isSafeNum(y) ? y : 0.5;
  24743. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  24744. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24745. return canvasGradient;
  24746. }
  24747. function getCanvasGradient(ctx, obj, rect) {
  24748. var canvasGradient = obj.type === 'radial'
  24749. ? createRadialGradient(ctx, obj, rect)
  24750. : createLinearGradient(ctx, obj, rect);
  24751. var colorStops = obj.colorStops;
  24752. for (var i = 0; i < colorStops.length; i++) {
  24753. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24754. }
  24755. return canvasGradient;
  24756. }
  24757. function isClipPathChanged(clipPaths, prevClipPaths) {
  24758. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24759. return false;
  24760. }
  24761. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24762. return true;
  24763. }
  24764. for (var i = 0; i < clipPaths.length; i++) {
  24765. if (clipPaths[i] !== prevClipPaths[i]) {
  24766. return true;
  24767. }
  24768. }
  24769. return false;
  24770. }
  24771. function parseInt10(val) {
  24772. return parseInt(val, 10);
  24773. }
  24774. function getSize(root, whIdx, opts) {
  24775. var wh = ['width', 'height'][whIdx];
  24776. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24777. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24778. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24779. if (opts[wh] != null && opts[wh] !== 'auto') {
  24780. return parseFloat(opts[wh]);
  24781. }
  24782. var stl = document.defaultView.getComputedStyle(root);
  24783. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24784. - (parseInt10(stl[plt]) || 0)
  24785. - (parseInt10(stl[prb]) || 0)) | 0;
  24786. }
  24787. function normalizeLineDash(lineType, lineWidth) {
  24788. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24789. return null;
  24790. }
  24791. return lineType === 'dashed'
  24792. ? [4 * lineWidth, 2 * lineWidth]
  24793. : lineType === 'dotted'
  24794. ? [lineWidth]
  24795. : isNumber(lineType)
  24796. ? [lineType] : isArray(lineType) ? lineType : null;
  24797. }
  24798. function getLineDash(el) {
  24799. var style = el.style;
  24800. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24801. var lineDashOffset = style.lineDashOffset;
  24802. if (lineDash) {
  24803. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24804. if (lineScale_1 && lineScale_1 !== 1) {
  24805. lineDash = map(lineDash, function (rawVal) {
  24806. return rawVal / lineScale_1;
  24807. });
  24808. lineDashOffset /= lineScale_1;
  24809. }
  24810. }
  24811. return [lineDash, lineDashOffset];
  24812. }
  24813. var pathProxyForDraw = new PathProxy(true);
  24814. function styleHasStroke(style) {
  24815. var stroke = style.stroke;
  24816. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24817. }
  24818. function isValidStrokeFillStyle(strokeOrFill) {
  24819. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24820. }
  24821. function styleHasFill(style) {
  24822. var fill = style.fill;
  24823. return fill != null && fill !== 'none';
  24824. }
  24825. function doFillPath(ctx, style) {
  24826. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24827. var originalGlobalAlpha = ctx.globalAlpha;
  24828. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24829. ctx.fill();
  24830. ctx.globalAlpha = originalGlobalAlpha;
  24831. }
  24832. else {
  24833. ctx.fill();
  24834. }
  24835. }
  24836. function doStrokePath(ctx, style) {
  24837. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24838. var originalGlobalAlpha = ctx.globalAlpha;
  24839. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24840. ctx.stroke();
  24841. ctx.globalAlpha = originalGlobalAlpha;
  24842. }
  24843. else {
  24844. ctx.stroke();
  24845. }
  24846. }
  24847. function createCanvasPattern(ctx, pattern, el) {
  24848. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24849. if (isImageReady(image)) {
  24850. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24851. if (typeof DOMMatrix === 'function'
  24852. && canvasPattern
  24853. && canvasPattern.setTransform) {
  24854. var matrix = new DOMMatrix();
  24855. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24856. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24857. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24858. canvasPattern.setTransform(matrix);
  24859. }
  24860. return canvasPattern;
  24861. }
  24862. }
  24863. function brushPath(ctx, el, style, inBatch) {
  24864. var _a;
  24865. var hasStroke = styleHasStroke(style);
  24866. var hasFill = styleHasFill(style);
  24867. var strokePercent = style.strokePercent;
  24868. var strokePart = strokePercent < 1;
  24869. var firstDraw = !el.path;
  24870. if ((!el.silent || strokePart) && firstDraw) {
  24871. el.createPathProxy();
  24872. }
  24873. var path = el.path || pathProxyForDraw;
  24874. var dirtyFlag = el.__dirty;
  24875. if (!inBatch) {
  24876. var fill = style.fill;
  24877. var stroke = style.stroke;
  24878. var hasFillGradient = hasFill && !!fill.colorStops;
  24879. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24880. var hasFillPattern = hasFill && !!fill.image;
  24881. var hasStrokePattern = hasStroke && !!stroke.image;
  24882. var fillGradient = void 0;
  24883. var strokeGradient = void 0;
  24884. var fillPattern = void 0;
  24885. var strokePattern = void 0;
  24886. var rect = void 0;
  24887. if (hasFillGradient || hasStrokeGradient) {
  24888. rect = el.getBoundingRect();
  24889. }
  24890. if (hasFillGradient) {
  24891. fillGradient = dirtyFlag
  24892. ? getCanvasGradient(ctx, fill, rect)
  24893. : el.__canvasFillGradient;
  24894. el.__canvasFillGradient = fillGradient;
  24895. }
  24896. if (hasStrokeGradient) {
  24897. strokeGradient = dirtyFlag
  24898. ? getCanvasGradient(ctx, stroke, rect)
  24899. : el.__canvasStrokeGradient;
  24900. el.__canvasStrokeGradient = strokeGradient;
  24901. }
  24902. if (hasFillPattern) {
  24903. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24904. ? createCanvasPattern(ctx, fill, el)
  24905. : el.__canvasFillPattern;
  24906. el.__canvasFillPattern = fillPattern;
  24907. }
  24908. if (hasStrokePattern) {
  24909. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24910. ? createCanvasPattern(ctx, stroke, el)
  24911. : el.__canvasStrokePattern;
  24912. el.__canvasStrokePattern = fillPattern;
  24913. }
  24914. if (hasFillGradient) {
  24915. ctx.fillStyle = fillGradient;
  24916. }
  24917. else if (hasFillPattern) {
  24918. if (fillPattern) {
  24919. ctx.fillStyle = fillPattern;
  24920. }
  24921. else {
  24922. hasFill = false;
  24923. }
  24924. }
  24925. if (hasStrokeGradient) {
  24926. ctx.strokeStyle = strokeGradient;
  24927. }
  24928. else if (hasStrokePattern) {
  24929. if (strokePattern) {
  24930. ctx.strokeStyle = strokePattern;
  24931. }
  24932. else {
  24933. hasStroke = false;
  24934. }
  24935. }
  24936. }
  24937. var scale = el.getGlobalScale();
  24938. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24939. var lineDash;
  24940. var lineDashOffset;
  24941. if (ctx.setLineDash && style.lineDash) {
  24942. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24943. }
  24944. var needsRebuild = true;
  24945. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24946. path.setDPR(ctx.dpr);
  24947. if (strokePart) {
  24948. path.setContext(null);
  24949. }
  24950. else {
  24951. path.setContext(ctx);
  24952. needsRebuild = false;
  24953. }
  24954. path.reset();
  24955. el.buildPath(path, el.shape, inBatch);
  24956. path.toStatic();
  24957. el.pathUpdated();
  24958. }
  24959. if (needsRebuild) {
  24960. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24961. }
  24962. if (lineDash) {
  24963. ctx.setLineDash(lineDash);
  24964. ctx.lineDashOffset = lineDashOffset;
  24965. }
  24966. if (!inBatch) {
  24967. if (style.strokeFirst) {
  24968. if (hasStroke) {
  24969. doStrokePath(ctx, style);
  24970. }
  24971. if (hasFill) {
  24972. doFillPath(ctx, style);
  24973. }
  24974. }
  24975. else {
  24976. if (hasFill) {
  24977. doFillPath(ctx, style);
  24978. }
  24979. if (hasStroke) {
  24980. doStrokePath(ctx, style);
  24981. }
  24982. }
  24983. }
  24984. if (lineDash) {
  24985. ctx.setLineDash([]);
  24986. }
  24987. }
  24988. function brushImage(ctx, el, style) {
  24989. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24990. if (!image || !isImageReady(image)) {
  24991. return;
  24992. }
  24993. var x = style.x || 0;
  24994. var y = style.y || 0;
  24995. var width = el.getWidth();
  24996. var height = el.getHeight();
  24997. var aspect = image.width / image.height;
  24998. if (width == null && height != null) {
  24999. width = height * aspect;
  25000. }
  25001. else if (height == null && width != null) {
  25002. height = width / aspect;
  25003. }
  25004. else if (width == null && height == null) {
  25005. width = image.width;
  25006. height = image.height;
  25007. }
  25008. if (style.sWidth && style.sHeight) {
  25009. var sx = style.sx || 0;
  25010. var sy = style.sy || 0;
  25011. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  25012. }
  25013. else if (style.sx && style.sy) {
  25014. var sx = style.sx;
  25015. var sy = style.sy;
  25016. var sWidth = width - sx;
  25017. var sHeight = height - sy;
  25018. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  25019. }
  25020. else {
  25021. ctx.drawImage(image, x, y, width, height);
  25022. }
  25023. }
  25024. function brushText(ctx, el, style) {
  25025. var _a;
  25026. var text = style.text;
  25027. text != null && (text += '');
  25028. if (text) {
  25029. ctx.font = style.font || DEFAULT_FONT;
  25030. ctx.textAlign = style.textAlign;
  25031. ctx.textBaseline = style.textBaseline;
  25032. var lineDash = void 0;
  25033. var lineDashOffset = void 0;
  25034. if (ctx.setLineDash && style.lineDash) {
  25035. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  25036. }
  25037. if (lineDash) {
  25038. ctx.setLineDash(lineDash);
  25039. ctx.lineDashOffset = lineDashOffset;
  25040. }
  25041. if (style.strokeFirst) {
  25042. if (styleHasStroke(style)) {
  25043. ctx.strokeText(text, style.x, style.y);
  25044. }
  25045. if (styleHasFill(style)) {
  25046. ctx.fillText(text, style.x, style.y);
  25047. }
  25048. }
  25049. else {
  25050. if (styleHasFill(style)) {
  25051. ctx.fillText(text, style.x, style.y);
  25052. }
  25053. if (styleHasStroke(style)) {
  25054. ctx.strokeText(text, style.x, style.y);
  25055. }
  25056. }
  25057. if (lineDash) {
  25058. ctx.setLineDash([]);
  25059. }
  25060. }
  25061. }
  25062. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  25063. var STROKE_PROPS = [
  25064. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  25065. ];
  25066. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  25067. var styleChanged = false;
  25068. if (!forceSetAll) {
  25069. prevStyle = prevStyle || {};
  25070. if (style === prevStyle) {
  25071. return false;
  25072. }
  25073. }
  25074. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  25075. flushPathDrawn(ctx, scope);
  25076. styleChanged = true;
  25077. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  25078. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  25079. }
  25080. if (forceSetAll || style.blend !== prevStyle.blend) {
  25081. if (!styleChanged) {
  25082. flushPathDrawn(ctx, scope);
  25083. styleChanged = true;
  25084. }
  25085. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  25086. }
  25087. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  25088. var propName = SHADOW_NUMBER_PROPS[i];
  25089. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25090. if (!styleChanged) {
  25091. flushPathDrawn(ctx, scope);
  25092. styleChanged = true;
  25093. }
  25094. ctx[propName] = ctx.dpr * (style[propName] || 0);
  25095. }
  25096. }
  25097. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  25098. if (!styleChanged) {
  25099. flushPathDrawn(ctx, scope);
  25100. styleChanged = true;
  25101. }
  25102. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  25103. }
  25104. return styleChanged;
  25105. }
  25106. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  25107. var style = getStyle(el, scope.inHover);
  25108. var prevStyle = forceSetAll
  25109. ? null
  25110. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  25111. if (style === prevStyle) {
  25112. return false;
  25113. }
  25114. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  25115. if (forceSetAll || style.fill !== prevStyle.fill) {
  25116. if (!styleChanged) {
  25117. flushPathDrawn(ctx, scope);
  25118. styleChanged = true;
  25119. }
  25120. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  25121. }
  25122. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  25123. if (!styleChanged) {
  25124. flushPathDrawn(ctx, scope);
  25125. styleChanged = true;
  25126. }
  25127. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  25128. }
  25129. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  25130. if (!styleChanged) {
  25131. flushPathDrawn(ctx, scope);
  25132. styleChanged = true;
  25133. }
  25134. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  25135. }
  25136. if (el.hasStroke()) {
  25137. var lineWidth = style.lineWidth;
  25138. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  25139. if (ctx.lineWidth !== newLineWidth) {
  25140. if (!styleChanged) {
  25141. flushPathDrawn(ctx, scope);
  25142. styleChanged = true;
  25143. }
  25144. ctx.lineWidth = newLineWidth;
  25145. }
  25146. }
  25147. for (var i = 0; i < STROKE_PROPS.length; i++) {
  25148. var prop = STROKE_PROPS[i];
  25149. var propName = prop[0];
  25150. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25151. if (!styleChanged) {
  25152. flushPathDrawn(ctx, scope);
  25153. styleChanged = true;
  25154. }
  25155. ctx[propName] = style[propName] || prop[1];
  25156. }
  25157. }
  25158. return styleChanged;
  25159. }
  25160. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  25161. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  25162. }
  25163. function setContextTransform(ctx, el) {
  25164. var m = el.transform;
  25165. var dpr = ctx.dpr || 1;
  25166. if (m) {
  25167. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  25168. }
  25169. else {
  25170. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  25171. }
  25172. }
  25173. function updateClipStatus(clipPaths, ctx, scope) {
  25174. var allClipped = false;
  25175. for (var i = 0; i < clipPaths.length; i++) {
  25176. var clipPath = clipPaths[i];
  25177. allClipped = allClipped || clipPath.isZeroArea();
  25178. setContextTransform(ctx, clipPath);
  25179. ctx.beginPath();
  25180. clipPath.buildPath(ctx, clipPath.shape);
  25181. ctx.clip();
  25182. }
  25183. scope.allClipped = allClipped;
  25184. }
  25185. function isTransformChanged(m0, m1) {
  25186. if (m0 && m1) {
  25187. return m0[0] !== m1[0]
  25188. || m0[1] !== m1[1]
  25189. || m0[2] !== m1[2]
  25190. || m0[3] !== m1[3]
  25191. || m0[4] !== m1[4]
  25192. || m0[5] !== m1[5];
  25193. }
  25194. else if (!m0 && !m1) {
  25195. return false;
  25196. }
  25197. return true;
  25198. }
  25199. var DRAW_TYPE_PATH = 1;
  25200. var DRAW_TYPE_IMAGE = 2;
  25201. var DRAW_TYPE_TEXT = 3;
  25202. var DRAW_TYPE_INCREMENTAL = 4;
  25203. function canPathBatch(style) {
  25204. var hasFill = styleHasFill(style);
  25205. var hasStroke = styleHasStroke(style);
  25206. return !(style.lineDash
  25207. || !(+hasFill ^ +hasStroke)
  25208. || (hasFill && typeof style.fill !== 'string')
  25209. || (hasStroke && typeof style.stroke !== 'string')
  25210. || style.strokePercent < 1
  25211. || style.strokeOpacity < 1
  25212. || style.fillOpacity < 1);
  25213. }
  25214. function flushPathDrawn(ctx, scope) {
  25215. scope.batchFill && ctx.fill();
  25216. scope.batchStroke && ctx.stroke();
  25217. scope.batchFill = '';
  25218. scope.batchStroke = '';
  25219. }
  25220. function getStyle(el, inHover) {
  25221. return inHover ? (el.__hoverStyle || el.style) : el.style;
  25222. }
  25223. function brushSingle(ctx, el) {
  25224. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  25225. }
  25226. function brush(ctx, el, scope, isLast) {
  25227. var m = el.transform;
  25228. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  25229. el.__dirty &= ~REDRAW_BIT;
  25230. el.__isRendered = false;
  25231. return;
  25232. }
  25233. var clipPaths = el.__clipPaths;
  25234. var prevElClipPaths = scope.prevElClipPaths;
  25235. var forceSetTransform = false;
  25236. var forceSetStyle = false;
  25237. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  25238. if (prevElClipPaths && prevElClipPaths.length) {
  25239. flushPathDrawn(ctx, scope);
  25240. ctx.restore();
  25241. forceSetStyle = forceSetTransform = true;
  25242. scope.prevElClipPaths = null;
  25243. scope.allClipped = false;
  25244. scope.prevEl = null;
  25245. }
  25246. if (clipPaths && clipPaths.length) {
  25247. flushPathDrawn(ctx, scope);
  25248. ctx.save();
  25249. updateClipStatus(clipPaths, ctx, scope);
  25250. forceSetTransform = true;
  25251. }
  25252. scope.prevElClipPaths = clipPaths;
  25253. }
  25254. if (scope.allClipped) {
  25255. el.__isRendered = false;
  25256. return;
  25257. }
  25258. el.beforeBrush && el.beforeBrush();
  25259. el.innerBeforeBrush();
  25260. var prevEl = scope.prevEl;
  25261. if (!prevEl) {
  25262. forceSetStyle = forceSetTransform = true;
  25263. }
  25264. var canBatchPath = el instanceof Path
  25265. && el.autoBatch
  25266. && canPathBatch(el.style);
  25267. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  25268. flushPathDrawn(ctx, scope);
  25269. setContextTransform(ctx, el);
  25270. }
  25271. else if (!canBatchPath) {
  25272. flushPathDrawn(ctx, scope);
  25273. }
  25274. var style = getStyle(el, scope.inHover);
  25275. if (el instanceof Path) {
  25276. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  25277. forceSetStyle = true;
  25278. scope.lastDrawType = DRAW_TYPE_PATH;
  25279. }
  25280. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25281. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  25282. ctx.beginPath();
  25283. }
  25284. brushPath(ctx, el, style, canBatchPath);
  25285. if (canBatchPath) {
  25286. scope.batchFill = style.fill || '';
  25287. scope.batchStroke = style.stroke || '';
  25288. }
  25289. }
  25290. else {
  25291. if (el instanceof TSpan) {
  25292. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  25293. forceSetStyle = true;
  25294. scope.lastDrawType = DRAW_TYPE_TEXT;
  25295. }
  25296. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25297. brushText(ctx, el, style);
  25298. }
  25299. else if (el instanceof ZRImage) {
  25300. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  25301. forceSetStyle = true;
  25302. scope.lastDrawType = DRAW_TYPE_IMAGE;
  25303. }
  25304. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  25305. brushImage(ctx, el, style);
  25306. }
  25307. else if (el.getTemporalDisplayables) {
  25308. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  25309. forceSetStyle = true;
  25310. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  25311. }
  25312. brushIncremental(ctx, el, scope);
  25313. }
  25314. }
  25315. if (canBatchPath && isLast) {
  25316. flushPathDrawn(ctx, scope);
  25317. }
  25318. el.innerAfterBrush();
  25319. el.afterBrush && el.afterBrush();
  25320. scope.prevEl = el;
  25321. el.__dirty = 0;
  25322. el.__isRendered = true;
  25323. }
  25324. function brushIncremental(ctx, el, scope) {
  25325. var displayables = el.getDisplayables();
  25326. var temporalDisplayables = el.getTemporalDisplayables();
  25327. ctx.save();
  25328. var innerScope = {
  25329. prevElClipPaths: null,
  25330. prevEl: null,
  25331. allClipped: false,
  25332. viewWidth: scope.viewWidth,
  25333. viewHeight: scope.viewHeight,
  25334. inHover: scope.inHover
  25335. };
  25336. var i;
  25337. var len;
  25338. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  25339. var displayable = displayables[i];
  25340. displayable.beforeBrush && displayable.beforeBrush();
  25341. displayable.innerBeforeBrush();
  25342. brush(ctx, displayable, innerScope, i === len - 1);
  25343. displayable.innerAfterBrush();
  25344. displayable.afterBrush && displayable.afterBrush();
  25345. innerScope.prevEl = displayable;
  25346. }
  25347. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  25348. var displayable = temporalDisplayables[i_1];
  25349. displayable.beforeBrush && displayable.beforeBrush();
  25350. displayable.innerBeforeBrush();
  25351. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  25352. displayable.innerAfterBrush();
  25353. displayable.afterBrush && displayable.afterBrush();
  25354. innerScope.prevEl = displayable;
  25355. }
  25356. el.clearTemporalDisplayables();
  25357. el.notClear = true;
  25358. ctx.restore();
  25359. }
  25360. var decalMap = new WeakMap();
  25361. var decalCache = new LRU(100);
  25362. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  25363. /**
  25364. * Create or update pattern image from decal options
  25365. *
  25366. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  25367. * @return {Pattern} pattern with generated image, null if no decal
  25368. */
  25369. function createOrUpdatePatternFromDecal(decalObject, api) {
  25370. if (decalObject === 'none') {
  25371. return null;
  25372. }
  25373. var dpr = api.getDevicePixelRatio();
  25374. var zr = api.getZr();
  25375. var isSVG = zr.painter.type === 'svg';
  25376. if (decalObject.dirty) {
  25377. decalMap["delete"](decalObject);
  25378. }
  25379. var oldPattern = decalMap.get(decalObject);
  25380. if (oldPattern) {
  25381. return oldPattern;
  25382. }
  25383. var decalOpt = defaults(decalObject, {
  25384. symbol: 'rect',
  25385. symbolSize: 1,
  25386. symbolKeepAspect: true,
  25387. color: 'rgba(0, 0, 0, 0.2)',
  25388. backgroundColor: null,
  25389. dashArrayX: 5,
  25390. dashArrayY: 5,
  25391. rotation: 0,
  25392. maxTileWidth: 512,
  25393. maxTileHeight: 512
  25394. });
  25395. if (decalOpt.backgroundColor === 'none') {
  25396. decalOpt.backgroundColor = null;
  25397. }
  25398. var pattern = {
  25399. repeat: 'repeat'
  25400. };
  25401. setPatternnSource(pattern);
  25402. pattern.rotation = decalOpt.rotation;
  25403. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  25404. decalMap.set(decalObject, pattern);
  25405. decalObject.dirty = false;
  25406. return pattern;
  25407. function setPatternnSource(pattern) {
  25408. var keys = [dpr];
  25409. var isValidKey = true;
  25410. for (var i = 0; i < decalKeys.length; ++i) {
  25411. var value = decalOpt[decalKeys[i]];
  25412. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  25413. isValidKey = false;
  25414. break;
  25415. }
  25416. keys.push(value);
  25417. }
  25418. var cacheKey;
  25419. if (isValidKey) {
  25420. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  25421. var cache = decalCache.get(cacheKey);
  25422. if (cache) {
  25423. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  25424. }
  25425. }
  25426. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  25427. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  25428. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  25429. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  25430. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  25431. var canvas = !isSVG && platformApi.createCanvas();
  25432. var svgRoot = isSVG && {
  25433. tag: 'g',
  25434. attrs: {},
  25435. key: 'dcl',
  25436. children: []
  25437. };
  25438. var pSize = getPatternSize();
  25439. var ctx;
  25440. if (canvas) {
  25441. canvas.width = pSize.width * dpr;
  25442. canvas.height = pSize.height * dpr;
  25443. ctx = canvas.getContext('2d');
  25444. }
  25445. brushDecal();
  25446. if (isValidKey) {
  25447. decalCache.put(cacheKey, canvas || svgRoot);
  25448. }
  25449. pattern.image = canvas;
  25450. pattern.svgElement = svgRoot;
  25451. pattern.svgWidth = pSize.width;
  25452. pattern.svgHeight = pSize.height;
  25453. /**
  25454. * Get minimum length that can make a repeatable pattern.
  25455. *
  25456. * @return {Object} pattern width and height
  25457. */
  25458. function getPatternSize() {
  25459. /**
  25460. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  25461. * |--- --- --- --- --- ...
  25462. * |-- -- -- -- -- -- -- -- ...
  25463. * |--- --- --- --- --- ...
  25464. * |-- -- -- -- -- -- -- -- ...
  25465. * So the minimum length of X is 15,
  25466. * which is the least common multiple of `3 + 2` and `2 + 1`
  25467. * |--- --- --- |--- --- ...
  25468. * |-- -- -- -- -- |-- -- -- ...
  25469. */
  25470. var width = 1;
  25471. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  25472. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  25473. }
  25474. var symbolRepeats = 1;
  25475. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25476. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25477. }
  25478. width *= symbolRepeats;
  25479. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25480. if ("development" !== 'production') {
  25481. var warn = function (attrName) {
  25482. /* eslint-disable-next-line */
  25483. 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.");
  25484. };
  25485. if (width > decalOpt.maxTileWidth) {
  25486. warn('maxTileWidth');
  25487. }
  25488. if (height > decalOpt.maxTileHeight) {
  25489. warn('maxTileHeight');
  25490. }
  25491. }
  25492. return {
  25493. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25494. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25495. };
  25496. }
  25497. function brushDecal() {
  25498. if (ctx) {
  25499. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25500. if (decalOpt.backgroundColor) {
  25501. ctx.fillStyle = decalOpt.backgroundColor;
  25502. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25503. }
  25504. }
  25505. var ySum = 0;
  25506. for (var i = 0; i < dashArrayY.length; ++i) {
  25507. ySum += dashArrayY[i];
  25508. }
  25509. if (ySum <= 0) {
  25510. // dashArrayY is 0, draw nothing
  25511. return;
  25512. }
  25513. var y = -lineBlockLengthY;
  25514. var yId = 0;
  25515. var yIdTotal = 0;
  25516. var xId0 = 0;
  25517. while (y < pSize.height) {
  25518. if (yId % 2 === 0) {
  25519. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25520. var x = 0;
  25521. var xId1 = 0;
  25522. var xId1Total = 0;
  25523. while (x < pSize.width * 2) {
  25524. var xSum = 0;
  25525. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25526. xSum += dashArrayX[xId0][i];
  25527. }
  25528. if (xSum <= 0) {
  25529. // Skip empty line
  25530. break;
  25531. }
  25532. // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25533. if (xId1 % 2 === 0) {
  25534. var size = (1 - decalOpt.symbolSize) * 0.5;
  25535. var left = x + dashArrayX[xId0][xId1] * size;
  25536. var top_1 = y + dashArrayY[yId] * size;
  25537. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25538. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25539. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25540. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25541. }
  25542. x += dashArrayX[xId0][xId1];
  25543. ++xId1Total;
  25544. ++xId1;
  25545. if (xId1 === dashArrayX[xId0].length) {
  25546. xId1 = 0;
  25547. }
  25548. }
  25549. ++xId0;
  25550. if (xId0 === dashArrayX.length) {
  25551. xId0 = 0;
  25552. }
  25553. }
  25554. y += dashArrayY[yId];
  25555. ++yIdTotal;
  25556. ++yId;
  25557. if (yId === dashArrayY.length) {
  25558. yId = 0;
  25559. }
  25560. }
  25561. function brushSymbol(x, y, width, height, symbolType) {
  25562. var scale = isSVG ? 1 : dpr;
  25563. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25564. if (isSVG) {
  25565. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  25566. if (symbolVNode) {
  25567. svgRoot.children.push(symbolVNode);
  25568. }
  25569. } else {
  25570. // Paint to canvas for all other renderers.
  25571. brushSingle(ctx, symbol);
  25572. }
  25573. }
  25574. }
  25575. }
  25576. }
  25577. /**
  25578. * Convert symbol array into normalized array
  25579. *
  25580. * @param {string | (string | string[])[]} symbol symbol input
  25581. * @return {string[][]} normolized symbol array
  25582. */
  25583. function normalizeSymbolArray(symbol) {
  25584. if (!symbol || symbol.length === 0) {
  25585. return [['rect']];
  25586. }
  25587. if (isString(symbol)) {
  25588. return [[symbol]];
  25589. }
  25590. var isAllString = true;
  25591. for (var i = 0; i < symbol.length; ++i) {
  25592. if (!isString(symbol[i])) {
  25593. isAllString = false;
  25594. break;
  25595. }
  25596. }
  25597. if (isAllString) {
  25598. return normalizeSymbolArray([symbol]);
  25599. }
  25600. var result = [];
  25601. for (var i = 0; i < symbol.length; ++i) {
  25602. if (isString(symbol[i])) {
  25603. result.push([symbol[i]]);
  25604. } else {
  25605. result.push(symbol[i]);
  25606. }
  25607. }
  25608. return result;
  25609. }
  25610. /**
  25611. * Convert dash input into dashArray
  25612. *
  25613. * @param {DecalDashArrayX} dash dash input
  25614. * @return {number[][]} normolized dash array
  25615. */
  25616. function normalizeDashArrayX(dash) {
  25617. if (!dash || dash.length === 0) {
  25618. return [[0, 0]];
  25619. }
  25620. if (isNumber(dash)) {
  25621. var dashValue = Math.ceil(dash);
  25622. return [[dashValue, dashValue]];
  25623. }
  25624. /**
  25625. * [20, 5] should be normalized into [[20, 5]],
  25626. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25627. */
  25628. var isAllNumber = true;
  25629. for (var i = 0; i < dash.length; ++i) {
  25630. if (!isNumber(dash[i])) {
  25631. isAllNumber = false;
  25632. break;
  25633. }
  25634. }
  25635. if (isAllNumber) {
  25636. return normalizeDashArrayX([dash]);
  25637. }
  25638. var result = [];
  25639. for (var i = 0; i < dash.length; ++i) {
  25640. if (isNumber(dash[i])) {
  25641. var dashValue = Math.ceil(dash[i]);
  25642. result.push([dashValue, dashValue]);
  25643. } else {
  25644. var dashValue = map(dash[i], function (n) {
  25645. return Math.ceil(n);
  25646. });
  25647. if (dashValue.length % 2 === 1) {
  25648. // [4, 2, 1] means |---- - -- |---- - -- |
  25649. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25650. result.push(dashValue.concat(dashValue));
  25651. } else {
  25652. result.push(dashValue);
  25653. }
  25654. }
  25655. }
  25656. return result;
  25657. }
  25658. /**
  25659. * Convert dash input into dashArray
  25660. *
  25661. * @param {DecalDashArrayY} dash dash input
  25662. * @return {number[]} normolized dash array
  25663. */
  25664. function normalizeDashArrayY(dash) {
  25665. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25666. return [0, 0];
  25667. }
  25668. if (isNumber(dash)) {
  25669. var dashValue_1 = Math.ceil(dash);
  25670. return [dashValue_1, dashValue_1];
  25671. }
  25672. var dashValue = map(dash, function (n) {
  25673. return Math.ceil(n);
  25674. });
  25675. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25676. }
  25677. /**
  25678. * Get block length of each line. A block is the length of dash line and space.
  25679. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25680. * that, so the block length of this line is 5.
  25681. *
  25682. * @param {number[][]} dash dash array of X or Y
  25683. * @return {number[]} block length of each line
  25684. */
  25685. function getLineBlockLengthX(dash) {
  25686. return map(dash, function (line) {
  25687. return getLineBlockLengthY(line);
  25688. });
  25689. }
  25690. function getLineBlockLengthY(dash) {
  25691. var blockLength = 0;
  25692. for (var i = 0; i < dash.length; ++i) {
  25693. blockLength += dash[i];
  25694. }
  25695. if (dash.length % 2 === 1) {
  25696. // [4, 2, 1] means |---- - -- |---- - -- |
  25697. // So total length is (4 + 2 + 1) * 2
  25698. return blockLength * 2;
  25699. }
  25700. return blockLength;
  25701. }
  25702. function decalVisual(ecModel, api) {
  25703. ecModel.eachRawSeries(function (seriesModel) {
  25704. if (ecModel.isSeriesFiltered(seriesModel)) {
  25705. return;
  25706. }
  25707. var data = seriesModel.getData();
  25708. if (data.hasItemVisual()) {
  25709. data.each(function (idx) {
  25710. var decal = data.getItemVisual(idx, 'decal');
  25711. if (decal) {
  25712. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25713. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25714. }
  25715. });
  25716. }
  25717. var decal = data.getVisual('decal');
  25718. if (decal) {
  25719. var style = data.getVisual('style');
  25720. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25721. }
  25722. });
  25723. }
  25724. var lifecycle = new Eventful();
  25725. // Implementation of exported APIs. For example registerMap, getMap.
  25726. // The implementations will be registered when installing the component.
  25727. // Avoid these code being bundled to the core module.
  25728. var implsStore = {};
  25729. // TODO Type
  25730. function registerImpl(name, impl) {
  25731. if ("development" !== 'production') {
  25732. if (implsStore[name]) {
  25733. error("Already has an implementation of " + name + ".");
  25734. }
  25735. }
  25736. implsStore[name] = impl;
  25737. }
  25738. function getImpl(name) {
  25739. if ("development" !== 'production') {
  25740. if (!implsStore[name]) {
  25741. error("Implementation of " + name + " doesn't exists.");
  25742. }
  25743. }
  25744. return implsStore[name];
  25745. }
  25746. var version$1 = '5.5.1';
  25747. var dependencies = {
  25748. zrender: '5.6.0'
  25749. };
  25750. var TEST_FRAME_REMAIN_TIME = 1;
  25751. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  25752. // Some data processors depends on the stack result dimension (to calculate data extent).
  25753. // So data stack stage should be in front of data processing stage.
  25754. var PRIORITY_PROCESSOR_DATASTACK = 900;
  25755. // "Data filter" will block the stream, so it should be
  25756. // put at the beginning of data processing.
  25757. var PRIORITY_PROCESSOR_FILTER = 1000;
  25758. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25759. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25760. var PRIORITY_VISUAL_LAYOUT = 1000;
  25761. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25762. var PRIORITY_VISUAL_GLOBAL = 2000;
  25763. var PRIORITY_VISUAL_CHART = 3000;
  25764. var PRIORITY_VISUAL_COMPONENT = 4000;
  25765. // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25766. // overwrite the viusal result of component (like `visualMap`)
  25767. // using data item specific setting (like itemStyle.xxx on data item)
  25768. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500;
  25769. // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25770. // visual result like `symbolSize`.
  25771. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25772. var PRIORITY_VISUAL_BRUSH = 5000;
  25773. var PRIORITY_VISUAL_ARIA = 6000;
  25774. var PRIORITY_VISUAL_DECAL = 7000;
  25775. var PRIORITY = {
  25776. PROCESSOR: {
  25777. FILTER: PRIORITY_PROCESSOR_FILTER,
  25778. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25779. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25780. },
  25781. VISUAL: {
  25782. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25783. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25784. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25785. CHART: PRIORITY_VISUAL_CHART,
  25786. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25787. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25788. BRUSH: PRIORITY_VISUAL_BRUSH,
  25789. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25790. ARIA: PRIORITY_VISUAL_ARIA,
  25791. DECAL: PRIORITY_VISUAL_DECAL
  25792. }
  25793. };
  25794. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25795. // where they must not be invoked nestedly, except the only case: invoke
  25796. // dispatchAction with updateMethod "none" in main process.
  25797. // This flag is used to carry out this rule.
  25798. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25799. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25800. var PENDING_UPDATE = '__pendingUpdate';
  25801. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25802. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25803. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25804. var CONNECT_STATUS_PENDING = 0;
  25805. var CONNECT_STATUS_UPDATING = 1;
  25806. var CONNECT_STATUS_UPDATED = 2;
  25807. function createRegisterEventWithLowercaseECharts(method) {
  25808. return function () {
  25809. var args = [];
  25810. for (var _i = 0; _i < arguments.length; _i++) {
  25811. args[_i] = arguments[_i];
  25812. }
  25813. if (this.isDisposed()) {
  25814. disposedWarning(this.id);
  25815. return;
  25816. }
  25817. return toLowercaseNameAndCallEventful(this, method, args);
  25818. };
  25819. }
  25820. function createRegisterEventWithLowercaseMessageCenter(method) {
  25821. return function () {
  25822. var args = [];
  25823. for (var _i = 0; _i < arguments.length; _i++) {
  25824. args[_i] = arguments[_i];
  25825. }
  25826. return toLowercaseNameAndCallEventful(this, method, args);
  25827. };
  25828. }
  25829. function toLowercaseNameAndCallEventful(host, method, args) {
  25830. // `args[0]` is event name. Event name is all lowercase.
  25831. args[0] = args[0] && args[0].toLowerCase();
  25832. return Eventful.prototype[method].apply(host, args);
  25833. }
  25834. var MessageCenter = /** @class */function (_super) {
  25835. __extends(MessageCenter, _super);
  25836. function MessageCenter() {
  25837. return _super !== null && _super.apply(this, arguments) || this;
  25838. }
  25839. return MessageCenter;
  25840. }(Eventful);
  25841. var messageCenterProto = MessageCenter.prototype;
  25842. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25843. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off');
  25844. // ---------------------------------------
  25845. // Internal method names for class ECharts
  25846. // ---------------------------------------
  25847. var prepare;
  25848. var prepareView;
  25849. var updateDirectly;
  25850. var updateMethods;
  25851. var doConvertPixel;
  25852. var updateStreamModes;
  25853. var doDispatchAction;
  25854. var flushPendingActions;
  25855. var triggerUpdatedEvent;
  25856. var bindRenderedEvent;
  25857. var bindMouseEvent;
  25858. var render;
  25859. var renderComponents;
  25860. var renderSeries;
  25861. var createExtensionAPI;
  25862. var enableConnect;
  25863. var markStatusToUpdate;
  25864. var applyChangedStates;
  25865. var ECharts = /** @class */function (_super) {
  25866. __extends(ECharts, _super);
  25867. function ECharts(dom,
  25868. // Theme name or themeOption.
  25869. theme, opts) {
  25870. var _this = _super.call(this, new ECEventProcessor()) || this;
  25871. _this._chartsViews = [];
  25872. _this._chartsMap = {};
  25873. _this._componentsViews = [];
  25874. _this._componentsMap = {};
  25875. // Can't dispatch action during rendering procedure
  25876. _this._pendingActions = [];
  25877. opts = opts || {};
  25878. // Get theme by name
  25879. if (isString(theme)) {
  25880. theme = themeStorage[theme];
  25881. }
  25882. _this._dom = dom;
  25883. var defaultRenderer = 'canvas';
  25884. var defaultCoarsePointer = 'auto';
  25885. var defaultUseDirtyRect = false;
  25886. if ("development" !== 'production') {
  25887. var root = /* eslint-disable-next-line */
  25888. env.hasGlobalWindow ? window : global;
  25889. if (root) {
  25890. defaultRenderer = retrieve2(root.__ECHARTS__DEFAULT__RENDERER__, defaultRenderer);
  25891. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  25892. defaultUseDirtyRect = retrieve2(root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__, defaultUseDirtyRect);
  25893. }
  25894. }
  25895. if (opts.ssr) {
  25896. registerSSRDataGetter(function (el) {
  25897. var ecData = getECData(el);
  25898. var dataIndex = ecData.dataIndex;
  25899. if (dataIndex == null) {
  25900. return;
  25901. }
  25902. var hashMap = createHashMap();
  25903. hashMap.set('series_index', ecData.seriesIndex);
  25904. hashMap.set('data_index', dataIndex);
  25905. ecData.ssrType && hashMap.set('ssr_type', ecData.ssrType);
  25906. return hashMap;
  25907. });
  25908. }
  25909. var zr = _this._zr = init(dom, {
  25910. renderer: opts.renderer || defaultRenderer,
  25911. devicePixelRatio: opts.devicePixelRatio,
  25912. width: opts.width,
  25913. height: opts.height,
  25914. ssr: opts.ssr,
  25915. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  25916. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  25917. pointerSize: opts.pointerSize
  25918. });
  25919. _this._ssr = opts.ssr;
  25920. // Expect 60 fps.
  25921. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25922. theme = clone(theme);
  25923. theme && globalBackwardCompat(theme, true);
  25924. _this._theme = theme;
  25925. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25926. _this._coordSysMgr = new CoordinateSystemManager();
  25927. var api = _this._api = createExtensionAPI(_this);
  25928. // Sort on demand
  25929. function prioritySortFunc(a, b) {
  25930. return a.__prio - b.__prio;
  25931. }
  25932. sort(visualFuncs, prioritySortFunc);
  25933. sort(dataProcessorFuncs, prioritySortFunc);
  25934. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25935. _this._messageCenter = new MessageCenter();
  25936. // Init mouse events
  25937. _this._initEvents();
  25938. // In case some people write `window.onresize = chart.resize`
  25939. _this.resize = bind(_this.resize, _this);
  25940. zr.animation.on('frame', _this._onframe, _this);
  25941. bindRenderedEvent(zr, _this);
  25942. bindMouseEvent(zr, _this);
  25943. // ECharts instance can be used as value.
  25944. setAsPrimitive(_this);
  25945. return _this;
  25946. }
  25947. ECharts.prototype._onframe = function () {
  25948. if (this._disposed) {
  25949. return;
  25950. }
  25951. applyChangedStates(this);
  25952. var scheduler = this._scheduler;
  25953. // Lazy update
  25954. if (this[PENDING_UPDATE]) {
  25955. var silent = this[PENDING_UPDATE].silent;
  25956. this[IN_MAIN_PROCESS_KEY] = true;
  25957. try {
  25958. prepare(this);
  25959. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25960. } catch (e) {
  25961. this[IN_MAIN_PROCESS_KEY] = false;
  25962. this[PENDING_UPDATE] = null;
  25963. throw e;
  25964. }
  25965. // At present, in each frame, zrender performs:
  25966. // (1) animation step forward.
  25967. // (2) trigger('frame') (where this `_onframe` is called)
  25968. // (3) zrender flush (render).
  25969. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25970. // will render the final state of the elements before the real animation started.
  25971. this._zr.flush();
  25972. this[IN_MAIN_PROCESS_KEY] = false;
  25973. this[PENDING_UPDATE] = null;
  25974. flushPendingActions.call(this, silent);
  25975. triggerUpdatedEvent.call(this, silent);
  25976. }
  25977. // Avoid do both lazy update and progress in one frame.
  25978. else if (scheduler.unfinished) {
  25979. // Stream progress.
  25980. var remainTime = TEST_FRAME_REMAIN_TIME;
  25981. var ecModel = this._model;
  25982. var api = this._api;
  25983. scheduler.unfinished = false;
  25984. do {
  25985. var startTime = +new Date();
  25986. scheduler.performSeriesTasks(ecModel);
  25987. // Currently dataProcessorFuncs do not check threshold.
  25988. scheduler.performDataProcessorTasks(ecModel);
  25989. updateStreamModes(this, ecModel);
  25990. // Do not update coordinate system here. Because that coord system update in
  25991. // each frame is not a good user experience. So we follow the rule that
  25992. // the extent of the coordinate system is determined in the first frame (the
  25993. // frame is executed immediately after task reset.
  25994. // this._coordSysMgr.update(ecModel, api);
  25995. // console.log('--- ec frame visual ---', remainTime);
  25996. scheduler.performVisualTasks(ecModel);
  25997. renderSeries(this, this._model, api, 'remain', {});
  25998. remainTime -= +new Date() - startTime;
  25999. } while (remainTime > 0 && scheduler.unfinished);
  26000. // Call flush explicitly for trigger finished event.
  26001. if (!scheduler.unfinished) {
  26002. this._zr.flush();
  26003. }
  26004. // Else, zr flushing be ensue within the same frame,
  26005. // because zr flushing is after onframe event.
  26006. }
  26007. };
  26008. ECharts.prototype.getDom = function () {
  26009. return this._dom;
  26010. };
  26011. ECharts.prototype.getId = function () {
  26012. return this.id;
  26013. };
  26014. ECharts.prototype.getZr = function () {
  26015. return this._zr;
  26016. };
  26017. ECharts.prototype.isSSR = function () {
  26018. return this._ssr;
  26019. };
  26020. /* eslint-disable-next-line */
  26021. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  26022. if (this[IN_MAIN_PROCESS_KEY]) {
  26023. if ("development" !== 'production') {
  26024. error('`setOption` should not be called during main process.');
  26025. }
  26026. return;
  26027. }
  26028. if (this._disposed) {
  26029. disposedWarning(this.id);
  26030. return;
  26031. }
  26032. var silent;
  26033. var replaceMerge;
  26034. var transitionOpt;
  26035. if (isObject(notMerge)) {
  26036. lazyUpdate = notMerge.lazyUpdate;
  26037. silent = notMerge.silent;
  26038. replaceMerge = notMerge.replaceMerge;
  26039. transitionOpt = notMerge.transition;
  26040. notMerge = notMerge.notMerge;
  26041. }
  26042. this[IN_MAIN_PROCESS_KEY] = true;
  26043. if (!this._model || notMerge) {
  26044. var optionManager = new OptionManager(this._api);
  26045. var theme = this._theme;
  26046. var ecModel = this._model = new GlobalModel();
  26047. ecModel.scheduler = this._scheduler;
  26048. ecModel.ssr = this._ssr;
  26049. ecModel.init(null, null, null, theme, this._locale, optionManager);
  26050. }
  26051. this._model.setOption(option, {
  26052. replaceMerge: replaceMerge
  26053. }, optionPreprocessorFuncs);
  26054. var updateParams = {
  26055. seriesTransition: transitionOpt,
  26056. optionChanged: true
  26057. };
  26058. if (lazyUpdate) {
  26059. this[PENDING_UPDATE] = {
  26060. silent: silent,
  26061. updateParams: updateParams
  26062. };
  26063. this[IN_MAIN_PROCESS_KEY] = false;
  26064. // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  26065. // It should wake it up to make sure zrender start to render at the next frame.
  26066. this.getZr().wakeUp();
  26067. } else {
  26068. try {
  26069. prepare(this);
  26070. updateMethods.update.call(this, null, updateParams);
  26071. } catch (e) {
  26072. this[PENDING_UPDATE] = null;
  26073. this[IN_MAIN_PROCESS_KEY] = false;
  26074. throw e;
  26075. }
  26076. // Ensure zr refresh sychronously, and then pixel in canvas can be
  26077. // fetched after `setOption`.
  26078. if (!this._ssr) {
  26079. // not use flush when using ssr mode.
  26080. this._zr.flush();
  26081. }
  26082. this[PENDING_UPDATE] = null;
  26083. this[IN_MAIN_PROCESS_KEY] = false;
  26084. flushPendingActions.call(this, silent);
  26085. triggerUpdatedEvent.call(this, silent);
  26086. }
  26087. };
  26088. /**
  26089. * @deprecated
  26090. */
  26091. ECharts.prototype.setTheme = function () {
  26092. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  26093. };
  26094. // We don't want developers to use getModel directly.
  26095. ECharts.prototype.getModel = function () {
  26096. return this._model;
  26097. };
  26098. ECharts.prototype.getOption = function () {
  26099. return this._model && this._model.getOption();
  26100. };
  26101. ECharts.prototype.getWidth = function () {
  26102. return this._zr.getWidth();
  26103. };
  26104. ECharts.prototype.getHeight = function () {
  26105. return this._zr.getHeight();
  26106. };
  26107. ECharts.prototype.getDevicePixelRatio = function () {
  26108. return this._zr.painter.dpr
  26109. /* eslint-disable-next-line */ || env.hasGlobalWindow && window.devicePixelRatio || 1;
  26110. };
  26111. /**
  26112. * Get canvas which has all thing rendered
  26113. * @deprecated Use renderToCanvas instead.
  26114. */
  26115. ECharts.prototype.getRenderedCanvas = function (opts) {
  26116. if ("development" !== 'production') {
  26117. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  26118. }
  26119. return this.renderToCanvas(opts);
  26120. };
  26121. ECharts.prototype.renderToCanvas = function (opts) {
  26122. opts = opts || {};
  26123. var painter = this._zr.painter;
  26124. if ("development" !== 'production') {
  26125. if (painter.type !== 'canvas') {
  26126. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  26127. }
  26128. }
  26129. return painter.getRenderedCanvas({
  26130. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  26131. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  26132. });
  26133. };
  26134. ECharts.prototype.renderToSVGString = function (opts) {
  26135. opts = opts || {};
  26136. var painter = this._zr.painter;
  26137. if ("development" !== 'production') {
  26138. if (painter.type !== 'svg') {
  26139. throw new Error('renderToSVGString can only be used in the svg renderer.');
  26140. }
  26141. }
  26142. return painter.renderToString({
  26143. useViewBox: opts.useViewBox
  26144. });
  26145. };
  26146. /**
  26147. * Get svg data url
  26148. */
  26149. ECharts.prototype.getSvgDataURL = function () {
  26150. if (!env.svgSupported) {
  26151. return;
  26152. }
  26153. var zr = this._zr;
  26154. var list = zr.storage.getDisplayList();
  26155. // Stop animations
  26156. each(list, function (el) {
  26157. el.stopAnimation(null, true);
  26158. });
  26159. return zr.painter.toDataURL();
  26160. };
  26161. ECharts.prototype.getDataURL = function (opts) {
  26162. if (this._disposed) {
  26163. disposedWarning(this.id);
  26164. return;
  26165. }
  26166. opts = opts || {};
  26167. var excludeComponents = opts.excludeComponents;
  26168. var ecModel = this._model;
  26169. var excludesComponentViews = [];
  26170. var self = this;
  26171. each(excludeComponents, function (componentType) {
  26172. ecModel.eachComponent({
  26173. mainType: componentType
  26174. }, function (component) {
  26175. var view = self._componentsMap[component.__viewId];
  26176. if (!view.group.ignore) {
  26177. excludesComponentViews.push(view);
  26178. view.group.ignore = true;
  26179. }
  26180. });
  26181. });
  26182. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  26183. each(excludesComponentViews, function (view) {
  26184. view.group.ignore = false;
  26185. });
  26186. return url;
  26187. };
  26188. ECharts.prototype.getConnectedDataURL = function (opts) {
  26189. if (this._disposed) {
  26190. disposedWarning(this.id);
  26191. return;
  26192. }
  26193. var isSvg = opts.type === 'svg';
  26194. var groupId = this.group;
  26195. var mathMin = Math.min;
  26196. var mathMax = Math.max;
  26197. var MAX_NUMBER = Infinity;
  26198. if (connectedGroups[groupId]) {
  26199. var left_1 = MAX_NUMBER;
  26200. var top_1 = MAX_NUMBER;
  26201. var right_1 = -MAX_NUMBER;
  26202. var bottom_1 = -MAX_NUMBER;
  26203. var canvasList_1 = [];
  26204. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  26205. each(instances$1, function (chart, id) {
  26206. if (chart.group === groupId) {
  26207. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  26208. var boundingRect = chart.getDom().getBoundingClientRect();
  26209. left_1 = mathMin(boundingRect.left, left_1);
  26210. top_1 = mathMin(boundingRect.top, top_1);
  26211. right_1 = mathMax(boundingRect.right, right_1);
  26212. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  26213. canvasList_1.push({
  26214. dom: canvas,
  26215. left: boundingRect.left,
  26216. top: boundingRect.top
  26217. });
  26218. }
  26219. });
  26220. left_1 *= dpr_1;
  26221. top_1 *= dpr_1;
  26222. right_1 *= dpr_1;
  26223. bottom_1 *= dpr_1;
  26224. var width = right_1 - left_1;
  26225. var height = bottom_1 - top_1;
  26226. var targetCanvas = platformApi.createCanvas();
  26227. var zr_1 = init(targetCanvas, {
  26228. renderer: isSvg ? 'svg' : 'canvas'
  26229. });
  26230. zr_1.resize({
  26231. width: width,
  26232. height: height
  26233. });
  26234. if (isSvg) {
  26235. var content_1 = '';
  26236. each(canvasList_1, function (item) {
  26237. var x = item.left - left_1;
  26238. var y = item.top - top_1;
  26239. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  26240. });
  26241. zr_1.painter.getSvgRoot().innerHTML = content_1;
  26242. if (opts.connectedBackgroundColor) {
  26243. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  26244. }
  26245. zr_1.refreshImmediately();
  26246. return zr_1.painter.toDataURL();
  26247. } else {
  26248. // Background between the charts
  26249. if (opts.connectedBackgroundColor) {
  26250. zr_1.add(new Rect({
  26251. shape: {
  26252. x: 0,
  26253. y: 0,
  26254. width: width,
  26255. height: height
  26256. },
  26257. style: {
  26258. fill: opts.connectedBackgroundColor
  26259. }
  26260. }));
  26261. }
  26262. each(canvasList_1, function (item) {
  26263. var img = new ZRImage({
  26264. style: {
  26265. x: item.left * dpr_1 - left_1,
  26266. y: item.top * dpr_1 - top_1,
  26267. image: item.dom
  26268. }
  26269. });
  26270. zr_1.add(img);
  26271. });
  26272. zr_1.refreshImmediately();
  26273. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  26274. }
  26275. } else {
  26276. return this.getDataURL(opts);
  26277. }
  26278. };
  26279. ECharts.prototype.convertToPixel = function (finder, value) {
  26280. return doConvertPixel(this, 'convertToPixel', finder, value);
  26281. };
  26282. ECharts.prototype.convertFromPixel = function (finder, value) {
  26283. return doConvertPixel(this, 'convertFromPixel', finder, value);
  26284. };
  26285. /**
  26286. * Is the specified coordinate systems or components contain the given pixel point.
  26287. * @param {Array|number} value
  26288. * @return {boolean} result
  26289. */
  26290. ECharts.prototype.containPixel = function (finder, value) {
  26291. if (this._disposed) {
  26292. disposedWarning(this.id);
  26293. return;
  26294. }
  26295. var ecModel = this._model;
  26296. var result;
  26297. var findResult = parseFinder(ecModel, finder);
  26298. each(findResult, function (models, key) {
  26299. key.indexOf('Models') >= 0 && each(models, function (model) {
  26300. var coordSys = model.coordinateSystem;
  26301. if (coordSys && coordSys.containPoint) {
  26302. result = result || !!coordSys.containPoint(value);
  26303. } else if (key === 'seriesModels') {
  26304. var view = this._chartsMap[model.__viewId];
  26305. if (view && view.containPoint) {
  26306. result = result || view.containPoint(value, model);
  26307. } else {
  26308. if ("development" !== 'production') {
  26309. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  26310. }
  26311. }
  26312. } else {
  26313. if ("development" !== 'production') {
  26314. warn(key + ': containPoint is not supported');
  26315. }
  26316. }
  26317. }, this);
  26318. }, this);
  26319. return !!result;
  26320. };
  26321. /**
  26322. * Get visual from series or data.
  26323. * @param finder
  26324. * If string, e.g., 'series', means {seriesIndex: 0}.
  26325. * If Object, could contain some of these properties below:
  26326. * {
  26327. * seriesIndex / seriesId / seriesName,
  26328. * dataIndex / dataIndexInside
  26329. * }
  26330. * If dataIndex is not specified, series visual will be fetched,
  26331. * but not data item visual.
  26332. * If all of seriesIndex, seriesId, seriesName are not specified,
  26333. * visual will be fetched from first series.
  26334. * @param visualType 'color', 'symbol', 'symbolSize'
  26335. */
  26336. ECharts.prototype.getVisual = function (finder, visualType) {
  26337. var ecModel = this._model;
  26338. var parsedFinder = parseFinder(ecModel, finder, {
  26339. defaultMainType: 'series'
  26340. });
  26341. var seriesModel = parsedFinder.seriesModel;
  26342. if ("development" !== 'production') {
  26343. if (!seriesModel) {
  26344. warn('There is no specified series model');
  26345. }
  26346. }
  26347. var data = seriesModel.getData();
  26348. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  26349. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  26350. };
  26351. /**
  26352. * Get view of corresponding component model
  26353. */
  26354. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  26355. return this._componentsMap[componentModel.__viewId];
  26356. };
  26357. /**
  26358. * Get view of corresponding series model
  26359. */
  26360. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  26361. return this._chartsMap[seriesModel.__viewId];
  26362. };
  26363. ECharts.prototype._initEvents = function () {
  26364. var _this = this;
  26365. each(MOUSE_EVENT_NAMES, function (eveName) {
  26366. var handler = function (e) {
  26367. var ecModel = _this.getModel();
  26368. var el = e.target;
  26369. var params;
  26370. var isGlobalOut = eveName === 'globalout';
  26371. // no e.target when 'globalout'.
  26372. if (isGlobalOut) {
  26373. params = {};
  26374. } else {
  26375. el && findEventDispatcher(el, function (parent) {
  26376. var ecData = getECData(parent);
  26377. if (ecData && ecData.dataIndex != null) {
  26378. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  26379. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType, el) || {};
  26380. return true;
  26381. }
  26382. // If element has custom eventData of components
  26383. else if (ecData.eventData) {
  26384. params = extend({}, ecData.eventData);
  26385. return true;
  26386. }
  26387. }, true);
  26388. }
  26389. // Contract: if params prepared in mouse event,
  26390. // these properties must be specified:
  26391. // {
  26392. // componentType: string (component main type)
  26393. // componentIndex: number
  26394. // }
  26395. // Otherwise event query can not work.
  26396. if (params) {
  26397. var componentType = params.componentType;
  26398. var componentIndex = params.componentIndex;
  26399. // Special handling for historic reason: when trigger by
  26400. // markLine/markPoint/markArea, the componentType is
  26401. // 'markLine'/'markPoint'/'markArea', but we should better
  26402. // enable them to be queried by seriesIndex, since their
  26403. // option is set in each series.
  26404. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  26405. componentType = 'series';
  26406. componentIndex = params.seriesIndex;
  26407. }
  26408. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  26409. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  26410. if ("development" !== 'production') {
  26411. // `event.componentType` and `event[componentTpype + 'Index']` must not
  26412. // be missed, otherwise there is no way to distinguish source component.
  26413. // See `dataFormat.getDataParams`.
  26414. if (!isGlobalOut && !(model && view)) {
  26415. warn('model or view can not be found by params');
  26416. }
  26417. }
  26418. params.event = e;
  26419. params.type = eveName;
  26420. _this._$eventProcessor.eventInfo = {
  26421. targetEl: el,
  26422. packedEvent: params,
  26423. model: model,
  26424. view: view
  26425. };
  26426. _this.trigger(eveName, params);
  26427. }
  26428. };
  26429. // Consider that some component (like tooltip, brush, ...)
  26430. // register zr event handler, but user event handler might
  26431. // do anything, such as call `setOption` or `dispatchAction`,
  26432. // which probably update any of the content and probably
  26433. // cause problem if it is called previous other inner handlers.
  26434. handler.zrEventfulCallAtLast = true;
  26435. _this._zr.on(eveName, handler, _this);
  26436. });
  26437. each(eventActionMap, function (actionType, eventType) {
  26438. _this._messageCenter.on(eventType, function (event) {
  26439. this.trigger(eventType, event);
  26440. }, _this);
  26441. });
  26442. // Extra events
  26443. // TODO register?
  26444. each(['selectchanged'], function (eventType) {
  26445. _this._messageCenter.on(eventType, function (event) {
  26446. this.trigger(eventType, event);
  26447. }, _this);
  26448. });
  26449. handleLegacySelectEvents(this._messageCenter, this, this._api);
  26450. };
  26451. ECharts.prototype.isDisposed = function () {
  26452. return this._disposed;
  26453. };
  26454. ECharts.prototype.clear = function () {
  26455. if (this._disposed) {
  26456. disposedWarning(this.id);
  26457. return;
  26458. }
  26459. this.setOption({
  26460. series: []
  26461. }, true);
  26462. };
  26463. ECharts.prototype.dispose = function () {
  26464. if (this._disposed) {
  26465. disposedWarning(this.id);
  26466. return;
  26467. }
  26468. this._disposed = true;
  26469. var dom = this.getDom();
  26470. if (dom) {
  26471. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  26472. }
  26473. var chart = this;
  26474. var api = chart._api;
  26475. var ecModel = chart._model;
  26476. each(chart._componentsViews, function (component) {
  26477. component.dispose(ecModel, api);
  26478. });
  26479. each(chart._chartsViews, function (chart) {
  26480. chart.dispose(ecModel, api);
  26481. });
  26482. // Dispose after all views disposed
  26483. chart._zr.dispose();
  26484. // Set properties to null.
  26485. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  26486. 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;
  26487. delete instances$1[chart.id];
  26488. };
  26489. /**
  26490. * Resize the chart
  26491. */
  26492. ECharts.prototype.resize = function (opts) {
  26493. if (this[IN_MAIN_PROCESS_KEY]) {
  26494. if ("development" !== 'production') {
  26495. error('`resize` should not be called during main process.');
  26496. }
  26497. return;
  26498. }
  26499. if (this._disposed) {
  26500. disposedWarning(this.id);
  26501. return;
  26502. }
  26503. this._zr.resize(opts);
  26504. var ecModel = this._model;
  26505. // Resize loading effect
  26506. this._loadingFX && this._loadingFX.resize();
  26507. if (!ecModel) {
  26508. return;
  26509. }
  26510. var needPrepare = ecModel.resetOption('media');
  26511. var silent = opts && opts.silent;
  26512. // There is some real cases that:
  26513. // chart.setOption(option, { lazyUpdate: true });
  26514. // chart.resize();
  26515. if (this[PENDING_UPDATE]) {
  26516. if (silent == null) {
  26517. silent = this[PENDING_UPDATE].silent;
  26518. }
  26519. needPrepare = true;
  26520. this[PENDING_UPDATE] = null;
  26521. }
  26522. this[IN_MAIN_PROCESS_KEY] = true;
  26523. try {
  26524. needPrepare && prepare(this);
  26525. updateMethods.update.call(this, {
  26526. type: 'resize',
  26527. animation: extend({
  26528. // Disable animation
  26529. duration: 0
  26530. }, opts && opts.animation)
  26531. });
  26532. } catch (e) {
  26533. this[IN_MAIN_PROCESS_KEY] = false;
  26534. throw e;
  26535. }
  26536. this[IN_MAIN_PROCESS_KEY] = false;
  26537. flushPendingActions.call(this, silent);
  26538. triggerUpdatedEvent.call(this, silent);
  26539. };
  26540. ECharts.prototype.showLoading = function (name, cfg) {
  26541. if (this._disposed) {
  26542. disposedWarning(this.id);
  26543. return;
  26544. }
  26545. if (isObject(name)) {
  26546. cfg = name;
  26547. name = '';
  26548. }
  26549. name = name || 'default';
  26550. this.hideLoading();
  26551. if (!loadingEffects[name]) {
  26552. if ("development" !== 'production') {
  26553. warn('Loading effects ' + name + ' not exists.');
  26554. }
  26555. return;
  26556. }
  26557. var el = loadingEffects[name](this._api, cfg);
  26558. var zr = this._zr;
  26559. this._loadingFX = el;
  26560. zr.add(el);
  26561. };
  26562. /**
  26563. * Hide loading effect
  26564. */
  26565. ECharts.prototype.hideLoading = function () {
  26566. if (this._disposed) {
  26567. disposedWarning(this.id);
  26568. return;
  26569. }
  26570. this._loadingFX && this._zr.remove(this._loadingFX);
  26571. this._loadingFX = null;
  26572. };
  26573. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  26574. var payload = extend({}, eventObj);
  26575. payload.type = eventActionMap[eventObj.type];
  26576. return payload;
  26577. };
  26578. /**
  26579. * @param opt If pass boolean, means opt.silent
  26580. * @param opt.silent Default `false`. Whether trigger events.
  26581. * @param opt.flush Default `undefined`.
  26582. * true: Flush immediately, and then pixel in canvas can be fetched
  26583. * immediately. Caution: it might affect performance.
  26584. * false: Not flush.
  26585. * undefined: Auto decide whether perform flush.
  26586. */
  26587. ECharts.prototype.dispatchAction = function (payload, opt) {
  26588. if (this._disposed) {
  26589. disposedWarning(this.id);
  26590. return;
  26591. }
  26592. if (!isObject(opt)) {
  26593. opt = {
  26594. silent: !!opt
  26595. };
  26596. }
  26597. if (!actions[payload.type]) {
  26598. return;
  26599. }
  26600. // Avoid dispatch action before setOption. Especially in `connect`.
  26601. if (!this._model) {
  26602. return;
  26603. }
  26604. // May dispatchAction in rendering procedure
  26605. if (this[IN_MAIN_PROCESS_KEY]) {
  26606. this._pendingActions.push(payload);
  26607. return;
  26608. }
  26609. var silent = opt.silent;
  26610. doDispatchAction.call(this, payload, silent);
  26611. var flush = opt.flush;
  26612. if (flush) {
  26613. this._zr.flush();
  26614. } else if (flush !== false && env.browser.weChat) {
  26615. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  26616. // hang when sliding page (on touch event), which cause that zr does not
  26617. // refresh until user interaction finished, which is not expected.
  26618. // But `dispatchAction` may be called too frequently when pan on touch
  26619. // screen, which impacts performance if do not throttle them.
  26620. this._throttledZrFlush();
  26621. }
  26622. flushPendingActions.call(this, silent);
  26623. triggerUpdatedEvent.call(this, silent);
  26624. };
  26625. ECharts.prototype.updateLabelLayout = function () {
  26626. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  26627. // Not adding series labels.
  26628. // TODO
  26629. updatedSeries: []
  26630. });
  26631. };
  26632. ECharts.prototype.appendData = function (params) {
  26633. if (this._disposed) {
  26634. disposedWarning(this.id);
  26635. return;
  26636. }
  26637. var seriesIndex = params.seriesIndex;
  26638. var ecModel = this.getModel();
  26639. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26640. if ("development" !== 'production') {
  26641. assert(params.data && seriesModel);
  26642. }
  26643. seriesModel.appendData(params);
  26644. // Note: `appendData` does not support that update extent of coordinate
  26645. // system, util some scenario require that. In the expected usage of
  26646. // `appendData`, the initial extent of coordinate system should better
  26647. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26648. // the extent changed while `appendData`, the location of the painted
  26649. // graphic elements have to be changed, which make the usage of
  26650. // `appendData` meaningless.
  26651. this._scheduler.unfinished = true;
  26652. this.getZr().wakeUp();
  26653. };
  26654. // A work around for no `internal` modifier in ts yet but
  26655. // need to strictly hide private methods to JS users.
  26656. ECharts.internalField = function () {
  26657. prepare = function (ecIns) {
  26658. var scheduler = ecIns._scheduler;
  26659. scheduler.restorePipelines(ecIns._model);
  26660. scheduler.prepareStageTasks();
  26661. prepareView(ecIns, true);
  26662. prepareView(ecIns, false);
  26663. scheduler.plan();
  26664. };
  26665. /**
  26666. * Prepare view instances of charts and components
  26667. */
  26668. prepareView = function (ecIns, isComponent) {
  26669. var ecModel = ecIns._model;
  26670. var scheduler = ecIns._scheduler;
  26671. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26672. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26673. var zr = ecIns._zr;
  26674. var api = ecIns._api;
  26675. for (var i = 0; i < viewList.length; i++) {
  26676. viewList[i].__alive = false;
  26677. }
  26678. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26679. componentType !== 'series' && doPrepare(model);
  26680. }) : ecModel.eachSeries(doPrepare);
  26681. function doPrepare(model) {
  26682. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  26683. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26684. // especially no id but have the same type & name & index. See the `model.id` generation
  26685. // rule in `makeIdAndName` and `viewId` generation rule here).
  26686. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26687. // the new model has nothing to do with the old model.
  26688. var requireNewView = model.__requireNewView;
  26689. // This command should not work twice.
  26690. model.__requireNewView = false;
  26691. // Consider: id same and type changed.
  26692. var viewId = '_ec_' + model.id + '_' + model.type;
  26693. var view = !requireNewView && viewMap[viewId];
  26694. if (!view) {
  26695. var classType = parseClassType(model.type);
  26696. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) :
  26697. // FIXME:TS
  26698. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26699. // For backward compat, still support a chart type declared as only subType
  26700. // like "liquidfill", but recommend "series.liquidfill"
  26701. // But need a base class to make a type series.
  26702. ChartView.getClass(classType.sub);
  26703. if ("development" !== 'production') {
  26704. assert(Clazz, classType.sub + ' does not exist.');
  26705. }
  26706. view = new Clazz();
  26707. view.init(ecModel, api);
  26708. viewMap[viewId] = view;
  26709. viewList.push(view);
  26710. zr.add(view.group);
  26711. }
  26712. model.__viewId = view.__id = viewId;
  26713. view.__alive = true;
  26714. view.__model = model;
  26715. view.group.__ecComponentInfo = {
  26716. mainType: model.mainType,
  26717. index: model.componentIndex
  26718. };
  26719. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26720. }
  26721. for (var i = 0; i < viewList.length;) {
  26722. var view = viewList[i];
  26723. if (!view.__alive) {
  26724. !isComponent && view.renderTask.dispose();
  26725. zr.remove(view.group);
  26726. view.dispose(ecModel, api);
  26727. viewList.splice(i, 1);
  26728. if (viewMap[view.__id] === view) {
  26729. delete viewMap[view.__id];
  26730. }
  26731. view.__id = view.group.__ecComponentInfo = null;
  26732. } else {
  26733. i++;
  26734. }
  26735. }
  26736. };
  26737. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26738. var ecModel = ecIns._model;
  26739. ecModel.setUpdatePayload(payload);
  26740. // broadcast
  26741. if (!mainType) {
  26742. // FIXME
  26743. // Chart will not be update directly here, except set dirty.
  26744. // But there is no such scenario now.
  26745. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26746. return;
  26747. }
  26748. var query = {};
  26749. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26750. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26751. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26752. var condition = {
  26753. mainType: mainType,
  26754. query: query
  26755. };
  26756. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26757. var excludeSeriesId = payload.excludeSeriesId;
  26758. var excludeSeriesIdMap;
  26759. if (excludeSeriesId != null) {
  26760. excludeSeriesIdMap = createHashMap();
  26761. each(normalizeToArray(excludeSeriesId), function (id) {
  26762. var modelId = convertOptionIdName(id, null);
  26763. if (modelId != null) {
  26764. excludeSeriesIdMap.set(modelId, true);
  26765. }
  26766. });
  26767. }
  26768. // If dispatchAction before setOption, do nothing.
  26769. ecModel && ecModel.eachComponent(condition, function (model) {
  26770. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26771. if (isExcluded) {
  26772. return;
  26773. }
  26774. if (isHighDownPayload(payload)) {
  26775. if (model instanceof SeriesModel) {
  26776. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26777. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26778. }
  26779. } else {
  26780. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26781. focusSelf = _a.focusSelf,
  26782. dispatchers = _a.dispatchers;
  26783. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26784. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26785. }
  26786. // PENDING:
  26787. // Whether to put this "enter emphasis" code in `ComponentView`,
  26788. // which will be the same as `ChartView` but might be not necessary
  26789. // and will be far from this logic.
  26790. if (dispatchers) {
  26791. each(dispatchers, function (dispatcher) {
  26792. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26793. });
  26794. }
  26795. }
  26796. } else if (isSelectChangePayload(payload)) {
  26797. // TODO geo
  26798. if (model instanceof SeriesModel) {
  26799. toggleSelectionFromPayload(model, payload, ecIns._api);
  26800. updateSeriesElementSelection(model);
  26801. markStatusToUpdate(ecIns);
  26802. }
  26803. }
  26804. }, ecIns);
  26805. ecModel && ecModel.eachComponent(condition, function (model) {
  26806. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26807. if (isExcluded) {
  26808. return;
  26809. }
  26810. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26811. }, ecIns);
  26812. function callView(view) {
  26813. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26814. }
  26815. };
  26816. updateMethods = {
  26817. prepareAndUpdate: function (payload) {
  26818. prepare(this);
  26819. updateMethods.update.call(this, payload, {
  26820. // Needs to mark option changed if newOption is given.
  26821. // It's from MagicType.
  26822. // TODO If use a separate flag optionChanged in payload?
  26823. optionChanged: payload.newOption != null
  26824. });
  26825. },
  26826. update: function (payload, updateParams) {
  26827. var ecModel = this._model;
  26828. var api = this._api;
  26829. var zr = this._zr;
  26830. var coordSysMgr = this._coordSysMgr;
  26831. var scheduler = this._scheduler;
  26832. // update before setOption
  26833. if (!ecModel) {
  26834. return;
  26835. }
  26836. ecModel.setUpdatePayload(payload);
  26837. scheduler.restoreData(ecModel, payload);
  26838. scheduler.performSeriesTasks(ecModel);
  26839. // TODO
  26840. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26841. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26842. // Create new coordinate system each update
  26843. // In LineView may save the old coordinate system and use it to get the original point.
  26844. coordSysMgr.create(ecModel, api);
  26845. scheduler.performDataProcessorTasks(ecModel, payload);
  26846. // Current stream render is not supported in data process. So we can update
  26847. // stream modes after data processing, where the filtered data is used to
  26848. // determine whether to use progressive rendering.
  26849. updateStreamModes(this, ecModel);
  26850. // We update stream modes before coordinate system updated, then the modes info
  26851. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26852. // the drawback is the full coord info can not be fetched. Fortunately this full
  26853. // coord is not required in stream mode updater currently.
  26854. coordSysMgr.update(ecModel, api);
  26855. clearColorPalette(ecModel);
  26856. scheduler.performVisualTasks(ecModel, payload);
  26857. render(this, ecModel, api, payload, updateParams);
  26858. // Set background
  26859. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26860. var darkMode = ecModel.get('darkMode');
  26861. zr.setBackgroundColor(backgroundColor);
  26862. // Force set dark mode.
  26863. if (darkMode != null && darkMode !== 'auto') {
  26864. zr.setDarkMode(darkMode);
  26865. }
  26866. lifecycle.trigger('afterupdate', ecModel, api);
  26867. },
  26868. updateTransform: function (payload) {
  26869. var _this = this;
  26870. var ecModel = this._model;
  26871. var api = this._api;
  26872. // update before setOption
  26873. if (!ecModel) {
  26874. return;
  26875. }
  26876. ecModel.setUpdatePayload(payload);
  26877. // ChartView.markUpdateMethod(payload, 'updateTransform');
  26878. var componentDirtyList = [];
  26879. ecModel.eachComponent(function (componentType, componentModel) {
  26880. if (componentType === 'series') {
  26881. return;
  26882. }
  26883. var componentView = _this.getViewOfComponentModel(componentModel);
  26884. if (componentView && componentView.__alive) {
  26885. if (componentView.updateTransform) {
  26886. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26887. result && result.update && componentDirtyList.push(componentView);
  26888. } else {
  26889. componentDirtyList.push(componentView);
  26890. }
  26891. }
  26892. });
  26893. var seriesDirtyMap = createHashMap();
  26894. ecModel.eachSeries(function (seriesModel) {
  26895. var chartView = _this._chartsMap[seriesModel.__viewId];
  26896. if (chartView.updateTransform) {
  26897. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26898. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26899. } else {
  26900. seriesDirtyMap.set(seriesModel.uid, 1);
  26901. }
  26902. });
  26903. clearColorPalette(ecModel);
  26904. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26905. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26906. this._scheduler.performVisualTasks(ecModel, payload, {
  26907. setDirty: true,
  26908. dirtyMap: seriesDirtyMap
  26909. });
  26910. // Currently, not call render of components. Geo render cost a lot.
  26911. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26912. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26913. lifecycle.trigger('afterupdate', ecModel, api);
  26914. },
  26915. updateView: function (payload) {
  26916. var ecModel = this._model;
  26917. // update before setOption
  26918. if (!ecModel) {
  26919. return;
  26920. }
  26921. ecModel.setUpdatePayload(payload);
  26922. ChartView.markUpdateMethod(payload, 'updateView');
  26923. clearColorPalette(ecModel);
  26924. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26925. this._scheduler.performVisualTasks(ecModel, payload, {
  26926. setDirty: true
  26927. });
  26928. render(this, ecModel, this._api, payload, {});
  26929. lifecycle.trigger('afterupdate', ecModel, this._api);
  26930. },
  26931. updateVisual: function (payload) {
  26932. // updateMethods.update.call(this, payload);
  26933. var _this = this;
  26934. var ecModel = this._model;
  26935. // update before setOption
  26936. if (!ecModel) {
  26937. return;
  26938. }
  26939. ecModel.setUpdatePayload(payload);
  26940. // clear all visual
  26941. ecModel.eachSeries(function (seriesModel) {
  26942. seriesModel.getData().clearAllVisual();
  26943. });
  26944. // Perform visual
  26945. ChartView.markUpdateMethod(payload, 'updateVisual');
  26946. clearColorPalette(ecModel);
  26947. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26948. this._scheduler.performVisualTasks(ecModel, payload, {
  26949. visualType: 'visual',
  26950. setDirty: true
  26951. });
  26952. ecModel.eachComponent(function (componentType, componentModel) {
  26953. if (componentType !== 'series') {
  26954. var componentView = _this.getViewOfComponentModel(componentModel);
  26955. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26956. }
  26957. });
  26958. ecModel.eachSeries(function (seriesModel) {
  26959. var chartView = _this._chartsMap[seriesModel.__viewId];
  26960. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26961. });
  26962. lifecycle.trigger('afterupdate', ecModel, this._api);
  26963. },
  26964. updateLayout: function (payload) {
  26965. updateMethods.update.call(this, payload);
  26966. }
  26967. };
  26968. doConvertPixel = function (ecIns, methodName, finder, value) {
  26969. if (ecIns._disposed) {
  26970. disposedWarning(ecIns.id);
  26971. return;
  26972. }
  26973. var ecModel = ecIns._model;
  26974. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26975. var result;
  26976. var parsedFinder = parseFinder(ecModel, finder);
  26977. for (var i = 0; i < coordSysList.length; i++) {
  26978. var coordSys = coordSysList[i];
  26979. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26980. return result;
  26981. }
  26982. }
  26983. if ("development" !== 'production') {
  26984. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26985. }
  26986. };
  26987. updateStreamModes = function (ecIns, ecModel) {
  26988. var chartsMap = ecIns._chartsMap;
  26989. var scheduler = ecIns._scheduler;
  26990. ecModel.eachSeries(function (seriesModel) {
  26991. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26992. });
  26993. };
  26994. doDispatchAction = function (payload, silent) {
  26995. var _this = this;
  26996. var ecModel = this.getModel();
  26997. var payloadType = payload.type;
  26998. var escapeConnect = payload.escapeConnect;
  26999. var actionWrap = actions[payloadType];
  27000. var actionInfo = actionWrap.actionInfo;
  27001. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  27002. var updateMethod = cptTypeTmp.pop();
  27003. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  27004. this[IN_MAIN_PROCESS_KEY] = true;
  27005. var payloads = [payload];
  27006. var batched = false;
  27007. // Batch action
  27008. if (payload.batch) {
  27009. batched = true;
  27010. payloads = map(payload.batch, function (item) {
  27011. item = defaults(extend({}, item), payload);
  27012. item.batch = null;
  27013. return item;
  27014. });
  27015. }
  27016. var eventObjBatch = [];
  27017. var eventObj;
  27018. var isSelectChange = isSelectChangePayload(payload);
  27019. var isHighDown = isHighDownPayload(payload);
  27020. // Only leave blur once if there are multiple batches.
  27021. if (isHighDown) {
  27022. allLeaveBlur(this._api);
  27023. }
  27024. each(payloads, function (batchItem) {
  27025. // Action can specify the event by return it.
  27026. eventObj = actionWrap.action(batchItem, _this._model, _this._api);
  27027. // Emit event outside
  27028. eventObj = eventObj || extend({}, batchItem);
  27029. // Convert type to eventType
  27030. eventObj.type = actionInfo.event || eventObj.type;
  27031. eventObjBatch.push(eventObj);
  27032. // light update does not perform data process, layout and visual.
  27033. if (isHighDown) {
  27034. var _a = preParseFinder(payload),
  27035. queryOptionMap = _a.queryOptionMap,
  27036. mainTypeSpecified = _a.mainTypeSpecified;
  27037. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  27038. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  27039. markStatusToUpdate(_this);
  27040. } else if (isSelectChange) {
  27041. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  27042. // geo still use 'geoselect'.
  27043. updateDirectly(_this, updateMethod, batchItem, 'series');
  27044. markStatusToUpdate(_this);
  27045. } else if (cptType) {
  27046. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  27047. }
  27048. });
  27049. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  27050. try {
  27051. // Still dirty
  27052. if (this[PENDING_UPDATE]) {
  27053. prepare(this);
  27054. updateMethods.update.call(this, payload);
  27055. this[PENDING_UPDATE] = null;
  27056. } else {
  27057. updateMethods[updateMethod].call(this, payload);
  27058. }
  27059. } catch (e) {
  27060. this[IN_MAIN_PROCESS_KEY] = false;
  27061. throw e;
  27062. }
  27063. }
  27064. // Follow the rule of action batch
  27065. if (batched) {
  27066. eventObj = {
  27067. type: actionInfo.event || payloadType,
  27068. escapeConnect: escapeConnect,
  27069. batch: eventObjBatch
  27070. };
  27071. } else {
  27072. eventObj = eventObjBatch[0];
  27073. }
  27074. this[IN_MAIN_PROCESS_KEY] = false;
  27075. if (!silent) {
  27076. var messageCenter = this._messageCenter;
  27077. messageCenter.trigger(eventObj.type, eventObj);
  27078. // Extra triggered 'selectchanged' event
  27079. if (isSelectChange) {
  27080. var newObj = {
  27081. type: 'selectchanged',
  27082. escapeConnect: escapeConnect,
  27083. selected: getAllSelectedIndices(ecModel),
  27084. isFromClick: payload.isFromClick || false,
  27085. fromAction: payload.type,
  27086. fromActionPayload: payload
  27087. };
  27088. messageCenter.trigger(newObj.type, newObj);
  27089. }
  27090. }
  27091. };
  27092. flushPendingActions = function (silent) {
  27093. var pendingActions = this._pendingActions;
  27094. while (pendingActions.length) {
  27095. var payload = pendingActions.shift();
  27096. doDispatchAction.call(this, payload, silent);
  27097. }
  27098. };
  27099. triggerUpdatedEvent = function (silent) {
  27100. !silent && this.trigger('updated');
  27101. };
  27102. /**
  27103. * Event `rendered` is triggered when zr
  27104. * rendered. It is useful for realtime
  27105. * snapshot (reflect animation).
  27106. *
  27107. * Event `finished` is triggered when:
  27108. * (1) zrender rendering finished.
  27109. * (2) initial animation finished.
  27110. * (3) progressive rendering finished.
  27111. * (4) no pending action.
  27112. * (5) no delayed setOption needs to be processed.
  27113. */
  27114. bindRenderedEvent = function (zr, ecIns) {
  27115. zr.on('rendered', function (params) {
  27116. ecIns.trigger('rendered', params);
  27117. // The `finished` event should not be triggered repeatedly,
  27118. // so it should only be triggered when rendering indeed happens
  27119. // in zrender. (Consider the case that dipatchAction is keep
  27120. // triggering when mouse move).
  27121. if (
  27122. // Although zr is dirty if initial animation is not finished
  27123. // and this checking is called on frame, we also check
  27124. // animation finished for robustness.
  27125. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  27126. ecIns.trigger('finished');
  27127. }
  27128. });
  27129. };
  27130. bindMouseEvent = function (zr, ecIns) {
  27131. zr.on('mouseover', function (e) {
  27132. var el = e.target;
  27133. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  27134. if (dispatcher) {
  27135. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  27136. markStatusToUpdate(ecIns);
  27137. }
  27138. }).on('mouseout', function (e) {
  27139. var el = e.target;
  27140. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  27141. if (dispatcher) {
  27142. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  27143. markStatusToUpdate(ecIns);
  27144. }
  27145. }).on('click', function (e) {
  27146. var el = e.target;
  27147. var dispatcher = findEventDispatcher(el, function (target) {
  27148. return getECData(target).dataIndex != null;
  27149. }, true);
  27150. if (dispatcher) {
  27151. var actionType = dispatcher.selected ? 'unselect' : 'select';
  27152. var ecData = getECData(dispatcher);
  27153. ecIns._api.dispatchAction({
  27154. type: actionType,
  27155. dataType: ecData.dataType,
  27156. dataIndexInside: ecData.dataIndex,
  27157. seriesIndex: ecData.seriesIndex,
  27158. isFromClick: true
  27159. });
  27160. }
  27161. });
  27162. };
  27163. function clearColorPalette(ecModel) {
  27164. ecModel.clearColorPalette();
  27165. ecModel.eachSeries(function (seriesModel) {
  27166. seriesModel.clearColorPalette();
  27167. });
  27168. }
  27169. // Allocate zlevels for series and components
  27170. function allocateZlevels(ecModel) {
  27171. var componentZLevels = [];
  27172. var seriesZLevels = [];
  27173. var hasSeparateZLevel = false;
  27174. ecModel.eachComponent(function (componentType, componentModel) {
  27175. var zlevel = componentModel.get('zlevel') || 0;
  27176. var z = componentModel.get('z') || 0;
  27177. var zlevelKey = componentModel.getZLevelKey();
  27178. hasSeparateZLevel = hasSeparateZLevel || !!zlevelKey;
  27179. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  27180. zlevel: zlevel,
  27181. z: z,
  27182. idx: componentModel.componentIndex,
  27183. type: componentType,
  27184. key: zlevelKey
  27185. });
  27186. });
  27187. if (hasSeparateZLevel) {
  27188. // Series after component
  27189. var zLevels = componentZLevels.concat(seriesZLevels);
  27190. var lastSeriesZLevel_1;
  27191. var lastSeriesKey_1;
  27192. sort(zLevels, function (a, b) {
  27193. if (a.zlevel === b.zlevel) {
  27194. return a.z - b.z;
  27195. }
  27196. return a.zlevel - b.zlevel;
  27197. });
  27198. each(zLevels, function (item) {
  27199. var componentModel = ecModel.getComponent(item.type, item.idx);
  27200. var zlevel = item.zlevel;
  27201. var key = item.key;
  27202. if (lastSeriesZLevel_1 != null) {
  27203. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  27204. }
  27205. if (key) {
  27206. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  27207. zlevel++;
  27208. }
  27209. lastSeriesKey_1 = key;
  27210. } else if (lastSeriesKey_1) {
  27211. if (zlevel === lastSeriesZLevel_1) {
  27212. zlevel++;
  27213. }
  27214. lastSeriesKey_1 = '';
  27215. }
  27216. lastSeriesZLevel_1 = zlevel;
  27217. componentModel.setZLevel(zlevel);
  27218. });
  27219. }
  27220. }
  27221. render = function (ecIns, ecModel, api, payload, updateParams) {
  27222. allocateZlevels(ecModel);
  27223. renderComponents(ecIns, ecModel, api, payload, updateParams);
  27224. each(ecIns._chartsViews, function (chart) {
  27225. chart.__alive = false;
  27226. });
  27227. renderSeries(ecIns, ecModel, api, payload, updateParams);
  27228. // Remove groups of unrendered charts
  27229. each(ecIns._chartsViews, function (chart) {
  27230. if (!chart.__alive) {
  27231. chart.remove(ecModel, api);
  27232. }
  27233. });
  27234. };
  27235. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  27236. each(dirtyList || ecIns._componentsViews, function (componentView) {
  27237. var componentModel = componentView.__model;
  27238. clearStates(componentModel, componentView);
  27239. componentView.render(componentModel, ecModel, api, payload);
  27240. updateZ(componentModel, componentView);
  27241. updateStates(componentModel, componentView);
  27242. });
  27243. };
  27244. /**
  27245. * Render each chart and component
  27246. */
  27247. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  27248. // Render all charts
  27249. var scheduler = ecIns._scheduler;
  27250. updateParams = extend(updateParams || {}, {
  27251. updatedSeries: ecModel.getSeries()
  27252. });
  27253. // TODO progressive?
  27254. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  27255. var unfinished = false;
  27256. ecModel.eachSeries(function (seriesModel) {
  27257. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27258. chartView.__alive = true;
  27259. var renderTask = chartView.renderTask;
  27260. scheduler.updatePayload(renderTask, payload);
  27261. // TODO states on marker.
  27262. clearStates(seriesModel, chartView);
  27263. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  27264. renderTask.dirty();
  27265. }
  27266. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  27267. unfinished = true;
  27268. }
  27269. chartView.group.silent = !!seriesModel.get('silent');
  27270. // Should not call markRedraw on group, because it will disable zrender
  27271. // incremental render (always render from the __startIndex each frame)
  27272. // chartView.group.markRedraw();
  27273. updateBlend(seriesModel, chartView);
  27274. updateSeriesElementSelection(seriesModel);
  27275. });
  27276. scheduler.unfinished = unfinished || scheduler.unfinished;
  27277. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams);
  27278. // transition after label is layouted.
  27279. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  27280. ecModel.eachSeries(function (seriesModel) {
  27281. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27282. // Update Z after labels updated. Before applying states.
  27283. updateZ(seriesModel, chartView);
  27284. // NOTE: Update states after label is updated.
  27285. // label should be in normal status when layouting.
  27286. updateStates(seriesModel, chartView);
  27287. });
  27288. // If use hover layer
  27289. updateHoverLayerStatus(ecIns, ecModel);
  27290. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  27291. };
  27292. markStatusToUpdate = function (ecIns) {
  27293. ecIns[STATUS_NEEDS_UPDATE_KEY] = true;
  27294. // Wake up zrender if it's sleep. Let it update states in the next frame.
  27295. ecIns.getZr().wakeUp();
  27296. };
  27297. applyChangedStates = function (ecIns) {
  27298. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  27299. return;
  27300. }
  27301. ecIns.getZr().storage.traverse(function (el) {
  27302. // Not applied on removed elements, it may still in fading.
  27303. if (isElementRemoved(el)) {
  27304. return;
  27305. }
  27306. applyElementStates(el);
  27307. });
  27308. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  27309. };
  27310. function applyElementStates(el) {
  27311. var newStates = [];
  27312. var oldStates = el.currentStates;
  27313. // Keep other states.
  27314. for (var i = 0; i < oldStates.length; i++) {
  27315. var stateName = oldStates[i];
  27316. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  27317. newStates.push(stateName);
  27318. }
  27319. }
  27320. // Only use states when it's exists.
  27321. if (el.selected && el.states.select) {
  27322. newStates.push('select');
  27323. }
  27324. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  27325. newStates.push('emphasis');
  27326. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  27327. newStates.push('blur');
  27328. }
  27329. el.useStates(newStates);
  27330. }
  27331. function updateHoverLayerStatus(ecIns, ecModel) {
  27332. var zr = ecIns._zr;
  27333. var storage = zr.storage;
  27334. var elCount = 0;
  27335. storage.traverse(function (el) {
  27336. if (!el.isGroup) {
  27337. elCount++;
  27338. }
  27339. });
  27340. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  27341. ecModel.eachSeries(function (seriesModel) {
  27342. if (seriesModel.preventUsingHoverLayer) {
  27343. return;
  27344. }
  27345. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27346. if (chartView.__alive) {
  27347. chartView.eachRendered(function (el) {
  27348. if (el.states.emphasis) {
  27349. el.states.emphasis.hoverLayer = true;
  27350. }
  27351. });
  27352. }
  27353. });
  27354. }
  27355. }
  27356. /**
  27357. * Update chart and blend.
  27358. */
  27359. function updateBlend(seriesModel, chartView) {
  27360. var blendMode = seriesModel.get('blendMode') || null;
  27361. chartView.eachRendered(function (el) {
  27362. // FIXME marker and other components
  27363. if (!el.isGroup) {
  27364. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  27365. el.style.blend = blendMode;
  27366. }
  27367. });
  27368. }
  27369. function updateZ(model, view) {
  27370. if (model.preventAutoZ) {
  27371. return;
  27372. }
  27373. var z = model.get('z') || 0;
  27374. var zlevel = model.get('zlevel') || 0;
  27375. // Set z and zlevel
  27376. view.eachRendered(function (el) {
  27377. doUpdateZ(el, z, zlevel, -Infinity);
  27378. // Don't traverse the children because it has been traversed in _updateZ.
  27379. return true;
  27380. });
  27381. }
  27382. function doUpdateZ(el, z, zlevel, maxZ2) {
  27383. // Group may also have textContent
  27384. var label = el.getTextContent();
  27385. var labelLine = el.getTextGuideLine();
  27386. var isGroup = el.isGroup;
  27387. if (isGroup) {
  27388. // set z & zlevel of children elements of Group
  27389. var children = el.childrenRef();
  27390. for (var i = 0; i < children.length; i++) {
  27391. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  27392. }
  27393. } else {
  27394. // not Group
  27395. el.z = z;
  27396. el.zlevel = zlevel;
  27397. maxZ2 = Math.max(el.z2, maxZ2);
  27398. }
  27399. // always set z and zlevel if label/labelLine exists
  27400. if (label) {
  27401. label.z = z;
  27402. label.zlevel = zlevel;
  27403. // lift z2 of text content
  27404. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  27405. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  27406. }
  27407. if (labelLine) {
  27408. var textGuideLineConfig = el.textGuideLineConfig;
  27409. labelLine.z = z;
  27410. labelLine.zlevel = zlevel;
  27411. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  27412. }
  27413. return maxZ2;
  27414. }
  27415. // Clear states without animation.
  27416. // TODO States on component.
  27417. function clearStates(model, view) {
  27418. view.eachRendered(function (el) {
  27419. // Not applied on removed elements, it may still in fading.
  27420. if (isElementRemoved(el)) {
  27421. return;
  27422. }
  27423. var textContent = el.getTextContent();
  27424. var textGuide = el.getTextGuideLine();
  27425. if (el.stateTransition) {
  27426. el.stateTransition = null;
  27427. }
  27428. if (textContent && textContent.stateTransition) {
  27429. textContent.stateTransition = null;
  27430. }
  27431. if (textGuide && textGuide.stateTransition) {
  27432. textGuide.stateTransition = null;
  27433. }
  27434. // TODO If el is incremental.
  27435. if (el.hasState()) {
  27436. el.prevStates = el.currentStates;
  27437. el.clearStates();
  27438. } else if (el.prevStates) {
  27439. el.prevStates = null;
  27440. }
  27441. });
  27442. }
  27443. function updateStates(model, view) {
  27444. var stateAnimationModel = model.getModel('stateAnimation');
  27445. var enableAnimation = model.isAnimationEnabled();
  27446. var duration = stateAnimationModel.get('duration');
  27447. var stateTransition = duration > 0 ? {
  27448. duration: duration,
  27449. delay: stateAnimationModel.get('delay'),
  27450. easing: stateAnimationModel.get('easing')
  27451. // additive: stateAnimationModel.get('additive')
  27452. } : null;
  27453. view.eachRendered(function (el) {
  27454. if (el.states && el.states.emphasis) {
  27455. // Not applied on removed elements, it may still in fading.
  27456. if (isElementRemoved(el)) {
  27457. return;
  27458. }
  27459. if (el instanceof Path) {
  27460. savePathStates(el);
  27461. }
  27462. // Only updated on changed element. In case element is incremental and don't want to rerender.
  27463. // TODO, a more proper way?
  27464. if (el.__dirty) {
  27465. var prevStates = el.prevStates;
  27466. // Restore states without animation
  27467. if (prevStates) {
  27468. el.useStates(prevStates);
  27469. }
  27470. }
  27471. // Update state transition and enable animation again.
  27472. if (enableAnimation) {
  27473. el.stateTransition = stateTransition;
  27474. var textContent = el.getTextContent();
  27475. var textGuide = el.getTextGuideLine();
  27476. // TODO Is it necessary to animate label?
  27477. if (textContent) {
  27478. textContent.stateTransition = stateTransition;
  27479. }
  27480. if (textGuide) {
  27481. textGuide.stateTransition = stateTransition;
  27482. }
  27483. }
  27484. // Use highlighted and selected flag to toggle states.
  27485. if (el.__dirty) {
  27486. applyElementStates(el);
  27487. }
  27488. }
  27489. });
  27490. }
  27491. createExtensionAPI = function (ecIns) {
  27492. return new ( /** @class */function (_super) {
  27493. __extends(class_1, _super);
  27494. function class_1() {
  27495. return _super !== null && _super.apply(this, arguments) || this;
  27496. }
  27497. class_1.prototype.getCoordinateSystems = function () {
  27498. return ecIns._coordSysMgr.getCoordinateSystems();
  27499. };
  27500. class_1.prototype.getComponentByElement = function (el) {
  27501. while (el) {
  27502. var modelInfo = el.__ecComponentInfo;
  27503. if (modelInfo != null) {
  27504. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  27505. }
  27506. el = el.parent;
  27507. }
  27508. };
  27509. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  27510. enterEmphasis(el, highlightDigit);
  27511. markStatusToUpdate(ecIns);
  27512. };
  27513. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  27514. leaveEmphasis(el, highlightDigit);
  27515. markStatusToUpdate(ecIns);
  27516. };
  27517. class_1.prototype.enterBlur = function (el) {
  27518. enterBlur(el);
  27519. markStatusToUpdate(ecIns);
  27520. };
  27521. class_1.prototype.leaveBlur = function (el) {
  27522. leaveBlur(el);
  27523. markStatusToUpdate(ecIns);
  27524. };
  27525. class_1.prototype.enterSelect = function (el) {
  27526. enterSelect(el);
  27527. markStatusToUpdate(ecIns);
  27528. };
  27529. class_1.prototype.leaveSelect = function (el) {
  27530. leaveSelect(el);
  27531. markStatusToUpdate(ecIns);
  27532. };
  27533. class_1.prototype.getModel = function () {
  27534. return ecIns.getModel();
  27535. };
  27536. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  27537. return ecIns.getViewOfComponentModel(componentModel);
  27538. };
  27539. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  27540. return ecIns.getViewOfSeriesModel(seriesModel);
  27541. };
  27542. return class_1;
  27543. }(ExtensionAPI))(ecIns);
  27544. };
  27545. enableConnect = function (chart) {
  27546. function updateConnectedChartsStatus(charts, status) {
  27547. for (var i = 0; i < charts.length; i++) {
  27548. var otherChart = charts[i];
  27549. otherChart[CONNECT_STATUS_KEY] = status;
  27550. }
  27551. }
  27552. each(eventActionMap, function (actionType, eventType) {
  27553. chart._messageCenter.on(eventType, function (event) {
  27554. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  27555. if (event && event.escapeConnect) {
  27556. return;
  27557. }
  27558. var action_1 = chart.makeActionFromEvent(event);
  27559. var otherCharts_1 = [];
  27560. each(instances$1, function (otherChart) {
  27561. if (otherChart !== chart && otherChart.group === chart.group) {
  27562. otherCharts_1.push(otherChart);
  27563. }
  27564. });
  27565. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  27566. each(otherCharts_1, function (otherChart) {
  27567. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  27568. otherChart.dispatchAction(action_1);
  27569. }
  27570. });
  27571. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  27572. }
  27573. });
  27574. });
  27575. };
  27576. }();
  27577. return ECharts;
  27578. }(Eventful);
  27579. var echartsProto = ECharts.prototype;
  27580. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  27581. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  27582. /**
  27583. * @deprecated
  27584. */
  27585. // @ts-ignore
  27586. echartsProto.one = function (eventName, cb, ctx) {
  27587. var self = this;
  27588. deprecateLog('ECharts#one is deprecated.');
  27589. function wrapped() {
  27590. var args2 = [];
  27591. for (var _i = 0; _i < arguments.length; _i++) {
  27592. args2[_i] = arguments[_i];
  27593. }
  27594. cb && cb.apply && cb.apply(this, args2);
  27595. // @ts-ignore
  27596. self.off(eventName, wrapped);
  27597. }
  27598. // @ts-ignore
  27599. this.on.call(this, eventName, wrapped, ctx);
  27600. };
  27601. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  27602. function disposedWarning(id) {
  27603. if ("development" !== 'production') {
  27604. warn('Instance ' + id + ' has been disposed');
  27605. }
  27606. }
  27607. var actions = {};
  27608. /**
  27609. * Map eventType to actionType
  27610. */
  27611. var eventActionMap = {};
  27612. var dataProcessorFuncs = [];
  27613. var optionPreprocessorFuncs = [];
  27614. var visualFuncs = [];
  27615. var themeStorage = {};
  27616. var loadingEffects = {};
  27617. var instances$1 = {};
  27618. var connectedGroups = {};
  27619. var idBase = +new Date() - 0;
  27620. var groupIdBase = +new Date() - 0;
  27621. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  27622. /**
  27623. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  27624. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  27625. * @param opts.width Use clientWidth of the input `dom` by default.
  27626. * Can be 'auto' (the same as null/undefined)
  27627. * @param opts.height Use clientHeight of the input `dom` by default.
  27628. * Can be 'auto' (the same as null/undefined)
  27629. * @param opts.locale Specify the locale.
  27630. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  27631. */
  27632. function init$1(dom, theme, opts) {
  27633. var isClient = !(opts && opts.ssr);
  27634. if (isClient) {
  27635. if ("development" !== 'production') {
  27636. if (!dom) {
  27637. throw new Error('Initialize failed: invalid dom.');
  27638. }
  27639. }
  27640. var existInstance = getInstanceByDom(dom);
  27641. if (existInstance) {
  27642. if ("development" !== 'production') {
  27643. warn('There is a chart instance already initialized on the dom.');
  27644. }
  27645. return existInstance;
  27646. }
  27647. if ("development" !== 'production') {
  27648. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  27649. 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.');
  27650. }
  27651. }
  27652. }
  27653. var chart = new ECharts(dom, theme, opts);
  27654. chart.id = 'ec_' + idBase++;
  27655. instances$1[chart.id] = chart;
  27656. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  27657. enableConnect(chart);
  27658. lifecycle.trigger('afterinit', chart);
  27659. return chart;
  27660. }
  27661. /**
  27662. * @usage
  27663. * (A)
  27664. * ```js
  27665. * let chart1 = echarts.init(dom1);
  27666. * let chart2 = echarts.init(dom2);
  27667. * chart1.group = 'xxx';
  27668. * chart2.group = 'xxx';
  27669. * echarts.connect('xxx');
  27670. * ```
  27671. * (B)
  27672. * ```js
  27673. * let chart1 = echarts.init(dom1);
  27674. * let chart2 = echarts.init(dom2);
  27675. * echarts.connect('xxx', [chart1, chart2]);
  27676. * ```
  27677. */
  27678. function connect(groupId) {
  27679. // Is array of charts
  27680. if (isArray(groupId)) {
  27681. var charts = groupId;
  27682. groupId = null;
  27683. // If any chart has group
  27684. each(charts, function (chart) {
  27685. if (chart.group != null) {
  27686. groupId = chart.group;
  27687. }
  27688. });
  27689. groupId = groupId || 'g_' + groupIdBase++;
  27690. each(charts, function (chart) {
  27691. chart.group = groupId;
  27692. });
  27693. }
  27694. connectedGroups[groupId] = true;
  27695. return groupId;
  27696. }
  27697. function disconnect(groupId) {
  27698. connectedGroups[groupId] = false;
  27699. }
  27700. /**
  27701. * Alias and backward compatibility
  27702. * @deprecated
  27703. */
  27704. var disConnect = disconnect;
  27705. /**
  27706. * Dispose a chart instance
  27707. */
  27708. function dispose$1(chart) {
  27709. if (isString(chart)) {
  27710. chart = instances$1[chart];
  27711. } else if (!(chart instanceof ECharts)) {
  27712. // Try to treat as dom
  27713. chart = getInstanceByDom(chart);
  27714. }
  27715. if (chart instanceof ECharts && !chart.isDisposed()) {
  27716. chart.dispose();
  27717. }
  27718. }
  27719. function getInstanceByDom(dom) {
  27720. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27721. }
  27722. function getInstanceById(key) {
  27723. return instances$1[key];
  27724. }
  27725. /**
  27726. * Register theme
  27727. */
  27728. function registerTheme(name, theme) {
  27729. themeStorage[name] = theme;
  27730. }
  27731. /**
  27732. * Register option preprocessor
  27733. */
  27734. function registerPreprocessor(preprocessorFunc) {
  27735. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27736. optionPreprocessorFuncs.push(preprocessorFunc);
  27737. }
  27738. }
  27739. function registerProcessor(priority, processor) {
  27740. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27741. }
  27742. /**
  27743. * Register postIniter
  27744. * @param {Function} postInitFunc
  27745. */
  27746. function registerPostInit(postInitFunc) {
  27747. registerUpdateLifecycle('afterinit', postInitFunc);
  27748. }
  27749. /**
  27750. * Register postUpdater
  27751. * @param {Function} postUpdateFunc
  27752. */
  27753. function registerPostUpdate(postUpdateFunc) {
  27754. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27755. }
  27756. function registerUpdateLifecycle(name, cb) {
  27757. lifecycle.on(name, cb);
  27758. }
  27759. function registerAction(actionInfo, eventName, action) {
  27760. if (isFunction(eventName)) {
  27761. action = eventName;
  27762. eventName = '';
  27763. }
  27764. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27765. event: eventName
  27766. }][0];
  27767. // Event name is all lowercase
  27768. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27769. eventName = actionInfo.event;
  27770. if (eventActionMap[eventName]) {
  27771. // Already registered.
  27772. return;
  27773. }
  27774. // Validate action type and event name.
  27775. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27776. if (!actions[actionType]) {
  27777. actions[actionType] = {
  27778. action: action,
  27779. actionInfo: actionInfo
  27780. };
  27781. }
  27782. eventActionMap[eventName] = actionType;
  27783. }
  27784. function registerCoordinateSystem(type, coordSysCreator) {
  27785. CoordinateSystemManager.register(type, coordSysCreator);
  27786. }
  27787. /**
  27788. * Get dimensions of specified coordinate system.
  27789. * @param {string} type
  27790. * @return {Array.<string|Object>}
  27791. */
  27792. function getCoordinateSystemDimensions(type) {
  27793. var coordSysCreator = CoordinateSystemManager.get(type);
  27794. if (coordSysCreator) {
  27795. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27796. }
  27797. }
  27798. function registerLayout(priority, layoutTask) {
  27799. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27800. }
  27801. function registerVisual(priority, visualTask) {
  27802. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27803. }
  27804. var registeredTasks = [];
  27805. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27806. if (isFunction(priority) || isObject(priority)) {
  27807. fn = priority;
  27808. priority = defaultPriority;
  27809. }
  27810. if ("development" !== 'production') {
  27811. if (isNaN(priority) || priority == null) {
  27812. throw new Error('Illegal priority');
  27813. }
  27814. // Check duplicate
  27815. each(targetList, function (wrap) {
  27816. assert(wrap.__raw !== fn);
  27817. });
  27818. }
  27819. // Already registered
  27820. if (indexOf(registeredTasks, fn) >= 0) {
  27821. return;
  27822. }
  27823. registeredTasks.push(fn);
  27824. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27825. stageHandler.__prio = priority;
  27826. stageHandler.__raw = fn;
  27827. targetList.push(stageHandler);
  27828. }
  27829. function registerLoading(name, loadingFx) {
  27830. loadingEffects[name] = loadingFx;
  27831. }
  27832. /**
  27833. * ZRender need a canvas context to do measureText.
  27834. * But in node environment canvas may be created by node-canvas.
  27835. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27836. *
  27837. *
  27838. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27839. *
  27840. * @example
  27841. * let Canvas = require('canvas');
  27842. * let echarts = require('echarts');
  27843. * echarts.setCanvasCreator(function () {
  27844. * // Small size is enough.
  27845. * return new Canvas(32, 32);
  27846. * });
  27847. */
  27848. function setCanvasCreator(creator) {
  27849. if ("development" !== 'production') {
  27850. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27851. }
  27852. setPlatformAPI({
  27853. createCanvas: creator
  27854. });
  27855. }
  27856. /**
  27857. * The parameters and usage: see `geoSourceManager.registerMap`.
  27858. * Compatible with previous `echarts.registerMap`.
  27859. */
  27860. function registerMap(mapName, geoJson, specialAreas) {
  27861. var registerMap = getImpl('registerMap');
  27862. registerMap && registerMap(mapName, geoJson, specialAreas);
  27863. }
  27864. function getMap(mapName) {
  27865. var getMap = getImpl('getMap');
  27866. return getMap && getMap(mapName);
  27867. }
  27868. var registerTransform = registerExternalTransform;
  27869. /**
  27870. * Globa dispatchAction to a specified chart instance.
  27871. */
  27872. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27873. // if (!payload || !payload.chartId) {
  27874. // // Must have chartId to find chart
  27875. // return;
  27876. // }
  27877. // const chart = instances[payload.chartId];
  27878. // if (chart) {
  27879. // chart.dispatchAction(payload, opt);
  27880. // }
  27881. // }
  27882. // Builtin global visual
  27883. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27884. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27885. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27886. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27887. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27888. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27889. registerPreprocessor(globalBackwardCompat);
  27890. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27891. registerLoading('default', defaultLoading);
  27892. // Default actions
  27893. registerAction({
  27894. type: HIGHLIGHT_ACTION_TYPE,
  27895. event: HIGHLIGHT_ACTION_TYPE,
  27896. update: HIGHLIGHT_ACTION_TYPE
  27897. }, noop);
  27898. registerAction({
  27899. type: DOWNPLAY_ACTION_TYPE,
  27900. event: DOWNPLAY_ACTION_TYPE,
  27901. update: DOWNPLAY_ACTION_TYPE
  27902. }, noop);
  27903. registerAction({
  27904. type: SELECT_ACTION_TYPE,
  27905. event: SELECT_ACTION_TYPE,
  27906. update: SELECT_ACTION_TYPE
  27907. }, noop);
  27908. registerAction({
  27909. type: UNSELECT_ACTION_TYPE,
  27910. event: UNSELECT_ACTION_TYPE,
  27911. update: UNSELECT_ACTION_TYPE
  27912. }, noop);
  27913. registerAction({
  27914. type: TOGGLE_SELECT_ACTION_TYPE,
  27915. event: TOGGLE_SELECT_ACTION_TYPE,
  27916. update: TOGGLE_SELECT_ACTION_TYPE
  27917. }, noop);
  27918. // Default theme
  27919. registerTheme('light', lightTheme);
  27920. registerTheme('dark', theme);
  27921. // For backward compatibility, where the namespace `dataTool` will
  27922. // be mounted on `echarts` is the extension `dataTool` is imported.
  27923. var dataTool = {};
  27924. var extensions = [];
  27925. var extensionRegisters = {
  27926. registerPreprocessor: registerPreprocessor,
  27927. registerProcessor: registerProcessor,
  27928. registerPostInit: registerPostInit,
  27929. registerPostUpdate: registerPostUpdate,
  27930. registerUpdateLifecycle: registerUpdateLifecycle,
  27931. registerAction: registerAction,
  27932. registerCoordinateSystem: registerCoordinateSystem,
  27933. registerLayout: registerLayout,
  27934. registerVisual: registerVisual,
  27935. registerTransform: registerTransform,
  27936. registerLoading: registerLoading,
  27937. registerMap: registerMap,
  27938. registerImpl: registerImpl,
  27939. PRIORITY: PRIORITY,
  27940. ComponentModel: ComponentModel,
  27941. ComponentView: ComponentView,
  27942. SeriesModel: SeriesModel,
  27943. ChartView: ChartView,
  27944. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27945. registerComponentModel: function (ComponentModelClass) {
  27946. ComponentModel.registerClass(ComponentModelClass);
  27947. },
  27948. registerComponentView: function (ComponentViewClass) {
  27949. ComponentView.registerClass(ComponentViewClass);
  27950. },
  27951. registerSeriesModel: function (SeriesModelClass) {
  27952. SeriesModel.registerClass(SeriesModelClass);
  27953. },
  27954. registerChartView: function (ChartViewClass) {
  27955. ChartView.registerClass(ChartViewClass);
  27956. },
  27957. registerSubTypeDefaulter: function (componentType, defaulter) {
  27958. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27959. },
  27960. registerPainter: function (painterType, PainterCtor) {
  27961. registerPainter(painterType, PainterCtor);
  27962. }
  27963. };
  27964. function use(ext) {
  27965. if (isArray(ext)) {
  27966. // use([ChartLine, ChartBar]);
  27967. each(ext, function (singleExt) {
  27968. use(singleExt);
  27969. });
  27970. return;
  27971. }
  27972. if (indexOf(extensions, ext) >= 0) {
  27973. return;
  27974. }
  27975. extensions.push(ext);
  27976. if (isFunction(ext)) {
  27977. ext = {
  27978. install: ext
  27979. };
  27980. }
  27981. ext.install(extensionRegisters);
  27982. }
  27983. /*
  27984. * Licensed to the Apache Software Foundation (ASF) under one
  27985. * or more contributor license agreements. See the NOTICE file
  27986. * distributed with this work for additional information
  27987. * regarding copyright ownership. The ASF licenses this file
  27988. * to you under the Apache License, Version 2.0 (the
  27989. * "License"); you may not use this file except in compliance
  27990. * with the License. You may obtain a copy of the License at
  27991. *
  27992. * http://www.apache.org/licenses/LICENSE-2.0
  27993. *
  27994. * Unless required by applicable law or agreed to in writing,
  27995. * software distributed under the License is distributed on an
  27996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27997. * KIND, either express or implied. See the License for the
  27998. * specific language governing permissions and limitations
  27999. * under the License.
  28000. */
  28001. /**
  28002. * AUTO-GENERATED FILE. DO NOT MODIFY.
  28003. */
  28004. /*
  28005. * Licensed to the Apache Software Foundation (ASF) under one
  28006. * or more contributor license agreements. See the NOTICE file
  28007. * distributed with this work for additional information
  28008. * regarding copyright ownership. The ASF licenses this file
  28009. * to you under the Apache License, Version 2.0 (the
  28010. * "License"); you may not use this file except in compliance
  28011. * with the License. You may obtain a copy of the License at
  28012. *
  28013. * http://www.apache.org/licenses/LICENSE-2.0
  28014. *
  28015. * Unless required by applicable law or agreed to in writing,
  28016. * software distributed under the License is distributed on an
  28017. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28018. * KIND, either express or implied. See the License for the
  28019. * specific language governing permissions and limitations
  28020. * under the License.
  28021. */
  28022. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  28023. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  28024. }
  28025. function defaultKeyGetter(item) {
  28026. return item;
  28027. }
  28028. var DataDiffer = /** @class */function () {
  28029. /**
  28030. * @param context Can be visited by this.context in callback.
  28031. */
  28032. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context,
  28033. // By default: 'oneToOne'.
  28034. diffMode) {
  28035. this._old = oldArr;
  28036. this._new = newArr;
  28037. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  28038. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  28039. // Visible in callback via `this.context`;
  28040. this.context = context;
  28041. this._diffModeMultiple = diffMode === 'multiple';
  28042. }
  28043. /**
  28044. * Callback function when add a data
  28045. */
  28046. DataDiffer.prototype.add = function (func) {
  28047. this._add = func;
  28048. return this;
  28049. };
  28050. /**
  28051. * Callback function when update a data
  28052. */
  28053. DataDiffer.prototype.update = function (func) {
  28054. this._update = func;
  28055. return this;
  28056. };
  28057. /**
  28058. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28059. */
  28060. DataDiffer.prototype.updateManyToOne = function (func) {
  28061. this._updateManyToOne = func;
  28062. return this;
  28063. };
  28064. /**
  28065. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28066. */
  28067. DataDiffer.prototype.updateOneToMany = function (func) {
  28068. this._updateOneToMany = func;
  28069. return this;
  28070. };
  28071. /**
  28072. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28073. */
  28074. DataDiffer.prototype.updateManyToMany = function (func) {
  28075. this._updateManyToMany = func;
  28076. return this;
  28077. };
  28078. /**
  28079. * Callback function when remove a data
  28080. */
  28081. DataDiffer.prototype.remove = function (func) {
  28082. this._remove = func;
  28083. return this;
  28084. };
  28085. DataDiffer.prototype.execute = function () {
  28086. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  28087. };
  28088. DataDiffer.prototype._executeOneToOne = function () {
  28089. var oldArr = this._old;
  28090. var newArr = this._new;
  28091. var newDataIndexMap = {};
  28092. var oldDataKeyArr = new Array(oldArr.length);
  28093. var newDataKeyArr = new Array(newArr.length);
  28094. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  28095. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  28096. for (var i = 0; i < oldArr.length; i++) {
  28097. var oldKey = oldDataKeyArr[i];
  28098. var newIdxMapVal = newDataIndexMap[oldKey];
  28099. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28100. // idx can never be empty array here. see 'set null' logic below.
  28101. if (newIdxMapValLen > 1) {
  28102. // Consider there is duplicate key (for example, use dataItem.name as key).
  28103. // We should make sure every item in newArr and oldArr can be visited.
  28104. var newIdx = newIdxMapVal.shift();
  28105. if (newIdxMapVal.length === 1) {
  28106. newDataIndexMap[oldKey] = newIdxMapVal[0];
  28107. }
  28108. this._update && this._update(newIdx, i);
  28109. } else if (newIdxMapValLen === 1) {
  28110. newDataIndexMap[oldKey] = null;
  28111. this._update && this._update(newIdxMapVal, i);
  28112. } else {
  28113. this._remove && this._remove(i);
  28114. }
  28115. }
  28116. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  28117. };
  28118. /**
  28119. * For example, consider the case:
  28120. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  28121. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  28122. * Where:
  28123. * o0, o1, n0 has key 'a' (many to one)
  28124. * o5, n4, n5, n6 has key 'b' (one to many)
  28125. * o2, n1 has key 'c' (one to one)
  28126. * n2, n3 has key 'd' (add)
  28127. * o3, o4 has key 'e' (remove)
  28128. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  28129. * Then:
  28130. * (The order of the following directives are not ensured.)
  28131. * this._updateManyToOne(n0, [o0, o1]);
  28132. * this._updateOneToMany([n4, n5, n6], o5);
  28133. * this._update(n1, o2);
  28134. * this._remove(o3);
  28135. * this._remove(o4);
  28136. * this._remove(o6);
  28137. * this._remove(o7);
  28138. * this._add(n2);
  28139. * this._add(n3);
  28140. * this._add(n7);
  28141. * this._add(n8);
  28142. */
  28143. DataDiffer.prototype._executeMultiple = function () {
  28144. var oldArr = this._old;
  28145. var newArr = this._new;
  28146. var oldDataIndexMap = {};
  28147. var newDataIndexMap = {};
  28148. var oldDataKeyArr = [];
  28149. var newDataKeyArr = [];
  28150. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  28151. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  28152. for (var i = 0; i < oldDataKeyArr.length; i++) {
  28153. var oldKey = oldDataKeyArr[i];
  28154. var oldIdxMapVal = oldDataIndexMap[oldKey];
  28155. var newIdxMapVal = newDataIndexMap[oldKey];
  28156. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  28157. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28158. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  28159. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  28160. newDataIndexMap[oldKey] = null;
  28161. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  28162. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  28163. newDataIndexMap[oldKey] = null;
  28164. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  28165. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  28166. newDataIndexMap[oldKey] = null;
  28167. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  28168. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  28169. newDataIndexMap[oldKey] = null;
  28170. } else if (oldIdxMapValLen > 1) {
  28171. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  28172. this._remove && this._remove(oldIdxMapVal[i_1]);
  28173. }
  28174. } else {
  28175. this._remove && this._remove(oldIdxMapVal);
  28176. }
  28177. }
  28178. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  28179. };
  28180. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  28181. for (var i = 0; i < newDataKeyArr.length; i++) {
  28182. var newKey = newDataKeyArr[i];
  28183. var newIdxMapVal = newDataIndexMap[newKey];
  28184. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28185. if (idxMapValLen > 1) {
  28186. for (var j = 0; j < idxMapValLen; j++) {
  28187. this._add && this._add(newIdxMapVal[j]);
  28188. }
  28189. } else if (idxMapValLen === 1) {
  28190. this._add && this._add(newIdxMapVal);
  28191. }
  28192. // Support both `newDataKeyArr` are duplication removed or not removed.
  28193. newDataIndexMap[newKey] = null;
  28194. }
  28195. };
  28196. DataDiffer.prototype._initIndexMap = function (arr,
  28197. // Can be null.
  28198. map,
  28199. // In 'byKey', the output `keyArr` is duplication removed.
  28200. // In 'byIndex', the output `keyArr` is not duplication removed and
  28201. // its indices are accurately corresponding to `arr`.
  28202. keyArr, keyGetterName) {
  28203. var cbModeMultiple = this._diffModeMultiple;
  28204. for (var i = 0; i < arr.length; i++) {
  28205. // Add prefix to avoid conflict with Object.prototype.
  28206. var key = '_ec_' + this[keyGetterName](arr[i], i);
  28207. if (!cbModeMultiple) {
  28208. keyArr[i] = key;
  28209. }
  28210. if (!map) {
  28211. continue;
  28212. }
  28213. var idxMapVal = map[key];
  28214. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  28215. if (idxMapValLen === 0) {
  28216. // Simple optimize: in most cases, one index has one key,
  28217. // do not need array.
  28218. map[key] = i;
  28219. if (cbModeMultiple) {
  28220. keyArr.push(key);
  28221. }
  28222. } else if (idxMapValLen === 1) {
  28223. map[key] = [idxMapVal, i];
  28224. } else {
  28225. idxMapVal.push(i);
  28226. }
  28227. }
  28228. };
  28229. return DataDiffer;
  28230. }();
  28231. var DimensionUserOuput = /** @class */function () {
  28232. function DimensionUserOuput(encode, dimRequest) {
  28233. this._encode = encode;
  28234. this._schema = dimRequest;
  28235. }
  28236. DimensionUserOuput.prototype.get = function () {
  28237. return {
  28238. // Do not generate full dimension name until fist used.
  28239. fullDimensions: this._getFullDimensionNames(),
  28240. encode: this._encode
  28241. };
  28242. };
  28243. /**
  28244. * Get all data store dimension names.
  28245. * Theoretically a series data store is defined both by series and used dataset (if any).
  28246. * If some dimensions are omitted for performance reason in `this.dimensions`,
  28247. * the dimension name may not be auto-generated if user does not specify a dimension name.
  28248. * In this case, the dimension name is `null`/`undefined`.
  28249. */
  28250. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  28251. if (!this._cachedDimNames) {
  28252. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  28253. }
  28254. return this._cachedDimNames;
  28255. };
  28256. return DimensionUserOuput;
  28257. }();
  28258. function summarizeDimensions(data, schema) {
  28259. var summary = {};
  28260. var encode = summary.encode = {};
  28261. var notExtraCoordDimMap = createHashMap();
  28262. var defaultedLabel = [];
  28263. var defaultedTooltip = [];
  28264. var userOutputEncode = {};
  28265. each(data.dimensions, function (dimName) {
  28266. var dimItem = data.getDimensionInfo(dimName);
  28267. var coordDim = dimItem.coordDim;
  28268. if (coordDim) {
  28269. if ("development" !== 'production') {
  28270. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  28271. }
  28272. var coordDimIndex = dimItem.coordDimIndex;
  28273. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  28274. if (!dimItem.isExtraCoord) {
  28275. notExtraCoordDimMap.set(coordDim, 1);
  28276. // Use the last coord dim (and label friendly) as default label,
  28277. // because when dataset is used, it is hard to guess which dimension
  28278. // can be value dimension. If both show x, y on label is not look good,
  28279. // and conventionally y axis is focused more.
  28280. if (mayLabelDimType(dimItem.type)) {
  28281. defaultedLabel[0] = dimName;
  28282. }
  28283. // User output encode do not contain generated coords.
  28284. // And it only has index. User can use index to retrieve value from the raw item array.
  28285. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  28286. }
  28287. if (dimItem.defaultTooltip) {
  28288. defaultedTooltip.push(dimName);
  28289. }
  28290. }
  28291. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  28292. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  28293. var dimIndex = dimItem.otherDims[otherDim];
  28294. if (dimIndex != null && dimIndex !== false) {
  28295. encodeArr[dimIndex] = dimItem.name;
  28296. }
  28297. });
  28298. });
  28299. var dataDimsOnCoord = [];
  28300. var encodeFirstDimNotExtra = {};
  28301. notExtraCoordDimMap.each(function (v, coordDim) {
  28302. var dimArr = encode[coordDim];
  28303. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  28304. // Not necessary to remove duplicate, because a data
  28305. // dim canot on more than one coordDim.
  28306. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  28307. });
  28308. summary.dataDimsOnCoord = dataDimsOnCoord;
  28309. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  28310. return data.getDimensionInfo(dimName).storeDimIndex;
  28311. });
  28312. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  28313. var encodeLabel = encode.label;
  28314. // FIXME `encode.label` is not recommended, because formatter cannot be set
  28315. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  28316. if (encodeLabel && encodeLabel.length) {
  28317. defaultedLabel = encodeLabel.slice();
  28318. }
  28319. var encodeTooltip = encode.tooltip;
  28320. if (encodeTooltip && encodeTooltip.length) {
  28321. defaultedTooltip = encodeTooltip.slice();
  28322. } else if (!defaultedTooltip.length) {
  28323. defaultedTooltip = defaultedLabel.slice();
  28324. }
  28325. encode.defaultedLabel = defaultedLabel;
  28326. encode.defaultedTooltip = defaultedTooltip;
  28327. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  28328. return summary;
  28329. }
  28330. function getOrCreateEncodeArr(encode, dim) {
  28331. if (!encode.hasOwnProperty(dim)) {
  28332. encode[dim] = [];
  28333. }
  28334. return encode[dim];
  28335. }
  28336. // FIXME:TS should be type `AxisType`
  28337. function getDimensionTypeByAxis(axisType) {
  28338. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  28339. }
  28340. function mayLabelDimType(dimType) {
  28341. // In most cases, ordinal and time do not suitable for label.
  28342. // Ordinal info can be displayed on axis. Time is too long.
  28343. return !(dimType === 'ordinal' || dimType === 'time');
  28344. }
  28345. // function findTheLastDimMayLabel(data) {
  28346. // // Get last value dim
  28347. // let dimensions = data.dimensions.slice();
  28348. // let valueType;
  28349. // let valueDim;
  28350. // while (dimensions.length && (
  28351. // valueDim = dimensions.pop(),
  28352. // valueType = data.getDimensionInfo(valueDim).type,
  28353. // valueType === 'ordinal' || valueType === 'time'
  28354. // )) {} // jshint ignore:line
  28355. // return valueDim;
  28356. // }
  28357. var SeriesDimensionDefine = /** @class */function () {
  28358. /**
  28359. * @param opt All of the fields will be shallow copied.
  28360. */
  28361. function SeriesDimensionDefine(opt) {
  28362. /**
  28363. * The format of `otherDims` is:
  28364. * ```js
  28365. * {
  28366. * tooltip?: number
  28367. * label?: number
  28368. * itemName?: number
  28369. * seriesName?: number
  28370. * }
  28371. * ```
  28372. *
  28373. * A `series.encode` can specified these fields:
  28374. * ```js
  28375. * encode: {
  28376. * // "3, 1, 5" is the index of data dimension.
  28377. * tooltip: [3, 1, 5],
  28378. * label: [0, 3],
  28379. * ...
  28380. * }
  28381. * ```
  28382. * `otherDims` is the parse result of the `series.encode` above, like:
  28383. * ```js
  28384. * // Suppose the index of this data dimension is `3`.
  28385. * this.otherDims = {
  28386. * // `3` is at the index `0` of the `encode.tooltip`
  28387. * tooltip: 0,
  28388. * // `3` is at the index `1` of the `encode.label`
  28389. * label: 1
  28390. * };
  28391. * ```
  28392. *
  28393. * This prop should never be `null`/`undefined` after initialized.
  28394. */
  28395. this.otherDims = {};
  28396. if (opt != null) {
  28397. extend(this, opt);
  28398. }
  28399. }
  28400. return SeriesDimensionDefine;
  28401. }();
  28402. var inner$4 = makeInner();
  28403. var dimTypeShort = {
  28404. float: 'f',
  28405. int: 'i',
  28406. ordinal: 'o',
  28407. number: 'n',
  28408. time: 't'
  28409. };
  28410. /**
  28411. * Represents the dimension requirement of a series.
  28412. *
  28413. * NOTICE:
  28414. * When there are too many dimensions in dataset and many series, only the used dimensions
  28415. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  28416. * But users may query data by other unused dimension names.
  28417. * In this case, users can only query data if and only if they have defined dimension names
  28418. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  28419. * `source` dimensions.
  28420. */
  28421. var SeriesDataSchema = /** @class */function () {
  28422. function SeriesDataSchema(opt) {
  28423. this.dimensions = opt.dimensions;
  28424. this._dimOmitted = opt.dimensionOmitted;
  28425. this.source = opt.source;
  28426. this._fullDimCount = opt.fullDimensionCount;
  28427. this._updateDimOmitted(opt.dimensionOmitted);
  28428. }
  28429. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  28430. return this._dimOmitted;
  28431. };
  28432. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  28433. this._dimOmitted = dimensionOmitted;
  28434. if (!dimensionOmitted) {
  28435. return;
  28436. }
  28437. if (!this._dimNameMap) {
  28438. this._dimNameMap = ensureSourceDimNameMap(this.source);
  28439. }
  28440. };
  28441. /**
  28442. * @caution Can only be used when `dimensionOmitted: true`.
  28443. *
  28444. * Get index by user defined dimension name (i.e., not internal generate name).
  28445. * That is, get index from `dimensionsDefine`.
  28446. * If no `dimensionsDefine`, or no name get, return -1.
  28447. */
  28448. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  28449. return retrieve2(this._dimNameMap.get(dimName), -1);
  28450. };
  28451. /**
  28452. * @caution Can only be used when `dimensionOmitted: true`.
  28453. *
  28454. * Notice: may return `null`/`undefined` if user not specify dimension names.
  28455. */
  28456. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  28457. var dimensionsDefine = this.source.dimensionsDefine;
  28458. if (dimensionsDefine) {
  28459. return dimensionsDefine[dimIndex];
  28460. }
  28461. };
  28462. SeriesDataSchema.prototype.makeStoreSchema = function () {
  28463. var dimCount = this._fullDimCount;
  28464. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  28465. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount);
  28466. // If source don't have dimensions or series don't omit unsed dimensions.
  28467. // Generate from seriesDimList directly
  28468. var dimHash = '';
  28469. var dims = [];
  28470. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  28471. var property = void 0;
  28472. var type = void 0;
  28473. var ordinalMeta = void 0;
  28474. var seriesDimDef = this.dimensions[seriesDimIdx];
  28475. // The list has been sorted by `storeDimIndex` asc.
  28476. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28477. property = willRetrieveDataByName ? seriesDimDef.name : null;
  28478. type = seriesDimDef.type;
  28479. ordinalMeta = seriesDimDef.ordinalMeta;
  28480. seriesDimIdx++;
  28481. } else {
  28482. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28483. if (sourceDimDef) {
  28484. property = willRetrieveDataByName ? sourceDimDef.name : null;
  28485. type = sourceDimDef.type;
  28486. }
  28487. }
  28488. dims.push({
  28489. property: property,
  28490. type: type,
  28491. ordinalMeta: ordinalMeta
  28492. });
  28493. // If retrieving data by index,
  28494. // use <index, type, ordinalMeta> to determine whether data can be shared.
  28495. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  28496. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  28497. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  28498. // use <property, type, ordinalMeta> in hash.
  28499. if (willRetrieveDataByName && property != null
  28500. // For data stack, we have make sure each series has its own dim on this store.
  28501. // So we do not add property to hash to make sure they can share this store.
  28502. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  28503. dimHash += makeHashStrict
  28504. // Use escape character '`' in case that property name contains '$'.
  28505. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2')
  28506. // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  28507. : property;
  28508. }
  28509. dimHash += '$';
  28510. dimHash += dimTypeShort[type] || 'f';
  28511. if (ordinalMeta) {
  28512. dimHash += ordinalMeta.uid;
  28513. }
  28514. dimHash += '$';
  28515. }
  28516. // Source from endpoint(usually series) will be read differently
  28517. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  28518. // So we use this three props as key.
  28519. var source = this.source;
  28520. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  28521. return {
  28522. dimensions: dims,
  28523. hash: hash
  28524. };
  28525. };
  28526. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  28527. var result = [];
  28528. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  28529. var name_1 = void 0;
  28530. var seriesDimDef = this.dimensions[seriesDimIdx];
  28531. // The list has been sorted by `storeDimIndex` asc.
  28532. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28533. if (!seriesDimDef.isCalculationCoord) {
  28534. name_1 = seriesDimDef.name;
  28535. }
  28536. seriesDimIdx++;
  28537. } else {
  28538. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28539. if (sourceDimDef) {
  28540. name_1 = sourceDimDef.name;
  28541. }
  28542. }
  28543. result.push(name_1);
  28544. }
  28545. return result;
  28546. };
  28547. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  28548. this.dimensions.push(dimDef);
  28549. dimDef.isCalculationCoord = true;
  28550. this._fullDimCount++;
  28551. // If append dimension on a data store, consider the store
  28552. // might be shared by different series, series dimensions not
  28553. // really map to store dimensions.
  28554. this._updateDimOmitted(true);
  28555. };
  28556. return SeriesDataSchema;
  28557. }();
  28558. function isSeriesDataSchema(schema) {
  28559. return schema instanceof SeriesDataSchema;
  28560. }
  28561. function createDimNameMap(dimsDef) {
  28562. var dataDimNameMap = createHashMap();
  28563. for (var i = 0; i < (dimsDef || []).length; i++) {
  28564. var dimDefItemRaw = dimsDef[i];
  28565. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  28566. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28567. dataDimNameMap.set(userDimName, i);
  28568. }
  28569. }
  28570. return dataDimNameMap;
  28571. }
  28572. function ensureSourceDimNameMap(source) {
  28573. var innerSource = inner$4(source);
  28574. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  28575. }
  28576. function shouldOmitUnusedDimensions(dimCount) {
  28577. return dimCount > 30;
  28578. }
  28579. var isObject$2 = isObject;
  28580. var map$1 = map;
  28581. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array;
  28582. // Use prefix to avoid index to be the same as otherIdList[idx],
  28583. // which will cause weird update animation.
  28584. var ID_PREFIX = 'e\0\0';
  28585. var INDEX_NOT_FOUND = -1;
  28586. // type SeriesDimensionIndex = DimensionIndex;
  28587. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  28588. var CLONE_PROPERTIES = ['_approximateExtent'];
  28589. // -----------------------------
  28590. // Internal method declarations:
  28591. // -----------------------------
  28592. var prepareInvertedIndex;
  28593. var getId;
  28594. var getIdNameFromStore;
  28595. var normalizeDimensions;
  28596. var transferProperties;
  28597. var cloneListForMapAndSample;
  28598. var makeIdFromName;
  28599. var SeriesData = /** @class */function () {
  28600. /**
  28601. * @param dimensionsInput.dimensions
  28602. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  28603. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  28604. */
  28605. function SeriesData(dimensionsInput, hostModel) {
  28606. this.type = 'list';
  28607. this._dimOmitted = false;
  28608. this._nameList = [];
  28609. this._idList = [];
  28610. // Models of data option is stored sparse for optimizing memory cost
  28611. // Never used yet (not used yet).
  28612. // private _optionModels: Model[] = [];
  28613. // Global visual properties after visual coding
  28614. this._visual = {};
  28615. // Global layout properties.
  28616. this._layout = {};
  28617. // Item visual properties after visual coding
  28618. this._itemVisuals = [];
  28619. // Item layout properties after layout
  28620. this._itemLayouts = [];
  28621. // Graphic elements
  28622. this._graphicEls = [];
  28623. // key: dim, value: extent
  28624. this._approximateExtent = {};
  28625. this._calculationInfo = {};
  28626. // Having detected that there is data item is non primitive type
  28627. // (in type `OptionDataItemObject`).
  28628. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  28629. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  28630. this.hasItemOption = false;
  28631. // Methods that create a new list based on this list should be listed here.
  28632. // Notice that those method should `RETURN` the new list.
  28633. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map'];
  28634. // Methods that change indices of this list should be listed here.
  28635. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28636. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  28637. var dimensions;
  28638. var assignStoreDimIdx = false;
  28639. if (isSeriesDataSchema(dimensionsInput)) {
  28640. dimensions = dimensionsInput.dimensions;
  28641. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  28642. this._schema = dimensionsInput;
  28643. } else {
  28644. assignStoreDimIdx = true;
  28645. dimensions = dimensionsInput;
  28646. }
  28647. dimensions = dimensions || ['x', 'y'];
  28648. var dimensionInfos = {};
  28649. var dimensionNames = [];
  28650. var invertedIndicesMap = {};
  28651. var needsHasOwn = false;
  28652. var emptyObj = {};
  28653. for (var i = 0; i < dimensions.length; i++) {
  28654. // Use the original dimensions[i], where other flag props may exists.
  28655. var dimInfoInput = dimensions[i];
  28656. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  28657. name: dimInfoInput
  28658. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  28659. var dimensionName = dimensionInfo.name;
  28660. dimensionInfo.type = dimensionInfo.type || 'float';
  28661. if (!dimensionInfo.coordDim) {
  28662. dimensionInfo.coordDim = dimensionName;
  28663. dimensionInfo.coordDimIndex = 0;
  28664. }
  28665. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  28666. dimensionNames.push(dimensionName);
  28667. dimensionInfos[dimensionName] = dimensionInfo;
  28668. if (emptyObj[dimensionName] != null) {
  28669. needsHasOwn = true;
  28670. }
  28671. if (dimensionInfo.createInvertedIndices) {
  28672. invertedIndicesMap[dimensionName] = [];
  28673. }
  28674. if (otherDims.itemName === 0) {
  28675. this._nameDimIdx = i;
  28676. }
  28677. if (otherDims.itemId === 0) {
  28678. this._idDimIdx = i;
  28679. }
  28680. if ("development" !== 'production') {
  28681. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  28682. }
  28683. if (assignStoreDimIdx) {
  28684. dimensionInfo.storeDimIndex = i;
  28685. }
  28686. }
  28687. this.dimensions = dimensionNames;
  28688. this._dimInfos = dimensionInfos;
  28689. this._initGetDimensionInfo(needsHasOwn);
  28690. this.hostModel = hostModel;
  28691. this._invertedIndicesMap = invertedIndicesMap;
  28692. if (this._dimOmitted) {
  28693. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  28694. each(dimensionNames, function (dimName) {
  28695. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  28696. });
  28697. }
  28698. }
  28699. /**
  28700. *
  28701. * Get concrete dimension name by dimension name or dimension index.
  28702. * If input a dimension name, do not validate whether the dimension name exits.
  28703. *
  28704. * @caution
  28705. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  28706. * Because only those dimensions will have auto-generated dimension names if not
  28707. * have a user-specified name, and other dimensions will get a return of null/undefined.
  28708. *
  28709. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  28710. * ```js
  28711. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  28712. * ```
  28713. *
  28714. * @return Concrete dim name.
  28715. */
  28716. SeriesData.prototype.getDimension = function (dim) {
  28717. var dimIdx = this._recognizeDimIndex(dim);
  28718. if (dimIdx == null) {
  28719. return dim;
  28720. }
  28721. dimIdx = dim;
  28722. if (!this._dimOmitted) {
  28723. return this.dimensions[dimIdx];
  28724. }
  28725. // Retrieve from series dimension definition because it probably contains
  28726. // generated dimension name (like 'x', 'y').
  28727. var dimName = this._dimIdxToName.get(dimIdx);
  28728. if (dimName != null) {
  28729. return dimName;
  28730. }
  28731. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28732. if (sourceDimDef) {
  28733. return sourceDimDef.name;
  28734. }
  28735. };
  28736. /**
  28737. * Get dimension index in data store. Return -1 if not found.
  28738. * Can be used to index value from getRawValue.
  28739. */
  28740. SeriesData.prototype.getDimensionIndex = function (dim) {
  28741. var dimIdx = this._recognizeDimIndex(dim);
  28742. if (dimIdx != null) {
  28743. return dimIdx;
  28744. }
  28745. if (dim == null) {
  28746. return -1;
  28747. }
  28748. var dimInfo = this._getDimInfo(dim);
  28749. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28750. };
  28751. /**
  28752. * The meanings of the input parameter `dim`:
  28753. *
  28754. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28755. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28756. * + If dim is a number-like string (e.g., `"1"`):
  28757. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28758. * it means that concrete name.
  28759. * + If not, it will be converted to a number, which means the index of the dimension.
  28760. * (why? because of the backward compatibility. We have been tolerating number-like string in
  28761. * dimension setting, although now it seems that it is not a good idea.)
  28762. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28763. * if no dimension name is defined as `"1"`.
  28764. * + If dim is a not-number-like string, it means the concrete dim name.
  28765. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28766. * or customized in `dimensions` property of option like `"age"`.
  28767. *
  28768. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28769. */
  28770. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28771. if (isNumber(dim)
  28772. // If being a number-like string but not being defined as a dimension name.
  28773. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28774. return +dim;
  28775. }
  28776. };
  28777. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28778. var dimIdx = this.getDimensionIndex(dim);
  28779. if ("development" !== 'production') {
  28780. if (dimIdx == null) {
  28781. throw new Error('Unknown dimension ' + dim);
  28782. }
  28783. }
  28784. return dimIdx;
  28785. };
  28786. /**
  28787. * Get type and calculation info of particular dimension
  28788. * @param dim
  28789. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28790. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28791. */
  28792. SeriesData.prototype.getDimensionInfo = function (dim) {
  28793. // Do not clone, because there may be categories in dimInfo.
  28794. return this._getDimInfo(this.getDimension(dim));
  28795. };
  28796. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28797. var dimensionInfos = this._dimInfos;
  28798. this._getDimInfo = needsHasOwn ? function (dimName) {
  28799. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28800. } : function (dimName) {
  28801. return dimensionInfos[dimName];
  28802. };
  28803. };
  28804. /**
  28805. * concrete dimension name list on coord.
  28806. */
  28807. SeriesData.prototype.getDimensionsOnCoord = function () {
  28808. return this._dimSummary.dataDimsOnCoord.slice();
  28809. };
  28810. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28811. var dimensionsSummary = this._dimSummary;
  28812. if (idx == null) {
  28813. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28814. }
  28815. var dims = dimensionsSummary.encode[coordDim];
  28816. return dims ? dims[idx] : null;
  28817. };
  28818. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28819. var dimensionsSummary = this._dimSummary;
  28820. var dims = dimensionsSummary.encode[coordDim];
  28821. return (dims || []).slice();
  28822. };
  28823. SeriesData.prototype.getStore = function () {
  28824. return this._store;
  28825. };
  28826. /**
  28827. * Initialize from data
  28828. * @param data source or data or data store.
  28829. * @param nameList The name of a datum is used on data diff and
  28830. * default label/tooltip.
  28831. * A name can be specified in encode.itemName,
  28832. * or dataItem.name (only for series option data),
  28833. * or provided in nameList from outside.
  28834. */
  28835. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28836. var _this = this;
  28837. var store;
  28838. if (data instanceof DataStore) {
  28839. store = data;
  28840. }
  28841. if (!store) {
  28842. var dimensions = this.dimensions;
  28843. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28844. store = new DataStore();
  28845. var dimensionInfos = map$1(dimensions, function (dimName) {
  28846. return {
  28847. type: _this._dimInfos[dimName].type,
  28848. property: dimName
  28849. };
  28850. });
  28851. store.initData(provider, dimensionInfos, dimValueGetter);
  28852. }
  28853. this._store = store;
  28854. // Reset
  28855. this._nameList = (nameList || []).slice();
  28856. this._idList = [];
  28857. this._nameRepeatCount = {};
  28858. this._doInit(0, store.count());
  28859. // Cache summary info for fast visit. See "dimensionHelper".
  28860. // Needs to be initialized after store is prepared.
  28861. this._dimSummary = summarizeDimensions(this, this._schema);
  28862. this.userOutput = this._dimSummary.userOutput;
  28863. };
  28864. /**
  28865. * Caution: Can be only called on raw data (before `this._indices` created).
  28866. */
  28867. SeriesData.prototype.appendData = function (data) {
  28868. var range = this._store.appendData(data);
  28869. this._doInit(range[0], range[1]);
  28870. };
  28871. /**
  28872. * Caution: Can be only called on raw data (before `this._indices` created).
  28873. * This method does not modify `rawData` (`dataProvider`), but only
  28874. * add values to store.
  28875. *
  28876. * The final count will be increased by `Math.max(values.length, names.length)`.
  28877. *
  28878. * @param values That is the SourceType: 'arrayRows', like
  28879. * [
  28880. * [12, 33, 44],
  28881. * [NaN, 43, 1],
  28882. * ['-', 'asdf', 0]
  28883. * ]
  28884. * Each item is exactly corresponding to a dimension.
  28885. */
  28886. SeriesData.prototype.appendValues = function (values, names) {
  28887. var _a = this._store.appendValues(values, names.length),
  28888. start = _a.start,
  28889. end = _a.end;
  28890. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28891. this._updateOrdinalMeta();
  28892. if (names) {
  28893. for (var idx = start; idx < end; idx++) {
  28894. var sourceIdx = idx - start;
  28895. this._nameList[idx] = names[sourceIdx];
  28896. if (shouldMakeIdFromName) {
  28897. makeIdFromName(this, idx);
  28898. }
  28899. }
  28900. }
  28901. };
  28902. SeriesData.prototype._updateOrdinalMeta = function () {
  28903. var store = this._store;
  28904. var dimensions = this.dimensions;
  28905. for (var i = 0; i < dimensions.length; i++) {
  28906. var dimInfo = this._dimInfos[dimensions[i]];
  28907. if (dimInfo.ordinalMeta) {
  28908. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28909. }
  28910. }
  28911. };
  28912. SeriesData.prototype._shouldMakeIdFromName = function () {
  28913. var provider = this._store.getProvider();
  28914. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28915. };
  28916. SeriesData.prototype._doInit = function (start, end) {
  28917. if (start >= end) {
  28918. return;
  28919. }
  28920. var store = this._store;
  28921. var provider = store.getProvider();
  28922. this._updateOrdinalMeta();
  28923. var nameList = this._nameList;
  28924. var idList = this._idList;
  28925. var sourceFormat = provider.getSource().sourceFormat;
  28926. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  28927. // Each data item is value
  28928. // [1, 2]
  28929. // 2
  28930. // Bar chart, line chart which uses category axis
  28931. // only gives the 'y' value. 'x' value is the indices of category
  28932. // Use a tempValue to normalize the value to be a (x, y) value
  28933. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28934. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28935. if (isFormatOriginal && !provider.pure) {
  28936. var sharedDataItem = [];
  28937. for (var idx = start; idx < end; idx++) {
  28938. // NOTICE: Try not to write things into dataItem
  28939. var dataItem = provider.getItem(idx, sharedDataItem);
  28940. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28941. this.hasItemOption = true;
  28942. }
  28943. if (dataItem) {
  28944. var itemName = dataItem.name;
  28945. if (nameList[idx] == null && itemName != null) {
  28946. nameList[idx] = convertOptionIdName(itemName, null);
  28947. }
  28948. var itemId = dataItem.id;
  28949. if (idList[idx] == null && itemId != null) {
  28950. idList[idx] = convertOptionIdName(itemId, null);
  28951. }
  28952. }
  28953. }
  28954. }
  28955. if (this._shouldMakeIdFromName()) {
  28956. for (var idx = start; idx < end; idx++) {
  28957. makeIdFromName(this, idx);
  28958. }
  28959. }
  28960. prepareInvertedIndex(this);
  28961. };
  28962. /**
  28963. * PENDING: In fact currently this function is only used to short-circuit
  28964. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28965. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28966. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28967. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28968. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28969. * be still needed.
  28970. *
  28971. * Optimize for the scenario that data is filtered by a given extent.
  28972. * Consider that if data amount is more than hundreds of thousand,
  28973. * extent calculation will cost more than 10ms and the cache will
  28974. * be erased because of the filtering.
  28975. */
  28976. SeriesData.prototype.getApproximateExtent = function (dim) {
  28977. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28978. };
  28979. /**
  28980. * Calculate extent on a filtered data might be time consuming.
  28981. * Approximate extent is only used for: calculate extent of filtered data outside.
  28982. */
  28983. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28984. dim = this.getDimension(dim);
  28985. this._approximateExtent[dim] = extent.slice();
  28986. };
  28987. SeriesData.prototype.getCalculationInfo = function (key) {
  28988. return this._calculationInfo[key];
  28989. };
  28990. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28991. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28992. };
  28993. /**
  28994. * @return Never be null/undefined. `number` will be converted to string. Because:
  28995. * In most cases, name is used in display, where returning a string is more convenient.
  28996. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28997. * rule that name `2` equals to name `'2'`.
  28998. */
  28999. SeriesData.prototype.getName = function (idx) {
  29000. var rawIndex = this.getRawIndex(idx);
  29001. var name = this._nameList[rawIndex];
  29002. if (name == null && this._nameDimIdx != null) {
  29003. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  29004. }
  29005. if (name == null) {
  29006. name = '';
  29007. }
  29008. return name;
  29009. };
  29010. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  29011. var ordinal = this._store.get(dimIdx, idx);
  29012. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  29013. if (ordinalMeta) {
  29014. return ordinalMeta.categories[ordinal];
  29015. }
  29016. return ordinal;
  29017. };
  29018. /**
  29019. * @return Never null/undefined. `number` will be converted to string. Because:
  29020. * In all cases having encountered at present, id is used in making diff comparison, which
  29021. * are usually based on hash map. We can keep the rule that the internal id are always string
  29022. * (treat `2` is the same as `'2'`) to make the related logic simple.
  29023. */
  29024. SeriesData.prototype.getId = function (idx) {
  29025. return getId(this, this.getRawIndex(idx));
  29026. };
  29027. SeriesData.prototype.count = function () {
  29028. return this._store.count();
  29029. };
  29030. /**
  29031. * Get value. Return NaN if idx is out of range.
  29032. *
  29033. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  29034. */
  29035. SeriesData.prototype.get = function (dim, idx) {
  29036. var store = this._store;
  29037. var dimInfo = this._dimInfos[dim];
  29038. if (dimInfo) {
  29039. return store.get(dimInfo.storeDimIndex, idx);
  29040. }
  29041. };
  29042. /**
  29043. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  29044. */
  29045. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  29046. var store = this._store;
  29047. var dimInfo = this._dimInfos[dim];
  29048. if (dimInfo) {
  29049. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  29050. }
  29051. };
  29052. SeriesData.prototype.getIndices = function () {
  29053. return this._store.getIndices();
  29054. };
  29055. SeriesData.prototype.getDataExtent = function (dim) {
  29056. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  29057. };
  29058. SeriesData.prototype.getSum = function (dim) {
  29059. return this._store.getSum(this._getStoreDimIndex(dim));
  29060. };
  29061. SeriesData.prototype.getMedian = function (dim) {
  29062. return this._store.getMedian(this._getStoreDimIndex(dim));
  29063. };
  29064. SeriesData.prototype.getValues = function (dimensions, idx) {
  29065. var _this = this;
  29066. var store = this._store;
  29067. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  29068. return _this._getStoreDimIndex(dim);
  29069. }), idx) : store.getValues(dimensions);
  29070. };
  29071. /**
  29072. * If value is NaN. Including '-'
  29073. * Only check the coord dimensions.
  29074. */
  29075. SeriesData.prototype.hasValue = function (idx) {
  29076. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  29077. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  29078. // Ordinal type originally can be string or number.
  29079. // But when an ordinal type is used on coord, it can
  29080. // not be string but only number. So we can also use isNaN.
  29081. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  29082. return false;
  29083. }
  29084. }
  29085. return true;
  29086. };
  29087. /**
  29088. * Retrieve the index with given name
  29089. */
  29090. SeriesData.prototype.indexOfName = function (name) {
  29091. for (var i = 0, len = this._store.count(); i < len; i++) {
  29092. if (this.getName(i) === name) {
  29093. return i;
  29094. }
  29095. }
  29096. return -1;
  29097. };
  29098. SeriesData.prototype.getRawIndex = function (idx) {
  29099. return this._store.getRawIndex(idx);
  29100. };
  29101. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  29102. return this._store.indexOfRawIndex(rawIndex);
  29103. };
  29104. /**
  29105. * Only support the dimension which inverted index created.
  29106. * Do not support other cases until required.
  29107. * @param dim concrete dim
  29108. * @param value ordinal index
  29109. * @return rawIndex
  29110. */
  29111. SeriesData.prototype.rawIndexOf = function (dim, value) {
  29112. var invertedIndices = dim && this._invertedIndicesMap[dim];
  29113. if ("development" !== 'production') {
  29114. if (!invertedIndices) {
  29115. throw new Error('Do not supported yet');
  29116. }
  29117. }
  29118. var rawIndex = invertedIndices[value];
  29119. if (rawIndex == null || isNaN(rawIndex)) {
  29120. return INDEX_NOT_FOUND;
  29121. }
  29122. return rawIndex;
  29123. };
  29124. /**
  29125. * Retrieve the index of nearest value
  29126. * @param dim
  29127. * @param value
  29128. * @param [maxDistance=Infinity]
  29129. * @return If and only if multiple indices has
  29130. * the same value, they are put to the result.
  29131. */
  29132. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  29133. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  29134. };
  29135. SeriesData.prototype.each = function (dims, cb, ctx) {
  29136. if (isFunction(dims)) {
  29137. ctx = cb;
  29138. cb = dims;
  29139. dims = [];
  29140. }
  29141. // ctxCompat just for compat echarts3
  29142. var fCtx = ctx || this;
  29143. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29144. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29145. };
  29146. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  29147. if (isFunction(dims)) {
  29148. ctx = cb;
  29149. cb = dims;
  29150. dims = [];
  29151. }
  29152. // ctxCompat just for compat echarts3
  29153. var fCtx = ctx || this;
  29154. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29155. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29156. return this;
  29157. };
  29158. /**
  29159. * Select data in range. (For optimization of filter)
  29160. * (Manually inline code, support 5 million data filtering in data zoom.)
  29161. */
  29162. SeriesData.prototype.selectRange = function (range) {
  29163. var _this = this;
  29164. var innerRange = {};
  29165. var dims = keys(range);
  29166. each(dims, function (dim) {
  29167. var dimIdx = _this._getStoreDimIndex(dim);
  29168. innerRange[dimIdx] = range[dim];
  29169. });
  29170. this._store = this._store.selectRange(innerRange);
  29171. return this;
  29172. };
  29173. /* eslint-enable max-len */
  29174. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  29175. if (isFunction(dims)) {
  29176. ctx = cb;
  29177. cb = dims;
  29178. dims = [];
  29179. }
  29180. // ctxCompat just for compat echarts3
  29181. ctx = ctx || this;
  29182. var result = [];
  29183. this.each(dims, function () {
  29184. result.push(cb && cb.apply(this, arguments));
  29185. }, ctx);
  29186. return result;
  29187. };
  29188. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  29189. // ctxCompat just for compat echarts3
  29190. var fCtx = ctx || ctxCompat || this;
  29191. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29192. var list = cloneListForMapAndSample(this);
  29193. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29194. return list;
  29195. };
  29196. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  29197. var _this = this;
  29198. // ctxCompat just for compat echarts3
  29199. var fCtx = ctx || ctxCompat || this;
  29200. if ("development" !== 'production') {
  29201. each(normalizeDimensions(dims), function (dim) {
  29202. var dimInfo = _this.getDimensionInfo(dim);
  29203. if (!dimInfo.isCalculationCoord) {
  29204. console.error('Danger: only stack dimension can be modified');
  29205. }
  29206. });
  29207. }
  29208. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29209. // If do shallow clone here, if there are too many stacked series,
  29210. // it still cost lots of memory, because `_store.dimensions` are not shared.
  29211. // We should consider there probably be shallow clone happen in each series
  29212. // in consequent filter/map.
  29213. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29214. };
  29215. /**
  29216. * Large data down sampling on given dimension
  29217. * @param sampleIndex Sample index for name and id
  29218. */
  29219. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  29220. var list = cloneListForMapAndSample(this);
  29221. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  29222. return list;
  29223. };
  29224. /**
  29225. * Large data down sampling using largest-triangle-three-buckets
  29226. * @param {string} valueDimension
  29227. * @param {number} targetCount
  29228. */
  29229. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  29230. var list = cloneListForMapAndSample(this);
  29231. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  29232. return list;
  29233. };
  29234. SeriesData.prototype.getRawDataItem = function (idx) {
  29235. return this._store.getRawDataItem(idx);
  29236. };
  29237. /**
  29238. * Get model of one data item.
  29239. */
  29240. // TODO: Type of data item
  29241. SeriesData.prototype.getItemModel = function (idx) {
  29242. var hostModel = this.hostModel;
  29243. var dataItem = this.getRawDataItem(idx);
  29244. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  29245. };
  29246. /**
  29247. * Create a data differ
  29248. */
  29249. SeriesData.prototype.diff = function (otherList) {
  29250. var thisList = this;
  29251. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  29252. return getId(otherList, idx);
  29253. }, function (idx) {
  29254. return getId(thisList, idx);
  29255. });
  29256. };
  29257. /**
  29258. * Get visual property.
  29259. */
  29260. SeriesData.prototype.getVisual = function (key) {
  29261. var visual = this._visual;
  29262. return visual && visual[key];
  29263. };
  29264. SeriesData.prototype.setVisual = function (kvObj, val) {
  29265. this._visual = this._visual || {};
  29266. if (isObject$2(kvObj)) {
  29267. extend(this._visual, kvObj);
  29268. } else {
  29269. this._visual[kvObj] = val;
  29270. }
  29271. };
  29272. /**
  29273. * Get visual property of single data item
  29274. */
  29275. // eslint-disable-next-line
  29276. SeriesData.prototype.getItemVisual = function (idx, key) {
  29277. var itemVisual = this._itemVisuals[idx];
  29278. var val = itemVisual && itemVisual[key];
  29279. if (val == null) {
  29280. // Use global visual property
  29281. return this.getVisual(key);
  29282. }
  29283. return val;
  29284. };
  29285. /**
  29286. * If exists visual property of single data item
  29287. */
  29288. SeriesData.prototype.hasItemVisual = function () {
  29289. return this._itemVisuals.length > 0;
  29290. };
  29291. /**
  29292. * Make sure itemVisual property is unique
  29293. */
  29294. // TODO: use key to save visual to reduce memory.
  29295. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  29296. var itemVisuals = this._itemVisuals;
  29297. var itemVisual = itemVisuals[idx];
  29298. if (!itemVisual) {
  29299. itemVisual = itemVisuals[idx] = {};
  29300. }
  29301. var val = itemVisual[key];
  29302. if (val == null) {
  29303. val = this.getVisual(key);
  29304. // TODO Performance?
  29305. if (isArray(val)) {
  29306. val = val.slice();
  29307. } else if (isObject$2(val)) {
  29308. val = extend({}, val);
  29309. }
  29310. itemVisual[key] = val;
  29311. }
  29312. return val;
  29313. };
  29314. // eslint-disable-next-line
  29315. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  29316. var itemVisual = this._itemVisuals[idx] || {};
  29317. this._itemVisuals[idx] = itemVisual;
  29318. if (isObject$2(key)) {
  29319. extend(itemVisual, key);
  29320. } else {
  29321. itemVisual[key] = value;
  29322. }
  29323. };
  29324. /**
  29325. * Clear itemVisuals and list visual.
  29326. */
  29327. SeriesData.prototype.clearAllVisual = function () {
  29328. this._visual = {};
  29329. this._itemVisuals = [];
  29330. };
  29331. SeriesData.prototype.setLayout = function (key, val) {
  29332. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  29333. };
  29334. /**
  29335. * Get layout property.
  29336. */
  29337. SeriesData.prototype.getLayout = function (key) {
  29338. return this._layout[key];
  29339. };
  29340. /**
  29341. * Get layout of single data item
  29342. */
  29343. SeriesData.prototype.getItemLayout = function (idx) {
  29344. return this._itemLayouts[idx];
  29345. };
  29346. /**
  29347. * Set layout of single data item
  29348. */
  29349. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  29350. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  29351. };
  29352. /**
  29353. * Clear all layout of single data item
  29354. */
  29355. SeriesData.prototype.clearItemLayouts = function () {
  29356. this._itemLayouts.length = 0;
  29357. };
  29358. /**
  29359. * Set graphic element relative to data. It can be set as null
  29360. */
  29361. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  29362. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  29363. setCommonECData(seriesIndex, this.dataType, idx, el);
  29364. this._graphicEls[idx] = el;
  29365. };
  29366. SeriesData.prototype.getItemGraphicEl = function (idx) {
  29367. return this._graphicEls[idx];
  29368. };
  29369. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  29370. each(this._graphicEls, function (el, idx) {
  29371. if (el) {
  29372. cb && cb.call(context, el, idx);
  29373. }
  29374. });
  29375. };
  29376. /**
  29377. * Shallow clone a new list except visual and layout properties, and graph elements.
  29378. * New list only change the indices.
  29379. */
  29380. SeriesData.prototype.cloneShallow = function (list) {
  29381. if (!list) {
  29382. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  29383. }
  29384. transferProperties(list, this);
  29385. list._store = this._store;
  29386. return list;
  29387. };
  29388. /**
  29389. * Wrap some method to add more feature
  29390. */
  29391. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  29392. var originalMethod = this[methodName];
  29393. if (!isFunction(originalMethod)) {
  29394. return;
  29395. }
  29396. this.__wrappedMethods = this.__wrappedMethods || [];
  29397. this.__wrappedMethods.push(methodName);
  29398. this[methodName] = function () {
  29399. var res = originalMethod.apply(this, arguments);
  29400. return injectFunction.apply(this, [res].concat(slice(arguments)));
  29401. };
  29402. };
  29403. // ----------------------------------------------------------
  29404. // A work around for internal method visiting private member.
  29405. // ----------------------------------------------------------
  29406. SeriesData.internalField = function () {
  29407. prepareInvertedIndex = function (data) {
  29408. var invertedIndicesMap = data._invertedIndicesMap;
  29409. each(invertedIndicesMap, function (invertedIndices, dim) {
  29410. var dimInfo = data._dimInfos[dim];
  29411. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  29412. var ordinalMeta = dimInfo.ordinalMeta;
  29413. var store = data._store;
  29414. if (ordinalMeta) {
  29415. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length);
  29416. // The default value of TypedArray is 0. To avoid miss
  29417. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  29418. for (var i = 0; i < invertedIndices.length; i++) {
  29419. invertedIndices[i] = INDEX_NOT_FOUND;
  29420. }
  29421. for (var i = 0; i < store.count(); i++) {
  29422. // Only support the case that all values are distinct.
  29423. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  29424. }
  29425. }
  29426. });
  29427. };
  29428. getIdNameFromStore = function (data, dimIdx, idx) {
  29429. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  29430. };
  29431. /**
  29432. * @see the comment of `List['getId']`.
  29433. */
  29434. getId = function (data, rawIndex) {
  29435. var id = data._idList[rawIndex];
  29436. if (id == null && data._idDimIdx != null) {
  29437. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  29438. }
  29439. if (id == null) {
  29440. id = ID_PREFIX + rawIndex;
  29441. }
  29442. return id;
  29443. };
  29444. normalizeDimensions = function (dimensions) {
  29445. if (!isArray(dimensions)) {
  29446. dimensions = dimensions != null ? [dimensions] : [];
  29447. }
  29448. return dimensions;
  29449. };
  29450. /**
  29451. * Data in excludeDimensions is copied, otherwise transferred.
  29452. */
  29453. cloneListForMapAndSample = function (original) {
  29454. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel);
  29455. // FIXME If needs stackedOn, value may already been stacked
  29456. transferProperties(list, original);
  29457. return list;
  29458. };
  29459. transferProperties = function (target, source) {
  29460. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  29461. if (source.hasOwnProperty(propName)) {
  29462. target[propName] = source[propName];
  29463. }
  29464. });
  29465. target.__wrappedMethods = source.__wrappedMethods;
  29466. each(CLONE_PROPERTIES, function (propName) {
  29467. target[propName] = clone(source[propName]);
  29468. });
  29469. target._calculationInfo = extend({}, source._calculationInfo);
  29470. };
  29471. makeIdFromName = function (data, idx) {
  29472. var nameList = data._nameList;
  29473. var idList = data._idList;
  29474. var nameDimIdx = data._nameDimIdx;
  29475. var idDimIdx = data._idDimIdx;
  29476. var name = nameList[idx];
  29477. var id = idList[idx];
  29478. if (name == null && nameDimIdx != null) {
  29479. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  29480. }
  29481. if (id == null && idDimIdx != null) {
  29482. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  29483. }
  29484. if (id == null && name != null) {
  29485. var nameRepeatCount = data._nameRepeatCount;
  29486. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  29487. id = name;
  29488. if (nmCnt > 1) {
  29489. id += '__ec__' + nmCnt;
  29490. }
  29491. idList[idx] = id;
  29492. }
  29493. };
  29494. }();
  29495. return SeriesData;
  29496. }();
  29497. /**
  29498. * For outside usage compat (like echarts-gl are using it).
  29499. */
  29500. function createDimensions(source, opt) {
  29501. return prepareSeriesDataSchema(source, opt).dimensions;
  29502. }
  29503. /**
  29504. * This method builds the relationship between:
  29505. * + "what the coord sys or series requires (see `coordDimensions`)",
  29506. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  29507. * + "what the data source provids (see `source`)".
  29508. *
  29509. * Some guess strategy will be adapted if user does not define something.
  29510. * If no 'value' dimension specified, the first no-named dimension will be
  29511. * named as 'value'.
  29512. *
  29513. * @return The results are always sorted by `storeDimIndex` asc.
  29514. */
  29515. function prepareSeriesDataSchema(
  29516. // TODO: TYPE completeDimensions type
  29517. source, opt) {
  29518. if (!isSourceInstance(source)) {
  29519. source = createSourceFromSeriesDataOption(source);
  29520. }
  29521. opt = opt || {};
  29522. var sysDims = opt.coordDimensions || [];
  29523. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  29524. var coordDimNameMap = createHashMap();
  29525. var resultList = [];
  29526. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount);
  29527. // Try to ignore unused dimensions if sharing a high dimension datastore
  29528. // 30 is an experience value.
  29529. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  29530. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  29531. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  29532. var encodeDef = opt.encodeDefine;
  29533. if (!encodeDef && opt.encodeDefaulter) {
  29534. encodeDef = opt.encodeDefaulter(source, dimCount);
  29535. }
  29536. var encodeDefMap = createHashMap(encodeDef);
  29537. var indicesMap = new CtorInt32Array(dimCount);
  29538. for (var i = 0; i < indicesMap.length; i++) {
  29539. indicesMap[i] = -1;
  29540. }
  29541. function getResultItem(dimIdx) {
  29542. var idx = indicesMap[dimIdx];
  29543. if (idx < 0) {
  29544. var dimDefItemRaw = dimsDef[dimIdx];
  29545. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  29546. name: dimDefItemRaw
  29547. };
  29548. var resultItem = new SeriesDimensionDefine();
  29549. var userDimName = dimDefItem.name;
  29550. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  29551. // Only if `series.dimensions` is defined in option
  29552. // displayName, will be set, and dimension will be displayed vertically in
  29553. // tooltip by default.
  29554. resultItem.name = resultItem.displayName = userDimName;
  29555. }
  29556. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  29557. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  29558. var newIdx = resultList.length;
  29559. indicesMap[dimIdx] = newIdx;
  29560. resultItem.storeDimIndex = dimIdx;
  29561. resultList.push(resultItem);
  29562. return resultItem;
  29563. }
  29564. return resultList[idx];
  29565. }
  29566. if (!omitUnusedDimensions) {
  29567. for (var i = 0; i < dimCount; i++) {
  29568. getResultItem(i);
  29569. }
  29570. }
  29571. // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  29572. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  29573. var dataDims = normalizeToArray(dataDimsRaw).slice();
  29574. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  29575. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  29576. // this case.
  29577. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  29578. encodeDefMap.set(coordDim, false);
  29579. return;
  29580. }
  29581. var validDataDims = encodeDefMap.set(coordDim, []);
  29582. each(dataDims, function (resultDimIdxOrName, idx) {
  29583. // The input resultDimIdx can be dim name or index.
  29584. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  29585. if (resultDimIdx != null && resultDimIdx < dimCount) {
  29586. validDataDims[idx] = resultDimIdx;
  29587. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  29588. }
  29589. });
  29590. });
  29591. // Apply templates and default order from `sysDims`.
  29592. var availDimIdx = 0;
  29593. each(sysDims, function (sysDimItemRaw) {
  29594. var coordDim;
  29595. var sysDimItemDimsDef;
  29596. var sysDimItemOtherDims;
  29597. var sysDimItem;
  29598. if (isString(sysDimItemRaw)) {
  29599. coordDim = sysDimItemRaw;
  29600. sysDimItem = {};
  29601. } else {
  29602. sysDimItem = sysDimItemRaw;
  29603. coordDim = sysDimItem.name;
  29604. var ordinalMeta = sysDimItem.ordinalMeta;
  29605. sysDimItem.ordinalMeta = null;
  29606. sysDimItem = extend({}, sysDimItem);
  29607. sysDimItem.ordinalMeta = ordinalMeta;
  29608. // `coordDimIndex` should not be set directly.
  29609. sysDimItemDimsDef = sysDimItem.dimsDef;
  29610. sysDimItemOtherDims = sysDimItem.otherDims;
  29611. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  29612. }
  29613. var dataDims = encodeDefMap.get(coordDim);
  29614. // negative resultDimIdx means no need to mapping.
  29615. if (dataDims === false) {
  29616. return;
  29617. }
  29618. dataDims = normalizeToArray(dataDims);
  29619. // dimensions provides default dim sequences.
  29620. if (!dataDims.length) {
  29621. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  29622. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  29623. availDimIdx++;
  29624. }
  29625. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  29626. }
  29627. }
  29628. // Apply templates.
  29629. each(dataDims, function (resultDimIdx, coordDimIndex) {
  29630. var resultItem = getResultItem(resultDimIdx);
  29631. // Coordinate system has a higher priority on dim type than source.
  29632. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  29633. resultItem.type = sysDimItem.type;
  29634. }
  29635. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  29636. if (resultItem.name == null && sysDimItemDimsDef) {
  29637. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  29638. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  29639. name: sysDimItemDimsDefItem
  29640. });
  29641. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  29642. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  29643. }
  29644. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  29645. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  29646. });
  29647. });
  29648. function applyDim(resultItem, coordDim, coordDimIndex) {
  29649. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  29650. resultItem.otherDims[coordDim] = coordDimIndex;
  29651. } else {
  29652. resultItem.coordDim = coordDim;
  29653. resultItem.coordDimIndex = coordDimIndex;
  29654. coordDimNameMap.set(coordDim, true);
  29655. }
  29656. }
  29657. // Make sure the first extra dim is 'value'.
  29658. var generateCoord = opt.generateCoord;
  29659. var generateCoordCount = opt.generateCoordCount;
  29660. var fromZero = generateCoordCount != null;
  29661. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29662. var extra = generateCoord || 'value';
  29663. function ifNoNameFillWithCoordName(resultItem) {
  29664. if (resultItem.name == null) {
  29665. // Duplication will be removed in the next step.
  29666. resultItem.name = resultItem.coordDim;
  29667. }
  29668. }
  29669. // Set dim `name` and other `coordDim` and other props.
  29670. if (!omitUnusedDimensions) {
  29671. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29672. var resultItem = getResultItem(resultDimIdx);
  29673. var coordDim = resultItem.coordDim;
  29674. if (coordDim == null) {
  29675. // TODO no need to generate coordDim for isExtraCoord?
  29676. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  29677. resultItem.coordDimIndex = 0;
  29678. // Series specified generateCoord is using out.
  29679. if (!generateCoord || generateCoordCount <= 0) {
  29680. resultItem.isExtraCoord = true;
  29681. }
  29682. generateCoordCount--;
  29683. }
  29684. ifNoNameFillWithCoordName(resultItem);
  29685. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must
  29686. // Consider the case:
  29687. // {
  29688. // dataset: {source: [
  29689. // ['2001', 123],
  29690. // ['2002', 456],
  29691. // ...
  29692. // ['The others', 987],
  29693. // ]},
  29694. // series: {type: 'pie'}
  29695. // }
  29696. // The first column should better be treated as a "ordinal" although it
  29697. // might not be detected as an "ordinal" by `guessOrdinal`.
  29698. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29699. resultItem.type = 'ordinal';
  29700. }
  29701. }
  29702. } else {
  29703. each(resultList, function (resultItem) {
  29704. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  29705. ifNoNameFillWithCoordName(resultItem);
  29706. });
  29707. // Sort dimensions: there are some rule that use the last dim as label,
  29708. // and for some latter travel process easier.
  29709. resultList.sort(function (item0, item1) {
  29710. return item0.storeDimIndex - item1.storeDimIndex;
  29711. });
  29712. }
  29713. removeDuplication(resultList);
  29714. return new SeriesDataSchema({
  29715. source: source,
  29716. dimensions: resultList,
  29717. fullDimensionCount: dimCount,
  29718. dimensionOmitted: omitUnusedDimensions
  29719. });
  29720. }
  29721. function removeDuplication(result) {
  29722. var duplicationMap = createHashMap();
  29723. for (var i = 0; i < result.length; i++) {
  29724. var dim = result[i];
  29725. var dimOriginalName = dim.name;
  29726. var count = duplicationMap.get(dimOriginalName) || 0;
  29727. if (count > 0) {
  29728. // Starts from 0.
  29729. dim.name = dimOriginalName + (count - 1);
  29730. }
  29731. count++;
  29732. duplicationMap.set(dimOriginalName, count);
  29733. }
  29734. }
  29735. // ??? TODO
  29736. // Originally detect dimCount by data[0]. Should we
  29737. // optimize it to only by sysDims and dimensions and encode.
  29738. // So only necessary dims will be initialized.
  29739. // But
  29740. // (1) custom series should be considered. where other dims
  29741. // may be visited.
  29742. // (2) sometimes user need to calculate bubble size or use visualMap
  29743. // on other dimensions besides coordSys needed.
  29744. // So, dims that is not used by system, should be shared in data store?
  29745. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29746. // Note that the result dimCount should not small than columns count
  29747. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29748. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29749. each(sysDims, function (sysDimItem) {
  29750. var sysDimItemDimsDef;
  29751. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29752. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29753. }
  29754. });
  29755. return dimCount;
  29756. }
  29757. function genCoordDimName(name, map, fromZero) {
  29758. if (fromZero || map.hasKey(name)) {
  29759. var i = 0;
  29760. while (map.hasKey(name + i)) {
  29761. i++;
  29762. }
  29763. name += i;
  29764. }
  29765. map.set(name, true);
  29766. return name;
  29767. }
  29768. /**
  29769. * @class
  29770. * For example:
  29771. * {
  29772. * coordSysName: 'cartesian2d',
  29773. * coordSysDims: ['x', 'y', ...],
  29774. * axisMap: HashMap({
  29775. * x: xAxisModel,
  29776. * y: yAxisModel
  29777. * }),
  29778. * categoryAxisMap: HashMap({
  29779. * x: xAxisModel,
  29780. * y: undefined
  29781. * }),
  29782. * // The index of the first category axis in `coordSysDims`.
  29783. * // `null/undefined` means no category axis exists.
  29784. * firstCategoryDimIndex: 1,
  29785. * // To replace user specified encode.
  29786. * }
  29787. */
  29788. var CoordSysInfo = /** @class */function () {
  29789. function CoordSysInfo(coordSysName) {
  29790. this.coordSysDims = [];
  29791. this.axisMap = createHashMap();
  29792. this.categoryAxisMap = createHashMap();
  29793. this.coordSysName = coordSysName;
  29794. }
  29795. return CoordSysInfo;
  29796. }();
  29797. function getCoordSysInfoBySeries(seriesModel) {
  29798. var coordSysName = seriesModel.get('coordinateSystem');
  29799. var result = new CoordSysInfo(coordSysName);
  29800. var fetch = fetchers[coordSysName];
  29801. if (fetch) {
  29802. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29803. return result;
  29804. }
  29805. }
  29806. var fetchers = {
  29807. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29808. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29809. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29810. if ("development" !== 'production') {
  29811. if (!xAxisModel) {
  29812. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29813. }
  29814. if (!yAxisModel) {
  29815. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29816. }
  29817. }
  29818. result.coordSysDims = ['x', 'y'];
  29819. axisMap.set('x', xAxisModel);
  29820. axisMap.set('y', yAxisModel);
  29821. if (isCategory(xAxisModel)) {
  29822. categoryAxisMap.set('x', xAxisModel);
  29823. result.firstCategoryDimIndex = 0;
  29824. }
  29825. if (isCategory(yAxisModel)) {
  29826. categoryAxisMap.set('y', yAxisModel);
  29827. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29828. }
  29829. },
  29830. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29831. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29832. if ("development" !== 'production') {
  29833. if (!singleAxisModel) {
  29834. throw new Error('singleAxis should be specified.');
  29835. }
  29836. }
  29837. result.coordSysDims = ['single'];
  29838. axisMap.set('single', singleAxisModel);
  29839. if (isCategory(singleAxisModel)) {
  29840. categoryAxisMap.set('single', singleAxisModel);
  29841. result.firstCategoryDimIndex = 0;
  29842. }
  29843. },
  29844. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29845. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29846. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29847. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29848. if ("development" !== 'production') {
  29849. if (!angleAxisModel) {
  29850. throw new Error('angleAxis option not found');
  29851. }
  29852. if (!radiusAxisModel) {
  29853. throw new Error('radiusAxis option not found');
  29854. }
  29855. }
  29856. result.coordSysDims = ['radius', 'angle'];
  29857. axisMap.set('radius', radiusAxisModel);
  29858. axisMap.set('angle', angleAxisModel);
  29859. if (isCategory(radiusAxisModel)) {
  29860. categoryAxisMap.set('radius', radiusAxisModel);
  29861. result.firstCategoryDimIndex = 0;
  29862. }
  29863. if (isCategory(angleAxisModel)) {
  29864. categoryAxisMap.set('angle', angleAxisModel);
  29865. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29866. }
  29867. },
  29868. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29869. result.coordSysDims = ['lng', 'lat'];
  29870. },
  29871. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29872. var ecModel = seriesModel.ecModel;
  29873. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29874. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29875. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29876. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29877. var axisDim = coordSysDims[index];
  29878. axisMap.set(axisDim, axisModel);
  29879. if (isCategory(axisModel)) {
  29880. categoryAxisMap.set(axisDim, axisModel);
  29881. if (result.firstCategoryDimIndex == null) {
  29882. result.firstCategoryDimIndex = index;
  29883. }
  29884. }
  29885. });
  29886. }
  29887. };
  29888. function isCategory(axisModel) {
  29889. return axisModel.get('type') === 'category';
  29890. }
  29891. /**
  29892. * Note that it is too complicated to support 3d stack by value
  29893. * (have to create two-dimension inverted index), so in 3d case
  29894. * we just support that stacked by index.
  29895. *
  29896. * @param seriesModel
  29897. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  29898. * The input will be modified.
  29899. * @param opt
  29900. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29901. * @param opt.byIndex=false
  29902. * @return calculationInfo
  29903. * {
  29904. * stackedDimension: string
  29905. * stackedByDimension: string
  29906. * isStackedByIndex: boolean
  29907. * stackedOverDimension: string
  29908. * stackResultDimension: string
  29909. * }
  29910. */
  29911. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29912. opt = opt || {};
  29913. var byIndex = opt.byIndex;
  29914. var stackedCoordDimension = opt.stackedCoordDimension;
  29915. var dimensionDefineList;
  29916. var schema;
  29917. var store;
  29918. if (isLegacyDimensionsInput(dimensionsInput)) {
  29919. dimensionDefineList = dimensionsInput;
  29920. } else {
  29921. schema = dimensionsInput.schema;
  29922. dimensionDefineList = schema.dimensions;
  29923. store = dimensionsInput.store;
  29924. }
  29925. // Compatibal: when `stack` is set as '', do not stack.
  29926. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29927. var stackedByDimInfo;
  29928. var stackedDimInfo;
  29929. var stackResultDimension;
  29930. var stackedOverDimension;
  29931. each(dimensionDefineList, function (dimensionInfo, index) {
  29932. if (isString(dimensionInfo)) {
  29933. dimensionDefineList[index] = dimensionInfo = {
  29934. name: dimensionInfo
  29935. };
  29936. }
  29937. if (mayStack && !dimensionInfo.isExtraCoord) {
  29938. // Find the first ordinal dimension as the stackedByDimInfo.
  29939. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29940. stackedByDimInfo = dimensionInfo;
  29941. }
  29942. // Find the first stackable dimension as the stackedDimInfo.
  29943. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29944. stackedDimInfo = dimensionInfo;
  29945. }
  29946. }
  29947. });
  29948. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29949. // Compatible with previous design, value axis (time axis) only stack by index.
  29950. // It may make sense if the user provides elaborately constructed data.
  29951. byIndex = true;
  29952. }
  29953. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29954. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29955. // might not be a good way.
  29956. if (stackedDimInfo) {
  29957. // Use a weird name that not duplicated with other names.
  29958. // Also need to use seriesModel.id as postfix because different
  29959. // series may share same data store. The stack dimension needs to be distinguished.
  29960. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29961. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id;
  29962. // Create inverted index to fast query index by value.
  29963. if (stackedByDimInfo) {
  29964. stackedByDimInfo.createInvertedIndices = true;
  29965. }
  29966. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29967. var stackedDimType = stackedDimInfo.type;
  29968. var stackedDimCoordIndex_1 = 0;
  29969. each(dimensionDefineList, function (dimensionInfo) {
  29970. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29971. stackedDimCoordIndex_1++;
  29972. }
  29973. });
  29974. var stackedOverDimensionDefine = {
  29975. name: stackResultDimension,
  29976. coordDim: stackedDimCoordDim_1,
  29977. coordDimIndex: stackedDimCoordIndex_1,
  29978. type: stackedDimType,
  29979. isExtraCoord: true,
  29980. isCalculationCoord: true,
  29981. storeDimIndex: dimensionDefineList.length
  29982. };
  29983. var stackResultDimensionDefine = {
  29984. name: stackedOverDimension,
  29985. // This dimension contains stack base (generally, 0), so do not set it as
  29986. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29987. coordDim: stackedOverDimension,
  29988. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29989. type: stackedDimType,
  29990. isExtraCoord: true,
  29991. isCalculationCoord: true,
  29992. storeDimIndex: dimensionDefineList.length + 1
  29993. };
  29994. if (schema) {
  29995. if (store) {
  29996. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29997. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29998. }
  29999. schema.appendCalculationDimension(stackedOverDimensionDefine);
  30000. schema.appendCalculationDimension(stackResultDimensionDefine);
  30001. } else {
  30002. dimensionDefineList.push(stackedOverDimensionDefine);
  30003. dimensionDefineList.push(stackResultDimensionDefine);
  30004. }
  30005. }
  30006. return {
  30007. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  30008. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  30009. isStackedByIndex: byIndex,
  30010. stackedOverDimension: stackedOverDimension,
  30011. stackResultDimension: stackResultDimension
  30012. };
  30013. }
  30014. function isLegacyDimensionsInput(dimensionsInput) {
  30015. return !isSeriesDataSchema(dimensionsInput.schema);
  30016. }
  30017. function isDimensionStacked(data, stackedDim) {
  30018. // Each single series only maps to one pair of axis. So we do not need to
  30019. // check stackByDim, whatever stacked by a dimension or stacked by index.
  30020. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  30021. }
  30022. function getStackedDimension(data, targetDim) {
  30023. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  30024. }
  30025. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  30026. var coordSysName = seriesModel.get('coordinateSystem');
  30027. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  30028. var coordSysDimDefs;
  30029. if (coordSysInfo && coordSysInfo.coordSysDims) {
  30030. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  30031. var dimInfo = {
  30032. name: dim
  30033. };
  30034. var axisModel = coordSysInfo.axisMap.get(dim);
  30035. if (axisModel) {
  30036. var axisType = axisModel.get('type');
  30037. dimInfo.type = getDimensionTypeByAxis(axisType);
  30038. }
  30039. return dimInfo;
  30040. });
  30041. }
  30042. if (!coordSysDimDefs) {
  30043. // Get dimensions from registered coordinate system
  30044. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  30045. }
  30046. return coordSysDimDefs;
  30047. }
  30048. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  30049. var firstCategoryDimIndex;
  30050. var hasNameEncode;
  30051. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  30052. var coordDim = dimInfo.coordDim;
  30053. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  30054. if (categoryAxisModel) {
  30055. if (firstCategoryDimIndex == null) {
  30056. firstCategoryDimIndex = dimIndex;
  30057. }
  30058. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  30059. if (createInvertedIndices) {
  30060. dimInfo.createInvertedIndices = true;
  30061. }
  30062. }
  30063. if (dimInfo.otherDims.itemName != null) {
  30064. hasNameEncode = true;
  30065. }
  30066. });
  30067. if (!hasNameEncode && firstCategoryDimIndex != null) {
  30068. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  30069. }
  30070. return firstCategoryDimIndex;
  30071. }
  30072. /**
  30073. * Caution: there are side effects to `sourceManager` in this method.
  30074. * Should better only be called in `Series['getInitialData']`.
  30075. */
  30076. function createSeriesData(sourceRaw, seriesModel, opt) {
  30077. opt = opt || {};
  30078. var sourceManager = seriesModel.getSourceManager();
  30079. var source;
  30080. var isOriginalSource = false;
  30081. if (sourceRaw) {
  30082. isOriginalSource = true;
  30083. source = createSourceFromSeriesDataOption(sourceRaw);
  30084. } else {
  30085. source = sourceManager.getSource();
  30086. // Is series.data. not dataset.
  30087. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  30088. }
  30089. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  30090. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  30091. var useEncodeDefaulter = opt.useEncodeDefaulter;
  30092. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  30093. var createDimensionOptions = {
  30094. coordDimensions: coordSysDimDefs,
  30095. generateCoord: opt.generateCoord,
  30096. encodeDefine: seriesModel.getEncode(),
  30097. encodeDefaulter: encodeDefaulter,
  30098. canOmitUnusedDimensions: !isOriginalSource
  30099. };
  30100. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  30101. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  30102. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  30103. var stackCalculationInfo = enableDataStack(seriesModel, {
  30104. schema: schema,
  30105. store: store
  30106. });
  30107. var data = new SeriesData(schema, seriesModel);
  30108. data.setCalculationInfo(stackCalculationInfo);
  30109. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  30110. // Use dataIndex as ordinal value in categoryAxis
  30111. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  30112. } : null;
  30113. data.hasItemOption = false;
  30114. data.initData(
  30115. // Try to reuse the data store in sourceManager if using dataset.
  30116. isOriginalSource ? source : store, null, dimValueGetter);
  30117. return data;
  30118. }
  30119. function isNeedCompleteOrdinalData(source) {
  30120. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  30121. var sampleItem = firstDataNotNull(source.data || []);
  30122. return !isArray(getDataItemValue(sampleItem));
  30123. }
  30124. }
  30125. function firstDataNotNull(arr) {
  30126. var i = 0;
  30127. while (i < arr.length && arr[i] == null) {
  30128. i++;
  30129. }
  30130. return arr[i];
  30131. }
  30132. var Scale = /** @class */function () {
  30133. function Scale(setting) {
  30134. this._setting = setting || {};
  30135. this._extent = [Infinity, -Infinity];
  30136. }
  30137. Scale.prototype.getSetting = function (name) {
  30138. return this._setting[name];
  30139. };
  30140. /**
  30141. * Set extent from data
  30142. */
  30143. Scale.prototype.unionExtent = function (other) {
  30144. var extent = this._extent;
  30145. other[0] < extent[0] && (extent[0] = other[0]);
  30146. other[1] > extent[1] && (extent[1] = other[1]);
  30147. // not setExtent because in log axis it may transformed to power
  30148. // this.setExtent(extent[0], extent[1]);
  30149. };
  30150. /**
  30151. * Set extent from data
  30152. */
  30153. Scale.prototype.unionExtentFromData = function (data, dim) {
  30154. this.unionExtent(data.getApproximateExtent(dim));
  30155. };
  30156. /**
  30157. * Get extent
  30158. *
  30159. * Extent is always in increase order.
  30160. */
  30161. Scale.prototype.getExtent = function () {
  30162. return this._extent.slice();
  30163. };
  30164. /**
  30165. * Set extent
  30166. */
  30167. Scale.prototype.setExtent = function (start, end) {
  30168. var thisExtent = this._extent;
  30169. if (!isNaN(start)) {
  30170. thisExtent[0] = start;
  30171. }
  30172. if (!isNaN(end)) {
  30173. thisExtent[1] = end;
  30174. }
  30175. };
  30176. /**
  30177. * If value is in extent range
  30178. */
  30179. Scale.prototype.isInExtentRange = function (value) {
  30180. return this._extent[0] <= value && this._extent[1] >= value;
  30181. };
  30182. /**
  30183. * When axis extent depends on data and no data exists,
  30184. * axis ticks should not be drawn, which is named 'blank'.
  30185. */
  30186. Scale.prototype.isBlank = function () {
  30187. return this._isBlank;
  30188. };
  30189. /**
  30190. * When axis extent depends on data and no data exists,
  30191. * axis ticks should not be drawn, which is named 'blank'.
  30192. */
  30193. Scale.prototype.setBlank = function (isBlank) {
  30194. this._isBlank = isBlank;
  30195. };
  30196. return Scale;
  30197. }();
  30198. enableClassManagement(Scale);
  30199. var uidBase = 0;
  30200. var OrdinalMeta = /** @class */function () {
  30201. function OrdinalMeta(opt) {
  30202. this.categories = opt.categories || [];
  30203. this._needCollect = opt.needCollect;
  30204. this._deduplication = opt.deduplication;
  30205. this.uid = ++uidBase;
  30206. }
  30207. OrdinalMeta.createByAxisModel = function (axisModel) {
  30208. var option = axisModel.option;
  30209. var data = option.data;
  30210. var categories = data && map(data, getName);
  30211. return new OrdinalMeta({
  30212. categories: categories,
  30213. needCollect: !categories,
  30214. // deduplication is default in axis.
  30215. deduplication: option.dedplication !== false
  30216. });
  30217. };
  30218. OrdinalMeta.prototype.getOrdinal = function (category) {
  30219. // @ts-ignore
  30220. return this._getOrCreateMap().get(category);
  30221. };
  30222. /**
  30223. * @return The ordinal. If not found, return NaN.
  30224. */
  30225. OrdinalMeta.prototype.parseAndCollect = function (category) {
  30226. var index;
  30227. var needCollect = this._needCollect;
  30228. // The value of category dim can be the index of the given category set.
  30229. // This feature is only supported when !needCollect, because we should
  30230. // consider a common case: a value is 2017, which is a number but is
  30231. // expected to be tread as a category. This case usually happen in dataset,
  30232. // where it happent to be no need of the index feature.
  30233. if (!isString(category) && !needCollect) {
  30234. return category;
  30235. }
  30236. // Optimize for the scenario:
  30237. // category is ['2012-01-01', '2012-01-02', ...], where the input
  30238. // data has been ensured not duplicate and is large data.
  30239. // Notice, if a dataset dimension provide categroies, usually echarts
  30240. // should remove duplication except user tell echarts dont do that
  30241. // (set axis.deduplication = false), because echarts do not know whether
  30242. // the values in the category dimension has duplication (consider the
  30243. // parallel-aqi example)
  30244. if (needCollect && !this._deduplication) {
  30245. index = this.categories.length;
  30246. this.categories[index] = category;
  30247. return index;
  30248. }
  30249. var map = this._getOrCreateMap();
  30250. // @ts-ignore
  30251. index = map.get(category);
  30252. if (index == null) {
  30253. if (needCollect) {
  30254. index = this.categories.length;
  30255. this.categories[index] = category;
  30256. // @ts-ignore
  30257. map.set(category, index);
  30258. } else {
  30259. index = NaN;
  30260. }
  30261. }
  30262. return index;
  30263. };
  30264. // Consider big data, do not create map until needed.
  30265. OrdinalMeta.prototype._getOrCreateMap = function () {
  30266. return this._map || (this._map = createHashMap(this.categories));
  30267. };
  30268. return OrdinalMeta;
  30269. }();
  30270. function getName(obj) {
  30271. if (isObject(obj) && obj.value != null) {
  30272. return obj.value;
  30273. } else {
  30274. return obj + '';
  30275. }
  30276. }
  30277. function isValueNice(val) {
  30278. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  30279. var f = Math.abs(val / exp10);
  30280. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  30281. }
  30282. function isIntervalOrLogScale(scale) {
  30283. return scale.type === 'interval' || scale.type === 'log';
  30284. }
  30285. /**
  30286. * @param extent Both extent[0] and extent[1] should be valid number.
  30287. * Should be extent[0] < extent[1].
  30288. * @param splitNumber splitNumber should be >= 1.
  30289. */
  30290. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  30291. var result = {};
  30292. var span = extent[1] - extent[0];
  30293. var interval = result.interval = nice(span / splitNumber, true);
  30294. if (minInterval != null && interval < minInterval) {
  30295. interval = result.interval = minInterval;
  30296. }
  30297. if (maxInterval != null && interval > maxInterval) {
  30298. interval = result.interval = maxInterval;
  30299. }
  30300. // Tow more digital for tick.
  30301. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  30302. // Niced extent inside original extent
  30303. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  30304. fixExtent(niceTickExtent, extent);
  30305. return result;
  30306. }
  30307. function increaseInterval(interval) {
  30308. var exp10 = Math.pow(10, quantityExponent(interval));
  30309. // Increase interval
  30310. var f = interval / exp10;
  30311. if (!f) {
  30312. f = 1;
  30313. } else if (f === 2) {
  30314. f = 3;
  30315. } else if (f === 3) {
  30316. f = 5;
  30317. } else {
  30318. // f is 1 or 5
  30319. f *= 2;
  30320. }
  30321. return round(f * exp10);
  30322. }
  30323. /**
  30324. * @return interval precision
  30325. */
  30326. function getIntervalPrecision(interval) {
  30327. // Tow more digital for tick.
  30328. return getPrecision(interval) + 2;
  30329. }
  30330. function clamp(niceTickExtent, idx, extent) {
  30331. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30332. }
  30333. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30334. function fixExtent(niceTickExtent, extent) {
  30335. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30336. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30337. clamp(niceTickExtent, 0, extent);
  30338. clamp(niceTickExtent, 1, extent);
  30339. if (niceTickExtent[0] > niceTickExtent[1]) {
  30340. niceTickExtent[0] = niceTickExtent[1];
  30341. }
  30342. }
  30343. function contain$1(val, extent) {
  30344. return val >= extent[0] && val <= extent[1];
  30345. }
  30346. function normalize$1(val, extent) {
  30347. if (extent[1] === extent[0]) {
  30348. return 0.5;
  30349. }
  30350. return (val - extent[0]) / (extent[1] - extent[0]);
  30351. }
  30352. function scale$2(val, extent) {
  30353. return val * (extent[1] - extent[0]) + extent[0];
  30354. }
  30355. var OrdinalScale = /** @class */function (_super) {
  30356. __extends(OrdinalScale, _super);
  30357. function OrdinalScale(setting) {
  30358. var _this = _super.call(this, setting) || this;
  30359. _this.type = 'ordinal';
  30360. var ordinalMeta = _this.getSetting('ordinalMeta');
  30361. // Caution: Should not use instanceof, consider ec-extensions using
  30362. // import approach to get OrdinalMeta class.
  30363. if (!ordinalMeta) {
  30364. ordinalMeta = new OrdinalMeta({});
  30365. }
  30366. if (isArray(ordinalMeta)) {
  30367. ordinalMeta = new OrdinalMeta({
  30368. categories: map(ordinalMeta, function (item) {
  30369. return isObject(item) ? item.value : item;
  30370. })
  30371. });
  30372. }
  30373. _this._ordinalMeta = ordinalMeta;
  30374. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  30375. return _this;
  30376. }
  30377. OrdinalScale.prototype.parse = function (val) {
  30378. // Caution: Math.round(null) will return `0` rather than `NaN`
  30379. if (val == null) {
  30380. return NaN;
  30381. }
  30382. return isString(val) ? this._ordinalMeta.getOrdinal(val)
  30383. // val might be float.
  30384. : Math.round(val);
  30385. };
  30386. OrdinalScale.prototype.contain = function (rank) {
  30387. rank = this.parse(rank);
  30388. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  30389. };
  30390. /**
  30391. * Normalize given rank or name to linear [0, 1]
  30392. * @param val raw ordinal number.
  30393. * @return normalized value in [0, 1].
  30394. */
  30395. OrdinalScale.prototype.normalize = function (val) {
  30396. val = this._getTickNumber(this.parse(val));
  30397. return normalize$1(val, this._extent);
  30398. };
  30399. /**
  30400. * @param val normalized value in [0, 1].
  30401. * @return raw ordinal number.
  30402. */
  30403. OrdinalScale.prototype.scale = function (val) {
  30404. val = Math.round(scale$2(val, this._extent));
  30405. return this.getRawOrdinalNumber(val);
  30406. };
  30407. OrdinalScale.prototype.getTicks = function () {
  30408. var ticks = [];
  30409. var extent = this._extent;
  30410. var rank = extent[0];
  30411. while (rank <= extent[1]) {
  30412. ticks.push({
  30413. value: rank
  30414. });
  30415. rank++;
  30416. }
  30417. return ticks;
  30418. };
  30419. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  30420. // Not support.
  30421. return;
  30422. };
  30423. /**
  30424. * @see `Ordinal['_ordinalNumbersByTick']`
  30425. */
  30426. OrdinalScale.prototype.setSortInfo = function (info) {
  30427. if (info == null) {
  30428. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  30429. return;
  30430. }
  30431. var infoOrdinalNumbers = info.ordinalNumbers;
  30432. var ordinalsByTick = this._ordinalNumbersByTick = [];
  30433. var ticksByOrdinal = this._ticksByOrdinalNumber = [];
  30434. // Unnecessary support negative tick in `realtimeSort`.
  30435. var tickNum = 0;
  30436. var allCategoryLen = this._ordinalMeta.categories.length;
  30437. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  30438. var ordinalNumber = infoOrdinalNumbers[tickNum];
  30439. ordinalsByTick[tickNum] = ordinalNumber;
  30440. ticksByOrdinal[ordinalNumber] = tickNum;
  30441. }
  30442. // Handle that `series.data` only covers part of the `axis.category.data`.
  30443. var unusedOrdinal = 0;
  30444. for (; tickNum < allCategoryLen; ++tickNum) {
  30445. while (ticksByOrdinal[unusedOrdinal] != null) {
  30446. unusedOrdinal++;
  30447. }
  30448. ordinalsByTick.push(unusedOrdinal);
  30449. ticksByOrdinal[unusedOrdinal] = tickNum;
  30450. }
  30451. };
  30452. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  30453. var ticksByOrdinalNumber = this._ticksByOrdinalNumber;
  30454. // also support ordinal out of range of `ordinalMeta.categories.length`,
  30455. // where ordinal numbers are used as tick value directly.
  30456. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  30457. };
  30458. /**
  30459. * @usage
  30460. * ```js
  30461. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  30462. *
  30463. * // case0
  30464. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  30465. * // case1
  30466. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  30467. * // case2
  30468. * const coord = axis.dataToCoord(ordinalNumber);
  30469. * ```
  30470. *
  30471. * @param {OrdinalNumber} tickNumber index of display
  30472. */
  30473. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  30474. var ordinalNumbersByTick = this._ordinalNumbersByTick;
  30475. // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  30476. // where ordinal numbers are used as tick value directly.
  30477. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  30478. };
  30479. /**
  30480. * Get item on tick
  30481. */
  30482. OrdinalScale.prototype.getLabel = function (tick) {
  30483. if (!this.isBlank()) {
  30484. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  30485. var cateogry = this._ordinalMeta.categories[ordinalNumber];
  30486. // Note that if no data, ordinalMeta.categories is an empty array.
  30487. // Return empty if it's not exist.
  30488. return cateogry == null ? '' : cateogry + '';
  30489. }
  30490. };
  30491. OrdinalScale.prototype.count = function () {
  30492. return this._extent[1] - this._extent[0] + 1;
  30493. };
  30494. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  30495. this.unionExtent(data.getApproximateExtent(dim));
  30496. };
  30497. /**
  30498. * @override
  30499. * If value is in extent range
  30500. */
  30501. OrdinalScale.prototype.isInExtentRange = function (value) {
  30502. value = this._getTickNumber(value);
  30503. return this._extent[0] <= value && this._extent[1] >= value;
  30504. };
  30505. OrdinalScale.prototype.getOrdinalMeta = function () {
  30506. return this._ordinalMeta;
  30507. };
  30508. OrdinalScale.prototype.calcNiceTicks = function () {};
  30509. OrdinalScale.prototype.calcNiceExtent = function () {};
  30510. OrdinalScale.type = 'ordinal';
  30511. return OrdinalScale;
  30512. }(Scale);
  30513. Scale.registerClass(OrdinalScale);
  30514. var roundNumber = round;
  30515. var IntervalScale = /** @class */function (_super) {
  30516. __extends(IntervalScale, _super);
  30517. function IntervalScale() {
  30518. var _this = _super !== null && _super.apply(this, arguments) || this;
  30519. _this.type = 'interval';
  30520. // Step is calculated in adjustExtent.
  30521. _this._interval = 0;
  30522. _this._intervalPrecision = 2;
  30523. return _this;
  30524. }
  30525. IntervalScale.prototype.parse = function (val) {
  30526. return val;
  30527. };
  30528. IntervalScale.prototype.contain = function (val) {
  30529. return contain$1(val, this._extent);
  30530. };
  30531. IntervalScale.prototype.normalize = function (val) {
  30532. return normalize$1(val, this._extent);
  30533. };
  30534. IntervalScale.prototype.scale = function (val) {
  30535. return scale$2(val, this._extent);
  30536. };
  30537. IntervalScale.prototype.setExtent = function (start, end) {
  30538. var thisExtent = this._extent;
  30539. // start,end may be a Number like '25',so...
  30540. if (!isNaN(start)) {
  30541. thisExtent[0] = parseFloat(start);
  30542. }
  30543. if (!isNaN(end)) {
  30544. thisExtent[1] = parseFloat(end);
  30545. }
  30546. };
  30547. IntervalScale.prototype.unionExtent = function (other) {
  30548. var extent = this._extent;
  30549. other[0] < extent[0] && (extent[0] = other[0]);
  30550. other[1] > extent[1] && (extent[1] = other[1]);
  30551. // unionExtent may called by it's sub classes
  30552. this.setExtent(extent[0], extent[1]);
  30553. };
  30554. IntervalScale.prototype.getInterval = function () {
  30555. return this._interval;
  30556. };
  30557. IntervalScale.prototype.setInterval = function (interval) {
  30558. this._interval = interval;
  30559. // Dropped auto calculated niceExtent and use user-set extent.
  30560. // We assume user wants to set both interval, min, max to get a better result.
  30561. this._niceExtent = this._extent.slice();
  30562. this._intervalPrecision = getIntervalPrecision(interval);
  30563. };
  30564. /**
  30565. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30566. */
  30567. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  30568. var interval = this._interval;
  30569. var extent = this._extent;
  30570. var niceTickExtent = this._niceExtent;
  30571. var intervalPrecision = this._intervalPrecision;
  30572. var ticks = [];
  30573. // If interval is 0, return [];
  30574. if (!interval) {
  30575. return ticks;
  30576. }
  30577. // Consider this case: using dataZoom toolbox, zoom and zoom.
  30578. var safeLimit = 10000;
  30579. if (extent[0] < niceTickExtent[0]) {
  30580. if (expandToNicedExtent) {
  30581. ticks.push({
  30582. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  30583. });
  30584. } else {
  30585. ticks.push({
  30586. value: extent[0]
  30587. });
  30588. }
  30589. }
  30590. var tick = niceTickExtent[0];
  30591. while (tick <= niceTickExtent[1]) {
  30592. ticks.push({
  30593. value: tick
  30594. });
  30595. // Avoid rounding error
  30596. tick = roundNumber(tick + interval, intervalPrecision);
  30597. if (tick === ticks[ticks.length - 1].value) {
  30598. // Consider out of safe float point, e.g.,
  30599. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30600. break;
  30601. }
  30602. if (ticks.length > safeLimit) {
  30603. return [];
  30604. }
  30605. }
  30606. // Consider this case: the last item of ticks is smaller
  30607. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30608. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  30609. if (extent[1] > lastNiceTick) {
  30610. if (expandToNicedExtent) {
  30611. ticks.push({
  30612. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  30613. });
  30614. } else {
  30615. ticks.push({
  30616. value: extent[1]
  30617. });
  30618. }
  30619. }
  30620. return ticks;
  30621. };
  30622. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  30623. var ticks = this.getTicks(true);
  30624. var minorTicks = [];
  30625. var extent = this.getExtent();
  30626. for (var i = 1; i < ticks.length; i++) {
  30627. var nextTick = ticks[i];
  30628. var prevTick = ticks[i - 1];
  30629. var count = 0;
  30630. var minorTicksGroup = [];
  30631. var interval = nextTick.value - prevTick.value;
  30632. var minorInterval = interval / splitNumber;
  30633. while (count < splitNumber - 1) {
  30634. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval);
  30635. // For the first and last interval. The count may be less than splitNumber.
  30636. if (minorTick > extent[0] && minorTick < extent[1]) {
  30637. minorTicksGroup.push(minorTick);
  30638. }
  30639. count++;
  30640. }
  30641. minorTicks.push(minorTicksGroup);
  30642. }
  30643. return minorTicks;
  30644. };
  30645. /**
  30646. * @param opt.precision If 'auto', use nice presision.
  30647. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  30648. */
  30649. IntervalScale.prototype.getLabel = function (data, opt) {
  30650. if (data == null) {
  30651. return '';
  30652. }
  30653. var precision = opt && opt.precision;
  30654. if (precision == null) {
  30655. precision = getPrecision(data.value) || 0;
  30656. } else if (precision === 'auto') {
  30657. // Should be more precise then tick.
  30658. precision = this._intervalPrecision;
  30659. }
  30660. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30661. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30662. var dataNum = roundNumber(data.value, precision, true);
  30663. return addCommas(dataNum);
  30664. };
  30665. /**
  30666. * @param splitNumber By default `5`.
  30667. */
  30668. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  30669. splitNumber = splitNumber || 5;
  30670. var extent = this._extent;
  30671. var span = extent[1] - extent[0];
  30672. if (!isFinite(span)) {
  30673. return;
  30674. }
  30675. // User may set axis min 0 and data are all negative
  30676. // FIXME If it needs to reverse ?
  30677. if (span < 0) {
  30678. span = -span;
  30679. extent.reverse();
  30680. }
  30681. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  30682. this._intervalPrecision = result.intervalPrecision;
  30683. this._interval = result.interval;
  30684. this._niceExtent = result.niceTickExtent;
  30685. };
  30686. IntervalScale.prototype.calcNiceExtent = function (opt) {
  30687. var extent = this._extent;
  30688. // If extent start and end are same, expand them
  30689. if (extent[0] === extent[1]) {
  30690. if (extent[0] !== 0) {
  30691. // Expand extent
  30692. // Note that extents can be both negative. See #13154
  30693. var expandSize = Math.abs(extent[0]);
  30694. // In the fowllowing case
  30695. // Axis has been fixed max 100
  30696. // Plus data are all 100 and axis extent are [100, 100].
  30697. // Extend to the both side will cause expanded max is larger than fixed max.
  30698. // So only expand to the smaller side.
  30699. if (!opt.fixMax) {
  30700. extent[1] += expandSize / 2;
  30701. extent[0] -= expandSize / 2;
  30702. } else {
  30703. extent[0] -= expandSize / 2;
  30704. }
  30705. } else {
  30706. extent[1] = 1;
  30707. }
  30708. }
  30709. var span = extent[1] - extent[0];
  30710. // If there are no data and extent are [Infinity, -Infinity]
  30711. if (!isFinite(span)) {
  30712. extent[0] = 0;
  30713. extent[1] = 1;
  30714. }
  30715. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30716. // let extent = this._extent;
  30717. var interval = this._interval;
  30718. if (!opt.fixMin) {
  30719. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30720. }
  30721. if (!opt.fixMax) {
  30722. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30723. }
  30724. };
  30725. IntervalScale.prototype.setNiceExtent = function (min, max) {
  30726. this._niceExtent = [min, max];
  30727. };
  30728. IntervalScale.type = 'interval';
  30729. return IntervalScale;
  30730. }(Scale);
  30731. Scale.registerClass(IntervalScale);
  30732. /* global Float32Array */
  30733. var supportFloat32Array = typeof Float32Array !== 'undefined';
  30734. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  30735. function createFloat32Array(arg) {
  30736. if (isArray(arg)) {
  30737. // Return self directly if don't support TypedArray.
  30738. return supportFloat32Array ? new Float32Array(arg) : arg;
  30739. }
  30740. // Else is number
  30741. return new Float32ArrayCtor(arg);
  30742. }
  30743. var STACK_PREFIX = '__ec_stack_';
  30744. function getSeriesStackId(seriesModel) {
  30745. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30746. }
  30747. function getAxisKey(axis) {
  30748. return axis.dim + axis.index;
  30749. }
  30750. function prepareLayoutBarSeries(seriesType, ecModel) {
  30751. var seriesModels = [];
  30752. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30753. // Check series coordinate, do layout for cartesian2d only
  30754. if (isOnCartesian(seriesModel)) {
  30755. seriesModels.push(seriesModel);
  30756. }
  30757. });
  30758. return seriesModels;
  30759. }
  30760. /**
  30761. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30762. * values.
  30763. * This works for time axes, value axes, and log axes.
  30764. * For a single time axis, return value is in the form like
  30765. * {'x_0': [1000000]}.
  30766. * The value of 1000000 is in milliseconds.
  30767. */
  30768. function getValueAxesMinGaps(barSeries) {
  30769. /**
  30770. * Map from axis.index to values.
  30771. * For a single time axis, axisValues is in the form like
  30772. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30773. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30774. * series.
  30775. */
  30776. var axisValues = {};
  30777. each(barSeries, function (seriesModel) {
  30778. var cartesian = seriesModel.coordinateSystem;
  30779. var baseAxis = cartesian.getBaseAxis();
  30780. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30781. return;
  30782. }
  30783. var data = seriesModel.getData();
  30784. var key = baseAxis.dim + '_' + baseAxis.index;
  30785. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30786. var store = data.getStore();
  30787. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30788. var value = store.get(dimIdx, i);
  30789. if (!axisValues[key]) {
  30790. // No previous data for the axis
  30791. axisValues[key] = [value];
  30792. } else {
  30793. // No value in previous series
  30794. axisValues[key].push(value);
  30795. }
  30796. // Ignore duplicated time values in the same axis
  30797. }
  30798. });
  30799. var axisMinGaps = {};
  30800. for (var key in axisValues) {
  30801. if (axisValues.hasOwnProperty(key)) {
  30802. var valuesInAxis = axisValues[key];
  30803. if (valuesInAxis) {
  30804. // Sort axis values into ascending order to calculate gaps
  30805. valuesInAxis.sort(function (a, b) {
  30806. return a - b;
  30807. });
  30808. var min = null;
  30809. for (var j = 1; j < valuesInAxis.length; ++j) {
  30810. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30811. if (delta > 0) {
  30812. // Ignore 0 delta because they are of the same axis value
  30813. min = min === null ? delta : Math.min(min, delta);
  30814. }
  30815. }
  30816. // Set to null if only have one data
  30817. axisMinGaps[key] = min;
  30818. }
  30819. }
  30820. }
  30821. return axisMinGaps;
  30822. }
  30823. function makeColumnLayout(barSeries) {
  30824. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30825. var seriesInfoList = [];
  30826. each(barSeries, function (seriesModel) {
  30827. var cartesian = seriesModel.coordinateSystem;
  30828. var baseAxis = cartesian.getBaseAxis();
  30829. var axisExtent = baseAxis.getExtent();
  30830. var bandWidth;
  30831. if (baseAxis.type === 'category') {
  30832. bandWidth = baseAxis.getBandWidth();
  30833. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30834. var key = baseAxis.dim + '_' + baseAxis.index;
  30835. var minGap = axisMinGaps[key];
  30836. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30837. var scale = baseAxis.scale.getExtent();
  30838. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30839. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30840. } else {
  30841. var data = seriesModel.getData();
  30842. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30843. }
  30844. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30845. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30846. var barMinWidth = parsePercent$1(
  30847. // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30848. // the auto-calculated bar width might be less than 0.5 / 1.
  30849. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30850. var barGap = seriesModel.get('barGap');
  30851. var barCategoryGap = seriesModel.get('barCategoryGap');
  30852. seriesInfoList.push({
  30853. bandWidth: bandWidth,
  30854. barWidth: barWidth,
  30855. barMaxWidth: barMaxWidth,
  30856. barMinWidth: barMinWidth,
  30857. barGap: barGap,
  30858. barCategoryGap: barCategoryGap,
  30859. axisKey: getAxisKey(baseAxis),
  30860. stackId: getSeriesStackId(seriesModel)
  30861. });
  30862. });
  30863. return doCalBarWidthAndOffset(seriesInfoList);
  30864. }
  30865. function doCalBarWidthAndOffset(seriesInfoList) {
  30866. // Columns info on each category axis. Key is cartesian name
  30867. var columnsMap = {};
  30868. each(seriesInfoList, function (seriesInfo, idx) {
  30869. var axisKey = seriesInfo.axisKey;
  30870. var bandWidth = seriesInfo.bandWidth;
  30871. var columnsOnAxis = columnsMap[axisKey] || {
  30872. bandWidth: bandWidth,
  30873. remainedWidth: bandWidth,
  30874. autoWidthCount: 0,
  30875. categoryGap: null,
  30876. gap: '20%',
  30877. stacks: {}
  30878. };
  30879. var stacks = columnsOnAxis.stacks;
  30880. columnsMap[axisKey] = columnsOnAxis;
  30881. var stackId = seriesInfo.stackId;
  30882. if (!stacks[stackId]) {
  30883. columnsOnAxis.autoWidthCount++;
  30884. }
  30885. stacks[stackId] = stacks[stackId] || {
  30886. width: 0,
  30887. maxWidth: 0
  30888. };
  30889. // Caution: In a single coordinate system, these barGrid attributes
  30890. // will be shared by series. Consider that they have default values,
  30891. // only the attributes set on the last series will work.
  30892. // Do not change this fact unless there will be a break change.
  30893. var barWidth = seriesInfo.barWidth;
  30894. if (barWidth && !stacks[stackId].width) {
  30895. // See #6312, do not restrict width.
  30896. stacks[stackId].width = barWidth;
  30897. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30898. columnsOnAxis.remainedWidth -= barWidth;
  30899. }
  30900. var barMaxWidth = seriesInfo.barMaxWidth;
  30901. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30902. var barMinWidth = seriesInfo.barMinWidth;
  30903. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30904. var barGap = seriesInfo.barGap;
  30905. barGap != null && (columnsOnAxis.gap = barGap);
  30906. var barCategoryGap = seriesInfo.barCategoryGap;
  30907. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30908. });
  30909. var result = {};
  30910. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30911. result[coordSysName] = {};
  30912. var stacks = columnsOnAxis.stacks;
  30913. var bandWidth = columnsOnAxis.bandWidth;
  30914. var categoryGapPercent = columnsOnAxis.categoryGap;
  30915. if (categoryGapPercent == null) {
  30916. var columnCount = keys(stacks).length;
  30917. // More columns in one group
  30918. // the spaces between group is smaller. Or the column will be too thin.
  30919. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30920. }
  30921. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30922. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30923. var remainedWidth = columnsOnAxis.remainedWidth;
  30924. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30925. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30926. autoWidth = Math.max(autoWidth, 0);
  30927. // Find if any auto calculated bar exceeded maxBarWidth
  30928. each(stacks, function (column) {
  30929. var maxWidth = column.maxWidth;
  30930. var minWidth = column.minWidth;
  30931. if (!column.width) {
  30932. var finalWidth = autoWidth;
  30933. if (maxWidth && maxWidth < finalWidth) {
  30934. finalWidth = Math.min(maxWidth, remainedWidth);
  30935. }
  30936. // `minWidth` has higher priority. `minWidth` decide that whether the
  30937. // bar is able to be visible. So `minWidth` should not be restricted
  30938. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30939. // the extreme cases for `value` axis, bars are allowed to overlap
  30940. // with each other if `minWidth` specified.
  30941. if (minWidth && minWidth > finalWidth) {
  30942. finalWidth = minWidth;
  30943. }
  30944. if (finalWidth !== autoWidth) {
  30945. column.width = finalWidth;
  30946. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30947. autoWidthCount--;
  30948. }
  30949. } else {
  30950. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30951. // CSS does. Because barWidth can be a percent value, where
  30952. // `barMaxWidth` can be used to restrict the final width.
  30953. var finalWidth = column.width;
  30954. if (maxWidth) {
  30955. finalWidth = Math.min(finalWidth, maxWidth);
  30956. }
  30957. // `minWidth` has higher priority, as described above
  30958. if (minWidth) {
  30959. finalWidth = Math.max(finalWidth, minWidth);
  30960. }
  30961. column.width = finalWidth;
  30962. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30963. autoWidthCount--;
  30964. }
  30965. });
  30966. // Recalculate width again
  30967. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30968. autoWidth = Math.max(autoWidth, 0);
  30969. var widthSum = 0;
  30970. var lastColumn;
  30971. each(stacks, function (column, idx) {
  30972. if (!column.width) {
  30973. column.width = autoWidth;
  30974. }
  30975. lastColumn = column;
  30976. widthSum += column.width * (1 + barGapPercent);
  30977. });
  30978. if (lastColumn) {
  30979. widthSum -= lastColumn.width * barGapPercent;
  30980. }
  30981. var offset = -widthSum / 2;
  30982. each(stacks, function (column, stackId) {
  30983. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30984. bandWidth: bandWidth,
  30985. offset: offset,
  30986. width: column.width
  30987. };
  30988. offset += column.width * (1 + barGapPercent);
  30989. });
  30990. });
  30991. return result;
  30992. }
  30993. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30994. if (barWidthAndOffset && axis) {
  30995. var result = barWidthAndOffset[getAxisKey(axis)];
  30996. if (result != null && seriesModel != null) {
  30997. return result[getSeriesStackId(seriesModel)];
  30998. }
  30999. return result;
  31000. }
  31001. }
  31002. function layout(seriesType, ecModel) {
  31003. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  31004. var barWidthAndOffset = makeColumnLayout(seriesModels);
  31005. each(seriesModels, function (seriesModel) {
  31006. var data = seriesModel.getData();
  31007. var cartesian = seriesModel.coordinateSystem;
  31008. var baseAxis = cartesian.getBaseAxis();
  31009. var stackId = getSeriesStackId(seriesModel);
  31010. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  31011. var columnOffset = columnLayoutInfo.offset;
  31012. var columnWidth = columnLayoutInfo.width;
  31013. data.setLayout({
  31014. bandWidth: columnLayoutInfo.bandWidth,
  31015. offset: columnOffset,
  31016. size: columnWidth
  31017. });
  31018. });
  31019. }
  31020. // TODO: Do not support stack in large mode yet.
  31021. function createProgressiveLayout(seriesType) {
  31022. return {
  31023. seriesType: seriesType,
  31024. plan: createRenderPlanner(),
  31025. reset: function (seriesModel) {
  31026. if (!isOnCartesian(seriesModel)) {
  31027. return;
  31028. }
  31029. var data = seriesModel.getData();
  31030. var cartesian = seriesModel.coordinateSystem;
  31031. var baseAxis = cartesian.getBaseAxis();
  31032. var valueAxis = cartesian.getOtherAxis(baseAxis);
  31033. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  31034. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  31035. var drawBackground = seriesModel.get('showBackground', true);
  31036. var valueDim = data.mapDimension(valueAxis.dim);
  31037. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31038. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  31039. var isValueAxisH = valueAxis.isHorizontal();
  31040. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  31041. var isLarge = isInLargeMode(seriesModel);
  31042. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  31043. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim);
  31044. // Layout info.
  31045. var columnWidth = data.getLayout('size');
  31046. var columnOffset = data.getLayout('offset');
  31047. return {
  31048. progress: function (params, data) {
  31049. var count = params.count;
  31050. var largePoints = isLarge && createFloat32Array(count * 3);
  31051. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  31052. var largeDataIndices = isLarge && createFloat32Array(count);
  31053. var coordLayout = cartesian.master.getRect();
  31054. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  31055. var dataIndex;
  31056. var store = data.getStore();
  31057. var idxOffset = 0;
  31058. while ((dataIndex = params.next()) != null) {
  31059. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  31060. var baseValue = store.get(baseDimIdx, dataIndex);
  31061. var baseCoord = valueAxisStart;
  31062. var stackStartValue = void 0;
  31063. // Because of the barMinHeight, we can not use the value in
  31064. // stackResultDimension directly.
  31065. if (stacked) {
  31066. stackStartValue = +value - store.get(valueDimIdx, dataIndex);
  31067. }
  31068. var x = void 0;
  31069. var y = void 0;
  31070. var width = void 0;
  31071. var height = void 0;
  31072. if (isValueAxisH) {
  31073. var coord = cartesian.dataToPoint([value, baseValue]);
  31074. if (stacked) {
  31075. var startCoord = cartesian.dataToPoint([stackStartValue, baseValue]);
  31076. baseCoord = startCoord[0];
  31077. }
  31078. x = baseCoord;
  31079. y = coord[1] + columnOffset;
  31080. width = coord[0] - baseCoord;
  31081. height = columnWidth;
  31082. if (Math.abs(width) < barMinHeight) {
  31083. width = (width < 0 ? -1 : 1) * barMinHeight;
  31084. }
  31085. } else {
  31086. var coord = cartesian.dataToPoint([baseValue, value]);
  31087. if (stacked) {
  31088. var startCoord = cartesian.dataToPoint([baseValue, stackStartValue]);
  31089. baseCoord = startCoord[1];
  31090. }
  31091. x = coord[0] + columnOffset;
  31092. y = baseCoord;
  31093. width = columnWidth;
  31094. height = coord[1] - baseCoord;
  31095. if (Math.abs(height) < barMinHeight) {
  31096. // Include zero to has a positive bar
  31097. height = (height <= 0 ? -1 : 1) * barMinHeight;
  31098. }
  31099. }
  31100. if (!isLarge) {
  31101. data.setItemLayout(dataIndex, {
  31102. x: x,
  31103. y: y,
  31104. width: width,
  31105. height: height
  31106. });
  31107. } else {
  31108. largePoints[idxOffset] = x;
  31109. largePoints[idxOffset + 1] = y;
  31110. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  31111. if (largeBackgroundPoints) {
  31112. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  31113. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  31114. largeBackgroundPoints[idxOffset + 2] = bgSize;
  31115. }
  31116. largeDataIndices[dataIndex] = dataIndex;
  31117. }
  31118. idxOffset += 3;
  31119. }
  31120. if (isLarge) {
  31121. data.setLayout({
  31122. largePoints: largePoints,
  31123. largeDataIndices: largeDataIndices,
  31124. largeBackgroundPoints: largeBackgroundPoints,
  31125. valueAxisHorizontal: isValueAxisH
  31126. });
  31127. }
  31128. }
  31129. };
  31130. }
  31131. };
  31132. }
  31133. function isOnCartesian(seriesModel) {
  31134. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  31135. }
  31136. function isInLargeMode(seriesModel) {
  31137. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  31138. }
  31139. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  31140. function getValueAxisStart(baseAxis, valueAxis) {
  31141. var startValue = valueAxis.model.get('startValue');
  31142. if (!startValue) {
  31143. startValue = 0;
  31144. }
  31145. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? startValue > 0 ? startValue : 1 : startValue));
  31146. }
  31147. // FIXME 公用?
  31148. var bisect = function (a, x, lo, hi) {
  31149. while (lo < hi) {
  31150. var mid = lo + hi >>> 1;
  31151. if (a[mid][1] < x) {
  31152. lo = mid + 1;
  31153. } else {
  31154. hi = mid;
  31155. }
  31156. }
  31157. return lo;
  31158. };
  31159. var TimeScale = /** @class */function (_super) {
  31160. __extends(TimeScale, _super);
  31161. function TimeScale(settings) {
  31162. var _this = _super.call(this, settings) || this;
  31163. _this.type = 'time';
  31164. return _this;
  31165. }
  31166. /**
  31167. * Get label is mainly for other components like dataZoom, tooltip.
  31168. */
  31169. TimeScale.prototype.getLabel = function (tick) {
  31170. var useUTC = this.getSetting('useUTC');
  31171. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  31172. };
  31173. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  31174. var isUTC = this.getSetting('useUTC');
  31175. var lang = this.getSetting('locale');
  31176. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  31177. };
  31178. /**
  31179. * @override
  31180. */
  31181. TimeScale.prototype.getTicks = function () {
  31182. var interval = this._interval;
  31183. var extent = this._extent;
  31184. var ticks = [];
  31185. // If interval is 0, return [];
  31186. if (!interval) {
  31187. return ticks;
  31188. }
  31189. ticks.push({
  31190. value: extent[0],
  31191. level: 0
  31192. });
  31193. var useUTC = this.getSetting('useUTC');
  31194. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  31195. ticks = ticks.concat(innerTicks);
  31196. ticks.push({
  31197. value: extent[1],
  31198. level: 0
  31199. });
  31200. return ticks;
  31201. };
  31202. TimeScale.prototype.calcNiceExtent = function (opt) {
  31203. var extent = this._extent;
  31204. // If extent start and end are same, expand them
  31205. if (extent[0] === extent[1]) {
  31206. // Expand extent
  31207. extent[0] -= ONE_DAY;
  31208. extent[1] += ONE_DAY;
  31209. }
  31210. // If there are no data and extent are [Infinity, -Infinity]
  31211. if (extent[1] === -Infinity && extent[0] === Infinity) {
  31212. var d = new Date();
  31213. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  31214. extent[0] = extent[1] - ONE_DAY;
  31215. }
  31216. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  31217. };
  31218. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  31219. approxTickNum = approxTickNum || 10;
  31220. var extent = this._extent;
  31221. var span = extent[1] - extent[0];
  31222. this._approxInterval = span / approxTickNum;
  31223. if (minInterval != null && this._approxInterval < minInterval) {
  31224. this._approxInterval = minInterval;
  31225. }
  31226. if (maxInterval != null && this._approxInterval > maxInterval) {
  31227. this._approxInterval = maxInterval;
  31228. }
  31229. var scaleIntervalsLen = scaleIntervals.length;
  31230. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1);
  31231. // Interval that can be used to calculate ticks
  31232. this._interval = scaleIntervals[idx][1];
  31233. // Min level used when picking ticks from top down.
  31234. // We check one more level to avoid the ticks are to sparse in some case.
  31235. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  31236. };
  31237. TimeScale.prototype.parse = function (val) {
  31238. // val might be float.
  31239. return isNumber(val) ? val : +parseDate(val);
  31240. };
  31241. TimeScale.prototype.contain = function (val) {
  31242. return contain$1(this.parse(val), this._extent);
  31243. };
  31244. TimeScale.prototype.normalize = function (val) {
  31245. return normalize$1(this.parse(val), this._extent);
  31246. };
  31247. TimeScale.prototype.scale = function (val) {
  31248. return scale$2(val, this._extent);
  31249. };
  31250. TimeScale.type = 'time';
  31251. return TimeScale;
  31252. }(IntervalScale);
  31253. /**
  31254. * This implementation was originally copied from "d3.js"
  31255. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  31256. * with some modifications made for this program.
  31257. * See the license statement at the head of this file.
  31258. */
  31259. var scaleIntervals = [
  31260. // Format interval
  31261. ['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
  31262. ];
  31263. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  31264. var dateA = parseDate(valueA);
  31265. var dateB = parseDate(valueB);
  31266. var isSame = function (unit) {
  31267. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  31268. };
  31269. var isSameYear = function () {
  31270. return isSame('year');
  31271. };
  31272. // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  31273. // const isSameQuater = () => isSameYear() && isSame('quarter');
  31274. var isSameMonth = function () {
  31275. return isSameYear() && isSame('month');
  31276. };
  31277. var isSameDay = function () {
  31278. return isSameMonth() && isSame('day');
  31279. };
  31280. // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  31281. var isSameHour = function () {
  31282. return isSameDay() && isSame('hour');
  31283. };
  31284. var isSameMinute = function () {
  31285. return isSameHour() && isSame('minute');
  31286. };
  31287. var isSameSecond = function () {
  31288. return isSameMinute() && isSame('second');
  31289. };
  31290. var isSameMilliSecond = function () {
  31291. return isSameSecond() && isSame('millisecond');
  31292. };
  31293. switch (unit) {
  31294. case 'year':
  31295. return isSameYear();
  31296. case 'month':
  31297. return isSameMonth();
  31298. case 'day':
  31299. return isSameDay();
  31300. case 'hour':
  31301. return isSameHour();
  31302. case 'minute':
  31303. return isSameMinute();
  31304. case 'second':
  31305. return isSameSecond();
  31306. case 'millisecond':
  31307. return isSameMilliSecond();
  31308. }
  31309. }
  31310. // const primaryUnitGetters = {
  31311. // year: fullYearGetterName(),
  31312. // month: monthGetterName(),
  31313. // day: dateGetterName(),
  31314. // hour: hoursGetterName(),
  31315. // minute: minutesGetterName(),
  31316. // second: secondsGetterName(),
  31317. // millisecond: millisecondsGetterName()
  31318. // };
  31319. // const primaryUnitUTCGetters = {
  31320. // year: fullYearGetterName(true),
  31321. // month: monthGetterName(true),
  31322. // day: dateGetterName(true),
  31323. // hour: hoursGetterName(true),
  31324. // minute: minutesGetterName(true),
  31325. // second: secondsGetterName(true),
  31326. // millisecond: millisecondsGetterName(true)
  31327. // };
  31328. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  31329. // step = step || 1;
  31330. // switch (getPrimaryTimeUnit(unitName)) {
  31331. // case 'year':
  31332. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  31333. // break;
  31334. // case 'month':
  31335. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  31336. // break;
  31337. // case 'day':
  31338. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  31339. // break;
  31340. // case 'hour':
  31341. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  31342. // break;
  31343. // case 'minute':
  31344. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  31345. // break;
  31346. // case 'second':
  31347. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  31348. // break;
  31349. // case 'millisecond':
  31350. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  31351. // break;
  31352. // }
  31353. // return date.getTime();
  31354. // }
  31355. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  31356. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  31357. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  31358. function getDateInterval(approxInterval, daysInMonth) {
  31359. approxInterval /= ONE_DAY;
  31360. return approxInterval > 16 ? 16
  31361. // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  31362. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  31363. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  31364. }
  31365. function getMonthInterval(approxInterval) {
  31366. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  31367. approxInterval /= APPROX_ONE_MONTH;
  31368. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  31369. }
  31370. function getHourInterval(approxInterval) {
  31371. approxInterval /= ONE_HOUR;
  31372. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  31373. }
  31374. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  31375. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  31376. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  31377. }
  31378. function getMillisecondsInterval(approxInterval) {
  31379. return nice(approxInterval, true);
  31380. }
  31381. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  31382. var outDate = new Date(date);
  31383. switch (getPrimaryTimeUnit(unitName)) {
  31384. case 'year':
  31385. case 'month':
  31386. outDate[monthSetterName(isUTC)](0);
  31387. case 'day':
  31388. outDate[dateSetterName(isUTC)](1);
  31389. case 'hour':
  31390. outDate[hoursSetterName(isUTC)](0);
  31391. case 'minute':
  31392. outDate[minutesSetterName(isUTC)](0);
  31393. case 'second':
  31394. outDate[secondsSetterName(isUTC)](0);
  31395. outDate[millisecondsSetterName(isUTC)](0);
  31396. }
  31397. return outDate.getTime();
  31398. }
  31399. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  31400. var safeLimit = 10000;
  31401. var unitNames = timeUnits;
  31402. var iter = 0;
  31403. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  31404. var date = new Date(minTimestamp);
  31405. var dateTime = minTimestamp;
  31406. var d = date[getMethodName]();
  31407. // if (isDate) {
  31408. // d -= 1; // Starts with 0; PENDING
  31409. // }
  31410. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  31411. out.push({
  31412. value: dateTime
  31413. });
  31414. d += interval;
  31415. date[setMethodName](d);
  31416. dateTime = date.getTime();
  31417. }
  31418. // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  31419. out.push({
  31420. value: dateTime,
  31421. notAdd: true
  31422. });
  31423. }
  31424. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  31425. var newAddedTicks = [];
  31426. var isFirstLevel = !lastLevelTicks.length;
  31427. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  31428. return;
  31429. }
  31430. if (isFirstLevel) {
  31431. lastLevelTicks = [{
  31432. // TODO Optimize. Not include so may ticks.
  31433. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  31434. }, {
  31435. value: extent[1]
  31436. }];
  31437. }
  31438. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  31439. var startTick = lastLevelTicks[i].value;
  31440. var endTick = lastLevelTicks[i + 1].value;
  31441. if (startTick === endTick) {
  31442. continue;
  31443. }
  31444. var interval = void 0;
  31445. var getterName = void 0;
  31446. var setterName = void 0;
  31447. var isDate = false;
  31448. switch (unitName) {
  31449. case 'year':
  31450. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  31451. getterName = fullYearGetterName(isUTC);
  31452. setterName = fullYearSetterName(isUTC);
  31453. break;
  31454. case 'half-year':
  31455. case 'quarter':
  31456. case 'month':
  31457. interval = getMonthInterval(approxInterval);
  31458. getterName = monthGetterName(isUTC);
  31459. setterName = monthSetterName(isUTC);
  31460. break;
  31461. case 'week': // PENDING If week is added. Ignore day.
  31462. case 'half-week':
  31463. case 'day':
  31464. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  31465. getterName = dateGetterName(isUTC);
  31466. setterName = dateSetterName(isUTC);
  31467. isDate = true;
  31468. break;
  31469. case 'half-day':
  31470. case 'quarter-day':
  31471. case 'hour':
  31472. interval = getHourInterval(approxInterval);
  31473. getterName = hoursGetterName(isUTC);
  31474. setterName = hoursSetterName(isUTC);
  31475. break;
  31476. case 'minute':
  31477. interval = getMinutesAndSecondsInterval(approxInterval, true);
  31478. getterName = minutesGetterName(isUTC);
  31479. setterName = minutesSetterName(isUTC);
  31480. break;
  31481. case 'second':
  31482. interval = getMinutesAndSecondsInterval(approxInterval, false);
  31483. getterName = secondsGetterName(isUTC);
  31484. setterName = secondsSetterName(isUTC);
  31485. break;
  31486. case 'millisecond':
  31487. interval = getMillisecondsInterval(approxInterval);
  31488. getterName = millisecondsGetterName(isUTC);
  31489. setterName = millisecondsSetterName(isUTC);
  31490. break;
  31491. }
  31492. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  31493. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  31494. // Add nearest years to the left extent.
  31495. levelTicks.unshift({
  31496. value: levelTicks[0].value - interval
  31497. });
  31498. }
  31499. }
  31500. for (var i = 0; i < newAddedTicks.length; i++) {
  31501. levelTicks.push(newAddedTicks[i]);
  31502. }
  31503. // newAddedTicks.length && console.log(unitName, newAddedTicks);
  31504. return newAddedTicks;
  31505. }
  31506. var levelsTicks = [];
  31507. var currentLevelTicks = [];
  31508. var tickCount = 0;
  31509. var lastLevelTickCount = 0;
  31510. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  31511. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  31512. if (!isPrimaryTimeUnit(unitNames[i])) {
  31513. // TODO
  31514. continue;
  31515. }
  31516. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  31517. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  31518. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  31519. if (currentLevelTicks.length) {
  31520. lastLevelTickCount = tickCount;
  31521. // Remove the duplicate so the tick count can be precisely.
  31522. currentLevelTicks.sort(function (a, b) {
  31523. return a.value - b.value;
  31524. });
  31525. var levelTicksRemoveDuplicated = [];
  31526. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  31527. var tickValue = currentLevelTicks[i_1].value;
  31528. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  31529. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  31530. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  31531. tickCount++;
  31532. }
  31533. }
  31534. }
  31535. var targetTickNum = (extent[1] - extent[0]) / approxInterval;
  31536. // Added too much in this level and not too less in last level
  31537. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  31538. break;
  31539. }
  31540. // Only treat primary time unit as one level.
  31541. levelsTicks.push(levelTicksRemoveDuplicated);
  31542. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  31543. break;
  31544. }
  31545. }
  31546. // Reset if next unitName is primary
  31547. currentLevelTicks = [];
  31548. }
  31549. }
  31550. if ("development" !== 'production') {
  31551. if (iter >= safeLimit) {
  31552. warn('Exceed safe limit.');
  31553. }
  31554. }
  31555. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  31556. return filter(levelTicks, function (tick) {
  31557. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  31558. });
  31559. }), function (levelTicks) {
  31560. return levelTicks.length > 0;
  31561. });
  31562. var ticks = [];
  31563. var maxLevel = levelsTicksInExtent.length - 1;
  31564. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  31565. var levelTicks = levelsTicksInExtent[i];
  31566. for (var k = 0; k < levelTicks.length; ++k) {
  31567. ticks.push({
  31568. value: levelTicks[k].value,
  31569. level: maxLevel - i
  31570. });
  31571. }
  31572. }
  31573. ticks.sort(function (a, b) {
  31574. return a.value - b.value;
  31575. });
  31576. // Remove duplicates
  31577. var result = [];
  31578. for (var i = 0; i < ticks.length; ++i) {
  31579. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  31580. result.push(ticks[i]);
  31581. }
  31582. }
  31583. return result;
  31584. }
  31585. Scale.registerClass(TimeScale);
  31586. var scaleProto = Scale.prototype;
  31587. // FIXME:TS refactor: not good to call it directly with `this`?
  31588. var intervalScaleProto = IntervalScale.prototype;
  31589. var roundingErrorFix = round;
  31590. var mathFloor = Math.floor;
  31591. var mathCeil = Math.ceil;
  31592. var mathPow$1 = Math.pow;
  31593. var mathLog = Math.log;
  31594. var LogScale = /** @class */function (_super) {
  31595. __extends(LogScale, _super);
  31596. function LogScale() {
  31597. var _this = _super !== null && _super.apply(this, arguments) || this;
  31598. _this.type = 'log';
  31599. _this.base = 10;
  31600. _this._originalScale = new IntervalScale();
  31601. // FIXME:TS actually used by `IntervalScale`
  31602. _this._interval = 0;
  31603. return _this;
  31604. }
  31605. /**
  31606. * @param Whether expand the ticks to niced extent.
  31607. */
  31608. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  31609. var originalScale = this._originalScale;
  31610. var extent = this._extent;
  31611. var originalExtent = originalScale.getExtent();
  31612. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  31613. return map(ticks, function (tick) {
  31614. var val = tick.value;
  31615. var powVal = round(mathPow$1(this.base, val));
  31616. // Fix #4158
  31617. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  31618. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  31619. return {
  31620. value: powVal
  31621. };
  31622. }, this);
  31623. };
  31624. LogScale.prototype.setExtent = function (start, end) {
  31625. var base = mathLog(this.base);
  31626. // log(-Infinity) is NaN, so safe guard here
  31627. start = mathLog(Math.max(0, start)) / base;
  31628. end = mathLog(Math.max(0, end)) / base;
  31629. intervalScaleProto.setExtent.call(this, start, end);
  31630. };
  31631. /**
  31632. * @return {number} end
  31633. */
  31634. LogScale.prototype.getExtent = function () {
  31635. var base = this.base;
  31636. var extent = scaleProto.getExtent.call(this);
  31637. extent[0] = mathPow$1(base, extent[0]);
  31638. extent[1] = mathPow$1(base, extent[1]);
  31639. // Fix #4158
  31640. var originalScale = this._originalScale;
  31641. var originalExtent = originalScale.getExtent();
  31642. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  31643. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  31644. return extent;
  31645. };
  31646. LogScale.prototype.unionExtent = function (extent) {
  31647. this._originalScale.unionExtent(extent);
  31648. var base = this.base;
  31649. extent[0] = mathLog(extent[0]) / mathLog(base);
  31650. extent[1] = mathLog(extent[1]) / mathLog(base);
  31651. scaleProto.unionExtent.call(this, extent);
  31652. };
  31653. LogScale.prototype.unionExtentFromData = function (data, dim) {
  31654. // TODO
  31655. // filter value that <= 0
  31656. this.unionExtent(data.getApproximateExtent(dim));
  31657. };
  31658. /**
  31659. * Update interval and extent of intervals for nice ticks
  31660. * @param approxTickNum default 10 Given approx tick number
  31661. */
  31662. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  31663. approxTickNum = approxTickNum || 10;
  31664. var extent = this._extent;
  31665. var span = extent[1] - extent[0];
  31666. if (span === Infinity || span <= 0) {
  31667. return;
  31668. }
  31669. var interval = quantity(span);
  31670. var err = approxTickNum / span * interval;
  31671. // Filter ticks to get closer to the desired count.
  31672. if (err <= 0.5) {
  31673. interval *= 10;
  31674. }
  31675. // Interval should be integer
  31676. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31677. interval *= 10;
  31678. }
  31679. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  31680. this._interval = interval;
  31681. this._niceExtent = niceExtent;
  31682. };
  31683. LogScale.prototype.calcNiceExtent = function (opt) {
  31684. intervalScaleProto.calcNiceExtent.call(this, opt);
  31685. this._fixMin = opt.fixMin;
  31686. this._fixMax = opt.fixMax;
  31687. };
  31688. LogScale.prototype.parse = function (val) {
  31689. return val;
  31690. };
  31691. LogScale.prototype.contain = function (val) {
  31692. val = mathLog(val) / mathLog(this.base);
  31693. return contain$1(val, this._extent);
  31694. };
  31695. LogScale.prototype.normalize = function (val) {
  31696. val = mathLog(val) / mathLog(this.base);
  31697. return normalize$1(val, this._extent);
  31698. };
  31699. LogScale.prototype.scale = function (val) {
  31700. val = scale$2(val, this._extent);
  31701. return mathPow$1(this.base, val);
  31702. };
  31703. LogScale.type = 'log';
  31704. return LogScale;
  31705. }(Scale);
  31706. var proto = LogScale.prototype;
  31707. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  31708. proto.getLabel = intervalScaleProto.getLabel;
  31709. function fixRoundingError(val, originalVal) {
  31710. return roundingErrorFix(val, getPrecision(originalVal));
  31711. }
  31712. Scale.registerClass(LogScale);
  31713. var ScaleRawExtentInfo = /** @class */function () {
  31714. function ScaleRawExtentInfo(scale, model,
  31715. // Usually: data extent from all series on this axis.
  31716. originalExtent) {
  31717. this._prepareParams(scale, model, originalExtent);
  31718. }
  31719. /**
  31720. * Parameters depending on outside (like model, user callback)
  31721. * are prepared and fixed here.
  31722. */
  31723. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model,
  31724. // Usually: data extent from all series on this axis.
  31725. dataExtent) {
  31726. if (dataExtent[1] < dataExtent[0]) {
  31727. dataExtent = [NaN, NaN];
  31728. }
  31729. this._dataMin = dataExtent[0];
  31730. this._dataMax = dataExtent[1];
  31731. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  31732. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  31733. var axisMinValue = model.get('min', true);
  31734. if (axisMinValue == null) {
  31735. axisMinValue = model.get('startValue', true);
  31736. }
  31737. var modelMinRaw = this._modelMinRaw = axisMinValue;
  31738. if (isFunction(modelMinRaw)) {
  31739. // This callback always provides users the full data extent (before data is filtered).
  31740. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  31741. min: dataExtent[0],
  31742. max: dataExtent[1]
  31743. }));
  31744. } else if (modelMinRaw !== 'dataMin') {
  31745. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  31746. }
  31747. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  31748. if (isFunction(modelMaxRaw)) {
  31749. // This callback always provides users the full data extent (before data is filtered).
  31750. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  31751. min: dataExtent[0],
  31752. max: dataExtent[1]
  31753. }));
  31754. } else if (modelMaxRaw !== 'dataMax') {
  31755. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  31756. }
  31757. if (isOrdinal) {
  31758. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  31759. // and progressive rendering is using, here the category result might just only contain
  31760. // the processed chunk rather than the entire result.
  31761. this._axisDataLen = model.getCategories().length;
  31762. } else {
  31763. var boundaryGap = model.get('boundaryGap');
  31764. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  31765. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  31766. if ("development" !== 'production') {
  31767. 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.');
  31768. }
  31769. this._boundaryGapInner = [0, 0];
  31770. } else {
  31771. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  31772. }
  31773. }
  31774. };
  31775. /**
  31776. * Calculate extent by prepared parameters.
  31777. * This method has no external dependency and can be called duplicatedly,
  31778. * getting the same result.
  31779. * If parameters changed, should call this method to recalcuate.
  31780. */
  31781. ScaleRawExtentInfo.prototype.calculate = function () {
  31782. // Notice: When min/max is not set (that is, when there are null/undefined,
  31783. // which is the most common case), these cases should be ensured:
  31784. // (1) For 'ordinal', show all axis.data.
  31785. // (2) For others:
  31786. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31787. // disabled).
  31788. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31789. // be the result that originalExtent enlarged by boundaryGap.
  31790. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31791. var isOrdinal = this._isOrdinal;
  31792. var dataMin = this._dataMin;
  31793. var dataMax = this._dataMax;
  31794. var axisDataLen = this._axisDataLen;
  31795. var boundaryGapInner = this._boundaryGapInner;
  31796. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null;
  31797. // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  31798. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  31799. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  31800. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum;
  31801. // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  31802. var minFixed = min != null;
  31803. var maxFixed = max != null;
  31804. if (min == null) {
  31805. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31806. }
  31807. if (max == null) {
  31808. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31809. }
  31810. (min == null || !isFinite(min)) && (min = NaN);
  31811. (max == null || !isFinite(max)) && (max = NaN);
  31812. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen;
  31813. // If data extent modified, need to recalculated to ensure cross zero.
  31814. if (this._needCrossZero) {
  31815. // Axis is over zero and min is not set
  31816. if (min > 0 && max > 0 && !minFixed) {
  31817. min = 0;
  31818. // minFixed = true;
  31819. }
  31820. // Axis is under zero and max is not set
  31821. if (min < 0 && max < 0 && !maxFixed) {
  31822. max = 0;
  31823. // maxFixed = true;
  31824. }
  31825. // PENDING:
  31826. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31827. // that the results processed by boundaryGap are positive/negative?
  31828. // If so, here `minFixed`/`maxFixed` need to be set.
  31829. }
  31830. var determinedMin = this._determinedMin;
  31831. var determinedMax = this._determinedMax;
  31832. if (determinedMin != null) {
  31833. min = determinedMin;
  31834. minFixed = true;
  31835. }
  31836. if (determinedMax != null) {
  31837. max = determinedMax;
  31838. maxFixed = true;
  31839. }
  31840. // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31841. // `NaN` means min/max axis is blank.
  31842. return {
  31843. min: min,
  31844. max: max,
  31845. minFixed: minFixed,
  31846. maxFixed: maxFixed,
  31847. isBlank: isBlank
  31848. };
  31849. };
  31850. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31851. if ("development" !== 'production') {
  31852. assert(!this.frozen);
  31853. }
  31854. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31855. };
  31856. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31857. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31858. if ("development" !== 'production') {
  31859. assert(!this.frozen
  31860. // Earse them usually means logic flaw.
  31861. && this[attr] == null);
  31862. }
  31863. this[attr] = val;
  31864. };
  31865. ScaleRawExtentInfo.prototype.freeze = function () {
  31866. // @ts-ignore
  31867. this.frozen = true;
  31868. };
  31869. return ScaleRawExtentInfo;
  31870. }();
  31871. var DETERMINED_MIN_MAX_ATTR = {
  31872. min: '_determinedMin',
  31873. max: '_determinedMax'
  31874. };
  31875. var DATA_MIN_MAX_ATTR = {
  31876. min: '_dataMin',
  31877. max: '_dataMax'
  31878. };
  31879. /**
  31880. * Get scale min max and related info only depends on model settings.
  31881. * This method can be called after coordinate system created.
  31882. * For example, in data processing stage.
  31883. *
  31884. * Scale extent info probably be required multiple times during a workflow.
  31885. * For example:
  31886. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31887. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31888. * (3) `coordSys.update` use it to finally decide the scale extent.
  31889. * But the callback of `min`/`max` should not be called multiple times.
  31890. * The code below should not be implemented repeatedly either.
  31891. * So we cache the result in the scale instance, which will be recreated at the beginning
  31892. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31893. */
  31894. function ensureScaleRawExtentInfo(scale, model,
  31895. // Usually: data extent from all series on this axis.
  31896. originalExtent) {
  31897. // Do not permit to recreate.
  31898. var rawExtentInfo = scale.rawExtentInfo;
  31899. if (rawExtentInfo) {
  31900. return rawExtentInfo;
  31901. }
  31902. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent);
  31903. // @ts-ignore
  31904. scale.rawExtentInfo = rawExtentInfo;
  31905. return rawExtentInfo;
  31906. }
  31907. function parseAxisModelMinMax(scale, minMax) {
  31908. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31909. }
  31910. /**
  31911. * Get axis scale extent before niced.
  31912. * Item of returned array can only be number (including Infinity and NaN).
  31913. *
  31914. * Caution:
  31915. * Precondition of calling this method:
  31916. * The scale extent has been initialized using series data extent via
  31917. * `scale.setExtent` or `scale.unionExtentFromData`;
  31918. */
  31919. function getScaleExtent(scale, model) {
  31920. var scaleType = scale.type;
  31921. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31922. scale.setBlank(rawExtentResult.isBlank);
  31923. var min = rawExtentResult.min;
  31924. var max = rawExtentResult.max;
  31925. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31926. // is base axis
  31927. // FIXME
  31928. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31929. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31930. // Should not depend on series type `bar`?
  31931. // (3) Fix that might overlap when using dataZoom.
  31932. // (4) Consider other chart types using `barGrid`?
  31933. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31934. var ecModel = model.ecModel;
  31935. if (ecModel && scaleType === 'time' /* || scaleType === 'interval' */) {
  31936. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31937. var isBaseAxisAndHasBarSeries_1 = false;
  31938. each(barSeriesModels, function (seriesModel) {
  31939. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31940. });
  31941. if (isBaseAxisAndHasBarSeries_1) {
  31942. // Calculate placement of bars on axis. TODO should be decoupled
  31943. // with barLayout
  31944. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  31945. // Adjust axis min and max to account for overflow
  31946. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31947. min = adjustedScale.min;
  31948. max = adjustedScale.max;
  31949. }
  31950. }
  31951. return {
  31952. extent: [min, max],
  31953. // "fix" means "fixed", the value should not be
  31954. // changed in the subsequent steps.
  31955. fixMin: rawExtentResult.minFixed,
  31956. fixMax: rawExtentResult.maxFixed
  31957. };
  31958. }
  31959. function adjustScaleForOverflow(min, max, model,
  31960. // Only support cartesian coord yet.
  31961. barWidthAndOffset) {
  31962. // Get Axis Length
  31963. var axisExtent = model.axis.getExtent();
  31964. var axisLength = axisExtent[1] - axisExtent[0];
  31965. // Get bars on current base axis and calculate min and max overflow
  31966. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31967. if (barsOnCurrentAxis === undefined) {
  31968. return {
  31969. min: min,
  31970. max: max
  31971. };
  31972. }
  31973. var minOverflow = Infinity;
  31974. each(barsOnCurrentAxis, function (item) {
  31975. minOverflow = Math.min(item.offset, minOverflow);
  31976. });
  31977. var maxOverflow = -Infinity;
  31978. each(barsOnCurrentAxis, function (item) {
  31979. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31980. });
  31981. minOverflow = Math.abs(minOverflow);
  31982. maxOverflow = Math.abs(maxOverflow);
  31983. var totalOverFlow = minOverflow + maxOverflow;
  31984. // Calculate required buffer based on old range and overflow
  31985. var oldRange = max - min;
  31986. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31987. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31988. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31989. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31990. return {
  31991. min: min,
  31992. max: max
  31993. };
  31994. }
  31995. // Precondition of calling this method:
  31996. // The scale extent has been initialized using series data extent via
  31997. // `scale.setExtent` or `scale.unionExtentFromData`;
  31998. function niceScaleExtent(scale, inModel) {
  31999. var model = inModel;
  32000. var extentInfo = getScaleExtent(scale, model);
  32001. var extent = extentInfo.extent;
  32002. var splitNumber = model.get('splitNumber');
  32003. if (scale instanceof LogScale) {
  32004. scale.base = model.get('logBase');
  32005. }
  32006. var scaleType = scale.type;
  32007. var interval = model.get('interval');
  32008. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  32009. scale.setExtent(extent[0], extent[1]);
  32010. scale.calcNiceExtent({
  32011. splitNumber: splitNumber,
  32012. fixMin: extentInfo.fixMin,
  32013. fixMax: extentInfo.fixMax,
  32014. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  32015. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  32016. });
  32017. // If some one specified the min, max. And the default calculated interval
  32018. // is not good enough. He can specify the interval. It is often appeared
  32019. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  32020. // to be 60.
  32021. // FIXME
  32022. if (interval != null) {
  32023. scale.setInterval && scale.setInterval(interval);
  32024. }
  32025. }
  32026. /**
  32027. * @param axisType Default retrieve from model.type
  32028. */
  32029. function createScaleByModel(model, axisType) {
  32030. axisType = axisType || model.get('type');
  32031. if (axisType) {
  32032. switch (axisType) {
  32033. // Buildin scale
  32034. case 'category':
  32035. return new OrdinalScale({
  32036. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  32037. extent: [Infinity, -Infinity]
  32038. });
  32039. case 'time':
  32040. return new TimeScale({
  32041. locale: model.ecModel.getLocaleModel(),
  32042. useUTC: model.ecModel.get('useUTC')
  32043. });
  32044. default:
  32045. // case 'value'/'interval', 'log', or others.
  32046. return new (Scale.getClass(axisType) || IntervalScale)();
  32047. }
  32048. }
  32049. }
  32050. /**
  32051. * Check if the axis cross 0
  32052. */
  32053. function ifAxisCrossZero(axis) {
  32054. var dataExtent = axis.scale.getExtent();
  32055. var min = dataExtent[0];
  32056. var max = dataExtent[1];
  32057. return !(min > 0 && max > 0 || min < 0 && max < 0);
  32058. }
  32059. /**
  32060. * @param axis
  32061. * @return Label formatter function.
  32062. * param: {number} tickValue,
  32063. * param: {number} idx, the index in all ticks.
  32064. * If category axis, this param is not required.
  32065. * return: {string} label string.
  32066. */
  32067. function makeLabelFormatter(axis) {
  32068. var labelFormatter = axis.getLabelModel().get('formatter');
  32069. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  32070. if (axis.scale.type === 'time') {
  32071. return function (tpl) {
  32072. return function (tick, idx) {
  32073. return axis.scale.getFormattedLabel(tick, idx, tpl);
  32074. };
  32075. }(labelFormatter);
  32076. } else if (isString(labelFormatter)) {
  32077. return function (tpl) {
  32078. return function (tick) {
  32079. // For category axis, get raw value; for numeric axis,
  32080. // get formatted label like '1,333,444'.
  32081. var label = axis.scale.getLabel(tick);
  32082. var text = tpl.replace('{value}', label != null ? label : '');
  32083. return text;
  32084. };
  32085. }(labelFormatter);
  32086. } else if (isFunction(labelFormatter)) {
  32087. return function (cb) {
  32088. return function (tick, idx) {
  32089. // The original intention of `idx` is "the index of the tick in all ticks".
  32090. // But the previous implementation of category axis do not consider the
  32091. // `axisLabel.interval`, which cause that, for example, the `interval` is
  32092. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  32093. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  32094. // the definition here for back compatibility.
  32095. if (categoryTickStart != null) {
  32096. idx = tick.value - categoryTickStart;
  32097. }
  32098. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  32099. level: tick.level
  32100. } : null);
  32101. };
  32102. }(labelFormatter);
  32103. } else {
  32104. return function (tick) {
  32105. return axis.scale.getLabel(tick);
  32106. };
  32107. }
  32108. }
  32109. function getAxisRawValue(axis, tick) {
  32110. // In category axis with data zoom, tick is not the original
  32111. // index of axis.data. So tick should not be exposed to user
  32112. // in category axis.
  32113. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  32114. }
  32115. /**
  32116. * @param axis
  32117. * @return Be null/undefined if no labels.
  32118. */
  32119. function estimateLabelUnionRect(axis) {
  32120. var axisModel = axis.model;
  32121. var scale = axis.scale;
  32122. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  32123. return;
  32124. }
  32125. var realNumberScaleTicks;
  32126. var tickCount;
  32127. var categoryScaleExtent = scale.getExtent();
  32128. // Optimize for large category data, avoid call `getTicks()`.
  32129. if (scale instanceof OrdinalScale) {
  32130. tickCount = scale.count();
  32131. } else {
  32132. realNumberScaleTicks = scale.getTicks();
  32133. tickCount = realNumberScaleTicks.length;
  32134. }
  32135. var axisLabelModel = axis.getLabelModel();
  32136. var labelFormatter = makeLabelFormatter(axis);
  32137. var rect;
  32138. var step = 1;
  32139. // Simple optimization for large amount of labels
  32140. if (tickCount > 40) {
  32141. step = Math.ceil(tickCount / 40);
  32142. }
  32143. for (var i = 0; i < tickCount; i += step) {
  32144. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  32145. value: categoryScaleExtent[0] + i
  32146. };
  32147. var label = labelFormatter(tick, i);
  32148. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  32149. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  32150. rect ? rect.union(singleRect) : rect = singleRect;
  32151. }
  32152. return rect;
  32153. }
  32154. function rotateTextRect(textRect, rotate) {
  32155. var rotateRadians = rotate * Math.PI / 180;
  32156. var beforeWidth = textRect.width;
  32157. var beforeHeight = textRect.height;
  32158. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  32159. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  32160. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  32161. return rotatedRect;
  32162. }
  32163. /**
  32164. * @param model axisLabelModel or axisTickModel
  32165. * @return {number|String} Can be null|'auto'|number|function
  32166. */
  32167. function getOptionCategoryInterval(model) {
  32168. var interval = model.get('interval');
  32169. return interval == null ? 'auto' : interval;
  32170. }
  32171. /**
  32172. * Set `categoryInterval` as 0 implicitly indicates that
  32173. * show all labels regardless of overlap.
  32174. * @param {Object} axis axisModel.axis
  32175. */
  32176. function shouldShowAllLabels(axis) {
  32177. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  32178. }
  32179. function getDataDimensionsOnAxis(data, axisDim) {
  32180. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  32181. var dataDimMap = {};
  32182. // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  32183. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  32184. // there has been stacked result dim?
  32185. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  32186. // For example, the extent of the original dimension
  32187. // is [0.1, 0.5], the extent of the `stackResultDimension`
  32188. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  32189. // because there is no graphic corresponding to [0.1, 0.5].
  32190. // See the case in `test/area-stack.html` `main1`, where area line
  32191. // stack needs `yAxis` not start from 0.
  32192. dataDimMap[getStackedDimension(data, dataDim)] = true;
  32193. });
  32194. return keys(dataDimMap);
  32195. }
  32196. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  32197. if (data) {
  32198. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  32199. var seriesExtent = data.getApproximateExtent(dim);
  32200. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  32201. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  32202. });
  32203. }
  32204. }
  32205. /*
  32206. * Licensed to the Apache Software Foundation (ASF) under one
  32207. * or more contributor license agreements. See the NOTICE file
  32208. * distributed with this work for additional information
  32209. * regarding copyright ownership. The ASF licenses this file
  32210. * to you under the Apache License, Version 2.0 (the
  32211. * "License"); you may not use this file except in compliance
  32212. * with the License. You may obtain a copy of the License at
  32213. *
  32214. * http://www.apache.org/licenses/LICENSE-2.0
  32215. *
  32216. * Unless required by applicable law or agreed to in writing,
  32217. * software distributed under the License is distributed on an
  32218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32219. * KIND, either express or implied. See the License for the
  32220. * specific language governing permissions and limitations
  32221. * under the License.
  32222. */
  32223. /**
  32224. * AUTO-GENERATED FILE. DO NOT MODIFY.
  32225. */
  32226. /*
  32227. * Licensed to the Apache Software Foundation (ASF) under one
  32228. * or more contributor license agreements. See the NOTICE file
  32229. * distributed with this work for additional information
  32230. * regarding copyright ownership. The ASF licenses this file
  32231. * to you under the Apache License, Version 2.0 (the
  32232. * "License"); you may not use this file except in compliance
  32233. * with the License. You may obtain a copy of the License at
  32234. *
  32235. * http://www.apache.org/licenses/LICENSE-2.0
  32236. *
  32237. * Unless required by applicable law or agreed to in writing,
  32238. * software distributed under the License is distributed on an
  32239. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32240. * KIND, either express or implied. See the License for the
  32241. * specific language governing permissions and limitations
  32242. * under the License.
  32243. */
  32244. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  32245. var AxisModelCommonMixin = /** @class */function () {
  32246. function AxisModelCommonMixin() {}
  32247. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  32248. var option = this.option;
  32249. return !option.scale;
  32250. };
  32251. /**
  32252. * Should be implemented by each axis model if necessary.
  32253. * @return coordinate system model
  32254. */
  32255. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  32256. return;
  32257. };
  32258. return AxisModelCommonMixin;
  32259. }();
  32260. /**
  32261. * Create a multi dimension List structure from seriesModel.
  32262. */
  32263. function createList(seriesModel) {
  32264. return createSeriesData(null, seriesModel);
  32265. }
  32266. var dataStack$1 = {
  32267. isDimensionStacked: isDimensionStacked,
  32268. enableDataStack: enableDataStack,
  32269. getStackedDimension: getStackedDimension
  32270. };
  32271. /**
  32272. * Create scale
  32273. * @param {Array.<number>} dataExtent
  32274. * @param {Object|module:echarts/Model} option If `optoin.type`
  32275. * is secified, it can only be `'value'` currently.
  32276. */
  32277. function createScale(dataExtent, option) {
  32278. var axisModel = option;
  32279. if (!(option instanceof Model)) {
  32280. axisModel = new Model(option);
  32281. // FIXME
  32282. // Currently AxisModelCommonMixin has nothing to do with the
  32283. // the requirements of `axisHelper.createScaleByModel`. For
  32284. // example the methods `getCategories` and `getOrdinalMeta`
  32285. // are required for `'category'` axis, and ecModel is required
  32286. // for `'time'` axis. But occasionally echarts-gl happened
  32287. // to only use `'value'` axis.
  32288. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  32289. }
  32290. var scale = createScaleByModel(axisModel);
  32291. scale.setExtent(dataExtent[0], dataExtent[1]);
  32292. niceScaleExtent(scale, axisModel);
  32293. return scale;
  32294. }
  32295. /**
  32296. * Mixin common methods to axis model,
  32297. *
  32298. * Include methods
  32299. * `getFormattedLabels() => Array.<string>`
  32300. * `getCategories() => Array.<string>`
  32301. * `getMin(origin: boolean) => number`
  32302. * `getMax(origin: boolean) => number`
  32303. * `getNeedCrossZero() => boolean`
  32304. */
  32305. function mixinAxisModelCommonMethods(Model) {
  32306. mixin(Model, AxisModelCommonMixin);
  32307. }
  32308. function createTextStyle$1(textStyleModel, opts) {
  32309. opts = opts || {};
  32310. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  32311. }
  32312. var helper = /*#__PURE__*/Object.freeze({
  32313. __proto__: null,
  32314. createList: createList,
  32315. getLayoutRect: getLayoutRect,
  32316. dataStack: dataStack$1,
  32317. createScale: createScale,
  32318. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  32319. getECData: getECData,
  32320. createTextStyle: createTextStyle$1,
  32321. createDimensions: createDimensions,
  32322. createSymbol: createSymbol,
  32323. enableHoverEmphasis: enableHoverEmphasis
  32324. });
  32325. var EPSILON$4 = 1e-8;
  32326. function isAroundEqual$1(a, b) {
  32327. return Math.abs(a - b) < EPSILON$4;
  32328. }
  32329. function contain$2(points, x, y) {
  32330. var w = 0;
  32331. var p = points[0];
  32332. if (!p) {
  32333. return false;
  32334. }
  32335. for (var i = 1; i < points.length; i++) {
  32336. var p2 = points[i];
  32337. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  32338. p = p2;
  32339. }
  32340. var p0 = points[0];
  32341. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  32342. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  32343. }
  32344. return w !== 0;
  32345. }
  32346. var TMP_TRANSFORM = [];
  32347. function transformPoints(points, transform) {
  32348. for (var p = 0; p < points.length; p++) {
  32349. applyTransform(points[p], points[p], transform);
  32350. }
  32351. }
  32352. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  32353. for (var i = 0; i < points.length; i++) {
  32354. var p = points[i];
  32355. if (projection) {
  32356. // projection may return null point.
  32357. p = projection.project(p);
  32358. }
  32359. if (p && isFinite(p[0]) && isFinite(p[1])) {
  32360. min(min$1, min$1, p);
  32361. max(max$1, max$1, p);
  32362. }
  32363. }
  32364. }
  32365. function centroid(points) {
  32366. var signedArea = 0;
  32367. var cx = 0;
  32368. var cy = 0;
  32369. var len = points.length;
  32370. var x0 = points[len - 1][0];
  32371. var y0 = points[len - 1][1];
  32372. // Polygon should been closed.
  32373. for (var i = 0; i < len; i++) {
  32374. var x1 = points[i][0];
  32375. var y1 = points[i][1];
  32376. var a = x0 * y1 - x1 * y0;
  32377. signedArea += a;
  32378. cx += (x0 + x1) * a;
  32379. cy += (y0 + y1) * a;
  32380. x0 = x1;
  32381. y0 = y1;
  32382. }
  32383. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  32384. }
  32385. var Region = /** @class */function () {
  32386. function Region(name) {
  32387. this.name = name;
  32388. }
  32389. Region.prototype.setCenter = function (center) {
  32390. this._center = center;
  32391. };
  32392. /**
  32393. * Get center point in data unit. That is,
  32394. * for GeoJSONRegion, the unit is lat/lng,
  32395. * for GeoSVGRegion, the unit is SVG local coord.
  32396. */
  32397. Region.prototype.getCenter = function () {
  32398. var center = this._center;
  32399. if (!center) {
  32400. // In most cases there are no need to calculate this center.
  32401. // So calculate only when called.
  32402. center = this._center = this.calcCenter();
  32403. }
  32404. return center;
  32405. };
  32406. return Region;
  32407. }();
  32408. var GeoJSONPolygonGeometry = /** @class */function () {
  32409. function GeoJSONPolygonGeometry(exterior, interiors) {
  32410. this.type = 'polygon';
  32411. this.exterior = exterior;
  32412. this.interiors = interiors;
  32413. }
  32414. return GeoJSONPolygonGeometry;
  32415. }();
  32416. var GeoJSONLineStringGeometry = /** @class */function () {
  32417. function GeoJSONLineStringGeometry(points) {
  32418. this.type = 'linestring';
  32419. this.points = points;
  32420. }
  32421. return GeoJSONLineStringGeometry;
  32422. }();
  32423. var GeoJSONRegion = /** @class */function (_super) {
  32424. __extends(GeoJSONRegion, _super);
  32425. function GeoJSONRegion(name, geometries, cp) {
  32426. var _this = _super.call(this, name) || this;
  32427. _this.type = 'geoJSON';
  32428. _this.geometries = geometries;
  32429. _this._center = cp && [cp[0], cp[1]];
  32430. return _this;
  32431. }
  32432. GeoJSONRegion.prototype.calcCenter = function () {
  32433. var geometries = this.geometries;
  32434. var largestGeo;
  32435. var largestGeoSize = 0;
  32436. for (var i = 0; i < geometries.length; i++) {
  32437. var geo = geometries[i];
  32438. var exterior = geo.exterior;
  32439. // Simple trick to use points count instead of polygon area as region size.
  32440. // Ignore linestring
  32441. var size = exterior && exterior.length;
  32442. if (size > largestGeoSize) {
  32443. largestGeo = geo;
  32444. largestGeoSize = size;
  32445. }
  32446. }
  32447. if (largestGeo) {
  32448. return centroid(largestGeo.exterior);
  32449. }
  32450. // from bounding rect by default.
  32451. var rect = this.getBoundingRect();
  32452. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32453. };
  32454. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  32455. var rect = this._rect;
  32456. // Always recalculate if using projection.
  32457. if (rect && !projection) {
  32458. return rect;
  32459. }
  32460. var min = [Infinity, Infinity];
  32461. var max = [-Infinity, -Infinity];
  32462. var geometries = this.geometries;
  32463. each(geometries, function (geo) {
  32464. if (geo.type === 'polygon') {
  32465. // Doesn't consider hole
  32466. updateBBoxFromPoints(geo.exterior, min, max, projection);
  32467. } else {
  32468. each(geo.points, function (points) {
  32469. updateBBoxFromPoints(points, min, max, projection);
  32470. });
  32471. }
  32472. });
  32473. // Normalie invalid bounding.
  32474. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  32475. min[0] = min[1] = max[0] = max[1] = 0;
  32476. }
  32477. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  32478. if (!projection) {
  32479. this._rect = rect;
  32480. }
  32481. return rect;
  32482. };
  32483. GeoJSONRegion.prototype.contain = function (coord) {
  32484. var rect = this.getBoundingRect();
  32485. var geometries = this.geometries;
  32486. if (!rect.contain(coord[0], coord[1])) {
  32487. return false;
  32488. }
  32489. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  32490. var geo = geometries[i];
  32491. // Only support polygon.
  32492. if (geo.type !== 'polygon') {
  32493. continue;
  32494. }
  32495. var exterior = geo.exterior;
  32496. var interiors = geo.interiors;
  32497. if (contain$2(exterior, coord[0], coord[1])) {
  32498. // Not in the region if point is in the hole.
  32499. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  32500. if (contain$2(interiors[k], coord[0], coord[1])) {
  32501. continue loopGeo;
  32502. }
  32503. }
  32504. return true;
  32505. }
  32506. }
  32507. return false;
  32508. };
  32509. /**
  32510. * Transform the raw coords to target bounding.
  32511. * @param x
  32512. * @param y
  32513. * @param width
  32514. * @param height
  32515. */
  32516. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  32517. var rect = this.getBoundingRect();
  32518. var aspect = rect.width / rect.height;
  32519. if (!width) {
  32520. width = aspect * height;
  32521. } else if (!height) {
  32522. height = width / aspect;
  32523. }
  32524. var target = new BoundingRect(x, y, width, height);
  32525. var transform = rect.calculateTransform(target);
  32526. var geometries = this.geometries;
  32527. for (var i = 0; i < geometries.length; i++) {
  32528. var geo = geometries[i];
  32529. if (geo.type === 'polygon') {
  32530. transformPoints(geo.exterior, transform);
  32531. each(geo.interiors, function (interior) {
  32532. transformPoints(interior, transform);
  32533. });
  32534. } else {
  32535. each(geo.points, function (points) {
  32536. transformPoints(points, transform);
  32537. });
  32538. }
  32539. }
  32540. rect = this._rect;
  32541. rect.copy(target);
  32542. // Update center
  32543. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32544. };
  32545. GeoJSONRegion.prototype.cloneShallow = function (name) {
  32546. name == null && (name = this.name);
  32547. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  32548. newRegion._rect = this._rect;
  32549. newRegion.transformTo = null; // Simply avoid to be called.
  32550. return newRegion;
  32551. };
  32552. return GeoJSONRegion;
  32553. }(Region);
  32554. var GeoSVGRegion = /** @class */function (_super) {
  32555. __extends(GeoSVGRegion, _super);
  32556. function GeoSVGRegion(name, elOnlyForCalculate) {
  32557. var _this = _super.call(this, name) || this;
  32558. _this.type = 'geoSVG';
  32559. _this._elOnlyForCalculate = elOnlyForCalculate;
  32560. return _this;
  32561. }
  32562. GeoSVGRegion.prototype.calcCenter = function () {
  32563. var el = this._elOnlyForCalculate;
  32564. var rect = el.getBoundingRect();
  32565. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32566. var mat = identity(TMP_TRANSFORM);
  32567. var target = el;
  32568. while (target && !target.isGeoSVGGraphicRoot) {
  32569. mul$1(mat, target.getLocalTransform(), mat);
  32570. target = target.parent;
  32571. }
  32572. invert(mat, mat);
  32573. applyTransform(center, center, mat);
  32574. return center;
  32575. };
  32576. return GeoSVGRegion;
  32577. }(Region);
  32578. function decode(json) {
  32579. if (!json.UTF8Encoding) {
  32580. return json;
  32581. }
  32582. var jsonCompressed = json;
  32583. var encodeScale = jsonCompressed.UTF8Scale;
  32584. if (encodeScale == null) {
  32585. encodeScale = 1024;
  32586. }
  32587. var features = jsonCompressed.features;
  32588. each(features, function (feature) {
  32589. var geometry = feature.geometry;
  32590. var encodeOffsets = geometry.encodeOffsets;
  32591. var coordinates = geometry.coordinates;
  32592. // Geometry may be appeded manually in the script after json loaded.
  32593. // In this case this geometry is usually not encoded.
  32594. if (!encodeOffsets) {
  32595. return;
  32596. }
  32597. switch (geometry.type) {
  32598. case 'LineString':
  32599. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  32600. break;
  32601. case 'Polygon':
  32602. decodeRings(coordinates, encodeOffsets, encodeScale);
  32603. break;
  32604. case 'MultiLineString':
  32605. decodeRings(coordinates, encodeOffsets, encodeScale);
  32606. break;
  32607. case 'MultiPolygon':
  32608. each(coordinates, function (rings, idx) {
  32609. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  32610. });
  32611. }
  32612. });
  32613. // Has been decoded
  32614. jsonCompressed.UTF8Encoding = false;
  32615. return jsonCompressed;
  32616. }
  32617. function decodeRings(rings, encodeOffsets, encodeScale) {
  32618. for (var c = 0; c < rings.length; c++) {
  32619. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  32620. }
  32621. }
  32622. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  32623. var result = [];
  32624. var prevX = encodeOffsets[0];
  32625. var prevY = encodeOffsets[1];
  32626. for (var i = 0; i < coordinate.length; i += 2) {
  32627. var x = coordinate.charCodeAt(i) - 64;
  32628. var y = coordinate.charCodeAt(i + 1) - 64;
  32629. // ZigZag decoding
  32630. x = x >> 1 ^ -(x & 1);
  32631. y = y >> 1 ^ -(y & 1);
  32632. // Delta deocding
  32633. x += prevX;
  32634. y += prevY;
  32635. prevX = x;
  32636. prevY = y;
  32637. // Dequantize
  32638. result.push([x / encodeScale, y / encodeScale]);
  32639. }
  32640. return result;
  32641. }
  32642. function parseGeoJSON(geoJson, nameProperty) {
  32643. geoJson = decode(geoJson);
  32644. return map(filter(geoJson.features, function (featureObj) {
  32645. // Output of mapshaper may have geometry null
  32646. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  32647. }), function (featureObj) {
  32648. var properties = featureObj.properties;
  32649. var geo = featureObj.geometry;
  32650. var geometries = [];
  32651. switch (geo.type) {
  32652. case 'Polygon':
  32653. var coordinates = geo.coordinates;
  32654. // According to the GeoJSON specification.
  32655. // First must be exterior, and the rest are all interior(holes).
  32656. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  32657. break;
  32658. case 'MultiPolygon':
  32659. each(geo.coordinates, function (item) {
  32660. if (item[0]) {
  32661. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  32662. }
  32663. });
  32664. break;
  32665. case 'LineString':
  32666. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  32667. break;
  32668. case 'MultiLineString':
  32669. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  32670. }
  32671. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  32672. region.properties = properties;
  32673. return region;
  32674. });
  32675. }
  32676. var number = /*#__PURE__*/Object.freeze({
  32677. __proto__: null,
  32678. linearMap: linearMap,
  32679. round: round,
  32680. asc: asc,
  32681. getPrecision: getPrecision,
  32682. getPrecisionSafe: getPrecisionSafe,
  32683. getPixelPrecision: getPixelPrecision,
  32684. getPercentWithPrecision: getPercentWithPrecision,
  32685. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  32686. remRadian: remRadian,
  32687. isRadianAroundZero: isRadianAroundZero,
  32688. parseDate: parseDate,
  32689. quantity: quantity,
  32690. quantityExponent: quantityExponent,
  32691. nice: nice,
  32692. quantile: quantile,
  32693. reformIntervals: reformIntervals,
  32694. isNumeric: isNumeric,
  32695. numericToNumber: numericToNumber
  32696. });
  32697. var time = /*#__PURE__*/Object.freeze({
  32698. __proto__: null,
  32699. parse: parseDate,
  32700. format: format
  32701. });
  32702. var graphic$1 = /*#__PURE__*/Object.freeze({
  32703. __proto__: null,
  32704. extendShape: extendShape,
  32705. extendPath: extendPath,
  32706. makePath: makePath,
  32707. makeImage: makeImage,
  32708. mergePath: mergePath$1,
  32709. resizePath: resizePath,
  32710. createIcon: createIcon,
  32711. updateProps: updateProps,
  32712. initProps: initProps,
  32713. getTransform: getTransform,
  32714. clipPointsByRect: clipPointsByRect,
  32715. clipRectByRect: clipRectByRect,
  32716. registerShape: registerShape,
  32717. getShapeClass: getShapeClass,
  32718. Group: Group,
  32719. Image: ZRImage,
  32720. Text: ZRText,
  32721. Circle: Circle,
  32722. Ellipse: Ellipse,
  32723. Sector: Sector,
  32724. Ring: Ring,
  32725. Polygon: Polygon,
  32726. Polyline: Polyline,
  32727. Rect: Rect,
  32728. Line: Line,
  32729. BezierCurve: BezierCurve,
  32730. Arc: Arc,
  32731. IncrementalDisplayable: IncrementalDisplayable,
  32732. CompoundPath: CompoundPath,
  32733. LinearGradient: LinearGradient,
  32734. RadialGradient: RadialGradient,
  32735. BoundingRect: BoundingRect
  32736. });
  32737. var format$1 = /*#__PURE__*/Object.freeze({
  32738. __proto__: null,
  32739. addCommas: addCommas,
  32740. toCamelCase: toCamelCase,
  32741. normalizeCssArray: normalizeCssArray$1,
  32742. encodeHTML: encodeHTML,
  32743. formatTpl: formatTpl,
  32744. getTooltipMarker: getTooltipMarker,
  32745. formatTime: formatTime,
  32746. capitalFirst: capitalFirst,
  32747. truncateText: truncateText,
  32748. getTextRect: getTextRect
  32749. });
  32750. var util$1 = /*#__PURE__*/Object.freeze({
  32751. __proto__: null,
  32752. map: map,
  32753. each: each,
  32754. indexOf: indexOf,
  32755. inherits: inherits,
  32756. reduce: reduce,
  32757. filter: filter,
  32758. bind: bind,
  32759. curry: curry,
  32760. isArray: isArray,
  32761. isString: isString,
  32762. isObject: isObject,
  32763. isFunction: isFunction,
  32764. extend: extend,
  32765. defaults: defaults,
  32766. clone: clone,
  32767. merge: merge
  32768. });
  32769. var inner$5 = makeInner();
  32770. function tickValuesToNumbers(axis, values) {
  32771. var nums = map(values, function (val) {
  32772. return axis.scale.parse(val);
  32773. });
  32774. if (axis.type === 'time' && nums.length > 0) {
  32775. // Time axis needs duplicate first/last tick (see TimeScale.getTicks())
  32776. // The first and last tick/label don't get drawn
  32777. nums.sort();
  32778. nums.unshift(nums[0]);
  32779. nums.push(nums[nums.length - 1]);
  32780. }
  32781. return nums;
  32782. }
  32783. function createAxisLabels(axis) {
  32784. var custom = axis.getLabelModel().get('customValues');
  32785. if (custom) {
  32786. var labelFormatter_1 = makeLabelFormatter(axis);
  32787. return {
  32788. labels: tickValuesToNumbers(axis, custom).map(function (numval) {
  32789. var tick = {
  32790. value: numval
  32791. };
  32792. return {
  32793. formattedLabel: labelFormatter_1(tick),
  32794. rawLabel: axis.scale.getLabel(tick),
  32795. tickValue: numval
  32796. };
  32797. })
  32798. };
  32799. }
  32800. // Only ordinal scale support tick interval
  32801. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  32802. }
  32803. /**
  32804. * @param {module:echats/coord/Axis} axis
  32805. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  32806. * @return {Object} {
  32807. * ticks: Array.<number>
  32808. * tickCategoryInterval: number
  32809. * }
  32810. */
  32811. function createAxisTicks(axis, tickModel) {
  32812. var custom = axis.getTickModel().get('customValues');
  32813. if (custom) {
  32814. return {
  32815. ticks: tickValuesToNumbers(axis, custom)
  32816. };
  32817. }
  32818. // Only ordinal scale support tick interval
  32819. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  32820. ticks: map(axis.scale.getTicks(), function (tick) {
  32821. return tick.value;
  32822. })
  32823. };
  32824. }
  32825. function makeCategoryLabels(axis) {
  32826. var labelModel = axis.getLabelModel();
  32827. var result = makeCategoryLabelsActually(axis, labelModel);
  32828. return !labelModel.get('show') || axis.scale.isBlank() ? {
  32829. labels: [],
  32830. labelCategoryInterval: result.labelCategoryInterval
  32831. } : result;
  32832. }
  32833. function makeCategoryLabelsActually(axis, labelModel) {
  32834. var labelsCache = getListCache(axis, 'labels');
  32835. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  32836. var result = listCacheGet(labelsCache, optionLabelInterval);
  32837. if (result) {
  32838. return result;
  32839. }
  32840. var labels;
  32841. var numericLabelInterval;
  32842. if (isFunction(optionLabelInterval)) {
  32843. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32844. } else {
  32845. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32846. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32847. }
  32848. // Cache to avoid calling interval function repeatedly.
  32849. return listCacheSet(labelsCache, optionLabelInterval, {
  32850. labels: labels,
  32851. labelCategoryInterval: numericLabelInterval
  32852. });
  32853. }
  32854. function makeCategoryTicks(axis, tickModel) {
  32855. var ticksCache = getListCache(axis, 'ticks');
  32856. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32857. var result = listCacheGet(ticksCache, optionTickInterval);
  32858. if (result) {
  32859. return result;
  32860. }
  32861. var ticks;
  32862. var tickCategoryInterval;
  32863. // Optimize for the case that large category data and no label displayed,
  32864. // we should not return all ticks.
  32865. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32866. ticks = [];
  32867. }
  32868. if (isFunction(optionTickInterval)) {
  32869. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32870. }
  32871. // Always use label interval by default despite label show. Consider this
  32872. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32873. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32874. else if (optionTickInterval === 'auto') {
  32875. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32876. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32877. ticks = map(labelsResult.labels, function (labelItem) {
  32878. return labelItem.tickValue;
  32879. });
  32880. } else {
  32881. tickCategoryInterval = optionTickInterval;
  32882. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32883. }
  32884. // Cache to avoid calling interval function repeatedly.
  32885. return listCacheSet(ticksCache, optionTickInterval, {
  32886. ticks: ticks,
  32887. tickCategoryInterval: tickCategoryInterval
  32888. });
  32889. }
  32890. function makeRealNumberLabels(axis) {
  32891. var ticks = axis.scale.getTicks();
  32892. var labelFormatter = makeLabelFormatter(axis);
  32893. return {
  32894. labels: map(ticks, function (tick, idx) {
  32895. return {
  32896. level: tick.level,
  32897. formattedLabel: labelFormatter(tick, idx),
  32898. rawLabel: axis.scale.getLabel(tick),
  32899. tickValue: tick.value
  32900. };
  32901. })
  32902. };
  32903. }
  32904. function getListCache(axis, prop) {
  32905. // Because key can be a function, and cache size always is small, we use array cache.
  32906. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  32907. }
  32908. function listCacheGet(cache, key) {
  32909. for (var i = 0; i < cache.length; i++) {
  32910. if (cache[i].key === key) {
  32911. return cache[i].value;
  32912. }
  32913. }
  32914. }
  32915. function listCacheSet(cache, key, value) {
  32916. cache.push({
  32917. key: key,
  32918. value: value
  32919. });
  32920. return value;
  32921. }
  32922. function makeAutoCategoryInterval(axis) {
  32923. var result = inner$5(axis).autoInterval;
  32924. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32925. }
  32926. /**
  32927. * Calculate interval for category axis ticks and labels.
  32928. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32929. * should be implemented in axis.
  32930. */
  32931. function calculateCategoryInterval(axis) {
  32932. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32933. var labelFormatter = makeLabelFormatter(axis);
  32934. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32935. var ordinalScale = axis.scale;
  32936. var ordinalExtent = ordinalScale.getExtent();
  32937. // Providing this method is for optimization:
  32938. // avoid generating a long array by `getTicks`
  32939. // in large category data case.
  32940. var tickCount = ordinalScale.count();
  32941. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32942. return 0;
  32943. }
  32944. var step = 1;
  32945. // Simple optimization. Empirical value: tick count should less than 40.
  32946. if (tickCount > 40) {
  32947. step = Math.max(1, Math.floor(tickCount / 40));
  32948. }
  32949. var tickValue = ordinalExtent[0];
  32950. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32951. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32952. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32953. var maxW = 0;
  32954. var maxH = 0;
  32955. // Caution: Performance sensitive for large category data.
  32956. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32957. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32958. var width = 0;
  32959. var height = 0;
  32960. // Not precise, do not consider align and vertical align
  32961. // and each distance from axis line yet.
  32962. var rect = getBoundingRect(labelFormatter({
  32963. value: tickValue
  32964. }), params.font, 'center', 'top');
  32965. // Magic number
  32966. width = rect.width * 1.3;
  32967. height = rect.height * 1.3;
  32968. // Min size, void long loop.
  32969. maxW = Math.max(maxW, width, 7);
  32970. maxH = Math.max(maxH, height, 7);
  32971. }
  32972. var dw = maxW / unitW;
  32973. var dh = maxH / unitH;
  32974. // 0/0 is NaN, 1/0 is Infinity.
  32975. isNaN(dw) && (dw = Infinity);
  32976. isNaN(dh) && (dh = Infinity);
  32977. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32978. var cache = inner$5(axis.model);
  32979. var axisExtent = axis.getExtent();
  32980. var lastAutoInterval = cache.lastAutoInterval;
  32981. var lastTickCount = cache.lastTickCount;
  32982. // Use cache to keep interval stable while moving zoom window,
  32983. // otherwise the calculated interval might jitter when the zoom
  32984. // window size is close to the interval-changing size.
  32985. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32986. // The jitter will cause that sometimes the displayed labels are
  32987. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32988. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1
  32989. // Always choose the bigger one, otherwise the critical
  32990. // point is not the same when zooming in or zooming out.
  32991. && lastAutoInterval > interval
  32992. // If the axis change is caused by chart resize, the cache should not
  32993. // be used. Otherwise some hidden labels might not be shown again.
  32994. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32995. interval = lastAutoInterval;
  32996. }
  32997. // Only update cache if cache not used, otherwise the
  32998. // changing of interval is too insensitive.
  32999. else {
  33000. cache.lastTickCount = tickCount;
  33001. cache.lastAutoInterval = interval;
  33002. cache.axisExtent0 = axisExtent[0];
  33003. cache.axisExtent1 = axisExtent[1];
  33004. }
  33005. return interval;
  33006. }
  33007. function fetchAutoCategoryIntervalCalculationParams(axis) {
  33008. var labelModel = axis.getLabelModel();
  33009. return {
  33010. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  33011. labelRotate: labelModel.get('rotate') || 0,
  33012. font: labelModel.getFont()
  33013. };
  33014. }
  33015. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  33016. var labelFormatter = makeLabelFormatter(axis);
  33017. var ordinalScale = axis.scale;
  33018. var ordinalExtent = ordinalScale.getExtent();
  33019. var labelModel = axis.getLabelModel();
  33020. var result = [];
  33021. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  33022. var step = Math.max((categoryInterval || 0) + 1, 1);
  33023. var startTick = ordinalExtent[0];
  33024. var tickCount = ordinalScale.count();
  33025. // Calculate start tick based on zero if possible to keep label consistent
  33026. // while zooming and moving while interval > 0. Otherwise the selection
  33027. // of displayable ticks and symbols probably keep changing.
  33028. // 3 is empirical value.
  33029. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  33030. startTick = Math.round(Math.ceil(startTick / step) * step);
  33031. }
  33032. // (1) Only add min max label here but leave overlap checking
  33033. // to render stage, which also ensure the returned list
  33034. // suitable for splitLine and splitArea rendering.
  33035. // (2) Scales except category always contain min max label so
  33036. // do not need to perform this process.
  33037. var showAllLabel = shouldShowAllLabels(axis);
  33038. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  33039. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  33040. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  33041. addItem(ordinalExtent[0]);
  33042. }
  33043. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  33044. var tickValue = startTick;
  33045. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33046. addItem(tickValue);
  33047. }
  33048. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  33049. addItem(ordinalExtent[1]);
  33050. }
  33051. function addItem(tickValue) {
  33052. var tickObj = {
  33053. value: tickValue
  33054. };
  33055. result.push(onlyTick ? tickValue : {
  33056. formattedLabel: labelFormatter(tickObj),
  33057. rawLabel: ordinalScale.getLabel(tickObj),
  33058. tickValue: tickValue
  33059. });
  33060. }
  33061. return result;
  33062. }
  33063. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  33064. var ordinalScale = axis.scale;
  33065. var labelFormatter = makeLabelFormatter(axis);
  33066. var result = [];
  33067. each(ordinalScale.getTicks(), function (tick) {
  33068. var rawLabel = ordinalScale.getLabel(tick);
  33069. var tickValue = tick.value;
  33070. if (categoryInterval(tick.value, rawLabel)) {
  33071. result.push(onlyTick ? tickValue : {
  33072. formattedLabel: labelFormatter(tick),
  33073. rawLabel: rawLabel,
  33074. tickValue: tickValue
  33075. });
  33076. }
  33077. });
  33078. return result;
  33079. }
  33080. var NORMALIZED_EXTENT = [0, 1];
  33081. /**
  33082. * Base class of Axis.
  33083. */
  33084. var Axis = /** @class */function () {
  33085. function Axis(dim, scale, extent) {
  33086. this.onBand = false;
  33087. this.inverse = false;
  33088. this.dim = dim;
  33089. this.scale = scale;
  33090. this._extent = extent || [0, 0];
  33091. }
  33092. /**
  33093. * If axis extent contain given coord
  33094. */
  33095. Axis.prototype.contain = function (coord) {
  33096. var extent = this._extent;
  33097. var min = Math.min(extent[0], extent[1]);
  33098. var max = Math.max(extent[0], extent[1]);
  33099. return coord >= min && coord <= max;
  33100. };
  33101. /**
  33102. * If axis extent contain given data
  33103. */
  33104. Axis.prototype.containData = function (data) {
  33105. return this.scale.contain(data);
  33106. };
  33107. /**
  33108. * Get coord extent.
  33109. */
  33110. Axis.prototype.getExtent = function () {
  33111. return this._extent.slice();
  33112. };
  33113. /**
  33114. * Get precision used for formatting
  33115. */
  33116. Axis.prototype.getPixelPrecision = function (dataExtent) {
  33117. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  33118. };
  33119. /**
  33120. * Set coord extent
  33121. */
  33122. Axis.prototype.setExtent = function (start, end) {
  33123. var extent = this._extent;
  33124. extent[0] = start;
  33125. extent[1] = end;
  33126. };
  33127. /**
  33128. * Convert data to coord. Data is the rank if it has an ordinal scale
  33129. */
  33130. Axis.prototype.dataToCoord = function (data, clamp) {
  33131. var extent = this._extent;
  33132. var scale = this.scale;
  33133. data = scale.normalize(data);
  33134. if (this.onBand && scale.type === 'ordinal') {
  33135. extent = extent.slice();
  33136. fixExtentWithBands(extent, scale.count());
  33137. }
  33138. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  33139. };
  33140. /**
  33141. * Convert coord to data. Data is the rank if it has an ordinal scale
  33142. */
  33143. Axis.prototype.coordToData = function (coord, clamp) {
  33144. var extent = this._extent;
  33145. var scale = this.scale;
  33146. if (this.onBand && scale.type === 'ordinal') {
  33147. extent = extent.slice();
  33148. fixExtentWithBands(extent, scale.count());
  33149. }
  33150. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  33151. return this.scale.scale(t);
  33152. };
  33153. /**
  33154. * Convert pixel point to data in axis
  33155. */
  33156. Axis.prototype.pointToData = function (point, clamp) {
  33157. // Should be implemented in derived class if necessary.
  33158. return;
  33159. };
  33160. /**
  33161. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  33162. * `axis.getTicksCoords` considers `onBand`, which is used by
  33163. * `boundaryGap:true` of category axis and splitLine and splitArea.
  33164. * @param opt.tickModel default: axis.model.getModel('axisTick')
  33165. * @param opt.clamp If `true`, the first and the last
  33166. * tick must be at the axis end points. Otherwise, clip ticks
  33167. * that outside the axis extent.
  33168. */
  33169. Axis.prototype.getTicksCoords = function (opt) {
  33170. opt = opt || {};
  33171. var tickModel = opt.tickModel || this.getTickModel();
  33172. var result = createAxisTicks(this, tickModel);
  33173. var ticks = result.ticks;
  33174. var ticksCoords = map(ticks, function (tickVal) {
  33175. return {
  33176. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  33177. tickValue: tickVal
  33178. };
  33179. }, this);
  33180. var alignWithLabel = tickModel.get('alignWithLabel');
  33181. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  33182. return ticksCoords;
  33183. };
  33184. Axis.prototype.getMinorTicksCoords = function () {
  33185. if (this.scale.type === 'ordinal') {
  33186. // Category axis doesn't support minor ticks
  33187. return [];
  33188. }
  33189. var minorTickModel = this.model.getModel('minorTick');
  33190. var splitNumber = minorTickModel.get('splitNumber');
  33191. // Protection.
  33192. if (!(splitNumber > 0 && splitNumber < 100)) {
  33193. splitNumber = 5;
  33194. }
  33195. var minorTicks = this.scale.getMinorTicks(splitNumber);
  33196. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  33197. return map(minorTicksGroup, function (minorTick) {
  33198. return {
  33199. coord: this.dataToCoord(minorTick),
  33200. tickValue: minorTick
  33201. };
  33202. }, this);
  33203. }, this);
  33204. return minorTicksCoords;
  33205. };
  33206. Axis.prototype.getViewLabels = function () {
  33207. return createAxisLabels(this).labels;
  33208. };
  33209. Axis.prototype.getLabelModel = function () {
  33210. return this.model.getModel('axisLabel');
  33211. };
  33212. /**
  33213. * Notice here we only get the default tick model. For splitLine
  33214. * or splitArea, we should pass the splitLineModel or splitAreaModel
  33215. * manually when calling `getTicksCoords`.
  33216. * In GL, this method may be overridden to:
  33217. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  33218. */
  33219. Axis.prototype.getTickModel = function () {
  33220. return this.model.getModel('axisTick');
  33221. };
  33222. /**
  33223. * Get width of band
  33224. */
  33225. Axis.prototype.getBandWidth = function () {
  33226. var axisExtent = this._extent;
  33227. var dataExtent = this.scale.getExtent();
  33228. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  33229. // Fix #2728, avoid NaN when only one data.
  33230. len === 0 && (len = 1);
  33231. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  33232. return Math.abs(size) / len;
  33233. };
  33234. /**
  33235. * Only be called in category axis.
  33236. * Can be overridden, consider other axes like in 3D.
  33237. * @return Auto interval for cateogry axis tick and label
  33238. */
  33239. Axis.prototype.calculateCategoryInterval = function () {
  33240. return calculateCategoryInterval(this);
  33241. };
  33242. return Axis;
  33243. }();
  33244. function fixExtentWithBands(extent, nTick) {
  33245. var size = extent[1] - extent[0];
  33246. var len = nTick;
  33247. var margin = size / len / 2;
  33248. extent[0] += margin;
  33249. extent[1] -= margin;
  33250. }
  33251. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  33252. // |---1---|---2---|---3---|---4---|.
  33253. // So the displayed ticks and splitLine/splitArea should between
  33254. // each data item, otherwise cause misleading (e.g., split tow bars
  33255. // of a single data item when there are two bar series).
  33256. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  33257. // splitLine/spliteArea should layout appropriately corresponding
  33258. // to displayed labels. (So we should not use `getBandWidth` in this
  33259. // case).
  33260. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  33261. var ticksLen = ticksCoords.length;
  33262. if (!axis.onBand || alignWithLabel || !ticksLen) {
  33263. return;
  33264. }
  33265. var axisExtent = axis.getExtent();
  33266. var last;
  33267. var diffSize;
  33268. if (ticksLen === 1) {
  33269. ticksCoords[0].coord = axisExtent[0];
  33270. last = ticksCoords[1] = {
  33271. coord: axisExtent[1]
  33272. };
  33273. } else {
  33274. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  33275. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  33276. each(ticksCoords, function (ticksItem) {
  33277. ticksItem.coord -= shift_1 / 2;
  33278. });
  33279. var dataExtent = axis.scale.getExtent();
  33280. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  33281. last = {
  33282. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  33283. };
  33284. ticksCoords.push(last);
  33285. }
  33286. var inverse = axisExtent[0] > axisExtent[1];
  33287. // Handling clamp.
  33288. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  33289. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  33290. }
  33291. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  33292. ticksCoords.unshift({
  33293. coord: axisExtent[0]
  33294. });
  33295. }
  33296. if (littleThan(axisExtent[1], last.coord)) {
  33297. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  33298. }
  33299. if (clamp && littleThan(last.coord, axisExtent[1])) {
  33300. ticksCoords.push({
  33301. coord: axisExtent[1]
  33302. });
  33303. }
  33304. function littleThan(a, b) {
  33305. // Avoid rounding error cause calculated tick coord different with extent.
  33306. // It may cause an extra unnecessary tick added.
  33307. a = round(a);
  33308. b = round(b);
  33309. return inverse ? a > b : a < b;
  33310. }
  33311. }
  33312. // --------------------- Deprecated Extension Methods ---------------------
  33313. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  33314. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  33315. // class Bar3DModel extends ComponentModel {}
  33316. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  33317. // echarts.use(install);
  33318. function extendComponentModel(proto) {
  33319. var Model = ComponentModel.extend(proto);
  33320. ComponentModel.registerClass(Model);
  33321. return Model;
  33322. }
  33323. function extendComponentView(proto) {
  33324. var View = ComponentView.extend(proto);
  33325. ComponentView.registerClass(View);
  33326. return View;
  33327. }
  33328. function extendSeriesModel(proto) {
  33329. var Model = SeriesModel.extend(proto);
  33330. SeriesModel.registerClass(Model);
  33331. return Model;
  33332. }
  33333. function extendChartView(proto) {
  33334. var View = ChartView.extend(proto);
  33335. ChartView.registerClass(View);
  33336. return View;
  33337. }
  33338. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  33339. var dx = x - x1;
  33340. var dy = y - y1;
  33341. var dx1 = x2 - x1;
  33342. var dy1 = y2 - y1;
  33343. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  33344. dx1 /= lineLen;
  33345. dy1 /= lineLen;
  33346. // dot product
  33347. var projectedLen = dx * dx1 + dy * dy1;
  33348. var t = projectedLen / lineLen;
  33349. if (limitToEnds) {
  33350. t = Math.min(Math.max(t, 0), 1);
  33351. }
  33352. t *= lineLen;
  33353. var ox = out[0] = x1 + t * dx1;
  33354. var oy = out[1] = y1 + t * dy1;
  33355. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33356. }
  33357. // Temporal variable for intermediate usage.
  33358. var pt0 = new Point();
  33359. var pt1 = new Point();
  33360. var pt2 = new Point();
  33361. var dir = new Point();
  33362. var dir2 = new Point();
  33363. // Temporal variable for the limitTurnAngle function
  33364. var tmpArr = [];
  33365. var tmpProjPoint = new Point();
  33366. /**
  33367. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  33368. * @param linePoints
  33369. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  33370. */
  33371. function limitTurnAngle(linePoints, minTurnAngle) {
  33372. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  33373. return;
  33374. }
  33375. minTurnAngle = minTurnAngle / 180 * Math.PI;
  33376. // The line points can be
  33377. // /pt1----pt2 (label)
  33378. // /
  33379. // pt0/
  33380. pt0.fromArray(linePoints[0]);
  33381. pt1.fromArray(linePoints[1]);
  33382. pt2.fromArray(linePoints[2]);
  33383. Point.sub(dir, pt0, pt1);
  33384. Point.sub(dir2, pt2, pt1);
  33385. var len1 = dir.len();
  33386. var len2 = dir2.len();
  33387. if (len1 < 1e-3 || len2 < 1e-3) {
  33388. return;
  33389. }
  33390. dir.scale(1 / len1);
  33391. dir2.scale(1 / len2);
  33392. var angleCos = dir.dot(dir2);
  33393. var minTurnAngleCos = Math.cos(minTurnAngle);
  33394. if (minTurnAngleCos < angleCos) {
  33395. // Smaller than minTurnAngle
  33396. // Calculate project point of pt0 on pt1-pt2
  33397. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33398. tmpProjPoint.fromArray(tmpArr);
  33399. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33400. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle));
  33401. // Limit the new calculated connect point between pt1 and pt2.
  33402. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33403. if (isNaN(t)) {
  33404. return;
  33405. }
  33406. if (t < 0) {
  33407. Point.copy(tmpProjPoint, pt1);
  33408. } else if (t > 1) {
  33409. Point.copy(tmpProjPoint, pt2);
  33410. }
  33411. tmpProjPoint.toArray(linePoints[1]);
  33412. }
  33413. }
  33414. /**
  33415. * Limit the angle of line and the surface
  33416. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  33417. */
  33418. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  33419. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  33420. return;
  33421. }
  33422. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  33423. pt0.fromArray(linePoints[0]);
  33424. pt1.fromArray(linePoints[1]);
  33425. pt2.fromArray(linePoints[2]);
  33426. Point.sub(dir, pt1, pt0);
  33427. Point.sub(dir2, pt2, pt1);
  33428. var len1 = dir.len();
  33429. var len2 = dir2.len();
  33430. if (len1 < 1e-3 || len2 < 1e-3) {
  33431. return;
  33432. }
  33433. dir.scale(1 / len1);
  33434. dir2.scale(1 / len2);
  33435. var angleCos = dir.dot(surfaceNormal);
  33436. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  33437. if (angleCos < maxSurfaceAngleCos) {
  33438. // Calculate project point of pt0 on pt1-pt2
  33439. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33440. tmpProjPoint.fromArray(tmpArr);
  33441. var HALF_PI = Math.PI / 2;
  33442. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  33443. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  33444. if (newAngle >= HALF_PI) {
  33445. // parallel
  33446. Point.copy(tmpProjPoint, pt2);
  33447. } else {
  33448. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33449. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle));
  33450. // Limit the new calculated connect point between pt1 and pt2.
  33451. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33452. if (isNaN(t)) {
  33453. return;
  33454. }
  33455. if (t < 0) {
  33456. Point.copy(tmpProjPoint, pt1);
  33457. } else if (t > 1) {
  33458. Point.copy(tmpProjPoint, pt2);
  33459. }
  33460. }
  33461. tmpProjPoint.toArray(linePoints[1]);
  33462. }
  33463. }
  33464. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  33465. var isNormal = stateName === 'normal';
  33466. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName);
  33467. // Make sure display.
  33468. stateObj.ignore = ignore;
  33469. // Set smooth
  33470. var smooth = stateModel.get('smooth');
  33471. if (smooth && smooth === true) {
  33472. smooth = 0.3;
  33473. }
  33474. stateObj.shape = stateObj.shape || {};
  33475. if (smooth > 0) {
  33476. stateObj.shape.smooth = smooth;
  33477. }
  33478. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  33479. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  33480. }
  33481. function buildLabelLinePath(path, shape) {
  33482. var smooth = shape.smooth;
  33483. var points = shape.points;
  33484. if (!points) {
  33485. return;
  33486. }
  33487. path.moveTo(points[0][0], points[0][1]);
  33488. if (smooth > 0 && points.length >= 3) {
  33489. var len1 = dist(points[0], points[1]);
  33490. var len2 = dist(points[1], points[2]);
  33491. if (!len1 || !len2) {
  33492. path.lineTo(points[1][0], points[1][1]);
  33493. path.lineTo(points[2][0], points[2][1]);
  33494. return;
  33495. }
  33496. var moveLen = Math.min(len1, len2) * smooth;
  33497. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  33498. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  33499. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  33500. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  33501. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  33502. } else {
  33503. for (var i = 1; i < points.length; i++) {
  33504. path.lineTo(points[i][0], points[i][1]);
  33505. }
  33506. }
  33507. }
  33508. /**
  33509. * Create a label line if necessary and set it's style.
  33510. */
  33511. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  33512. var labelLine = targetEl.getTextGuideLine();
  33513. var label = targetEl.getTextContent();
  33514. if (!label) {
  33515. // Not show label line if there is no label.
  33516. if (labelLine) {
  33517. targetEl.removeTextGuideLine();
  33518. }
  33519. return;
  33520. }
  33521. var normalModel = statesModels.normal;
  33522. var showNormal = normalModel.get('show');
  33523. var labelIgnoreNormal = label.ignore;
  33524. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  33525. var stateName = DISPLAY_STATES[i];
  33526. var stateModel = statesModels[stateName];
  33527. var isNormal = stateName === 'normal';
  33528. if (stateModel) {
  33529. var stateShow = stateModel.get('show');
  33530. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  33531. if (isLabelIgnored // Not show when label is not shown in this state.
  33532. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  33533. ) {
  33534. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  33535. if (stateObj) {
  33536. stateObj.ignore = true;
  33537. }
  33538. if (!!labelLine) {
  33539. setLabelLineState(labelLine, true, stateName, stateModel);
  33540. }
  33541. continue;
  33542. }
  33543. // Create labelLine if not exists
  33544. if (!labelLine) {
  33545. labelLine = new Polyline();
  33546. targetEl.setTextGuideLine(labelLine);
  33547. // Reset state of normal because it's new created.
  33548. // NOTE: NORMAL should always been the first!
  33549. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  33550. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  33551. }
  33552. // Use same state proxy.
  33553. if (targetEl.stateProxy) {
  33554. labelLine.stateProxy = targetEl.stateProxy;
  33555. }
  33556. }
  33557. setLabelLineState(labelLine, false, stateName, stateModel);
  33558. }
  33559. }
  33560. if (labelLine) {
  33561. defaults(labelLine.style, defaultStyle);
  33562. // Not fill.
  33563. labelLine.style.fill = null;
  33564. var showAbove = normalModel.get('showAbove');
  33565. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  33566. labelLineConfig.showAbove = showAbove || false;
  33567. // Custom the buildPath.
  33568. labelLine.buildPath = buildLabelLinePath;
  33569. }
  33570. }
  33571. function getLabelLineStatesModels(itemModel, labelLineName) {
  33572. labelLineName = labelLineName || 'labelLine';
  33573. var statesModels = {
  33574. normal: itemModel.getModel(labelLineName)
  33575. };
  33576. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  33577. var stateName = SPECIAL_STATES[i];
  33578. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  33579. }
  33580. return statesModels;
  33581. }
  33582. function prepareLayoutList(input) {
  33583. var list = [];
  33584. for (var i = 0; i < input.length; i++) {
  33585. var rawItem = input[i];
  33586. if (rawItem.defaultAttr.ignore) {
  33587. continue;
  33588. }
  33589. var label = rawItem.label;
  33590. var transform = label.getComputedTransform();
  33591. // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  33592. var localRect = label.getBoundingRect();
  33593. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  33594. var minMargin = label.style.margin || 0;
  33595. var globalRect = localRect.clone();
  33596. globalRect.applyTransform(transform);
  33597. globalRect.x -= minMargin / 2;
  33598. globalRect.y -= minMargin / 2;
  33599. globalRect.width += minMargin;
  33600. globalRect.height += minMargin;
  33601. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  33602. list.push({
  33603. label: label,
  33604. labelLine: rawItem.labelLine,
  33605. rect: globalRect,
  33606. localRect: localRect,
  33607. obb: obb,
  33608. priority: rawItem.priority,
  33609. defaultAttr: rawItem.defaultAttr,
  33610. layoutOption: rawItem.computedLayoutOption,
  33611. axisAligned: isAxisAligned,
  33612. transform: transform
  33613. });
  33614. }
  33615. return list;
  33616. }
  33617. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  33618. var len = list.length;
  33619. if (len < 2) {
  33620. return;
  33621. }
  33622. list.sort(function (a, b) {
  33623. return a.rect[xyDim] - b.rect[xyDim];
  33624. });
  33625. var lastPos = 0;
  33626. var delta;
  33627. var adjusted = false;
  33628. var totalShifts = 0;
  33629. for (var i = 0; i < len; i++) {
  33630. var item = list[i];
  33631. var rect = item.rect;
  33632. delta = rect[xyDim] - lastPos;
  33633. if (delta < 0) {
  33634. // shiftForward(i, len, -delta);
  33635. rect[xyDim] -= delta;
  33636. item.label[xyDim] -= delta;
  33637. adjusted = true;
  33638. }
  33639. var shift = Math.max(-delta, 0);
  33640. totalShifts += shift;
  33641. lastPos = rect[xyDim] + rect[sizeDim];
  33642. }
  33643. if (totalShifts > 0 && balanceShift) {
  33644. // Shift back to make the distribution more equally.
  33645. shiftList(-totalShifts / len, 0, len);
  33646. }
  33647. // TODO bleedMargin?
  33648. var first = list[0];
  33649. var last = list[len - 1];
  33650. var minGap;
  33651. var maxGap;
  33652. updateMinMaxGap();
  33653. // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  33654. minGap < 0 && squeezeGaps(-minGap, 0.8);
  33655. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  33656. updateMinMaxGap();
  33657. takeBoundsGap(minGap, maxGap, 1);
  33658. takeBoundsGap(maxGap, minGap, -1);
  33659. // Handle bailout when there is not enough space.
  33660. updateMinMaxGap();
  33661. if (minGap < 0) {
  33662. squeezeWhenBailout(-minGap);
  33663. }
  33664. if (maxGap < 0) {
  33665. squeezeWhenBailout(maxGap);
  33666. }
  33667. function updateMinMaxGap() {
  33668. minGap = first.rect[xyDim] - minBound;
  33669. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  33670. }
  33671. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  33672. if (gapThisBound < 0) {
  33673. // Move from other gap if can.
  33674. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  33675. if (moveFromMaxGap > 0) {
  33676. shiftList(moveFromMaxGap * moveDir, 0, len);
  33677. var remained = moveFromMaxGap + gapThisBound;
  33678. if (remained < 0) {
  33679. squeezeGaps(-remained * moveDir, 1);
  33680. }
  33681. } else {
  33682. squeezeGaps(-gapThisBound * moveDir, 1);
  33683. }
  33684. }
  33685. }
  33686. function shiftList(delta, start, end) {
  33687. if (delta !== 0) {
  33688. adjusted = true;
  33689. }
  33690. for (var i = start; i < end; i++) {
  33691. var item = list[i];
  33692. var rect = item.rect;
  33693. rect[xyDim] += delta;
  33694. item.label[xyDim] += delta;
  33695. }
  33696. }
  33697. // Squeeze gaps if the labels exceed margin.
  33698. function squeezeGaps(delta, maxSqeezePercent) {
  33699. var gaps = [];
  33700. var totalGaps = 0;
  33701. for (var i = 1; i < len; i++) {
  33702. var prevItemRect = list[i - 1].rect;
  33703. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  33704. gaps.push(gap);
  33705. totalGaps += gap;
  33706. }
  33707. if (!totalGaps) {
  33708. return;
  33709. }
  33710. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  33711. if (delta > 0) {
  33712. for (var i = 0; i < len - 1; i++) {
  33713. // Distribute the shift delta to all gaps.
  33714. var movement = gaps[i] * squeezePercent;
  33715. // Forward
  33716. shiftList(movement, 0, i + 1);
  33717. }
  33718. } else {
  33719. // Backward
  33720. for (var i = len - 1; i > 0; i--) {
  33721. // Distribute the shift delta to all gaps.
  33722. var movement = gaps[i - 1] * squeezePercent;
  33723. shiftList(-movement, i, len);
  33724. }
  33725. }
  33726. }
  33727. /**
  33728. * Squeeze to allow overlap if there is no more space available.
  33729. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  33730. */
  33731. function squeezeWhenBailout(delta) {
  33732. var dir = delta < 0 ? -1 : 1;
  33733. delta = Math.abs(delta);
  33734. var moveForEachLabel = Math.ceil(delta / (len - 1));
  33735. for (var i = 0; i < len - 1; i++) {
  33736. if (dir > 0) {
  33737. // Forward
  33738. shiftList(moveForEachLabel, 0, i + 1);
  33739. } else {
  33740. // Backward
  33741. shiftList(-moveForEachLabel, len - i - 1, len);
  33742. }
  33743. delta -= moveForEachLabel;
  33744. if (delta <= 0) {
  33745. return;
  33746. }
  33747. }
  33748. }
  33749. return adjusted;
  33750. }
  33751. /**
  33752. * Adjust labels on y direction to avoid overlap.
  33753. */
  33754. function shiftLayoutOnY(list, topBound, bottomBound,
  33755. // If average the shifts on all labels and add them to 0
  33756. balanceShift) {
  33757. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  33758. }
  33759. function hideOverlap(labelList) {
  33760. var displayedLabels = [];
  33761. // TODO, render overflow visible first, put in the displayedLabels.
  33762. labelList.sort(function (a, b) {
  33763. return b.priority - a.priority;
  33764. });
  33765. var globalRect = new BoundingRect(0, 0, 0, 0);
  33766. function hideEl(el) {
  33767. if (!el.ignore) {
  33768. // Show on emphasis.
  33769. var emphasisState = el.ensureState('emphasis');
  33770. if (emphasisState.ignore == null) {
  33771. emphasisState.ignore = false;
  33772. }
  33773. }
  33774. el.ignore = true;
  33775. }
  33776. for (var i = 0; i < labelList.length; i++) {
  33777. var labelItem = labelList[i];
  33778. var isAxisAligned = labelItem.axisAligned;
  33779. var localRect = labelItem.localRect;
  33780. var transform = labelItem.transform;
  33781. var label = labelItem.label;
  33782. var labelLine = labelItem.labelLine;
  33783. globalRect.copy(labelItem.rect);
  33784. // Add a threshold because layout may be aligned precisely.
  33785. globalRect.width -= 0.1;
  33786. globalRect.height -= 0.1;
  33787. globalRect.x += 0.05;
  33788. globalRect.y += 0.05;
  33789. var obb = labelItem.obb;
  33790. var overlapped = false;
  33791. for (var j = 0; j < displayedLabels.length; j++) {
  33792. var existsTextCfg = displayedLabels[j];
  33793. // Fast rejection.
  33794. if (!globalRect.intersect(existsTextCfg.rect)) {
  33795. continue;
  33796. }
  33797. if (isAxisAligned && existsTextCfg.axisAligned) {
  33798. // Is overlapped
  33799. overlapped = true;
  33800. break;
  33801. }
  33802. if (!existsTextCfg.obb) {
  33803. // If self is not axis aligned. But other is.
  33804. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  33805. }
  33806. if (!obb) {
  33807. // If self is axis aligned. But other is not.
  33808. obb = new OrientedBoundingRect(localRect, transform);
  33809. }
  33810. if (obb.intersect(existsTextCfg.obb)) {
  33811. overlapped = true;
  33812. break;
  33813. }
  33814. }
  33815. // TODO Callback to determine if this overlap should be handled?
  33816. if (overlapped) {
  33817. hideEl(label);
  33818. labelLine && hideEl(labelLine);
  33819. } else {
  33820. label.attr('ignore', labelItem.defaultAttr.ignore);
  33821. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  33822. displayedLabels.push(labelItem);
  33823. }
  33824. }
  33825. }
  33826. var mathSin$4 = Math.sin;
  33827. var mathCos$4 = Math.cos;
  33828. var PI$4 = Math.PI;
  33829. var PI2$6 = Math.PI * 2;
  33830. var degree = 180 / PI$4;
  33831. var SVGPathRebuilder = (function () {
  33832. function SVGPathRebuilder() {
  33833. }
  33834. SVGPathRebuilder.prototype.reset = function (precision) {
  33835. this._start = true;
  33836. this._d = [];
  33837. this._str = '';
  33838. this._p = Math.pow(10, precision || 4);
  33839. };
  33840. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  33841. this._add('M', x, y);
  33842. };
  33843. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  33844. this._add('L', x, y);
  33845. };
  33846. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  33847. this._add('C', x, y, x2, y2, x3, y3);
  33848. };
  33849. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  33850. this._add('Q', x, y, x2, y2);
  33851. };
  33852. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  33853. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  33854. };
  33855. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  33856. var dTheta = endAngle - startAngle;
  33857. var clockwise = !anticlockwise;
  33858. var dThetaPositive = Math.abs(dTheta);
  33859. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  33860. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  33861. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  33862. var large = false;
  33863. if (isCircle) {
  33864. large = true;
  33865. }
  33866. else if (isAroundZero$1(dThetaPositive)) {
  33867. large = false;
  33868. }
  33869. else {
  33870. large = (unifiedTheta >= PI$4) === !!clockwise;
  33871. }
  33872. var x0 = cx + rx * mathCos$4(startAngle);
  33873. var y0 = cy + ry * mathSin$4(startAngle);
  33874. if (this._start) {
  33875. this._add('M', x0, y0);
  33876. }
  33877. var xRot = Math.round(psi * degree);
  33878. if (isCircle) {
  33879. var p = 1 / this._p;
  33880. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$6 - p);
  33881. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  33882. if (p > 1e-2) {
  33883. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  33884. }
  33885. }
  33886. else {
  33887. var x = cx + rx * mathCos$4(endAngle);
  33888. var y = cy + ry * mathSin$4(endAngle);
  33889. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  33890. }
  33891. };
  33892. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  33893. this._add('M', x, y);
  33894. this._add('l', w, 0);
  33895. this._add('l', 0, h);
  33896. this._add('l', -w, 0);
  33897. this._add('Z');
  33898. };
  33899. SVGPathRebuilder.prototype.closePath = function () {
  33900. if (this._d.length > 0) {
  33901. this._add('Z');
  33902. }
  33903. };
  33904. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  33905. var vals = [];
  33906. var p = this._p;
  33907. for (var i = 1; i < arguments.length; i++) {
  33908. var val = arguments[i];
  33909. if (isNaN(val)) {
  33910. this._invalid = true;
  33911. return;
  33912. }
  33913. vals.push(Math.round(val * p) / p);
  33914. }
  33915. this._d.push(cmd + vals.join(' '));
  33916. this._start = cmd === 'Z';
  33917. };
  33918. SVGPathRebuilder.prototype.generateStr = function () {
  33919. this._str = this._invalid ? '' : this._d.join('');
  33920. this._d = [];
  33921. };
  33922. SVGPathRebuilder.prototype.getStr = function () {
  33923. return this._str;
  33924. };
  33925. return SVGPathRebuilder;
  33926. }());
  33927. var NONE = 'none';
  33928. var mathRound$1 = Math.round;
  33929. function pathHasFill(style) {
  33930. var fill = style.fill;
  33931. return fill != null && fill !== NONE;
  33932. }
  33933. function pathHasStroke(style) {
  33934. var stroke = style.stroke;
  33935. return stroke != null && stroke !== NONE;
  33936. }
  33937. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  33938. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  33939. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  33940. var opacity = style.opacity == null ? 1 : style.opacity;
  33941. if (el instanceof ZRImage) {
  33942. updateAttr('opacity', opacity);
  33943. return;
  33944. }
  33945. if (pathHasFill(style)) {
  33946. var fill = normalizeColor(style.fill);
  33947. updateAttr('fill', fill.color);
  33948. var fillOpacity = style.fillOpacity != null
  33949. ? style.fillOpacity * fill.opacity * opacity
  33950. : fill.opacity * opacity;
  33951. if (forceUpdate || fillOpacity < 1) {
  33952. updateAttr('fill-opacity', fillOpacity);
  33953. }
  33954. }
  33955. else {
  33956. updateAttr('fill', NONE);
  33957. }
  33958. if (pathHasStroke(style)) {
  33959. var stroke = normalizeColor(style.stroke);
  33960. updateAttr('stroke', stroke.color);
  33961. var strokeScale = style.strokeNoScale
  33962. ? el.getLineScale()
  33963. : 1;
  33964. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  33965. var strokeOpacity = style.strokeOpacity != null
  33966. ? style.strokeOpacity * stroke.opacity * opacity
  33967. : stroke.opacity * opacity;
  33968. var strokeFirst = style.strokeFirst;
  33969. if (forceUpdate || strokeWidth !== 1) {
  33970. updateAttr('stroke-width', strokeWidth);
  33971. }
  33972. if (forceUpdate || strokeFirst) {
  33973. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  33974. }
  33975. if (forceUpdate || strokeOpacity < 1) {
  33976. updateAttr('stroke-opacity', strokeOpacity);
  33977. }
  33978. if (style.lineDash) {
  33979. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  33980. if (lineDash) {
  33981. lineDashOffset = mathRound$1(lineDashOffset || 0);
  33982. updateAttr('stroke-dasharray', lineDash.join(','));
  33983. if (lineDashOffset || forceUpdate) {
  33984. updateAttr('stroke-dashoffset', lineDashOffset);
  33985. }
  33986. }
  33987. }
  33988. else if (forceUpdate) {
  33989. updateAttr('stroke-dasharray', NONE);
  33990. }
  33991. for (var i = 0; i < strokeProps.length; i++) {
  33992. var propName = strokeProps[i];
  33993. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  33994. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  33995. val && updateAttr(svgStrokeProps[i], val);
  33996. }
  33997. }
  33998. }
  33999. else if (forceUpdate) {
  34000. updateAttr('stroke', NONE);
  34001. }
  34002. }
  34003. var SVGNS = 'http://www.w3.org/2000/svg';
  34004. var XLINKNS = 'http://www.w3.org/1999/xlink';
  34005. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  34006. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  34007. var META_DATA_PREFIX = 'ecmeta_';
  34008. function createElement(name) {
  34009. return document.createElementNS(SVGNS, name);
  34010. }
  34011. function createVNode(tag, key, attrs, children, text) {
  34012. return {
  34013. tag: tag,
  34014. attrs: attrs || {},
  34015. children: children,
  34016. text: text,
  34017. key: key
  34018. };
  34019. }
  34020. function createElementOpen(name, attrs) {
  34021. var attrsStr = [];
  34022. if (attrs) {
  34023. for (var key in attrs) {
  34024. var val = attrs[key];
  34025. var part = key;
  34026. if (val === false) {
  34027. continue;
  34028. }
  34029. else if (val !== true && val != null) {
  34030. part += "=\"" + val + "\"";
  34031. }
  34032. attrsStr.push(part);
  34033. }
  34034. }
  34035. return "<" + name + " " + attrsStr.join(' ') + ">";
  34036. }
  34037. function createElementClose(name) {
  34038. return "</" + name + ">";
  34039. }
  34040. function vNodeToString(el, opts) {
  34041. opts = opts || {};
  34042. var S = opts.newline ? '\n' : '';
  34043. function convertElToString(el) {
  34044. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  34045. return createElementOpen(tag, attrs)
  34046. + (tag !== 'style' ? encodeHTML(text) : text || '')
  34047. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  34048. + createElementClose(tag);
  34049. }
  34050. return convertElToString(el);
  34051. }
  34052. function getCssString(selectorNodes, animationNodes, opts) {
  34053. opts = opts || {};
  34054. var S = opts.newline ? '\n' : '';
  34055. var bracketBegin = " {" + S;
  34056. var bracketEnd = S + "}";
  34057. var selectors = map(keys(selectorNodes), function (className) {
  34058. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  34059. return attrName + ":" + selectorNodes[className][attrName] + ";";
  34060. }).join(S) + bracketEnd;
  34061. }).join(S);
  34062. var animations = map(keys(animationNodes), function (animationName) {
  34063. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  34064. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  34065. var val = animationNodes[animationName][percent][attrName];
  34066. if (attrName === 'd') {
  34067. val = "path(\"" + val + "\")";
  34068. }
  34069. return attrName + ":" + val + ";";
  34070. }).join(S) + bracketEnd;
  34071. }).join(S) + bracketEnd;
  34072. }).join(S);
  34073. if (!selectors && !animations) {
  34074. return '';
  34075. }
  34076. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  34077. }
  34078. function createBrushScope(zrId) {
  34079. return {
  34080. zrId: zrId,
  34081. shadowCache: {},
  34082. patternCache: {},
  34083. gradientCache: {},
  34084. clipPathCache: {},
  34085. defs: {},
  34086. cssNodes: {},
  34087. cssAnims: {},
  34088. cssStyleCache: {},
  34089. cssAnimIdx: 0,
  34090. shadowIdx: 0,
  34091. gradientIdx: 0,
  34092. patternIdx: 0,
  34093. clipPathIdx: 0
  34094. };
  34095. }
  34096. function createSVGVNode(width, height, children, useViewBox) {
  34097. return createVNode('svg', 'root', {
  34098. 'width': width,
  34099. 'height': height,
  34100. 'xmlns': SVGNS,
  34101. 'xmlns:xlink': XLINKNS,
  34102. 'version': '1.1',
  34103. 'baseProfile': 'full',
  34104. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  34105. }, children);
  34106. }
  34107. var cssClassIdx = 0;
  34108. function getClassId() {
  34109. return cssClassIdx++;
  34110. }
  34111. var EASING_MAP = {
  34112. cubicIn: '0.32,0,0.67,0',
  34113. cubicOut: '0.33,1,0.68,1',
  34114. cubicInOut: '0.65,0,0.35,1',
  34115. quadraticIn: '0.11,0,0.5,0',
  34116. quadraticOut: '0.5,1,0.89,1',
  34117. quadraticInOut: '0.45,0,0.55,1',
  34118. quarticIn: '0.5,0,0.75,0',
  34119. quarticOut: '0.25,1,0.5,1',
  34120. quarticInOut: '0.76,0,0.24,1',
  34121. quinticIn: '0.64,0,0.78,0',
  34122. quinticOut: '0.22,1,0.36,1',
  34123. quinticInOut: '0.83,0,0.17,1',
  34124. sinusoidalIn: '0.12,0,0.39,0',
  34125. sinusoidalOut: '0.61,1,0.88,1',
  34126. sinusoidalInOut: '0.37,0,0.63,1',
  34127. exponentialIn: '0.7,0,0.84,0',
  34128. exponentialOut: '0.16,1,0.3,1',
  34129. exponentialInOut: '0.87,0,0.13,1',
  34130. circularIn: '0.55,0,1,0.45',
  34131. circularOut: '0,0.55,0.45,1',
  34132. circularInOut: '0.85,0,0.15,1'
  34133. };
  34134. var transformOriginKey = 'transform-origin';
  34135. function buildPathString(el, kfShape, path) {
  34136. var shape = extend({}, el.shape);
  34137. extend(shape, kfShape);
  34138. el.buildPath(path, shape);
  34139. var svgPathBuilder = new SVGPathRebuilder();
  34140. svgPathBuilder.reset(getPathPrecision(el));
  34141. path.rebuildPath(svgPathBuilder, 1);
  34142. svgPathBuilder.generateStr();
  34143. return svgPathBuilder.getStr();
  34144. }
  34145. function setTransformOrigin(target, transform) {
  34146. var originX = transform.originX, originY = transform.originY;
  34147. if (originX || originY) {
  34148. target[transformOriginKey] = originX + "px " + originY + "px";
  34149. }
  34150. }
  34151. var ANIMATE_STYLE_MAP = {
  34152. fill: 'fill',
  34153. opacity: 'opacity',
  34154. lineWidth: 'stroke-width',
  34155. lineDashOffset: 'stroke-dashoffset'
  34156. };
  34157. function addAnimation(cssAnim, scope) {
  34158. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  34159. scope.cssAnims[animationName] = cssAnim;
  34160. return animationName;
  34161. }
  34162. function createCompoundPathCSSAnimation(el, attrs, scope) {
  34163. var paths = el.shape.paths;
  34164. var composedAnim = {};
  34165. var cssAnimationCfg;
  34166. var cssAnimationName;
  34167. each(paths, function (path) {
  34168. var subScope = createBrushScope(scope.zrId);
  34169. subScope.animation = true;
  34170. createCSSAnimation(path, {}, subScope, true);
  34171. var cssAnims = subScope.cssAnims;
  34172. var cssNodes = subScope.cssNodes;
  34173. var animNames = keys(cssAnims);
  34174. var len = animNames.length;
  34175. if (!len) {
  34176. return;
  34177. }
  34178. cssAnimationName = animNames[len - 1];
  34179. var lastAnim = cssAnims[cssAnimationName];
  34180. for (var percent in lastAnim) {
  34181. var kf = lastAnim[percent];
  34182. composedAnim[percent] = composedAnim[percent] || { d: '' };
  34183. composedAnim[percent].d += kf.d || '';
  34184. }
  34185. for (var className in cssNodes) {
  34186. var val = cssNodes[className].animation;
  34187. if (val.indexOf(cssAnimationName) >= 0) {
  34188. cssAnimationCfg = val;
  34189. }
  34190. }
  34191. });
  34192. if (!cssAnimationCfg) {
  34193. return;
  34194. }
  34195. attrs.d = false;
  34196. var animationName = addAnimation(composedAnim, scope);
  34197. return cssAnimationCfg.replace(cssAnimationName, animationName);
  34198. }
  34199. function getEasingFunc(easing) {
  34200. return isString(easing)
  34201. ? EASING_MAP[easing]
  34202. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  34203. : createCubicEasingFunc(easing) ? easing : ''
  34204. : '';
  34205. }
  34206. function createCSSAnimation(el, attrs, scope, onlyShape) {
  34207. var animators = el.animators;
  34208. var len = animators.length;
  34209. var cssAnimations = [];
  34210. if (el instanceof CompoundPath) {
  34211. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  34212. if (animationCfg) {
  34213. cssAnimations.push(animationCfg);
  34214. }
  34215. else if (!len) {
  34216. return;
  34217. }
  34218. }
  34219. else if (!len) {
  34220. return;
  34221. }
  34222. var groupAnimators = {};
  34223. for (var i = 0; i < len; i++) {
  34224. var animator = animators[i];
  34225. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  34226. var easing = getEasingFunc(animator.getClip().easing);
  34227. var delay = animator.getDelay();
  34228. if (easing) {
  34229. cfgArr.push(easing);
  34230. }
  34231. else {
  34232. cfgArr.push('linear');
  34233. }
  34234. if (delay) {
  34235. cfgArr.push(delay / 1000 + 's');
  34236. }
  34237. if (animator.getLoop()) {
  34238. cfgArr.push('infinite');
  34239. }
  34240. var cfg = cfgArr.join(' ');
  34241. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  34242. groupAnimators[cfg][1].push(animator);
  34243. }
  34244. function createSingleCSSAnimation(groupAnimator) {
  34245. var animators = groupAnimator[1];
  34246. var len = animators.length;
  34247. var transformKfs = {};
  34248. var shapeKfs = {};
  34249. var finalKfs = {};
  34250. var animationTimingFunctionAttrName = 'animation-timing-function';
  34251. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  34252. var tracks = animator.getTracks();
  34253. var maxTime = animator.getMaxTime();
  34254. for (var k = 0; k < tracks.length; k++) {
  34255. var track = tracks[k];
  34256. if (track.needsAnimate()) {
  34257. var kfs = track.keyframes;
  34258. var attrName = track.propName;
  34259. toCssAttrName && (attrName = toCssAttrName(attrName));
  34260. if (attrName) {
  34261. for (var i = 0; i < kfs.length; i++) {
  34262. var kf = kfs[i];
  34263. var percent = Math.round(kf.time / maxTime * 100) + '%';
  34264. var kfEasing = getEasingFunc(kf.easing);
  34265. var rawValue = kf.rawValue;
  34266. if (isString(rawValue) || isNumber(rawValue)) {
  34267. cssKfs[percent] = cssKfs[percent] || {};
  34268. cssKfs[percent][attrName] = kf.rawValue;
  34269. if (kfEasing) {
  34270. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  34271. }
  34272. }
  34273. }
  34274. }
  34275. }
  34276. }
  34277. }
  34278. for (var i = 0; i < len; i++) {
  34279. var animator = animators[i];
  34280. var targetProp = animator.targetName;
  34281. if (!targetProp) {
  34282. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  34283. }
  34284. else if (targetProp === 'shape') {
  34285. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  34286. }
  34287. }
  34288. for (var percent in transformKfs) {
  34289. var transform = {};
  34290. copyTransform(transform, el);
  34291. extend(transform, transformKfs[percent]);
  34292. var str = getSRTTransformString(transform);
  34293. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  34294. finalKfs[percent] = str ? {
  34295. transform: str
  34296. } : {};
  34297. setTransformOrigin(finalKfs[percent], transform);
  34298. if (timingFunction) {
  34299. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34300. }
  34301. }
  34302. var path;
  34303. var canAnimateShape = true;
  34304. for (var percent in shapeKfs) {
  34305. finalKfs[percent] = finalKfs[percent] || {};
  34306. var isFirst = !path;
  34307. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  34308. if (isFirst) {
  34309. path = new PathProxy();
  34310. }
  34311. var len_1 = path.len();
  34312. path.reset();
  34313. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  34314. var newLen = path.len();
  34315. if (!isFirst && len_1 !== newLen) {
  34316. canAnimateShape = false;
  34317. break;
  34318. }
  34319. if (timingFunction) {
  34320. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34321. }
  34322. }
  34323. if (!canAnimateShape) {
  34324. for (var percent in finalKfs) {
  34325. delete finalKfs[percent].d;
  34326. }
  34327. }
  34328. if (!onlyShape) {
  34329. for (var i = 0; i < len; i++) {
  34330. var animator = animators[i];
  34331. var targetProp = animator.targetName;
  34332. if (targetProp === 'style') {
  34333. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  34334. }
  34335. }
  34336. }
  34337. var percents = keys(finalKfs);
  34338. var allTransformOriginSame = true;
  34339. var transformOrigin;
  34340. for (var i = 1; i < percents.length; i++) {
  34341. var p0 = percents[i - 1];
  34342. var p1 = percents[i];
  34343. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  34344. allTransformOriginSame = false;
  34345. break;
  34346. }
  34347. transformOrigin = finalKfs[p0][transformOriginKey];
  34348. }
  34349. if (allTransformOriginSame && transformOrigin) {
  34350. for (var percent in finalKfs) {
  34351. if (finalKfs[percent][transformOriginKey]) {
  34352. delete finalKfs[percent][transformOriginKey];
  34353. }
  34354. }
  34355. attrs[transformOriginKey] = transformOrigin;
  34356. }
  34357. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  34358. var animationName = addAnimation(finalKfs, scope);
  34359. return animationName + " " + groupAnimator[0] + " both";
  34360. }
  34361. }
  34362. for (var key in groupAnimators) {
  34363. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  34364. if (animationCfg) {
  34365. cssAnimations.push(animationCfg);
  34366. }
  34367. }
  34368. if (cssAnimations.length) {
  34369. var className = scope.zrId + '-cls-' + getClassId();
  34370. scope.cssNodes['.' + className] = {
  34371. animation: cssAnimations.join(',')
  34372. };
  34373. attrs["class"] = className;
  34374. }
  34375. }
  34376. function createCSSEmphasis(el, attrs, scope) {
  34377. if (!el.ignore) {
  34378. if (el.isSilent()) {
  34379. var style = {
  34380. 'pointer-events': 'none'
  34381. };
  34382. setClassAttribute(style, attrs, scope, true);
  34383. }
  34384. else {
  34385. var emphasisStyle = el.states.emphasis && el.states.emphasis.style
  34386. ? el.states.emphasis.style
  34387. : {};
  34388. var fill = emphasisStyle.fill;
  34389. if (!fill) {
  34390. var normalFill = el.style && el.style.fill;
  34391. var selectFill = el.states.select
  34392. && el.states.select.style
  34393. && el.states.select.style.fill;
  34394. var fromFill = el.currentStates.indexOf('select') >= 0
  34395. ? (selectFill || normalFill)
  34396. : normalFill;
  34397. if (fromFill) {
  34398. fill = liftColor(fromFill);
  34399. }
  34400. }
  34401. var lineWidth = emphasisStyle.lineWidth;
  34402. if (lineWidth) {
  34403. var scaleX = (!emphasisStyle.strokeNoScale && el.transform)
  34404. ? el.transform[0]
  34405. : 1;
  34406. lineWidth = lineWidth / scaleX;
  34407. }
  34408. var style = {
  34409. cursor: 'pointer'
  34410. };
  34411. if (fill) {
  34412. style.fill = fill;
  34413. }
  34414. if (emphasisStyle.stroke) {
  34415. style.stroke = emphasisStyle.stroke;
  34416. }
  34417. if (lineWidth) {
  34418. style['stroke-width'] = lineWidth;
  34419. }
  34420. setClassAttribute(style, attrs, scope, true);
  34421. }
  34422. }
  34423. }
  34424. function setClassAttribute(style, attrs, scope, withHover) {
  34425. var styleKey = JSON.stringify(style);
  34426. var className = scope.cssStyleCache[styleKey];
  34427. if (!className) {
  34428. className = scope.zrId + '-cls-' + getClassId();
  34429. scope.cssStyleCache[styleKey] = className;
  34430. scope.cssNodes['.' + className + (withHover ? ':hover' : '')] = style;
  34431. }
  34432. attrs["class"] = attrs["class"] ? (attrs["class"] + ' ' + className) : className;
  34433. }
  34434. var round$2 = Math.round;
  34435. function isImageLike$1(val) {
  34436. return val && isString(val.src);
  34437. }
  34438. function isCanvasLike(val) {
  34439. return val && isFunction(val.toDataURL);
  34440. }
  34441. function setStyleAttrs(attrs, style, el, scope) {
  34442. mapStyleToAttrs(function (key, val) {
  34443. var isFillStroke = key === 'fill' || key === 'stroke';
  34444. if (isFillStroke && isGradient(val)) {
  34445. setGradient(style, attrs, key, scope);
  34446. }
  34447. else if (isFillStroke && isPattern(val)) {
  34448. setPattern(el, attrs, key, scope);
  34449. }
  34450. else if (isFillStroke && val === 'none') {
  34451. attrs[key] = 'transparent';
  34452. }
  34453. else {
  34454. attrs[key] = val;
  34455. }
  34456. }, style, el, false);
  34457. setShadow(el, attrs, scope);
  34458. }
  34459. function setMetaData(attrs, el) {
  34460. var metaData = getElementSSRData(el);
  34461. if (metaData) {
  34462. metaData.each(function (val, key) {
  34463. val != null && (attrs[(META_DATA_PREFIX + key).toLowerCase()] = val + '');
  34464. });
  34465. if (el.isSilent()) {
  34466. attrs[META_DATA_PREFIX + 'silent'] = 'true';
  34467. }
  34468. }
  34469. }
  34470. function noRotateScale(m) {
  34471. return isAroundZero$1(m[0] - 1)
  34472. && isAroundZero$1(m[1])
  34473. && isAroundZero$1(m[2])
  34474. && isAroundZero$1(m[3] - 1);
  34475. }
  34476. function noTranslate(m) {
  34477. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  34478. }
  34479. function setTransform(attrs, m, compress) {
  34480. if (m && !(noTranslate(m) && noRotateScale(m))) {
  34481. var mul = compress ? 10 : 1e4;
  34482. attrs.transform = noRotateScale(m)
  34483. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  34484. }
  34485. }
  34486. function convertPolyShape(shape, attrs, mul) {
  34487. var points = shape.points;
  34488. var strArr = [];
  34489. for (var i = 0; i < points.length; i++) {
  34490. strArr.push(round$2(points[i][0] * mul) / mul);
  34491. strArr.push(round$2(points[i][1] * mul) / mul);
  34492. }
  34493. attrs.points = strArr.join(' ');
  34494. }
  34495. function validatePolyShape(shape) {
  34496. return !shape.smooth;
  34497. }
  34498. function createAttrsConvert(desc) {
  34499. var normalizedDesc = map(desc, function (item) {
  34500. return (typeof item === 'string' ? [item, item] : item);
  34501. });
  34502. return function (shape, attrs, mul) {
  34503. for (var i = 0; i < normalizedDesc.length; i++) {
  34504. var item = normalizedDesc[i];
  34505. var val = shape[item[0]];
  34506. if (val != null) {
  34507. attrs[item[1]] = round$2(val * mul) / mul;
  34508. }
  34509. }
  34510. };
  34511. }
  34512. var builtinShapesDef = {
  34513. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  34514. polyline: [convertPolyShape, validatePolyShape],
  34515. polygon: [convertPolyShape, validatePolyShape]
  34516. };
  34517. function hasShapeAnimation(el) {
  34518. var animators = el.animators;
  34519. for (var i = 0; i < animators.length; i++) {
  34520. if (animators[i].targetName === 'shape') {
  34521. return true;
  34522. }
  34523. }
  34524. return false;
  34525. }
  34526. function brushSVGPath(el, scope) {
  34527. var style = el.style;
  34528. var shape = el.shape;
  34529. var builtinShpDef = builtinShapesDef[el.type];
  34530. var attrs = {};
  34531. var needsAnimate = scope.animation;
  34532. var svgElType = 'path';
  34533. var strokePercent = el.style.strokePercent;
  34534. var precision = (scope.compress && getPathPrecision(el)) || 4;
  34535. if (builtinShpDef
  34536. && !scope.willUpdate
  34537. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  34538. && !(needsAnimate && hasShapeAnimation(el))
  34539. && !(strokePercent < 1)) {
  34540. svgElType = el.type;
  34541. var mul = Math.pow(10, precision);
  34542. builtinShpDef[0](shape, attrs, mul);
  34543. }
  34544. else {
  34545. var needBuildPath = !el.path || el.shapeChanged();
  34546. if (!el.path) {
  34547. el.createPathProxy();
  34548. }
  34549. var path = el.path;
  34550. if (needBuildPath) {
  34551. path.beginPath();
  34552. el.buildPath(path, el.shape);
  34553. el.pathUpdated();
  34554. }
  34555. var pathVersion = path.getVersion();
  34556. var elExt = el;
  34557. var svgPathBuilder = elExt.__svgPathBuilder;
  34558. if (elExt.__svgPathVersion !== pathVersion
  34559. || !svgPathBuilder
  34560. || strokePercent !== elExt.__svgPathStrokePercent) {
  34561. if (!svgPathBuilder) {
  34562. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  34563. }
  34564. svgPathBuilder.reset(precision);
  34565. path.rebuildPath(svgPathBuilder, strokePercent);
  34566. svgPathBuilder.generateStr();
  34567. elExt.__svgPathVersion = pathVersion;
  34568. elExt.__svgPathStrokePercent = strokePercent;
  34569. }
  34570. attrs.d = svgPathBuilder.getStr();
  34571. }
  34572. setTransform(attrs, el.transform);
  34573. setStyleAttrs(attrs, style, el, scope);
  34574. setMetaData(attrs, el);
  34575. scope.animation && createCSSAnimation(el, attrs, scope);
  34576. scope.emphasis && createCSSEmphasis(el, attrs, scope);
  34577. return createVNode(svgElType, el.id + '', attrs);
  34578. }
  34579. function brushSVGImage(el, scope) {
  34580. var style = el.style;
  34581. var image = style.image;
  34582. if (image && !isString(image)) {
  34583. if (isImageLike$1(image)) {
  34584. image = image.src;
  34585. }
  34586. else if (isCanvasLike(image)) {
  34587. image = image.toDataURL();
  34588. }
  34589. }
  34590. if (!image) {
  34591. return;
  34592. }
  34593. var x = style.x || 0;
  34594. var y = style.y || 0;
  34595. var dw = style.width;
  34596. var dh = style.height;
  34597. var attrs = {
  34598. href: image,
  34599. width: dw,
  34600. height: dh
  34601. };
  34602. if (x) {
  34603. attrs.x = x;
  34604. }
  34605. if (y) {
  34606. attrs.y = y;
  34607. }
  34608. setTransform(attrs, el.transform);
  34609. setStyleAttrs(attrs, style, el, scope);
  34610. setMetaData(attrs, el);
  34611. scope.animation && createCSSAnimation(el, attrs, scope);
  34612. return createVNode('image', el.id + '', attrs);
  34613. }
  34614. function brushSVGTSpan(el, scope) {
  34615. var style = el.style;
  34616. var text = style.text;
  34617. text != null && (text += '');
  34618. if (!text || isNaN(style.x) || isNaN(style.y)) {
  34619. return;
  34620. }
  34621. var font = style.font || DEFAULT_FONT;
  34622. var x = style.x || 0;
  34623. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  34624. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  34625. || style.textAlign;
  34626. var attrs = {
  34627. 'dominant-baseline': 'central',
  34628. 'text-anchor': textAlign
  34629. };
  34630. if (hasSeparateFont(style)) {
  34631. var separatedFontStr = '';
  34632. var fontStyle = style.fontStyle;
  34633. var fontSize = parseFontSize(style.fontSize);
  34634. if (!parseFloat(fontSize)) {
  34635. return;
  34636. }
  34637. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  34638. var fontWeight = style.fontWeight;
  34639. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  34640. if (fontStyle && fontStyle !== 'normal') {
  34641. separatedFontStr += "font-style:" + fontStyle + ";";
  34642. }
  34643. if (fontWeight && fontWeight !== 'normal') {
  34644. separatedFontStr += "font-weight:" + fontWeight + ";";
  34645. }
  34646. attrs.style = separatedFontStr;
  34647. }
  34648. else {
  34649. attrs.style = "font: " + font;
  34650. }
  34651. if (text.match(/\s/)) {
  34652. attrs['xml:space'] = 'preserve';
  34653. }
  34654. if (x) {
  34655. attrs.x = x;
  34656. }
  34657. if (y) {
  34658. attrs.y = y;
  34659. }
  34660. setTransform(attrs, el.transform);
  34661. setStyleAttrs(attrs, style, el, scope);
  34662. setMetaData(attrs, el);
  34663. scope.animation && createCSSAnimation(el, attrs, scope);
  34664. return createVNode('text', el.id + '', attrs, undefined, text);
  34665. }
  34666. function brush$1(el, scope) {
  34667. if (el instanceof Path) {
  34668. return brushSVGPath(el, scope);
  34669. }
  34670. else if (el instanceof ZRImage) {
  34671. return brushSVGImage(el, scope);
  34672. }
  34673. else if (el instanceof TSpan) {
  34674. return brushSVGTSpan(el, scope);
  34675. }
  34676. }
  34677. function setShadow(el, attrs, scope) {
  34678. var style = el.style;
  34679. if (hasShadow(style)) {
  34680. var shadowKey = getShadowKey(el);
  34681. var shadowCache = scope.shadowCache;
  34682. var shadowId = shadowCache[shadowKey];
  34683. if (!shadowId) {
  34684. var globalScale = el.getGlobalScale();
  34685. var scaleX = globalScale[0];
  34686. var scaleY = globalScale[1];
  34687. if (!scaleX || !scaleY) {
  34688. return;
  34689. }
  34690. var offsetX = style.shadowOffsetX || 0;
  34691. var offsetY = style.shadowOffsetY || 0;
  34692. var blur_1 = style.shadowBlur;
  34693. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  34694. var stdDx = blur_1 / 2 / scaleX;
  34695. var stdDy = blur_1 / 2 / scaleY;
  34696. var stdDeviation = stdDx + ' ' + stdDy;
  34697. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  34698. scope.defs[shadowId] = createVNode('filter', shadowId, {
  34699. 'id': shadowId,
  34700. 'x': '-100%',
  34701. 'y': '-100%',
  34702. 'width': '300%',
  34703. 'height': '300%'
  34704. }, [
  34705. createVNode('feDropShadow', '', {
  34706. 'dx': offsetX / scaleX,
  34707. 'dy': offsetY / scaleY,
  34708. 'stdDeviation': stdDeviation,
  34709. 'flood-color': color,
  34710. 'flood-opacity': opacity
  34711. })
  34712. ]);
  34713. shadowCache[shadowKey] = shadowId;
  34714. }
  34715. attrs.filter = getIdURL(shadowId);
  34716. }
  34717. }
  34718. function setGradient(style, attrs, target, scope) {
  34719. var val = style[target];
  34720. var gradientTag;
  34721. var gradientAttrs = {
  34722. 'gradientUnits': val.global
  34723. ? 'userSpaceOnUse'
  34724. : 'objectBoundingBox'
  34725. };
  34726. if (isLinearGradient(val)) {
  34727. gradientTag = 'linearGradient';
  34728. gradientAttrs.x1 = val.x;
  34729. gradientAttrs.y1 = val.y;
  34730. gradientAttrs.x2 = val.x2;
  34731. gradientAttrs.y2 = val.y2;
  34732. }
  34733. else if (isRadialGradient(val)) {
  34734. gradientTag = 'radialGradient';
  34735. gradientAttrs.cx = retrieve2(val.x, 0.5);
  34736. gradientAttrs.cy = retrieve2(val.y, 0.5);
  34737. gradientAttrs.r = retrieve2(val.r, 0.5);
  34738. }
  34739. else {
  34740. if ("development" !== 'production') {
  34741. logError('Illegal gradient type.');
  34742. }
  34743. return;
  34744. }
  34745. var colors = val.colorStops;
  34746. var colorStops = [];
  34747. for (var i = 0, len = colors.length; i < len; ++i) {
  34748. var offset = round4(colors[i].offset) * 100 + '%';
  34749. var stopColor = colors[i].color;
  34750. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  34751. var stopsAttrs = {
  34752. 'offset': offset
  34753. };
  34754. stopsAttrs['stop-color'] = color;
  34755. if (opacity < 1) {
  34756. stopsAttrs['stop-opacity'] = opacity;
  34757. }
  34758. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  34759. }
  34760. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  34761. var gradientKey = vNodeToString(gradientVNode);
  34762. var gradientCache = scope.gradientCache;
  34763. var gradientId = gradientCache[gradientKey];
  34764. if (!gradientId) {
  34765. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  34766. gradientCache[gradientKey] = gradientId;
  34767. gradientAttrs.id = gradientId;
  34768. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  34769. }
  34770. attrs[target] = getIdURL(gradientId);
  34771. }
  34772. function setPattern(el, attrs, target, scope) {
  34773. var val = el.style[target];
  34774. var boundingRect = el.getBoundingRect();
  34775. var patternAttrs = {};
  34776. var repeat = val.repeat;
  34777. var noRepeat = repeat === 'no-repeat';
  34778. var repeatX = repeat === 'repeat-x';
  34779. var repeatY = repeat === 'repeat-y';
  34780. var child;
  34781. if (isImagePattern(val)) {
  34782. var imageWidth_1 = val.imageWidth;
  34783. var imageHeight_1 = val.imageHeight;
  34784. var imageSrc = void 0;
  34785. var patternImage = val.image;
  34786. if (isString(patternImage)) {
  34787. imageSrc = patternImage;
  34788. }
  34789. else if (isImageLike$1(patternImage)) {
  34790. imageSrc = patternImage.src;
  34791. }
  34792. else if (isCanvasLike(patternImage)) {
  34793. imageSrc = patternImage.toDataURL();
  34794. }
  34795. if (typeof Image === 'undefined') {
  34796. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  34797. assert(imageWidth_1, errMsg);
  34798. assert(imageHeight_1, errMsg);
  34799. }
  34800. else if (imageWidth_1 == null || imageHeight_1 == null) {
  34801. var setSizeToVNode_1 = function (vNode, img) {
  34802. if (vNode) {
  34803. var svgEl = vNode.elm;
  34804. var width = imageWidth_1 || img.width;
  34805. var height = imageHeight_1 || img.height;
  34806. if (vNode.tag === 'pattern') {
  34807. if (repeatX) {
  34808. height = 1;
  34809. width /= boundingRect.width;
  34810. }
  34811. else if (repeatY) {
  34812. width = 1;
  34813. height /= boundingRect.height;
  34814. }
  34815. }
  34816. vNode.attrs.width = width;
  34817. vNode.attrs.height = height;
  34818. if (svgEl) {
  34819. svgEl.setAttribute('width', width);
  34820. svgEl.setAttribute('height', height);
  34821. }
  34822. }
  34823. };
  34824. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  34825. noRepeat || setSizeToVNode_1(patternVNode, img);
  34826. setSizeToVNode_1(child, img);
  34827. });
  34828. if (createdImage && createdImage.width && createdImage.height) {
  34829. imageWidth_1 = imageWidth_1 || createdImage.width;
  34830. imageHeight_1 = imageHeight_1 || createdImage.height;
  34831. }
  34832. }
  34833. child = createVNode('image', 'img', {
  34834. href: imageSrc,
  34835. width: imageWidth_1,
  34836. height: imageHeight_1
  34837. });
  34838. patternAttrs.width = imageWidth_1;
  34839. patternAttrs.height = imageHeight_1;
  34840. }
  34841. else if (val.svgElement) {
  34842. child = clone(val.svgElement);
  34843. patternAttrs.width = val.svgWidth;
  34844. patternAttrs.height = val.svgHeight;
  34845. }
  34846. if (!child) {
  34847. return;
  34848. }
  34849. var patternWidth;
  34850. var patternHeight;
  34851. if (noRepeat) {
  34852. patternWidth = patternHeight = 1;
  34853. }
  34854. else if (repeatX) {
  34855. patternHeight = 1;
  34856. patternWidth = patternAttrs.width / boundingRect.width;
  34857. }
  34858. else if (repeatY) {
  34859. patternWidth = 1;
  34860. patternHeight = patternAttrs.height / boundingRect.height;
  34861. }
  34862. else {
  34863. patternAttrs.patternUnits = 'userSpaceOnUse';
  34864. }
  34865. if (patternWidth != null && !isNaN(patternWidth)) {
  34866. patternAttrs.width = patternWidth;
  34867. }
  34868. if (patternHeight != null && !isNaN(patternHeight)) {
  34869. patternAttrs.height = patternHeight;
  34870. }
  34871. var patternTransform = getSRTTransformString(val);
  34872. patternTransform && (patternAttrs.patternTransform = patternTransform);
  34873. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  34874. var patternKey = vNodeToString(patternVNode);
  34875. var patternCache = scope.patternCache;
  34876. var patternId = patternCache[patternKey];
  34877. if (!patternId) {
  34878. patternId = scope.zrId + '-p' + scope.patternIdx++;
  34879. patternCache[patternKey] = patternId;
  34880. patternAttrs.id = patternId;
  34881. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  34882. }
  34883. attrs[target] = getIdURL(patternId);
  34884. }
  34885. function setClipPath(clipPath, attrs, scope) {
  34886. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  34887. var clipPathId = clipPathCache[clipPath.id];
  34888. if (!clipPathId) {
  34889. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  34890. var clipPathAttrs = {
  34891. id: clipPathId
  34892. };
  34893. clipPathCache[clipPath.id] = clipPathId;
  34894. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  34895. }
  34896. attrs['clip-path'] = getIdURL(clipPathId);
  34897. }
  34898. function createTextNode(text) {
  34899. return document.createTextNode(text);
  34900. }
  34901. function insertBefore(parentNode, newNode, referenceNode) {
  34902. parentNode.insertBefore(newNode, referenceNode);
  34903. }
  34904. function removeChild(node, child) {
  34905. node.removeChild(child);
  34906. }
  34907. function appendChild(node, child) {
  34908. node.appendChild(child);
  34909. }
  34910. function parentNode(node) {
  34911. return node.parentNode;
  34912. }
  34913. function nextSibling(node) {
  34914. return node.nextSibling;
  34915. }
  34916. function setTextContent(node, text) {
  34917. node.textContent = text;
  34918. }
  34919. var colonChar = 58;
  34920. var xChar = 120;
  34921. var emptyNode = createVNode('', '');
  34922. function isUndef(s) {
  34923. return s === undefined;
  34924. }
  34925. function isDef(s) {
  34926. return s !== undefined;
  34927. }
  34928. function createKeyToOldIdx(children, beginIdx, endIdx) {
  34929. var map = {};
  34930. for (var i = beginIdx; i <= endIdx; ++i) {
  34931. var key = children[i].key;
  34932. if (key !== undefined) {
  34933. if ("development" !== 'production') {
  34934. if (map[key] != null) {
  34935. console.error("Duplicate key " + key);
  34936. }
  34937. }
  34938. map[key] = i;
  34939. }
  34940. }
  34941. return map;
  34942. }
  34943. function sameVnode(vnode1, vnode2) {
  34944. var isSameKey = vnode1.key === vnode2.key;
  34945. var isSameTag = vnode1.tag === vnode2.tag;
  34946. return isSameTag && isSameKey;
  34947. }
  34948. function createElm(vnode) {
  34949. var i;
  34950. var children = vnode.children;
  34951. var tag = vnode.tag;
  34952. if (isDef(tag)) {
  34953. var elm = (vnode.elm = createElement(tag));
  34954. updateAttrs(emptyNode, vnode);
  34955. if (isArray(children)) {
  34956. for (i = 0; i < children.length; ++i) {
  34957. var ch = children[i];
  34958. if (ch != null) {
  34959. appendChild(elm, createElm(ch));
  34960. }
  34961. }
  34962. }
  34963. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  34964. appendChild(elm, createTextNode(vnode.text));
  34965. }
  34966. }
  34967. else {
  34968. vnode.elm = createTextNode(vnode.text);
  34969. }
  34970. return vnode.elm;
  34971. }
  34972. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  34973. for (; startIdx <= endIdx; ++startIdx) {
  34974. var ch = vnodes[startIdx];
  34975. if (ch != null) {
  34976. insertBefore(parentElm, createElm(ch), before);
  34977. }
  34978. }
  34979. }
  34980. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  34981. for (; startIdx <= endIdx; ++startIdx) {
  34982. var ch = vnodes[startIdx];
  34983. if (ch != null) {
  34984. if (isDef(ch.tag)) {
  34985. var parent_1 = parentNode(ch.elm);
  34986. removeChild(parent_1, ch.elm);
  34987. }
  34988. else {
  34989. removeChild(parentElm, ch.elm);
  34990. }
  34991. }
  34992. }
  34993. }
  34994. function updateAttrs(oldVnode, vnode) {
  34995. var key;
  34996. var elm = vnode.elm;
  34997. var oldAttrs = oldVnode && oldVnode.attrs || {};
  34998. var attrs = vnode.attrs || {};
  34999. if (oldAttrs === attrs) {
  35000. return;
  35001. }
  35002. for (key in attrs) {
  35003. var cur = attrs[key];
  35004. var old = oldAttrs[key];
  35005. if (old !== cur) {
  35006. if (cur === true) {
  35007. elm.setAttribute(key, '');
  35008. }
  35009. else if (cur === false) {
  35010. elm.removeAttribute(key);
  35011. }
  35012. else {
  35013. if (key === 'style') {
  35014. elm.style.cssText = cur;
  35015. }
  35016. else if (key.charCodeAt(0) !== xChar) {
  35017. elm.setAttribute(key, cur);
  35018. }
  35019. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  35020. elm.setAttributeNS(XMLNS, key, cur);
  35021. }
  35022. else if (key.charCodeAt(3) === colonChar) {
  35023. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  35024. }
  35025. else if (key.charCodeAt(5) === colonChar) {
  35026. elm.setAttributeNS(XLINKNS, key, cur);
  35027. }
  35028. else {
  35029. elm.setAttribute(key, cur);
  35030. }
  35031. }
  35032. }
  35033. }
  35034. for (key in oldAttrs) {
  35035. if (!(key in attrs)) {
  35036. elm.removeAttribute(key);
  35037. }
  35038. }
  35039. }
  35040. function updateChildren(parentElm, oldCh, newCh) {
  35041. var oldStartIdx = 0;
  35042. var newStartIdx = 0;
  35043. var oldEndIdx = oldCh.length - 1;
  35044. var oldStartVnode = oldCh[0];
  35045. var oldEndVnode = oldCh[oldEndIdx];
  35046. var newEndIdx = newCh.length - 1;
  35047. var newStartVnode = newCh[0];
  35048. var newEndVnode = newCh[newEndIdx];
  35049. var oldKeyToIdx;
  35050. var idxInOld;
  35051. var elmToMove;
  35052. var before;
  35053. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  35054. if (oldStartVnode == null) {
  35055. oldStartVnode = oldCh[++oldStartIdx];
  35056. }
  35057. else if (oldEndVnode == null) {
  35058. oldEndVnode = oldCh[--oldEndIdx];
  35059. }
  35060. else if (newStartVnode == null) {
  35061. newStartVnode = newCh[++newStartIdx];
  35062. }
  35063. else if (newEndVnode == null) {
  35064. newEndVnode = newCh[--newEndIdx];
  35065. }
  35066. else if (sameVnode(oldStartVnode, newStartVnode)) {
  35067. patchVnode(oldStartVnode, newStartVnode);
  35068. oldStartVnode = oldCh[++oldStartIdx];
  35069. newStartVnode = newCh[++newStartIdx];
  35070. }
  35071. else if (sameVnode(oldEndVnode, newEndVnode)) {
  35072. patchVnode(oldEndVnode, newEndVnode);
  35073. oldEndVnode = oldCh[--oldEndIdx];
  35074. newEndVnode = newCh[--newEndIdx];
  35075. }
  35076. else if (sameVnode(oldStartVnode, newEndVnode)) {
  35077. patchVnode(oldStartVnode, newEndVnode);
  35078. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  35079. oldStartVnode = oldCh[++oldStartIdx];
  35080. newEndVnode = newCh[--newEndIdx];
  35081. }
  35082. else if (sameVnode(oldEndVnode, newStartVnode)) {
  35083. patchVnode(oldEndVnode, newStartVnode);
  35084. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  35085. oldEndVnode = oldCh[--oldEndIdx];
  35086. newStartVnode = newCh[++newStartIdx];
  35087. }
  35088. else {
  35089. if (isUndef(oldKeyToIdx)) {
  35090. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  35091. }
  35092. idxInOld = oldKeyToIdx[newStartVnode.key];
  35093. if (isUndef(idxInOld)) {
  35094. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35095. }
  35096. else {
  35097. elmToMove = oldCh[idxInOld];
  35098. if (elmToMove.tag !== newStartVnode.tag) {
  35099. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35100. }
  35101. else {
  35102. patchVnode(elmToMove, newStartVnode);
  35103. oldCh[idxInOld] = undefined;
  35104. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  35105. }
  35106. }
  35107. newStartVnode = newCh[++newStartIdx];
  35108. }
  35109. }
  35110. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  35111. if (oldStartIdx > oldEndIdx) {
  35112. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  35113. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  35114. }
  35115. else {
  35116. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  35117. }
  35118. }
  35119. }
  35120. function patchVnode(oldVnode, vnode) {
  35121. var elm = (vnode.elm = oldVnode.elm);
  35122. var oldCh = oldVnode.children;
  35123. var ch = vnode.children;
  35124. if (oldVnode === vnode) {
  35125. return;
  35126. }
  35127. updateAttrs(oldVnode, vnode);
  35128. if (isUndef(vnode.text)) {
  35129. if (isDef(oldCh) && isDef(ch)) {
  35130. if (oldCh !== ch) {
  35131. updateChildren(elm, oldCh, ch);
  35132. }
  35133. }
  35134. else if (isDef(ch)) {
  35135. if (isDef(oldVnode.text)) {
  35136. setTextContent(elm, '');
  35137. }
  35138. addVnodes(elm, null, ch, 0, ch.length - 1);
  35139. }
  35140. else if (isDef(oldCh)) {
  35141. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35142. }
  35143. else if (isDef(oldVnode.text)) {
  35144. setTextContent(elm, '');
  35145. }
  35146. }
  35147. else if (oldVnode.text !== vnode.text) {
  35148. if (isDef(oldCh)) {
  35149. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35150. }
  35151. setTextContent(elm, vnode.text);
  35152. }
  35153. }
  35154. function patch(oldVnode, vnode) {
  35155. if (sameVnode(oldVnode, vnode)) {
  35156. patchVnode(oldVnode, vnode);
  35157. }
  35158. else {
  35159. var elm = oldVnode.elm;
  35160. var parent_2 = parentNode(elm);
  35161. createElm(vnode);
  35162. if (parent_2 !== null) {
  35163. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  35164. removeVnodes(parent_2, [oldVnode], 0, 0);
  35165. }
  35166. }
  35167. return vnode;
  35168. }
  35169. var svgId = 0;
  35170. var SVGPainter = (function () {
  35171. function SVGPainter(root, storage, opts) {
  35172. this.type = 'svg';
  35173. this.refreshHover = createMethodNotSupport('refreshHover');
  35174. this.configLayer = createMethodNotSupport('configLayer');
  35175. this.storage = storage;
  35176. this._opts = opts = extend({}, opts);
  35177. this.root = root;
  35178. this._id = 'zr' + svgId++;
  35179. this._oldVNode = createSVGVNode(opts.width, opts.height);
  35180. if (root && !opts.ssr) {
  35181. var viewport = this._viewport = document.createElement('div');
  35182. viewport.style.cssText = 'position:relative;overflow:hidden';
  35183. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  35184. updateAttrs(null, this._oldVNode);
  35185. viewport.appendChild(svgDom);
  35186. root.appendChild(viewport);
  35187. }
  35188. this.resize(opts.width, opts.height);
  35189. }
  35190. SVGPainter.prototype.getType = function () {
  35191. return this.type;
  35192. };
  35193. SVGPainter.prototype.getViewportRoot = function () {
  35194. return this._viewport;
  35195. };
  35196. SVGPainter.prototype.getViewportRootOffset = function () {
  35197. var viewportRoot = this.getViewportRoot();
  35198. if (viewportRoot) {
  35199. return {
  35200. offsetLeft: viewportRoot.offsetLeft || 0,
  35201. offsetTop: viewportRoot.offsetTop || 0
  35202. };
  35203. }
  35204. };
  35205. SVGPainter.prototype.getSvgDom = function () {
  35206. return this._svgDom;
  35207. };
  35208. SVGPainter.prototype.refresh = function () {
  35209. if (this.root) {
  35210. var vnode = this.renderToVNode({
  35211. willUpdate: true
  35212. });
  35213. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  35214. patch(this._oldVNode, vnode);
  35215. this._oldVNode = vnode;
  35216. }
  35217. };
  35218. SVGPainter.prototype.renderOneToVNode = function (el) {
  35219. return brush$1(el, createBrushScope(this._id));
  35220. };
  35221. SVGPainter.prototype.renderToVNode = function (opts) {
  35222. opts = opts || {};
  35223. var list = this.storage.getDisplayList(true);
  35224. var width = this._width;
  35225. var height = this._height;
  35226. var scope = createBrushScope(this._id);
  35227. scope.animation = opts.animation;
  35228. scope.willUpdate = opts.willUpdate;
  35229. scope.compress = opts.compress;
  35230. scope.emphasis = opts.emphasis;
  35231. var children = [];
  35232. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  35233. bgVNode && children.push(bgVNode);
  35234. var mainVNode = !opts.compress
  35235. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  35236. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  35237. mainVNode && children.push(mainVNode);
  35238. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  35239. if (defs.length) {
  35240. children.push(createVNode('defs', 'defs', {}, defs));
  35241. }
  35242. if (opts.animation) {
  35243. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  35244. if (animationCssStr) {
  35245. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  35246. children.push(styleNode);
  35247. }
  35248. }
  35249. return createSVGVNode(width, height, children, opts.useViewBox);
  35250. };
  35251. SVGPainter.prototype.renderToString = function (opts) {
  35252. opts = opts || {};
  35253. return vNodeToString(this.renderToVNode({
  35254. animation: retrieve2(opts.cssAnimation, true),
  35255. emphasis: retrieve2(opts.cssEmphasis, true),
  35256. willUpdate: false,
  35257. compress: true,
  35258. useViewBox: retrieve2(opts.useViewBox, true)
  35259. }), { newline: true });
  35260. };
  35261. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35262. this._backgroundColor = backgroundColor;
  35263. };
  35264. SVGPainter.prototype.getSvgRoot = function () {
  35265. return this._mainVNode && this._mainVNode.elm;
  35266. };
  35267. SVGPainter.prototype._paintList = function (list, scope, out) {
  35268. var listLen = list.length;
  35269. var clipPathsGroupsStack = [];
  35270. var clipPathsGroupsStackDepth = 0;
  35271. var currentClipPathGroup;
  35272. var prevClipPaths;
  35273. var clipGroupNodeIdx = 0;
  35274. for (var i = 0; i < listLen; i++) {
  35275. var displayable = list[i];
  35276. if (!displayable.invisible) {
  35277. var clipPaths = displayable.__clipPaths;
  35278. var len = clipPaths && clipPaths.length || 0;
  35279. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  35280. var lca = void 0;
  35281. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  35282. if (clipPaths && prevClipPaths
  35283. && clipPaths[lca] === prevClipPaths[lca]) {
  35284. break;
  35285. }
  35286. }
  35287. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  35288. clipPathsGroupsStackDepth--;
  35289. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  35290. }
  35291. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  35292. var groupAttrs = {};
  35293. setClipPath(clipPaths[i_2], groupAttrs, scope);
  35294. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  35295. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  35296. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  35297. currentClipPathGroup = g;
  35298. }
  35299. prevClipPaths = clipPaths;
  35300. var ret = brush$1(displayable, scope);
  35301. if (ret) {
  35302. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  35303. }
  35304. }
  35305. }
  35306. };
  35307. SVGPainter.prototype.resize = function (width, height) {
  35308. var opts = this._opts;
  35309. var root = this.root;
  35310. var viewport = this._viewport;
  35311. width != null && (opts.width = width);
  35312. height != null && (opts.height = height);
  35313. if (root && viewport) {
  35314. viewport.style.display = 'none';
  35315. width = getSize(root, 0, opts);
  35316. height = getSize(root, 1, opts);
  35317. viewport.style.display = '';
  35318. }
  35319. if (this._width !== width || this._height !== height) {
  35320. this._width = width;
  35321. this._height = height;
  35322. if (viewport) {
  35323. var viewportStyle = viewport.style;
  35324. viewportStyle.width = width + 'px';
  35325. viewportStyle.height = height + 'px';
  35326. }
  35327. if (!isPattern(this._backgroundColor)) {
  35328. var svgDom = this._svgDom;
  35329. if (svgDom) {
  35330. svgDom.setAttribute('width', width);
  35331. svgDom.setAttribute('height', height);
  35332. }
  35333. var bgEl = this._bgVNode && this._bgVNode.elm;
  35334. if (bgEl) {
  35335. bgEl.setAttribute('width', width);
  35336. bgEl.setAttribute('height', height);
  35337. }
  35338. }
  35339. else {
  35340. this.refresh();
  35341. }
  35342. }
  35343. };
  35344. SVGPainter.prototype.getWidth = function () {
  35345. return this._width;
  35346. };
  35347. SVGPainter.prototype.getHeight = function () {
  35348. return this._height;
  35349. };
  35350. SVGPainter.prototype.dispose = function () {
  35351. if (this.root) {
  35352. this.root.innerHTML = '';
  35353. }
  35354. this._svgDom =
  35355. this._viewport =
  35356. this.storage =
  35357. this._oldVNode =
  35358. this._bgVNode =
  35359. this._mainVNode = null;
  35360. };
  35361. SVGPainter.prototype.clear = function () {
  35362. if (this._svgDom) {
  35363. this._svgDom.innerHTML = null;
  35364. }
  35365. this._oldVNode = null;
  35366. };
  35367. SVGPainter.prototype.toDataURL = function (base64) {
  35368. var str = this.renderToString();
  35369. var prefix = 'data:image/svg+xml;';
  35370. if (base64) {
  35371. str = encodeBase64(str);
  35372. return str && prefix + 'base64,' + str;
  35373. }
  35374. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  35375. };
  35376. return SVGPainter;
  35377. }());
  35378. function createMethodNotSupport(method) {
  35379. return function () {
  35380. if ("development" !== 'production') {
  35381. logError('In SVG mode painter not support method "' + method + '"');
  35382. }
  35383. };
  35384. }
  35385. function createBackgroundVNode(width, height, backgroundColor, scope) {
  35386. var bgVNode;
  35387. if (backgroundColor && backgroundColor !== 'none') {
  35388. bgVNode = createVNode('rect', 'bg', {
  35389. width: width,
  35390. height: height,
  35391. x: '0',
  35392. y: '0'
  35393. });
  35394. if (isGradient(backgroundColor)) {
  35395. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  35396. }
  35397. else if (isPattern(backgroundColor)) {
  35398. setPattern({
  35399. style: {
  35400. fill: backgroundColor
  35401. },
  35402. dirty: noop,
  35403. getBoundingRect: function () { return ({ width: width, height: height }); }
  35404. }, bgVNode.attrs, 'fill', scope);
  35405. }
  35406. else {
  35407. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  35408. bgVNode.attrs.fill = color;
  35409. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  35410. }
  35411. }
  35412. return bgVNode;
  35413. }
  35414. function install(registers) {
  35415. registers.registerPainter('svg', SVGPainter);
  35416. }
  35417. function createDom(id, painter, dpr) {
  35418. var newDom = platformApi.createCanvas();
  35419. var width = painter.getWidth();
  35420. var height = painter.getHeight();
  35421. var newDomStyle = newDom.style;
  35422. if (newDomStyle) {
  35423. newDomStyle.position = 'absolute';
  35424. newDomStyle.left = '0';
  35425. newDomStyle.top = '0';
  35426. newDomStyle.width = width + 'px';
  35427. newDomStyle.height = height + 'px';
  35428. newDom.setAttribute('data-zr-dom-id', id);
  35429. }
  35430. newDom.width = width * dpr;
  35431. newDom.height = height * dpr;
  35432. return newDom;
  35433. }
  35434. var Layer = (function (_super) {
  35435. __extends(Layer, _super);
  35436. function Layer(id, painter, dpr) {
  35437. var _this = _super.call(this) || this;
  35438. _this.motionBlur = false;
  35439. _this.lastFrameAlpha = 0.7;
  35440. _this.dpr = 1;
  35441. _this.virtual = false;
  35442. _this.config = {};
  35443. _this.incremental = false;
  35444. _this.zlevel = 0;
  35445. _this.maxRepaintRectCount = 5;
  35446. _this.__dirty = true;
  35447. _this.__firstTimePaint = true;
  35448. _this.__used = false;
  35449. _this.__drawIndex = 0;
  35450. _this.__startIndex = 0;
  35451. _this.__endIndex = 0;
  35452. _this.__prevStartIndex = null;
  35453. _this.__prevEndIndex = null;
  35454. var dom;
  35455. dpr = dpr || devicePixelRatio;
  35456. if (typeof id === 'string') {
  35457. dom = createDom(id, painter, dpr);
  35458. }
  35459. else if (isObject(id)) {
  35460. dom = id;
  35461. id = dom.id;
  35462. }
  35463. _this.id = id;
  35464. _this.dom = dom;
  35465. var domStyle = dom.style;
  35466. if (domStyle) {
  35467. disableUserSelect(dom);
  35468. dom.onselectstart = function () { return false; };
  35469. domStyle.padding = '0';
  35470. domStyle.margin = '0';
  35471. domStyle.borderWidth = '0';
  35472. }
  35473. _this.painter = painter;
  35474. _this.dpr = dpr;
  35475. return _this;
  35476. }
  35477. Layer.prototype.getElementCount = function () {
  35478. return this.__endIndex - this.__startIndex;
  35479. };
  35480. Layer.prototype.afterBrush = function () {
  35481. this.__prevStartIndex = this.__startIndex;
  35482. this.__prevEndIndex = this.__endIndex;
  35483. };
  35484. Layer.prototype.initContext = function () {
  35485. this.ctx = this.dom.getContext('2d');
  35486. this.ctx.dpr = this.dpr;
  35487. };
  35488. Layer.prototype.setUnpainted = function () {
  35489. this.__firstTimePaint = true;
  35490. };
  35491. Layer.prototype.createBackBuffer = function () {
  35492. var dpr = this.dpr;
  35493. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  35494. this.ctxBack = this.domBack.getContext('2d');
  35495. if (dpr !== 1) {
  35496. this.ctxBack.scale(dpr, dpr);
  35497. }
  35498. };
  35499. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  35500. if (this.__firstTimePaint) {
  35501. this.__firstTimePaint = false;
  35502. return null;
  35503. }
  35504. var mergedRepaintRects = [];
  35505. var maxRepaintRectCount = this.maxRepaintRectCount;
  35506. var full = false;
  35507. var pendingRect = new BoundingRect(0, 0, 0, 0);
  35508. function addRectToMergePool(rect) {
  35509. if (!rect.isFinite() || rect.isZero()) {
  35510. return;
  35511. }
  35512. if (mergedRepaintRects.length === 0) {
  35513. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35514. boundingRect.copy(rect);
  35515. mergedRepaintRects.push(boundingRect);
  35516. }
  35517. else {
  35518. var isMerged = false;
  35519. var minDeltaArea = Infinity;
  35520. var bestRectToMergeIdx = 0;
  35521. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  35522. var mergedRect = mergedRepaintRects[i];
  35523. if (mergedRect.intersect(rect)) {
  35524. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  35525. pendingRect_1.copy(mergedRect);
  35526. pendingRect_1.union(rect);
  35527. mergedRepaintRects[i] = pendingRect_1;
  35528. isMerged = true;
  35529. break;
  35530. }
  35531. else if (full) {
  35532. pendingRect.copy(rect);
  35533. pendingRect.union(mergedRect);
  35534. var aArea = rect.width * rect.height;
  35535. var bArea = mergedRect.width * mergedRect.height;
  35536. var pendingArea = pendingRect.width * pendingRect.height;
  35537. var deltaArea = pendingArea - aArea - bArea;
  35538. if (deltaArea < minDeltaArea) {
  35539. minDeltaArea = deltaArea;
  35540. bestRectToMergeIdx = i;
  35541. }
  35542. }
  35543. }
  35544. if (full) {
  35545. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  35546. isMerged = true;
  35547. }
  35548. if (!isMerged) {
  35549. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35550. boundingRect.copy(rect);
  35551. mergedRepaintRects.push(boundingRect);
  35552. }
  35553. if (!full) {
  35554. full = mergedRepaintRects.length >= maxRepaintRectCount;
  35555. }
  35556. }
  35557. }
  35558. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  35559. var el = displayList[i];
  35560. if (el) {
  35561. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35562. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  35563. ? el.getPrevPaintRect()
  35564. : null;
  35565. if (prevRect) {
  35566. addRectToMergePool(prevRect);
  35567. }
  35568. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  35569. ? el.getPaintRect()
  35570. : null;
  35571. if (curRect) {
  35572. addRectToMergePool(curRect);
  35573. }
  35574. }
  35575. }
  35576. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  35577. var el = prevList[i];
  35578. var shouldPaint = el && el.shouldBePainted(viewWidth, viewHeight, true, true);
  35579. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  35580. var prevRect = el.getPrevPaintRect();
  35581. if (prevRect) {
  35582. addRectToMergePool(prevRect);
  35583. }
  35584. }
  35585. }
  35586. var hasIntersections;
  35587. do {
  35588. hasIntersections = false;
  35589. for (var i = 0; i < mergedRepaintRects.length;) {
  35590. if (mergedRepaintRects[i].isZero()) {
  35591. mergedRepaintRects.splice(i, 1);
  35592. continue;
  35593. }
  35594. for (var j = i + 1; j < mergedRepaintRects.length;) {
  35595. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  35596. hasIntersections = true;
  35597. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  35598. mergedRepaintRects.splice(j, 1);
  35599. }
  35600. else {
  35601. j++;
  35602. }
  35603. }
  35604. i++;
  35605. }
  35606. } while (hasIntersections);
  35607. this._paintRects = mergedRepaintRects;
  35608. return mergedRepaintRects;
  35609. };
  35610. Layer.prototype.debugGetPaintRects = function () {
  35611. return (this._paintRects || []).slice();
  35612. };
  35613. Layer.prototype.resize = function (width, height) {
  35614. var dpr = this.dpr;
  35615. var dom = this.dom;
  35616. var domStyle = dom.style;
  35617. var domBack = this.domBack;
  35618. if (domStyle) {
  35619. domStyle.width = width + 'px';
  35620. domStyle.height = height + 'px';
  35621. }
  35622. dom.width = width * dpr;
  35623. dom.height = height * dpr;
  35624. if (domBack) {
  35625. domBack.width = width * dpr;
  35626. domBack.height = height * dpr;
  35627. if (dpr !== 1) {
  35628. this.ctxBack.scale(dpr, dpr);
  35629. }
  35630. }
  35631. };
  35632. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  35633. var dom = this.dom;
  35634. var ctx = this.ctx;
  35635. var width = dom.width;
  35636. var height = dom.height;
  35637. clearColor = clearColor || this.clearColor;
  35638. var haveMotionBLur = this.motionBlur && !clearAll;
  35639. var lastFrameAlpha = this.lastFrameAlpha;
  35640. var dpr = this.dpr;
  35641. var self = this;
  35642. if (haveMotionBLur) {
  35643. if (!this.domBack) {
  35644. this.createBackBuffer();
  35645. }
  35646. this.ctxBack.globalCompositeOperation = 'copy';
  35647. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  35648. }
  35649. var domBack = this.domBack;
  35650. function doClear(x, y, width, height) {
  35651. ctx.clearRect(x, y, width, height);
  35652. if (clearColor && clearColor !== 'transparent') {
  35653. var clearColorGradientOrPattern = void 0;
  35654. if (isGradientObject(clearColor)) {
  35655. var shouldCache = clearColor.global || (clearColor.__width === width
  35656. && clearColor.__height === height);
  35657. clearColorGradientOrPattern = shouldCache
  35658. && clearColor.__canvasGradient
  35659. || getCanvasGradient(ctx, clearColor, {
  35660. x: 0,
  35661. y: 0,
  35662. width: width,
  35663. height: height
  35664. });
  35665. clearColor.__canvasGradient = clearColorGradientOrPattern;
  35666. clearColor.__width = width;
  35667. clearColor.__height = height;
  35668. }
  35669. else if (isImagePatternObject(clearColor)) {
  35670. clearColor.scaleX = clearColor.scaleX || dpr;
  35671. clearColor.scaleY = clearColor.scaleY || dpr;
  35672. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  35673. dirty: function () {
  35674. self.setUnpainted();
  35675. self.painter.refresh();
  35676. }
  35677. });
  35678. }
  35679. ctx.save();
  35680. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  35681. ctx.fillRect(x, y, width, height);
  35682. ctx.restore();
  35683. }
  35684. if (haveMotionBLur) {
  35685. ctx.save();
  35686. ctx.globalAlpha = lastFrameAlpha;
  35687. ctx.drawImage(domBack, x, y, width, height);
  35688. ctx.restore();
  35689. }
  35690. }
  35691. if (!repaintRects || haveMotionBLur) {
  35692. doClear(0, 0, width, height);
  35693. }
  35694. else if (repaintRects.length) {
  35695. each(repaintRects, function (rect) {
  35696. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35697. });
  35698. }
  35699. };
  35700. return Layer;
  35701. }(Eventful));
  35702. var HOVER_LAYER_ZLEVEL = 1e5;
  35703. var CANVAS_ZLEVEL = 314159;
  35704. var EL_AFTER_INCREMENTAL_INC = 0.01;
  35705. var INCREMENTAL_INC = 0.001;
  35706. function isLayerValid(layer) {
  35707. if (!layer) {
  35708. return false;
  35709. }
  35710. if (layer.__builtin__) {
  35711. return true;
  35712. }
  35713. if (typeof (layer.resize) !== 'function'
  35714. || typeof (layer.refresh) !== 'function') {
  35715. return false;
  35716. }
  35717. return true;
  35718. }
  35719. function createRoot(width, height) {
  35720. var domRoot = document.createElement('div');
  35721. domRoot.style.cssText = [
  35722. 'position:relative',
  35723. 'width:' + width + 'px',
  35724. 'height:' + height + 'px',
  35725. 'padding:0',
  35726. 'margin:0',
  35727. 'border-width:0'
  35728. ].join(';') + ';';
  35729. return domRoot;
  35730. }
  35731. var CanvasPainter = (function () {
  35732. function CanvasPainter(root, storage, opts, id) {
  35733. this.type = 'canvas';
  35734. this._zlevelList = [];
  35735. this._prevDisplayList = [];
  35736. this._layers = {};
  35737. this._layerConfig = {};
  35738. this._needsManuallyCompositing = false;
  35739. this.type = 'canvas';
  35740. var singleCanvas = !root.nodeName
  35741. || root.nodeName.toUpperCase() === 'CANVAS';
  35742. this._opts = opts = extend({}, opts || {});
  35743. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  35744. this._singleCanvas = singleCanvas;
  35745. this.root = root;
  35746. var rootStyle = root.style;
  35747. if (rootStyle) {
  35748. disableUserSelect(root);
  35749. root.innerHTML = '';
  35750. }
  35751. this.storage = storage;
  35752. var zlevelList = this._zlevelList;
  35753. this._prevDisplayList = [];
  35754. var layers = this._layers;
  35755. if (!singleCanvas) {
  35756. this._width = getSize(root, 0, opts);
  35757. this._height = getSize(root, 1, opts);
  35758. var domRoot = this._domRoot = createRoot(this._width, this._height);
  35759. root.appendChild(domRoot);
  35760. }
  35761. else {
  35762. var rootCanvas = root;
  35763. var width = rootCanvas.width;
  35764. var height = rootCanvas.height;
  35765. if (opts.width != null) {
  35766. width = opts.width;
  35767. }
  35768. if (opts.height != null) {
  35769. height = opts.height;
  35770. }
  35771. this.dpr = opts.devicePixelRatio || 1;
  35772. rootCanvas.width = width * this.dpr;
  35773. rootCanvas.height = height * this.dpr;
  35774. this._width = width;
  35775. this._height = height;
  35776. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  35777. mainLayer.__builtin__ = true;
  35778. mainLayer.initContext();
  35779. layers[CANVAS_ZLEVEL] = mainLayer;
  35780. mainLayer.zlevel = CANVAS_ZLEVEL;
  35781. zlevelList.push(CANVAS_ZLEVEL);
  35782. this._domRoot = root;
  35783. }
  35784. }
  35785. CanvasPainter.prototype.getType = function () {
  35786. return 'canvas';
  35787. };
  35788. CanvasPainter.prototype.isSingleCanvas = function () {
  35789. return this._singleCanvas;
  35790. };
  35791. CanvasPainter.prototype.getViewportRoot = function () {
  35792. return this._domRoot;
  35793. };
  35794. CanvasPainter.prototype.getViewportRootOffset = function () {
  35795. var viewportRoot = this.getViewportRoot();
  35796. if (viewportRoot) {
  35797. return {
  35798. offsetLeft: viewportRoot.offsetLeft || 0,
  35799. offsetTop: viewportRoot.offsetTop || 0
  35800. };
  35801. }
  35802. };
  35803. CanvasPainter.prototype.refresh = function (paintAll) {
  35804. var list = this.storage.getDisplayList(true);
  35805. var prevList = this._prevDisplayList;
  35806. var zlevelList = this._zlevelList;
  35807. this._redrawId = Math.random();
  35808. this._paintList(list, prevList, paintAll, this._redrawId);
  35809. for (var i = 0; i < zlevelList.length; i++) {
  35810. var z = zlevelList[i];
  35811. var layer = this._layers[z];
  35812. if (!layer.__builtin__ && layer.refresh) {
  35813. var clearColor = i === 0 ? this._backgroundColor : null;
  35814. layer.refresh(clearColor);
  35815. }
  35816. }
  35817. if (this._opts.useDirtyRect) {
  35818. this._prevDisplayList = list.slice();
  35819. }
  35820. return this;
  35821. };
  35822. CanvasPainter.prototype.refreshHover = function () {
  35823. this._paintHoverList(this.storage.getDisplayList(false));
  35824. };
  35825. CanvasPainter.prototype._paintHoverList = function (list) {
  35826. var len = list.length;
  35827. var hoverLayer = this._hoverlayer;
  35828. hoverLayer && hoverLayer.clear();
  35829. if (!len) {
  35830. return;
  35831. }
  35832. var scope = {
  35833. inHover: true,
  35834. viewWidth: this._width,
  35835. viewHeight: this._height
  35836. };
  35837. var ctx;
  35838. for (var i = 0; i < len; i++) {
  35839. var el = list[i];
  35840. if (el.__inHover) {
  35841. if (!hoverLayer) {
  35842. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  35843. }
  35844. if (!ctx) {
  35845. ctx = hoverLayer.ctx;
  35846. ctx.save();
  35847. }
  35848. brush(ctx, el, scope, i === len - 1);
  35849. }
  35850. }
  35851. if (ctx) {
  35852. ctx.restore();
  35853. }
  35854. };
  35855. CanvasPainter.prototype.getHoverLayer = function () {
  35856. return this.getLayer(HOVER_LAYER_ZLEVEL);
  35857. };
  35858. CanvasPainter.prototype.paintOne = function (ctx, el) {
  35859. brushSingle(ctx, el);
  35860. };
  35861. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  35862. if (this._redrawId !== redrawId) {
  35863. return;
  35864. }
  35865. paintAll = paintAll || false;
  35866. this._updateLayerStatus(list);
  35867. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  35868. if (this._needsManuallyCompositing) {
  35869. this._compositeManually();
  35870. }
  35871. if (needsRefreshHover) {
  35872. this._paintHoverList(list);
  35873. }
  35874. if (!finished) {
  35875. var self_1 = this;
  35876. requestAnimationFrame$1(function () {
  35877. self_1._paintList(list, prevList, paintAll, redrawId);
  35878. });
  35879. }
  35880. else {
  35881. this.eachLayer(function (layer) {
  35882. layer.afterBrush && layer.afterBrush();
  35883. });
  35884. }
  35885. };
  35886. CanvasPainter.prototype._compositeManually = function () {
  35887. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  35888. var width = this._domRoot.width;
  35889. var height = this._domRoot.height;
  35890. ctx.clearRect(0, 0, width, height);
  35891. this.eachBuiltinLayer(function (layer) {
  35892. if (layer.virtual) {
  35893. ctx.drawImage(layer.dom, 0, 0, width, height);
  35894. }
  35895. });
  35896. };
  35897. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  35898. var _this = this;
  35899. var layerList = [];
  35900. var useDirtyRect = this._opts.useDirtyRect;
  35901. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  35902. var zlevel = this._zlevelList[zi];
  35903. var layer = this._layers[zlevel];
  35904. if (layer.__builtin__
  35905. && layer !== this._hoverlayer
  35906. && (layer.__dirty || paintAll)) {
  35907. layerList.push(layer);
  35908. }
  35909. }
  35910. var finished = true;
  35911. var needsRefreshHover = false;
  35912. var _loop_1 = function (k) {
  35913. var layer = layerList[k];
  35914. var ctx = layer.ctx;
  35915. var repaintRects = useDirtyRect
  35916. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  35917. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  35918. var useTimer = !paintAll && layer.incremental && Date.now;
  35919. var startTime = useTimer && Date.now();
  35920. var clearColor = layer.zlevel === this_1._zlevelList[0]
  35921. ? this_1._backgroundColor : null;
  35922. if (layer.__startIndex === layer.__endIndex) {
  35923. layer.clear(false, clearColor, repaintRects);
  35924. }
  35925. else if (start === layer.__startIndex) {
  35926. var firstEl = list[start];
  35927. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  35928. layer.clear(false, clearColor, repaintRects);
  35929. }
  35930. }
  35931. if (start === -1) {
  35932. console.error('For some unknown reason. drawIndex is -1');
  35933. start = layer.__startIndex;
  35934. }
  35935. var i;
  35936. var repaint = function (repaintRect) {
  35937. var scope = {
  35938. inHover: false,
  35939. allClipped: false,
  35940. prevEl: null,
  35941. viewWidth: _this._width,
  35942. viewHeight: _this._height
  35943. };
  35944. for (i = start; i < layer.__endIndex; i++) {
  35945. var el = list[i];
  35946. if (el.__inHover) {
  35947. needsRefreshHover = true;
  35948. }
  35949. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  35950. if (useTimer) {
  35951. var dTime = Date.now() - startTime;
  35952. if (dTime > 15) {
  35953. break;
  35954. }
  35955. }
  35956. }
  35957. if (scope.prevElClipPaths) {
  35958. ctx.restore();
  35959. }
  35960. };
  35961. if (repaintRects) {
  35962. if (repaintRects.length === 0) {
  35963. i = layer.__endIndex;
  35964. }
  35965. else {
  35966. var dpr = this_1.dpr;
  35967. for (var r = 0; r < repaintRects.length; ++r) {
  35968. var rect = repaintRects[r];
  35969. ctx.save();
  35970. ctx.beginPath();
  35971. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35972. ctx.clip();
  35973. repaint(rect);
  35974. ctx.restore();
  35975. }
  35976. }
  35977. }
  35978. else {
  35979. ctx.save();
  35980. repaint();
  35981. ctx.restore();
  35982. }
  35983. layer.__drawIndex = i;
  35984. if (layer.__drawIndex < layer.__endIndex) {
  35985. finished = false;
  35986. }
  35987. };
  35988. var this_1 = this;
  35989. for (var k = 0; k < layerList.length; k++) {
  35990. _loop_1(k);
  35991. }
  35992. if (env.wxa) {
  35993. each(this._layers, function (layer) {
  35994. if (layer && layer.ctx && layer.ctx.draw) {
  35995. layer.ctx.draw();
  35996. }
  35997. });
  35998. }
  35999. return {
  36000. finished: finished,
  36001. needsRefreshHover: needsRefreshHover
  36002. };
  36003. };
  36004. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  36005. var ctx = currentLayer.ctx;
  36006. if (useDirtyRect) {
  36007. var paintRect = el.getPaintRect();
  36008. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  36009. brush(ctx, el, scope, isLast);
  36010. el.setPrevPaintRect(paintRect);
  36011. }
  36012. }
  36013. else {
  36014. brush(ctx, el, scope, isLast);
  36015. }
  36016. };
  36017. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  36018. if (this._singleCanvas && !this._needsManuallyCompositing) {
  36019. zlevel = CANVAS_ZLEVEL;
  36020. }
  36021. var layer = this._layers[zlevel];
  36022. if (!layer) {
  36023. layer = new Layer('zr_' + zlevel, this, this.dpr);
  36024. layer.zlevel = zlevel;
  36025. layer.__builtin__ = true;
  36026. if (this._layerConfig[zlevel]) {
  36027. merge(layer, this._layerConfig[zlevel], true);
  36028. }
  36029. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  36030. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  36031. }
  36032. if (virtual) {
  36033. layer.virtual = virtual;
  36034. }
  36035. this.insertLayer(zlevel, layer);
  36036. layer.initContext();
  36037. }
  36038. return layer;
  36039. };
  36040. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  36041. var layersMap = this._layers;
  36042. var zlevelList = this._zlevelList;
  36043. var len = zlevelList.length;
  36044. var domRoot = this._domRoot;
  36045. var prevLayer = null;
  36046. var i = -1;
  36047. if (layersMap[zlevel]) {
  36048. if ("development" !== 'production') {
  36049. logError('ZLevel ' + zlevel + ' has been used already');
  36050. }
  36051. return;
  36052. }
  36053. if (!isLayerValid(layer)) {
  36054. if ("development" !== 'production') {
  36055. logError('Layer of zlevel ' + zlevel + ' is not valid');
  36056. }
  36057. return;
  36058. }
  36059. if (len > 0 && zlevel > zlevelList[0]) {
  36060. for (i = 0; i < len - 1; i++) {
  36061. if (zlevelList[i] < zlevel
  36062. && zlevelList[i + 1] > zlevel) {
  36063. break;
  36064. }
  36065. }
  36066. prevLayer = layersMap[zlevelList[i]];
  36067. }
  36068. zlevelList.splice(i + 1, 0, zlevel);
  36069. layersMap[zlevel] = layer;
  36070. if (!layer.virtual) {
  36071. if (prevLayer) {
  36072. var prevDom = prevLayer.dom;
  36073. if (prevDom.nextSibling) {
  36074. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  36075. }
  36076. else {
  36077. domRoot.appendChild(layer.dom);
  36078. }
  36079. }
  36080. else {
  36081. if (domRoot.firstChild) {
  36082. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  36083. }
  36084. else {
  36085. domRoot.appendChild(layer.dom);
  36086. }
  36087. }
  36088. }
  36089. layer.painter || (layer.painter = this);
  36090. };
  36091. CanvasPainter.prototype.eachLayer = function (cb, context) {
  36092. var zlevelList = this._zlevelList;
  36093. for (var i = 0; i < zlevelList.length; i++) {
  36094. var z = zlevelList[i];
  36095. cb.call(context, this._layers[z], z);
  36096. }
  36097. };
  36098. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  36099. var zlevelList = this._zlevelList;
  36100. for (var i = 0; i < zlevelList.length; i++) {
  36101. var z = zlevelList[i];
  36102. var layer = this._layers[z];
  36103. if (layer.__builtin__) {
  36104. cb.call(context, layer, z);
  36105. }
  36106. }
  36107. };
  36108. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  36109. var zlevelList = this._zlevelList;
  36110. for (var i = 0; i < zlevelList.length; i++) {
  36111. var z = zlevelList[i];
  36112. var layer = this._layers[z];
  36113. if (!layer.__builtin__) {
  36114. cb.call(context, layer, z);
  36115. }
  36116. }
  36117. };
  36118. CanvasPainter.prototype.getLayers = function () {
  36119. return this._layers;
  36120. };
  36121. CanvasPainter.prototype._updateLayerStatus = function (list) {
  36122. this.eachBuiltinLayer(function (layer, z) {
  36123. layer.__dirty = layer.__used = false;
  36124. });
  36125. function updatePrevLayer(idx) {
  36126. if (prevLayer) {
  36127. if (prevLayer.__endIndex !== idx) {
  36128. prevLayer.__dirty = true;
  36129. }
  36130. prevLayer.__endIndex = idx;
  36131. }
  36132. }
  36133. if (this._singleCanvas) {
  36134. for (var i_1 = 1; i_1 < list.length; i_1++) {
  36135. var el = list[i_1];
  36136. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  36137. this._needsManuallyCompositing = true;
  36138. break;
  36139. }
  36140. }
  36141. }
  36142. var prevLayer = null;
  36143. var incrementalLayerCount = 0;
  36144. var prevZlevel;
  36145. var i;
  36146. for (i = 0; i < list.length; i++) {
  36147. var el = list[i];
  36148. var zlevel = el.zlevel;
  36149. var layer = void 0;
  36150. if (prevZlevel !== zlevel) {
  36151. prevZlevel = zlevel;
  36152. incrementalLayerCount = 0;
  36153. }
  36154. if (el.incremental) {
  36155. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  36156. layer.incremental = true;
  36157. incrementalLayerCount = 1;
  36158. }
  36159. else {
  36160. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  36161. }
  36162. if (!layer.__builtin__) {
  36163. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  36164. }
  36165. if (layer !== prevLayer) {
  36166. layer.__used = true;
  36167. if (layer.__startIndex !== i) {
  36168. layer.__dirty = true;
  36169. }
  36170. layer.__startIndex = i;
  36171. if (!layer.incremental) {
  36172. layer.__drawIndex = i;
  36173. }
  36174. else {
  36175. layer.__drawIndex = -1;
  36176. }
  36177. updatePrevLayer(i);
  36178. prevLayer = layer;
  36179. }
  36180. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  36181. layer.__dirty = true;
  36182. if (layer.incremental && layer.__drawIndex < 0) {
  36183. layer.__drawIndex = i;
  36184. }
  36185. }
  36186. }
  36187. updatePrevLayer(i);
  36188. this.eachBuiltinLayer(function (layer, z) {
  36189. if (!layer.__used && layer.getElementCount() > 0) {
  36190. layer.__dirty = true;
  36191. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  36192. }
  36193. if (layer.__dirty && layer.__drawIndex < 0) {
  36194. layer.__drawIndex = layer.__startIndex;
  36195. }
  36196. });
  36197. };
  36198. CanvasPainter.prototype.clear = function () {
  36199. this.eachBuiltinLayer(this._clearLayer);
  36200. return this;
  36201. };
  36202. CanvasPainter.prototype._clearLayer = function (layer) {
  36203. layer.clear();
  36204. };
  36205. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  36206. this._backgroundColor = backgroundColor;
  36207. each(this._layers, function (layer) {
  36208. layer.setUnpainted();
  36209. });
  36210. };
  36211. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  36212. if (config) {
  36213. var layerConfig = this._layerConfig;
  36214. if (!layerConfig[zlevel]) {
  36215. layerConfig[zlevel] = config;
  36216. }
  36217. else {
  36218. merge(layerConfig[zlevel], config, true);
  36219. }
  36220. for (var i = 0; i < this._zlevelList.length; i++) {
  36221. var _zlevel = this._zlevelList[i];
  36222. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  36223. var layer = this._layers[_zlevel];
  36224. merge(layer, layerConfig[zlevel], true);
  36225. }
  36226. }
  36227. }
  36228. };
  36229. CanvasPainter.prototype.delLayer = function (zlevel) {
  36230. var layers = this._layers;
  36231. var zlevelList = this._zlevelList;
  36232. var layer = layers[zlevel];
  36233. if (!layer) {
  36234. return;
  36235. }
  36236. layer.dom.parentNode.removeChild(layer.dom);
  36237. delete layers[zlevel];
  36238. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  36239. };
  36240. CanvasPainter.prototype.resize = function (width, height) {
  36241. if (!this._domRoot.style) {
  36242. if (width == null || height == null) {
  36243. return;
  36244. }
  36245. this._width = width;
  36246. this._height = height;
  36247. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  36248. }
  36249. else {
  36250. var domRoot = this._domRoot;
  36251. domRoot.style.display = 'none';
  36252. var opts = this._opts;
  36253. var root = this.root;
  36254. width != null && (opts.width = width);
  36255. height != null && (opts.height = height);
  36256. width = getSize(root, 0, opts);
  36257. height = getSize(root, 1, opts);
  36258. domRoot.style.display = '';
  36259. if (this._width !== width || height !== this._height) {
  36260. domRoot.style.width = width + 'px';
  36261. domRoot.style.height = height + 'px';
  36262. for (var id in this._layers) {
  36263. if (this._layers.hasOwnProperty(id)) {
  36264. this._layers[id].resize(width, height);
  36265. }
  36266. }
  36267. this.refresh(true);
  36268. }
  36269. this._width = width;
  36270. this._height = height;
  36271. }
  36272. return this;
  36273. };
  36274. CanvasPainter.prototype.clearLayer = function (zlevel) {
  36275. var layer = this._layers[zlevel];
  36276. if (layer) {
  36277. layer.clear();
  36278. }
  36279. };
  36280. CanvasPainter.prototype.dispose = function () {
  36281. this.root.innerHTML = '';
  36282. this.root =
  36283. this.storage =
  36284. this._domRoot =
  36285. this._layers = null;
  36286. };
  36287. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  36288. opts = opts || {};
  36289. if (this._singleCanvas && !this._compositeManually) {
  36290. return this._layers[CANVAS_ZLEVEL].dom;
  36291. }
  36292. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  36293. imageLayer.initContext();
  36294. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  36295. var ctx = imageLayer.ctx;
  36296. if (opts.pixelRatio <= this.dpr) {
  36297. this.refresh();
  36298. var width_1 = imageLayer.dom.width;
  36299. var height_1 = imageLayer.dom.height;
  36300. this.eachLayer(function (layer) {
  36301. if (layer.__builtin__) {
  36302. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  36303. }
  36304. else if (layer.renderToCanvas) {
  36305. ctx.save();
  36306. layer.renderToCanvas(ctx);
  36307. ctx.restore();
  36308. }
  36309. });
  36310. }
  36311. else {
  36312. var scope = {
  36313. inHover: false,
  36314. viewWidth: this._width,
  36315. viewHeight: this._height
  36316. };
  36317. var displayList = this.storage.getDisplayList(true);
  36318. for (var i = 0, len = displayList.length; i < len; i++) {
  36319. var el = displayList[i];
  36320. brush(ctx, el, scope, i === len - 1);
  36321. }
  36322. }
  36323. return imageLayer.dom;
  36324. };
  36325. CanvasPainter.prototype.getWidth = function () {
  36326. return this._width;
  36327. };
  36328. CanvasPainter.prototype.getHeight = function () {
  36329. return this._height;
  36330. };
  36331. return CanvasPainter;
  36332. }());
  36333. function install$1(registers) {
  36334. registers.registerPainter('canvas', CanvasPainter);
  36335. }
  36336. var LineSeriesModel = /** @class */function (_super) {
  36337. __extends(LineSeriesModel, _super);
  36338. function LineSeriesModel() {
  36339. var _this = _super !== null && _super.apply(this, arguments) || this;
  36340. _this.type = LineSeriesModel.type;
  36341. _this.hasSymbolVisual = true;
  36342. return _this;
  36343. }
  36344. LineSeriesModel.prototype.getInitialData = function (option) {
  36345. if ("development" !== 'production') {
  36346. var coordSys = option.coordinateSystem;
  36347. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  36348. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  36349. }
  36350. }
  36351. return createSeriesData(null, this, {
  36352. useEncodeDefaulter: true
  36353. });
  36354. };
  36355. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  36356. var group = new Group();
  36357. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  36358. group.add(line);
  36359. line.setStyle(opt.lineStyle);
  36360. var visualType = this.getData().getVisual('symbol');
  36361. var visualRotate = this.getData().getVisual('symbolRotate');
  36362. var symbolType = visualType === 'none' ? 'circle' : visualType;
  36363. // Symbol size is 80% when there is a line
  36364. var size = opt.itemHeight * 0.8;
  36365. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  36366. group.add(symbol);
  36367. symbol.setStyle(opt.itemStyle);
  36368. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  36369. symbol.rotation = symbolRotate * Math.PI / 180;
  36370. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  36371. if (symbolType.indexOf('empty') > -1) {
  36372. symbol.style.stroke = symbol.style.fill;
  36373. symbol.style.fill = '#fff';
  36374. symbol.style.lineWidth = 2;
  36375. }
  36376. return group;
  36377. };
  36378. LineSeriesModel.type = 'series.line';
  36379. LineSeriesModel.dependencies = ['grid', 'polar'];
  36380. LineSeriesModel.defaultOption = {
  36381. // zlevel: 0,
  36382. z: 3,
  36383. coordinateSystem: 'cartesian2d',
  36384. legendHoverLink: true,
  36385. clip: true,
  36386. label: {
  36387. position: 'top'
  36388. },
  36389. // itemStyle: {
  36390. // },
  36391. endLabel: {
  36392. show: false,
  36393. valueAnimation: true,
  36394. distance: 8
  36395. },
  36396. lineStyle: {
  36397. width: 2,
  36398. type: 'solid'
  36399. },
  36400. emphasis: {
  36401. scale: true
  36402. },
  36403. // areaStyle: {
  36404. // origin of areaStyle. Valid values:
  36405. // `'auto'/null/undefined`: from axisLine to data
  36406. // `'start'`: from min to data
  36407. // `'end'`: from data to max
  36408. // origin: 'auto'
  36409. // },
  36410. // false, 'start', 'end', 'middle'
  36411. step: false,
  36412. // Disabled if step is true
  36413. smooth: false,
  36414. smoothMonotone: null,
  36415. symbol: 'emptyCircle',
  36416. symbolSize: 4,
  36417. symbolRotate: null,
  36418. showSymbol: true,
  36419. // `false`: follow the label interval strategy.
  36420. // `true`: show all symbols.
  36421. // `'auto'`: If possible, show all symbols, otherwise
  36422. // follow the label interval strategy.
  36423. showAllSymbol: 'auto',
  36424. // Whether to connect break point.
  36425. connectNulls: false,
  36426. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  36427. sampling: 'none',
  36428. animationEasing: 'linear',
  36429. // Disable progressive
  36430. progressive: 0,
  36431. hoverLayerThreshold: Infinity,
  36432. universalTransition: {
  36433. divideShape: 'clone'
  36434. },
  36435. triggerLineEvent: false
  36436. };
  36437. return LineSeriesModel;
  36438. }(SeriesModel);
  36439. /**
  36440. * @return label string. Not null/undefined
  36441. */
  36442. function getDefaultLabel(data, dataIndex) {
  36443. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36444. var len = labelDims.length;
  36445. // Simple optimization (in lots of cases, label dims length is 1)
  36446. if (len === 1) {
  36447. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  36448. return rawVal != null ? rawVal + '' : null;
  36449. } else if (len) {
  36450. var vals = [];
  36451. for (var i = 0; i < labelDims.length; i++) {
  36452. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  36453. }
  36454. return vals.join(' ');
  36455. }
  36456. }
  36457. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  36458. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36459. if (!isArray(interpolatedValue)) {
  36460. return interpolatedValue + '';
  36461. }
  36462. var vals = [];
  36463. for (var i = 0; i < labelDims.length; i++) {
  36464. var dimIndex = data.getDimensionIndex(labelDims[i]);
  36465. if (dimIndex >= 0) {
  36466. vals.push(interpolatedValue[dimIndex]);
  36467. }
  36468. }
  36469. return vals.join(' ');
  36470. }
  36471. var Symbol = /** @class */function (_super) {
  36472. __extends(Symbol, _super);
  36473. function Symbol(data, idx, seriesScope, opts) {
  36474. var _this = _super.call(this) || this;
  36475. _this.updateData(data, idx, seriesScope, opts);
  36476. return _this;
  36477. }
  36478. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  36479. // Remove paths created before
  36480. this.removeAll();
  36481. // let symbolPath = createSymbol(
  36482. // symbolType, -0.5, -0.5, 1, 1, color
  36483. // );
  36484. // If width/height are set too small (e.g., set to 1) on ios10
  36485. // and macOS Sierra, a circle stroke become a rect, no matter what
  36486. // the scale is set. So we set width/height as 2. See #4150.
  36487. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  36488. symbolPath.attr({
  36489. z2: 100,
  36490. culling: true,
  36491. scaleX: symbolSize[0] / 2,
  36492. scaleY: symbolSize[1] / 2
  36493. });
  36494. // Rewrite drift method
  36495. symbolPath.drift = driftSymbol;
  36496. this._symbolType = symbolType;
  36497. this.add(symbolPath);
  36498. };
  36499. /**
  36500. * Stop animation
  36501. * @param {boolean} toLastFrame
  36502. */
  36503. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  36504. this.childAt(0).stopAnimation(null, toLastFrame);
  36505. };
  36506. Symbol.prototype.getSymbolType = function () {
  36507. return this._symbolType;
  36508. };
  36509. /**
  36510. * FIXME:
  36511. * Caution: This method breaks the encapsulation of this module,
  36512. * but it indeed brings convenience. So do not use the method
  36513. * unless you detailedly know all the implements of `Symbol`,
  36514. * especially animation.
  36515. *
  36516. * Get symbol path element.
  36517. */
  36518. Symbol.prototype.getSymbolPath = function () {
  36519. return this.childAt(0);
  36520. };
  36521. /**
  36522. * Highlight symbol
  36523. */
  36524. Symbol.prototype.highlight = function () {
  36525. enterEmphasis(this.childAt(0));
  36526. };
  36527. /**
  36528. * Downplay symbol
  36529. */
  36530. Symbol.prototype.downplay = function () {
  36531. leaveEmphasis(this.childAt(0));
  36532. };
  36533. /**
  36534. * @param {number} zlevel
  36535. * @param {number} z
  36536. */
  36537. Symbol.prototype.setZ = function (zlevel, z) {
  36538. var symbolPath = this.childAt(0);
  36539. symbolPath.zlevel = zlevel;
  36540. symbolPath.z = z;
  36541. };
  36542. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  36543. var symbolPath = this.childAt(0);
  36544. symbolPath.draggable = draggable;
  36545. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  36546. };
  36547. /**
  36548. * Update symbol properties
  36549. */
  36550. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  36551. this.silent = false;
  36552. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36553. var seriesModel = data.hostModel;
  36554. var symbolSize = Symbol.getSymbolSize(data, idx);
  36555. var isInit = symbolType !== this._symbolType;
  36556. var disableAnimation = opts && opts.disableAnimation;
  36557. if (isInit) {
  36558. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  36559. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  36560. } else {
  36561. var symbolPath = this.childAt(0);
  36562. symbolPath.silent = false;
  36563. var target = {
  36564. scaleX: symbolSize[0] / 2,
  36565. scaleY: symbolSize[1] / 2
  36566. };
  36567. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  36568. saveOldStyle(symbolPath);
  36569. }
  36570. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  36571. if (isInit) {
  36572. var symbolPath = this.childAt(0);
  36573. if (!disableAnimation) {
  36574. var target = {
  36575. scaleX: this._sizeX,
  36576. scaleY: this._sizeY,
  36577. style: {
  36578. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  36579. opacity: symbolPath.style.opacity
  36580. }
  36581. };
  36582. symbolPath.scaleX = symbolPath.scaleY = 0;
  36583. symbolPath.style.opacity = 0;
  36584. initProps(symbolPath, target, seriesModel, idx);
  36585. }
  36586. }
  36587. if (disableAnimation) {
  36588. // Must stop leave transition manually if don't call initProps or updateProps.
  36589. this.childAt(0).stopAnimation('leave');
  36590. }
  36591. };
  36592. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  36593. var symbolPath = this.childAt(0);
  36594. var seriesModel = data.hostModel;
  36595. var emphasisItemStyle;
  36596. var blurItemStyle;
  36597. var selectItemStyle;
  36598. var focus;
  36599. var blurScope;
  36600. var emphasisDisabled;
  36601. var labelStatesModels;
  36602. var hoverScale;
  36603. var cursorStyle;
  36604. if (seriesScope) {
  36605. emphasisItemStyle = seriesScope.emphasisItemStyle;
  36606. blurItemStyle = seriesScope.blurItemStyle;
  36607. selectItemStyle = seriesScope.selectItemStyle;
  36608. focus = seriesScope.focus;
  36609. blurScope = seriesScope.blurScope;
  36610. labelStatesModels = seriesScope.labelStatesModels;
  36611. hoverScale = seriesScope.hoverScale;
  36612. cursorStyle = seriesScope.cursorStyle;
  36613. emphasisDisabled = seriesScope.emphasisDisabled;
  36614. }
  36615. if (!seriesScope || data.hasItemOption) {
  36616. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  36617. var emphasisModel = itemModel.getModel('emphasis');
  36618. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  36619. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  36620. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  36621. focus = emphasisModel.get('focus');
  36622. blurScope = emphasisModel.get('blurScope');
  36623. emphasisDisabled = emphasisModel.get('disabled');
  36624. labelStatesModels = getLabelStatesModels(itemModel);
  36625. hoverScale = emphasisModel.getShallow('scale');
  36626. cursorStyle = itemModel.getShallow('cursor');
  36627. }
  36628. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  36629. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  36630. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  36631. if (symbolOffset) {
  36632. symbolPath.x = symbolOffset[0];
  36633. symbolPath.y = symbolOffset[1];
  36634. }
  36635. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  36636. var symbolStyle = data.getItemVisual(idx, 'style');
  36637. var visualColor = symbolStyle.fill;
  36638. if (symbolPath instanceof ZRImage) {
  36639. var pathStyle = symbolPath.style;
  36640. symbolPath.useStyle(extend({
  36641. // TODO other properties like x, y ?
  36642. image: pathStyle.image,
  36643. x: pathStyle.x,
  36644. y: pathStyle.y,
  36645. width: pathStyle.width,
  36646. height: pathStyle.height
  36647. }, symbolStyle));
  36648. } else {
  36649. if (symbolPath.__isEmptyBrush) {
  36650. // fill and stroke will be swapped if it's empty.
  36651. // So we cloned a new style to avoid it affecting the original style in visual storage.
  36652. // TODO Better implementation. No empty logic!
  36653. symbolPath.useStyle(extend({}, symbolStyle));
  36654. } else {
  36655. symbolPath.useStyle(symbolStyle);
  36656. }
  36657. // Disable decal because symbol scale will been applied on the decal.
  36658. symbolPath.style.decal = null;
  36659. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  36660. symbolPath.style.strokeNoScale = true;
  36661. }
  36662. var liftZ = data.getItemVisual(idx, 'liftZ');
  36663. var z2Origin = this._z2;
  36664. if (liftZ != null) {
  36665. if (z2Origin == null) {
  36666. this._z2 = symbolPath.z2;
  36667. symbolPath.z2 += liftZ;
  36668. }
  36669. } else if (z2Origin != null) {
  36670. symbolPath.z2 = z2Origin;
  36671. this._z2 = null;
  36672. }
  36673. var useNameLabel = opts && opts.useNameLabel;
  36674. setLabelStyle(symbolPath, labelStatesModels, {
  36675. labelFetcher: seriesModel,
  36676. labelDataIndex: idx,
  36677. defaultText: getLabelDefaultText,
  36678. inheritColor: visualColor,
  36679. defaultOpacity: symbolStyle.opacity
  36680. });
  36681. // Do not execute util needed.
  36682. function getLabelDefaultText(idx) {
  36683. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  36684. }
  36685. this._sizeX = symbolSize[0] / 2;
  36686. this._sizeY = symbolSize[1] / 2;
  36687. var emphasisState = symbolPath.ensureState('emphasis');
  36688. emphasisState.style = emphasisItemStyle;
  36689. symbolPath.ensureState('select').style = selectItemStyle;
  36690. symbolPath.ensureState('blur').style = blurItemStyle;
  36691. // null / undefined / true means to use default strategy.
  36692. // 0 / false / negative number / NaN / Infinity means no scale.
  36693. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY)
  36694. // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  36695. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1;
  36696. // always set scale to allow resetting
  36697. emphasisState.scaleX = this._sizeX * scaleRatio;
  36698. emphasisState.scaleY = this._sizeY * scaleRatio;
  36699. this.setSymbolScale(1);
  36700. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  36701. };
  36702. Symbol.prototype.setSymbolScale = function (scale) {
  36703. this.scaleX = this.scaleY = scale;
  36704. };
  36705. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  36706. var symbolPath = this.childAt(0);
  36707. var dataIndex = getECData(this).dataIndex;
  36708. var animationOpt = opt && opt.animation;
  36709. // Avoid mistaken hover when fading out
  36710. this.silent = symbolPath.silent = true;
  36711. // Not show text when animating
  36712. if (opt && opt.fadeLabel) {
  36713. var textContent = symbolPath.getTextContent();
  36714. if (textContent) {
  36715. removeElement(textContent, {
  36716. style: {
  36717. opacity: 0
  36718. }
  36719. }, seriesModel, {
  36720. dataIndex: dataIndex,
  36721. removeOpt: animationOpt,
  36722. cb: function () {
  36723. symbolPath.removeTextContent();
  36724. }
  36725. });
  36726. }
  36727. } else {
  36728. symbolPath.removeTextContent();
  36729. }
  36730. removeElement(symbolPath, {
  36731. style: {
  36732. opacity: 0
  36733. },
  36734. scaleX: 0,
  36735. scaleY: 0
  36736. }, seriesModel, {
  36737. dataIndex: dataIndex,
  36738. cb: cb,
  36739. removeOpt: animationOpt
  36740. });
  36741. };
  36742. Symbol.getSymbolSize = function (data, idx) {
  36743. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  36744. };
  36745. return Symbol;
  36746. }(Group);
  36747. function driftSymbol(dx, dy) {
  36748. this.parent.drift(dx, dy);
  36749. }
  36750. function symbolNeedsDraw(data, point, idx, opt) {
  36751. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx))
  36752. // We do not set clipShape on group, because it will cut part of
  36753. // the symbol element shape. We use the same clip shape here as
  36754. // the line clip.
  36755. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  36756. }
  36757. function normalizeUpdateOpt(opt) {
  36758. if (opt != null && !isObject(opt)) {
  36759. opt = {
  36760. isIgnore: opt
  36761. };
  36762. }
  36763. return opt || {};
  36764. }
  36765. function makeSeriesScope(data) {
  36766. var seriesModel = data.hostModel;
  36767. var emphasisModel = seriesModel.getModel('emphasis');
  36768. return {
  36769. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  36770. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  36771. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  36772. focus: emphasisModel.get('focus'),
  36773. blurScope: emphasisModel.get('blurScope'),
  36774. emphasisDisabled: emphasisModel.get('disabled'),
  36775. hoverScale: emphasisModel.get('scale'),
  36776. labelStatesModels: getLabelStatesModels(seriesModel),
  36777. cursorStyle: seriesModel.get('cursor')
  36778. };
  36779. }
  36780. var SymbolDraw = /** @class */function () {
  36781. function SymbolDraw(SymbolCtor) {
  36782. this.group = new Group();
  36783. this._SymbolCtor = SymbolCtor || Symbol;
  36784. }
  36785. /**
  36786. * Update symbols draw by new data
  36787. */
  36788. SymbolDraw.prototype.updateData = function (data, opt) {
  36789. // Remove progressive els.
  36790. this._progressiveEls = null;
  36791. opt = normalizeUpdateOpt(opt);
  36792. var group = this.group;
  36793. var seriesModel = data.hostModel;
  36794. var oldData = this._data;
  36795. var SymbolCtor = this._SymbolCtor;
  36796. var disableAnimation = opt.disableAnimation;
  36797. var seriesScope = makeSeriesScope(data);
  36798. var symbolUpdateOpt = {
  36799. disableAnimation: disableAnimation
  36800. };
  36801. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  36802. return data.getItemLayout(idx);
  36803. };
  36804. // There is no oldLineData only when first rendering or switching from
  36805. // stream mode to normal mode, where previous elements should be removed.
  36806. if (!oldData) {
  36807. group.removeAll();
  36808. }
  36809. data.diff(oldData).add(function (newIdx) {
  36810. var point = getSymbolPoint(newIdx);
  36811. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  36812. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36813. symbolEl.setPosition(point);
  36814. data.setItemGraphicEl(newIdx, symbolEl);
  36815. group.add(symbolEl);
  36816. }
  36817. }).update(function (newIdx, oldIdx) {
  36818. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36819. var point = getSymbolPoint(newIdx);
  36820. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  36821. group.remove(symbolEl);
  36822. return;
  36823. }
  36824. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  36825. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  36826. if (!symbolEl
  36827. // Create a new if symbol type changed.
  36828. || oldSymbolType && oldSymbolType !== newSymbolType) {
  36829. group.remove(symbolEl);
  36830. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36831. symbolEl.setPosition(point);
  36832. } else {
  36833. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  36834. var target = {
  36835. x: point[0],
  36836. y: point[1]
  36837. };
  36838. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  36839. }
  36840. // Add back
  36841. group.add(symbolEl);
  36842. data.setItemGraphicEl(newIdx, symbolEl);
  36843. }).remove(function (oldIdx) {
  36844. var el = oldData.getItemGraphicEl(oldIdx);
  36845. el && el.fadeOut(function () {
  36846. group.remove(el);
  36847. }, seriesModel);
  36848. }).execute();
  36849. this._getSymbolPoint = getSymbolPoint;
  36850. this._data = data;
  36851. };
  36852. SymbolDraw.prototype.updateLayout = function () {
  36853. var _this = this;
  36854. var data = this._data;
  36855. if (data) {
  36856. // Not use animation
  36857. data.eachItemGraphicEl(function (el, idx) {
  36858. var point = _this._getSymbolPoint(idx);
  36859. el.setPosition(point);
  36860. el.markRedraw();
  36861. });
  36862. }
  36863. };
  36864. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  36865. this._seriesScope = makeSeriesScope(data);
  36866. this._data = null;
  36867. this.group.removeAll();
  36868. };
  36869. /**
  36870. * Update symbols draw by new data
  36871. */
  36872. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  36873. // Clear
  36874. this._progressiveEls = [];
  36875. opt = normalizeUpdateOpt(opt);
  36876. function updateIncrementalAndHover(el) {
  36877. if (!el.isGroup) {
  36878. el.incremental = true;
  36879. el.ensureState('emphasis').hoverLayer = true;
  36880. }
  36881. }
  36882. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  36883. var point = data.getItemLayout(idx);
  36884. if (symbolNeedsDraw(data, point, idx, opt)) {
  36885. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  36886. el.traverse(updateIncrementalAndHover);
  36887. el.setPosition(point);
  36888. this.group.add(el);
  36889. data.setItemGraphicEl(idx, el);
  36890. this._progressiveEls.push(el);
  36891. }
  36892. }
  36893. };
  36894. SymbolDraw.prototype.eachRendered = function (cb) {
  36895. traverseElements(this._progressiveEls || this.group, cb);
  36896. };
  36897. SymbolDraw.prototype.remove = function (enableAnimation) {
  36898. var group = this.group;
  36899. var data = this._data;
  36900. // Incremental model do not have this._data.
  36901. if (data && enableAnimation) {
  36902. data.eachItemGraphicEl(function (el) {
  36903. el.fadeOut(function () {
  36904. group.remove(el);
  36905. }, data.hostModel);
  36906. });
  36907. } else {
  36908. group.removeAll();
  36909. }
  36910. };
  36911. return SymbolDraw;
  36912. }();
  36913. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  36914. var baseAxis = coordSys.getBaseAxis();
  36915. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36916. var valueStart = getValueStart(valueAxis, valueOrigin);
  36917. var baseAxisDim = baseAxis.dim;
  36918. var valueAxisDim = valueAxis.dim;
  36919. var valueDim = data.mapDimension(valueAxisDim);
  36920. var baseDim = data.mapDimension(baseAxisDim);
  36921. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  36922. var dims = map(coordSys.dimensions, function (coordDim) {
  36923. return data.mapDimension(coordDim);
  36924. });
  36925. var stacked = false;
  36926. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36927. if (isDimensionStacked(data, dims[0] /* , dims[1] */)) {
  36928. // jshint ignore:line
  36929. stacked = true;
  36930. dims[0] = stackResultDim;
  36931. }
  36932. if (isDimensionStacked(data, dims[1] /* , dims[0] */)) {
  36933. // jshint ignore:line
  36934. stacked = true;
  36935. dims[1] = stackResultDim;
  36936. }
  36937. return {
  36938. dataDimsForPoint: dims,
  36939. valueStart: valueStart,
  36940. valueAxisDim: valueAxisDim,
  36941. baseAxisDim: baseAxisDim,
  36942. stacked: !!stacked,
  36943. valueDim: valueDim,
  36944. baseDim: baseDim,
  36945. baseDataOffset: baseDataOffset,
  36946. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  36947. };
  36948. }
  36949. function getValueStart(valueAxis, valueOrigin) {
  36950. var valueStart = 0;
  36951. var extent = valueAxis.scale.getExtent();
  36952. if (valueOrigin === 'start') {
  36953. valueStart = extent[0];
  36954. } else if (valueOrigin === 'end') {
  36955. valueStart = extent[1];
  36956. }
  36957. // If origin is specified as a number, use it as
  36958. // valueStart directly
  36959. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  36960. valueStart = valueOrigin;
  36961. }
  36962. // auto
  36963. else {
  36964. // Both positive
  36965. if (extent[0] > 0) {
  36966. valueStart = extent[0];
  36967. }
  36968. // Both negative
  36969. else if (extent[1] < 0) {
  36970. valueStart = extent[1];
  36971. }
  36972. // If is one positive, and one negative, onZero shall be true
  36973. }
  36974. return valueStart;
  36975. }
  36976. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  36977. var value = NaN;
  36978. if (dataCoordInfo.stacked) {
  36979. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  36980. }
  36981. if (isNaN(value)) {
  36982. value = dataCoordInfo.valueStart;
  36983. }
  36984. var baseDataOffset = dataCoordInfo.baseDataOffset;
  36985. var stackedData = [];
  36986. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  36987. stackedData[1 - baseDataOffset] = value;
  36988. return coordSys.dataToPoint(stackedData);
  36989. }
  36990. function diffData(oldData, newData) {
  36991. var diffResult = [];
  36992. newData.diff(oldData).add(function (idx) {
  36993. diffResult.push({
  36994. cmd: '+',
  36995. idx: idx
  36996. });
  36997. }).update(function (newIdx, oldIdx) {
  36998. diffResult.push({
  36999. cmd: '=',
  37000. idx: oldIdx,
  37001. idx1: newIdx
  37002. });
  37003. }).remove(function (idx) {
  37004. diffResult.push({
  37005. cmd: '-',
  37006. idx: idx
  37007. });
  37008. }).execute();
  37009. return diffResult;
  37010. }
  37011. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  37012. var diff = diffData(oldData, newData);
  37013. // let newIdList = newData.mapArray(newData.getId);
  37014. // let oldIdList = oldData.mapArray(oldData.getId);
  37015. // convertToIntId(newIdList, oldIdList);
  37016. // // FIXME One data ?
  37017. // diff = arrayDiff(oldIdList, newIdList);
  37018. var currPoints = [];
  37019. var nextPoints = [];
  37020. // Points for stacking base line
  37021. var currStackedPoints = [];
  37022. var nextStackedPoints = [];
  37023. var status = [];
  37024. var sortedIndices = [];
  37025. var rawIndices = [];
  37026. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  37027. // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  37028. var oldPoints = oldData.getLayout('points') || [];
  37029. var newPoints = newData.getLayout('points') || [];
  37030. for (var i = 0; i < diff.length; i++) {
  37031. var diffItem = diff[i];
  37032. var pointAdded = true;
  37033. var oldIdx2 = void 0;
  37034. var newIdx2 = void 0;
  37035. // FIXME, animation is not so perfect when dataZoom window moves fast
  37036. // Which is in case remvoing or add more than one data in the tail or head
  37037. switch (diffItem.cmd) {
  37038. case '=':
  37039. oldIdx2 = diffItem.idx * 2;
  37040. newIdx2 = diffItem.idx1 * 2;
  37041. var currentX = oldPoints[oldIdx2];
  37042. var currentY = oldPoints[oldIdx2 + 1];
  37043. var nextX = newPoints[newIdx2];
  37044. var nextY = newPoints[newIdx2 + 1];
  37045. // If previous data is NaN, use next point directly
  37046. if (isNaN(currentX) || isNaN(currentY)) {
  37047. currentX = nextX;
  37048. currentY = nextY;
  37049. }
  37050. currPoints.push(currentX, currentY);
  37051. nextPoints.push(nextX, nextY);
  37052. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  37053. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37054. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  37055. break;
  37056. case '+':
  37057. var newIdx = diffItem.idx;
  37058. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  37059. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  37060. newIdx2 = newIdx * 2;
  37061. currPoints.push(oldPt[0], oldPt[1]);
  37062. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  37063. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  37064. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  37065. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37066. rawIndices.push(newData.getRawIndex(newIdx));
  37067. break;
  37068. case '-':
  37069. pointAdded = false;
  37070. }
  37071. // Original indices
  37072. if (pointAdded) {
  37073. status.push(diffItem);
  37074. sortedIndices.push(sortedIndices.length);
  37075. }
  37076. }
  37077. // Diff result may be crossed if all items are changed
  37078. // Sort by data index
  37079. sortedIndices.sort(function (a, b) {
  37080. return rawIndices[a] - rawIndices[b];
  37081. });
  37082. var len = currPoints.length;
  37083. var sortedCurrPoints = createFloat32Array(len);
  37084. var sortedNextPoints = createFloat32Array(len);
  37085. var sortedCurrStackedPoints = createFloat32Array(len);
  37086. var sortedNextStackedPoints = createFloat32Array(len);
  37087. var sortedStatus = [];
  37088. for (var i = 0; i < sortedIndices.length; i++) {
  37089. var idx = sortedIndices[i];
  37090. var i2 = i * 2;
  37091. var idx2 = idx * 2;
  37092. sortedCurrPoints[i2] = currPoints[idx2];
  37093. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  37094. sortedNextPoints[i2] = nextPoints[idx2];
  37095. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  37096. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  37097. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  37098. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  37099. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  37100. sortedStatus[i] = status[idx];
  37101. }
  37102. return {
  37103. current: sortedCurrPoints,
  37104. next: sortedNextPoints,
  37105. stackedOnCurrent: sortedCurrStackedPoints,
  37106. stackedOnNext: sortedNextStackedPoints,
  37107. status: sortedStatus
  37108. };
  37109. }
  37110. var mathMin$5 = Math.min;
  37111. var mathMax$5 = Math.max;
  37112. function isPointNull(x, y) {
  37113. return isNaN(x) || isNaN(y);
  37114. }
  37115. /**
  37116. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  37117. * situations. This should be used when points are non-monotone neither in x or
  37118. * y dimension.
  37119. */
  37120. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  37121. var prevX;
  37122. var prevY;
  37123. var cpx0;
  37124. var cpy0;
  37125. var cpx1;
  37126. var cpy1;
  37127. var idx = start;
  37128. var k = 0;
  37129. for (; k < segLen; k++) {
  37130. var x = points[idx * 2];
  37131. var y = points[idx * 2 + 1];
  37132. if (idx >= allLen || idx < 0) {
  37133. break;
  37134. }
  37135. if (isPointNull(x, y)) {
  37136. if (connectNulls) {
  37137. idx += dir;
  37138. continue;
  37139. }
  37140. break;
  37141. }
  37142. if (idx === start) {
  37143. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  37144. cpx0 = x;
  37145. cpy0 = y;
  37146. } else {
  37147. var dx = x - prevX;
  37148. var dy = y - prevY;
  37149. // Ignore tiny segment.
  37150. if (dx * dx + dy * dy < 0.5) {
  37151. idx += dir;
  37152. continue;
  37153. }
  37154. if (smooth > 0) {
  37155. var nextIdx = idx + dir;
  37156. var nextX = points[nextIdx * 2];
  37157. var nextY = points[nextIdx * 2 + 1];
  37158. // Ignore duplicate point
  37159. while (nextX === x && nextY === y && k < segLen) {
  37160. k++;
  37161. nextIdx += dir;
  37162. idx += dir;
  37163. nextX = points[nextIdx * 2];
  37164. nextY = points[nextIdx * 2 + 1];
  37165. x = points[idx * 2];
  37166. y = points[idx * 2 + 1];
  37167. dx = x - prevX;
  37168. dy = y - prevY;
  37169. }
  37170. var tmpK = k + 1;
  37171. if (connectNulls) {
  37172. // Find next point not null
  37173. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  37174. tmpK++;
  37175. nextIdx += dir;
  37176. nextX = points[nextIdx * 2];
  37177. nextY = points[nextIdx * 2 + 1];
  37178. }
  37179. }
  37180. var ratioNextSeg = 0.5;
  37181. var vx = 0;
  37182. var vy = 0;
  37183. var nextCpx0 = void 0;
  37184. var nextCpy0 = void 0;
  37185. // Is last point
  37186. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  37187. cpx1 = x;
  37188. cpy1 = y;
  37189. } else {
  37190. vx = nextX - prevX;
  37191. vy = nextY - prevY;
  37192. var dx0 = x - prevX;
  37193. var dx1 = nextX - x;
  37194. var dy0 = y - prevY;
  37195. var dy1 = nextY - y;
  37196. var lenPrevSeg = void 0;
  37197. var lenNextSeg = void 0;
  37198. if (smoothMonotone === 'x') {
  37199. lenPrevSeg = Math.abs(dx0);
  37200. lenNextSeg = Math.abs(dx1);
  37201. var dir_1 = vx > 0 ? 1 : -1;
  37202. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  37203. cpy1 = y;
  37204. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  37205. nextCpy0 = y;
  37206. } else if (smoothMonotone === 'y') {
  37207. lenPrevSeg = Math.abs(dy0);
  37208. lenNextSeg = Math.abs(dy1);
  37209. var dir_2 = vy > 0 ? 1 : -1;
  37210. cpx1 = x;
  37211. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  37212. nextCpx0 = x;
  37213. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  37214. } else {
  37215. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  37216. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  37217. // Use ratio of seg length
  37218. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  37219. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  37220. cpy1 = y - vy * smooth * (1 - ratioNextSeg);
  37221. // cp0 of next segment
  37222. nextCpx0 = x + vx * smooth * ratioNextSeg;
  37223. nextCpy0 = y + vy * smooth * ratioNextSeg;
  37224. // Smooth constraint between point and next point.
  37225. // Avoid exceeding extreme after smoothing.
  37226. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  37227. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  37228. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  37229. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y));
  37230. // Reclaculate cp1 based on the adjusted cp0 of next seg.
  37231. vx = nextCpx0 - x;
  37232. vy = nextCpy0 - y;
  37233. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  37234. cpy1 = y - vy * lenPrevSeg / lenNextSeg;
  37235. // Smooth constraint between point and prev point.
  37236. // Avoid exceeding extreme after smoothing.
  37237. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  37238. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  37239. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  37240. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y));
  37241. // Adjust next cp0 again.
  37242. vx = x - cpx1;
  37243. vy = y - cpy1;
  37244. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  37245. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  37246. }
  37247. }
  37248. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  37249. cpx0 = nextCpx0;
  37250. cpy0 = nextCpy0;
  37251. } else {
  37252. ctx.lineTo(x, y);
  37253. }
  37254. }
  37255. prevX = x;
  37256. prevY = y;
  37257. idx += dir;
  37258. }
  37259. return k;
  37260. }
  37261. var ECPolylineShape = /** @class */function () {
  37262. function ECPolylineShape() {
  37263. this.smooth = 0;
  37264. this.smoothConstraint = true;
  37265. }
  37266. return ECPolylineShape;
  37267. }();
  37268. var ECPolyline = /** @class */function (_super) {
  37269. __extends(ECPolyline, _super);
  37270. function ECPolyline(opts) {
  37271. var _this = _super.call(this, opts) || this;
  37272. _this.type = 'ec-polyline';
  37273. return _this;
  37274. }
  37275. ECPolyline.prototype.getDefaultStyle = function () {
  37276. return {
  37277. stroke: '#000',
  37278. fill: null
  37279. };
  37280. };
  37281. ECPolyline.prototype.getDefaultShape = function () {
  37282. return new ECPolylineShape();
  37283. };
  37284. ECPolyline.prototype.buildPath = function (ctx, shape) {
  37285. var points = shape.points;
  37286. var i = 0;
  37287. var len = points.length / 2;
  37288. // const result = getBoundingBox(points, shape.smoothConstraint);
  37289. if (shape.connectNulls) {
  37290. // Must remove first and last null values avoid draw error in polygon
  37291. for (; len > 0; len--) {
  37292. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37293. break;
  37294. }
  37295. }
  37296. for (; i < len; i++) {
  37297. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37298. break;
  37299. }
  37300. }
  37301. }
  37302. while (i < len) {
  37303. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  37304. }
  37305. };
  37306. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  37307. if (!this.path) {
  37308. this.createPathProxy();
  37309. this.buildPath(this.path, this.shape);
  37310. }
  37311. var path = this.path;
  37312. var data = path.data;
  37313. var CMD = PathProxy.CMD;
  37314. var x0;
  37315. var y0;
  37316. var isDimX = dim === 'x';
  37317. var roots = [];
  37318. for (var i = 0; i < data.length;) {
  37319. var cmd = data[i++];
  37320. var x = void 0;
  37321. var y = void 0;
  37322. var x2 = void 0;
  37323. var y2 = void 0;
  37324. var x3 = void 0;
  37325. var y3 = void 0;
  37326. var t = void 0;
  37327. switch (cmd) {
  37328. case CMD.M:
  37329. x0 = data[i++];
  37330. y0 = data[i++];
  37331. break;
  37332. case CMD.L:
  37333. x = data[i++];
  37334. y = data[i++];
  37335. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  37336. if (t <= 1 && t >= 0) {
  37337. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  37338. return isDimX ? [xOrY, val] : [val, xOrY];
  37339. }
  37340. x0 = x;
  37341. y0 = y;
  37342. break;
  37343. case CMD.C:
  37344. x = data[i++];
  37345. y = data[i++];
  37346. x2 = data[i++];
  37347. y2 = data[i++];
  37348. x3 = data[i++];
  37349. y3 = data[i++];
  37350. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  37351. if (nRoot > 0) {
  37352. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  37353. var t_1 = roots[i_1];
  37354. if (t_1 <= 1 && t_1 >= 0) {
  37355. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  37356. return isDimX ? [xOrY, val] : [val, xOrY];
  37357. }
  37358. }
  37359. }
  37360. x0 = x3;
  37361. y0 = y3;
  37362. break;
  37363. }
  37364. }
  37365. };
  37366. return ECPolyline;
  37367. }(Path);
  37368. var ECPolygonShape = /** @class */function (_super) {
  37369. __extends(ECPolygonShape, _super);
  37370. function ECPolygonShape() {
  37371. return _super !== null && _super.apply(this, arguments) || this;
  37372. }
  37373. return ECPolygonShape;
  37374. }(ECPolylineShape);
  37375. var ECPolygon = /** @class */function (_super) {
  37376. __extends(ECPolygon, _super);
  37377. function ECPolygon(opts) {
  37378. var _this = _super.call(this, opts) || this;
  37379. _this.type = 'ec-polygon';
  37380. return _this;
  37381. }
  37382. ECPolygon.prototype.getDefaultShape = function () {
  37383. return new ECPolygonShape();
  37384. };
  37385. ECPolygon.prototype.buildPath = function (ctx, shape) {
  37386. var points = shape.points;
  37387. var stackedOnPoints = shape.stackedOnPoints;
  37388. var i = 0;
  37389. var len = points.length / 2;
  37390. var smoothMonotone = shape.smoothMonotone;
  37391. if (shape.connectNulls) {
  37392. // Must remove first and last null values avoid draw error in polygon
  37393. for (; len > 0; len--) {
  37394. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37395. break;
  37396. }
  37397. }
  37398. for (; i < len; i++) {
  37399. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37400. break;
  37401. }
  37402. }
  37403. }
  37404. while (i < len) {
  37405. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  37406. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  37407. i += k + 1;
  37408. ctx.closePath();
  37409. }
  37410. };
  37411. return ECPolygon;
  37412. }(Path);
  37413. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  37414. var rect = cartesian.getArea();
  37415. var x = rect.x;
  37416. var y = rect.y;
  37417. var width = rect.width;
  37418. var height = rect.height;
  37419. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2;
  37420. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  37421. x -= lineWidth / 2;
  37422. y -= lineWidth / 2;
  37423. width += lineWidth;
  37424. height += lineWidth;
  37425. // fix: https://github.com/apache/incubator-echarts/issues/11369
  37426. width = Math.ceil(width);
  37427. if (x !== Math.floor(x)) {
  37428. x = Math.floor(x);
  37429. // if no extra 1px on `width`, it will still be clipped since `x` is floored
  37430. width++;
  37431. }
  37432. var clipPath = new Rect({
  37433. shape: {
  37434. x: x,
  37435. y: y,
  37436. width: width,
  37437. height: height
  37438. }
  37439. });
  37440. if (hasAnimation) {
  37441. var baseAxis = cartesian.getBaseAxis();
  37442. var isHorizontal = baseAxis.isHorizontal();
  37443. var isAxisInversed = baseAxis.inverse;
  37444. if (isHorizontal) {
  37445. if (isAxisInversed) {
  37446. clipPath.shape.x += width;
  37447. }
  37448. clipPath.shape.width = 0;
  37449. } else {
  37450. if (!isAxisInversed) {
  37451. clipPath.shape.y += height;
  37452. }
  37453. clipPath.shape.height = 0;
  37454. }
  37455. var duringCb = isFunction(during) ? function (percent) {
  37456. during(percent, clipPath);
  37457. } : null;
  37458. initProps(clipPath, {
  37459. shape: {
  37460. width: width,
  37461. height: height,
  37462. x: x,
  37463. y: y
  37464. }
  37465. }, seriesModel, null, done, duringCb);
  37466. }
  37467. return clipPath;
  37468. }
  37469. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  37470. var sectorArea = polar.getArea();
  37471. // Avoid float number rounding error for symbol on the edge of axis extent.
  37472. var r0 = round(sectorArea.r0, 1);
  37473. var r = round(sectorArea.r, 1);
  37474. var clipPath = new Sector({
  37475. shape: {
  37476. cx: round(polar.cx, 1),
  37477. cy: round(polar.cy, 1),
  37478. r0: r0,
  37479. r: r,
  37480. startAngle: sectorArea.startAngle,
  37481. endAngle: sectorArea.endAngle,
  37482. clockwise: sectorArea.clockwise
  37483. }
  37484. });
  37485. if (hasAnimation) {
  37486. var isRadial = polar.getBaseAxis().dim === 'angle';
  37487. if (isRadial) {
  37488. clipPath.shape.endAngle = sectorArea.startAngle;
  37489. } else {
  37490. clipPath.shape.r = r0;
  37491. }
  37492. initProps(clipPath, {
  37493. shape: {
  37494. endAngle: sectorArea.endAngle,
  37495. r: r
  37496. }
  37497. }, seriesModel);
  37498. }
  37499. return clipPath;
  37500. }
  37501. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  37502. if (!coordSys) {
  37503. return null;
  37504. } else if (coordSys.type === 'polar') {
  37505. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37506. } else if (coordSys.type === 'cartesian2d') {
  37507. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  37508. }
  37509. return null;
  37510. }
  37511. /*
  37512. * Licensed to the Apache Software Foundation (ASF) under one
  37513. * or more contributor license agreements. See the NOTICE file
  37514. * distributed with this work for additional information
  37515. * regarding copyright ownership. The ASF licenses this file
  37516. * to you under the Apache License, Version 2.0 (the
  37517. * "License"); you may not use this file except in compliance
  37518. * with the License. You may obtain a copy of the License at
  37519. *
  37520. * http://www.apache.org/licenses/LICENSE-2.0
  37521. *
  37522. * Unless required by applicable law or agreed to in writing,
  37523. * software distributed under the License is distributed on an
  37524. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37525. * KIND, either express or implied. See the License for the
  37526. * specific language governing permissions and limitations
  37527. * under the License.
  37528. */
  37529. /**
  37530. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37531. */
  37532. /*
  37533. * Licensed to the Apache Software Foundation (ASF) under one
  37534. * or more contributor license agreements. See the NOTICE file
  37535. * distributed with this work for additional information
  37536. * regarding copyright ownership. The ASF licenses this file
  37537. * to you under the Apache License, Version 2.0 (the
  37538. * "License"); you may not use this file except in compliance
  37539. * with the License. You may obtain a copy of the License at
  37540. *
  37541. * http://www.apache.org/licenses/LICENSE-2.0
  37542. *
  37543. * Unless required by applicable law or agreed to in writing,
  37544. * software distributed under the License is distributed on an
  37545. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37546. * KIND, either express or implied. See the License for the
  37547. * specific language governing permissions and limitations
  37548. * under the License.
  37549. */
  37550. function isCoordinateSystemType(coordSys, type) {
  37551. return coordSys.type === type;
  37552. }
  37553. function isPointsSame(points1, points2) {
  37554. if (points1.length !== points2.length) {
  37555. return;
  37556. }
  37557. for (var i = 0; i < points1.length; i++) {
  37558. if (points1[i] !== points2[i]) {
  37559. return;
  37560. }
  37561. }
  37562. return true;
  37563. }
  37564. function bboxFromPoints(points) {
  37565. var minX = Infinity;
  37566. var minY = Infinity;
  37567. var maxX = -Infinity;
  37568. var maxY = -Infinity;
  37569. for (var i = 0; i < points.length;) {
  37570. var x = points[i++];
  37571. var y = points[i++];
  37572. if (!isNaN(x)) {
  37573. minX = Math.min(x, minX);
  37574. maxX = Math.max(x, maxX);
  37575. }
  37576. if (!isNaN(y)) {
  37577. minY = Math.min(y, minY);
  37578. maxY = Math.max(y, maxY);
  37579. }
  37580. }
  37581. return [[minX, minY], [maxX, maxY]];
  37582. }
  37583. function getBoundingDiff(points1, points2) {
  37584. var _a = bboxFromPoints(points1),
  37585. min1 = _a[0],
  37586. max1 = _a[1];
  37587. var _b = bboxFromPoints(points2),
  37588. min2 = _b[0],
  37589. max2 = _b[1];
  37590. // Get a max value from each corner of two boundings.
  37591. 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]));
  37592. }
  37593. function getSmooth(smooth) {
  37594. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  37595. }
  37596. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  37597. if (!dataCoordInfo.valueDim) {
  37598. return [];
  37599. }
  37600. var len = data.count();
  37601. var points = createFloat32Array(len * 2);
  37602. for (var idx = 0; idx < len; idx++) {
  37603. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  37604. points[idx * 2] = pt[0];
  37605. points[idx * 2 + 1] = pt[1];
  37606. }
  37607. return points;
  37608. }
  37609. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  37610. var baseAxis = coordSys.getBaseAxis();
  37611. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  37612. var stepPoints = [];
  37613. var i = 0;
  37614. var stepPt = [];
  37615. var pt = [];
  37616. var nextPt = [];
  37617. var filteredPoints = [];
  37618. if (connectNulls) {
  37619. for (i = 0; i < points.length; i += 2) {
  37620. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  37621. filteredPoints.push(points[i], points[i + 1]);
  37622. }
  37623. }
  37624. points = filteredPoints;
  37625. }
  37626. for (i = 0; i < points.length - 2; i += 2) {
  37627. nextPt[0] = points[i + 2];
  37628. nextPt[1] = points[i + 3];
  37629. pt[0] = points[i];
  37630. pt[1] = points[i + 1];
  37631. stepPoints.push(pt[0], pt[1]);
  37632. switch (stepTurnAt) {
  37633. case 'end':
  37634. stepPt[baseIndex] = nextPt[baseIndex];
  37635. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37636. stepPoints.push(stepPt[0], stepPt[1]);
  37637. break;
  37638. case 'middle':
  37639. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  37640. var stepPt2 = [];
  37641. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  37642. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37643. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  37644. stepPoints.push(stepPt[0], stepPt[1]);
  37645. stepPoints.push(stepPt2[0], stepPt2[1]);
  37646. break;
  37647. default:
  37648. // default is start
  37649. stepPt[baseIndex] = pt[baseIndex];
  37650. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  37651. stepPoints.push(stepPt[0], stepPt[1]);
  37652. }
  37653. }
  37654. // Last points
  37655. stepPoints.push(points[i++], points[i++]);
  37656. return stepPoints;
  37657. }
  37658. /**
  37659. * Clip color stops to edge. Avoid creating too large gradients.
  37660. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  37661. *
  37662. * The stops has been sorted from small to large.
  37663. */
  37664. function clipColorStops(colorStops, maxSize) {
  37665. var newColorStops = [];
  37666. var len = colorStops.length;
  37667. // coord will always < 0 in prevOutOfRangeColorStop.
  37668. var prevOutOfRangeColorStop;
  37669. var prevInRangeColorStop;
  37670. function lerpStop(stop0, stop1, clippedCoord) {
  37671. var coord0 = stop0.coord;
  37672. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  37673. var color = lerp$1(p, [stop0.color, stop1.color]);
  37674. return {
  37675. coord: clippedCoord,
  37676. color: color
  37677. };
  37678. }
  37679. for (var i = 0; i < len; i++) {
  37680. var stop_1 = colorStops[i];
  37681. var coord = stop_1.coord;
  37682. if (coord < 0) {
  37683. prevOutOfRangeColorStop = stop_1;
  37684. } else if (coord > maxSize) {
  37685. if (prevInRangeColorStop) {
  37686. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  37687. } else if (prevOutOfRangeColorStop) {
  37688. // If there are two stops and coord range is between these two stops
  37689. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  37690. }
  37691. // All following stop will be out of range. So just ignore them.
  37692. break;
  37693. } else {
  37694. if (prevOutOfRangeColorStop) {
  37695. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0));
  37696. // Reset
  37697. prevOutOfRangeColorStop = null;
  37698. }
  37699. newColorStops.push(stop_1);
  37700. prevInRangeColorStop = stop_1;
  37701. }
  37702. }
  37703. return newColorStops;
  37704. }
  37705. function getVisualGradient(data, coordSys, api) {
  37706. var visualMetaList = data.getVisual('visualMeta');
  37707. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  37708. // When data.count() is 0, gradient range can not be calculated.
  37709. return;
  37710. }
  37711. if (coordSys.type !== 'cartesian2d') {
  37712. if ("development" !== 'production') {
  37713. console.warn('Visual map on line style is only supported on cartesian2d.');
  37714. }
  37715. return;
  37716. }
  37717. var coordDim;
  37718. var visualMeta;
  37719. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  37720. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  37721. coordDim = dimInfo && dimInfo.coordDim;
  37722. // Can only be x or y
  37723. if (coordDim === 'x' || coordDim === 'y') {
  37724. visualMeta = visualMetaList[i];
  37725. break;
  37726. }
  37727. }
  37728. if (!visualMeta) {
  37729. if ("development" !== 'production') {
  37730. console.warn('Visual map on line style only support x or y dimension.');
  37731. }
  37732. return;
  37733. }
  37734. // If the area to be rendered is bigger than area defined by LinearGradient,
  37735. // the canvas spec prescribes that the color of the first stop and the last
  37736. // stop should be used. But if two stops are added at offset 0, in effect
  37737. // browsers use the color of the second stop to render area outside
  37738. // LinearGradient. So we can only infinitesimally extend area defined in
  37739. // LinearGradient to render `outerColors`.
  37740. var axis = coordSys.getAxis(coordDim);
  37741. // dataToCoord mapping may not be linear, but must be monotonic.
  37742. var colorStops = map(visualMeta.stops, function (stop) {
  37743. // offset will be calculated later.
  37744. return {
  37745. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  37746. color: stop.color
  37747. };
  37748. });
  37749. var stopLen = colorStops.length;
  37750. var outerColors = visualMeta.outerColors.slice();
  37751. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  37752. colorStops.reverse();
  37753. outerColors.reverse();
  37754. }
  37755. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  37756. var inRangeStopLen = colorStopsInRange.length;
  37757. if (!inRangeStopLen && stopLen) {
  37758. // All stops are out of range. All will be the same color.
  37759. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  37760. }
  37761. var tinyExtent = 10; // Arbitrary value: 10px
  37762. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  37763. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  37764. var coordSpan = maxCoord - minCoord;
  37765. if (coordSpan < 1e-3) {
  37766. return 'transparent';
  37767. }
  37768. each(colorStopsInRange, function (stop) {
  37769. stop.offset = (stop.coord - minCoord) / coordSpan;
  37770. });
  37771. colorStopsInRange.push({
  37772. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  37773. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  37774. color: outerColors[1] || 'transparent'
  37775. });
  37776. colorStopsInRange.unshift({
  37777. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  37778. color: outerColors[0] || 'transparent'
  37779. });
  37780. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  37781. gradient[coordDim] = minCoord;
  37782. gradient[coordDim + '2'] = maxCoord;
  37783. return gradient;
  37784. }
  37785. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  37786. var showAllSymbol = seriesModel.get('showAllSymbol');
  37787. var isAuto = showAllSymbol === 'auto';
  37788. if (showAllSymbol && !isAuto) {
  37789. return;
  37790. }
  37791. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  37792. if (!categoryAxis) {
  37793. return;
  37794. }
  37795. // Note that category label interval strategy might bring some weird effect
  37796. // in some scenario: users may wonder why some of the symbols are not
  37797. // displayed. So we show all symbols as possible as we can.
  37798. if (isAuto
  37799. // Simplify the logic, do not determine label overlap here.
  37800. && canShowAllSymbolForCategory(categoryAxis, data)) {
  37801. return;
  37802. }
  37803. // Otherwise follow the label interval strategy on category axis.
  37804. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  37805. var labelMap = {};
  37806. each(categoryAxis.getViewLabels(), function (labelItem) {
  37807. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  37808. labelMap[ordinalNumber] = 1;
  37809. });
  37810. return function (dataIndex) {
  37811. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  37812. };
  37813. }
  37814. function canShowAllSymbolForCategory(categoryAxis, data) {
  37815. // In most cases, line is monotonous on category axis, and the label size
  37816. // is close with each other. So we check the symbol size and some of the
  37817. // label size alone with the category axis to estimate whether all symbol
  37818. // can be shown without overlap.
  37819. var axisExtent = categoryAxis.getExtent();
  37820. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  37821. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  37822. // Sampling some points, max 5.
  37823. var dataLen = data.count();
  37824. var step = Math.max(1, Math.round(dataLen / 5));
  37825. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  37826. if (Symbol.getSymbolSize(data, dataIndex
  37827. // Only for cartesian, where `isHorizontal` exists.
  37828. )[categoryAxis.isHorizontal() ? 1 : 0]
  37829. // Empirical number
  37830. * 1.5 > availSize) {
  37831. return false;
  37832. }
  37833. }
  37834. return true;
  37835. }
  37836. function isPointNull$1(x, y) {
  37837. return isNaN(x) || isNaN(y);
  37838. }
  37839. function getLastIndexNotNull(points) {
  37840. var len = points.length / 2;
  37841. for (; len > 0; len--) {
  37842. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  37843. break;
  37844. }
  37845. }
  37846. return len - 1;
  37847. }
  37848. function getPointAtIndex(points, idx) {
  37849. return [points[idx * 2], points[idx * 2 + 1]];
  37850. }
  37851. function getIndexRange(points, xOrY, dim) {
  37852. var len = points.length / 2;
  37853. var dimIdx = dim === 'x' ? 0 : 1;
  37854. var a;
  37855. var b;
  37856. var prevIndex = 0;
  37857. var nextIndex = -1;
  37858. for (var i = 0; i < len; i++) {
  37859. b = points[i * 2 + dimIdx];
  37860. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  37861. continue;
  37862. }
  37863. if (i === 0) {
  37864. a = b;
  37865. continue;
  37866. }
  37867. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  37868. nextIndex = i;
  37869. break;
  37870. }
  37871. prevIndex = i;
  37872. a = b;
  37873. }
  37874. return {
  37875. range: [prevIndex, nextIndex],
  37876. t: (xOrY - a) / (b - a)
  37877. };
  37878. }
  37879. function anyStateShowEndLabel(seriesModel) {
  37880. if (seriesModel.get(['endLabel', 'show'])) {
  37881. return true;
  37882. }
  37883. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  37884. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  37885. return true;
  37886. }
  37887. }
  37888. return false;
  37889. }
  37890. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  37891. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  37892. var endLabelModel_1 = seriesModel.getModel('endLabel');
  37893. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  37894. var data_1 = seriesModel.getData();
  37895. var labelAnimationRecord_1 = {
  37896. lastFrameIndex: 0
  37897. };
  37898. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  37899. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  37900. } : null;
  37901. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  37902. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  37903. var endLabel = lineView._endLabel;
  37904. if (endLabel && hasAnimation) {
  37905. if (labelAnimationRecord_1.originalX != null) {
  37906. endLabel.attr({
  37907. x: labelAnimationRecord_1.originalX,
  37908. y: labelAnimationRecord_1.originalY
  37909. });
  37910. }
  37911. }
  37912. }, during);
  37913. // Expand clip shape to avoid clipping when line value exceeds axis
  37914. if (!seriesModel.get('clip', true)) {
  37915. var rectShape = clipPath.shape;
  37916. var expandSize = Math.max(rectShape.width, rectShape.height);
  37917. if (isHorizontal) {
  37918. rectShape.y -= expandSize;
  37919. rectShape.height += expandSize * 2;
  37920. } else {
  37921. rectShape.x -= expandSize;
  37922. rectShape.width += expandSize * 2;
  37923. }
  37924. }
  37925. // Set to the final frame. To make sure label layout is right.
  37926. if (during) {
  37927. during(1, clipPath);
  37928. }
  37929. return clipPath;
  37930. } else {
  37931. if ("development" !== 'production') {
  37932. if (seriesModel.get(['endLabel', 'show'])) {
  37933. console.warn('endLabel is not supported for lines in polar systems.');
  37934. }
  37935. }
  37936. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37937. }
  37938. }
  37939. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  37940. var baseAxis = coordSys.getBaseAxis();
  37941. var isHorizontal = baseAxis.isHorizontal();
  37942. var isBaseInversed = baseAxis.inverse;
  37943. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  37944. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  37945. return {
  37946. normal: {
  37947. align: endLabelModel.get('align') || align,
  37948. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  37949. }
  37950. };
  37951. }
  37952. var LineView = /** @class */function (_super) {
  37953. __extends(LineView, _super);
  37954. function LineView() {
  37955. return _super !== null && _super.apply(this, arguments) || this;
  37956. }
  37957. LineView.prototype.init = function () {
  37958. var lineGroup = new Group();
  37959. var symbolDraw = new SymbolDraw();
  37960. this.group.add(symbolDraw.group);
  37961. this._symbolDraw = symbolDraw;
  37962. this._lineGroup = lineGroup;
  37963. };
  37964. LineView.prototype.render = function (seriesModel, ecModel, api) {
  37965. var _this = this;
  37966. var coordSys = seriesModel.coordinateSystem;
  37967. var group = this.group;
  37968. var data = seriesModel.getData();
  37969. var lineStyleModel = seriesModel.getModel('lineStyle');
  37970. var areaStyleModel = seriesModel.getModel('areaStyle');
  37971. var points = data.getLayout('points') || [];
  37972. var isCoordSysPolar = coordSys.type === 'polar';
  37973. var prevCoordSys = this._coordSys;
  37974. var symbolDraw = this._symbolDraw;
  37975. var polyline = this._polyline;
  37976. var polygon = this._polygon;
  37977. var lineGroup = this._lineGroup;
  37978. var hasAnimation = !ecModel.ssr && seriesModel.get('animation');
  37979. var isAreaChart = !areaStyleModel.isEmpty();
  37980. var valueOrigin = areaStyleModel.get('origin');
  37981. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  37982. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  37983. var showSymbol = seriesModel.get('showSymbol');
  37984. var connectNulls = seriesModel.get('connectNulls');
  37985. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys);
  37986. // Remove temporary symbols
  37987. var oldData = this._data;
  37988. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  37989. if (el.__temp) {
  37990. group.remove(el);
  37991. oldData.setItemGraphicEl(idx, null);
  37992. }
  37993. });
  37994. // Remove previous created symbols if showSymbol changed to false
  37995. if (!showSymbol) {
  37996. symbolDraw.remove();
  37997. }
  37998. group.add(lineGroup);
  37999. // FIXME step not support polar
  38000. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  38001. var clipShapeForSymbol;
  38002. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  38003. clipShapeForSymbol = coordSys.getArea();
  38004. // Avoid float number rounding error for symbol on the edge of axis extent.
  38005. // See #7913 and `test/dataZoom-clip.html`.
  38006. if (clipShapeForSymbol.width != null) {
  38007. clipShapeForSymbol.x -= 0.1;
  38008. clipShapeForSymbol.y -= 0.1;
  38009. clipShapeForSymbol.width += 0.2;
  38010. clipShapeForSymbol.height += 0.2;
  38011. } else if (clipShapeForSymbol.r0) {
  38012. clipShapeForSymbol.r0 -= 0.5;
  38013. clipShapeForSymbol.r += 0.5;
  38014. }
  38015. }
  38016. this._clipShapeForSymbol = clipShapeForSymbol;
  38017. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')];
  38018. // Initialization animation or coordinate system changed
  38019. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  38020. showSymbol && symbolDraw.updateData(data, {
  38021. isIgnore: isIgnoreFunc,
  38022. clipShape: clipShapeForSymbol,
  38023. disableAnimation: true,
  38024. getSymbolPoint: function (idx) {
  38025. return [points[idx * 2], points[idx * 2 + 1]];
  38026. }
  38027. });
  38028. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  38029. if (step) {
  38030. // TODO If stacked series is not step
  38031. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38032. if (stackedOnPoints) {
  38033. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38034. }
  38035. }
  38036. polyline = this._newPolyline(points);
  38037. if (isAreaChart) {
  38038. polygon = this._newPolygon(points, stackedOnPoints);
  38039. } // If areaStyle is removed
  38040. else if (polygon) {
  38041. lineGroup.remove(polygon);
  38042. polygon = this._polygon = null;
  38043. }
  38044. // NOTE: Must update _endLabel before setClipPath.
  38045. if (!isCoordSysPolar) {
  38046. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38047. }
  38048. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38049. } else {
  38050. if (isAreaChart && !polygon) {
  38051. // If areaStyle is added
  38052. polygon = this._newPolygon(points, stackedOnPoints);
  38053. } else if (polygon && !isAreaChart) {
  38054. // If areaStyle is removed
  38055. lineGroup.remove(polygon);
  38056. polygon = this._polygon = null;
  38057. }
  38058. // NOTE: Must update _endLabel before setClipPath.
  38059. if (!isCoordSysPolar) {
  38060. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38061. }
  38062. // Update clipPath
  38063. var oldClipPath = lineGroup.getClipPath();
  38064. if (oldClipPath) {
  38065. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  38066. initProps(oldClipPath, {
  38067. shape: newClipPath.shape
  38068. }, seriesModel);
  38069. } else {
  38070. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38071. }
  38072. // Always update, or it is wrong in the case turning on legend
  38073. // because points are not changed.
  38074. showSymbol && symbolDraw.updateData(data, {
  38075. isIgnore: isIgnoreFunc,
  38076. clipShape: clipShapeForSymbol,
  38077. disableAnimation: true,
  38078. getSymbolPoint: function (idx) {
  38079. return [points[idx * 2], points[idx * 2 + 1]];
  38080. }
  38081. });
  38082. // In the case data zoom triggered refreshing frequently
  38083. // Data may not change if line has a category axis. So it should animate nothing.
  38084. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  38085. if (hasAnimation) {
  38086. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  38087. } else {
  38088. // Not do it in update with animation
  38089. if (step) {
  38090. // TODO If stacked series is not step
  38091. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38092. if (stackedOnPoints) {
  38093. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38094. }
  38095. }
  38096. polyline.setShape({
  38097. points: points
  38098. });
  38099. polygon && polygon.setShape({
  38100. points: points,
  38101. stackedOnPoints: stackedOnPoints
  38102. });
  38103. }
  38104. }
  38105. }
  38106. var emphasisModel = seriesModel.getModel('emphasis');
  38107. var focus = emphasisModel.get('focus');
  38108. var blurScope = emphasisModel.get('blurScope');
  38109. var emphasisDisabled = emphasisModel.get('disabled');
  38110. polyline.useStyle(defaults(
  38111. // Use color in lineStyle first
  38112. lineStyleModel.getLineStyle(), {
  38113. fill: 'none',
  38114. stroke: visualColor,
  38115. lineJoin: 'bevel'
  38116. }));
  38117. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  38118. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  38119. var emphasisLineStyle = polyline.getState('emphasis').style;
  38120. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  38121. }
  38122. // Needs seriesIndex for focus
  38123. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  38124. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  38125. var smooth = getSmooth(seriesModel.get('smooth'));
  38126. var smoothMonotone = seriesModel.get('smoothMonotone');
  38127. polyline.setShape({
  38128. smooth: smooth,
  38129. smoothMonotone: smoothMonotone,
  38130. connectNulls: connectNulls
  38131. });
  38132. if (polygon) {
  38133. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  38134. var stackedOnSmooth = 0;
  38135. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38136. fill: visualColor,
  38137. opacity: 0.7,
  38138. lineJoin: 'bevel',
  38139. decal: data.getVisual('style').decal
  38140. }));
  38141. if (stackedOnSeries) {
  38142. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  38143. }
  38144. polygon.setShape({
  38145. smooth: smooth,
  38146. stackedOnSmooth: stackedOnSmooth,
  38147. smoothMonotone: smoothMonotone,
  38148. connectNulls: connectNulls
  38149. });
  38150. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle');
  38151. // Needs seriesIndex for focus
  38152. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  38153. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  38154. }
  38155. var changePolyState = function (toState) {
  38156. _this._changePolyState(toState);
  38157. };
  38158. data.eachItemGraphicEl(function (el) {
  38159. // Switch polyline / polygon state if element changed its state.
  38160. el && (el.onHoverStateChange = changePolyState);
  38161. });
  38162. this._polyline.onHoverStateChange = changePolyState;
  38163. this._data = data;
  38164. // Save the coordinate system for transition animation when data changed
  38165. this._coordSys = coordSys;
  38166. this._stackedOnPoints = stackedOnPoints;
  38167. this._points = points;
  38168. this._step = step;
  38169. this._valueOrigin = valueOrigin;
  38170. if (seriesModel.get('triggerLineEvent')) {
  38171. this.packEventData(seriesModel, polyline);
  38172. polygon && this.packEventData(seriesModel, polygon);
  38173. }
  38174. };
  38175. LineView.prototype.packEventData = function (seriesModel, el) {
  38176. getECData(el).eventData = {
  38177. componentType: 'series',
  38178. componentSubType: 'line',
  38179. componentIndex: seriesModel.componentIndex,
  38180. seriesIndex: seriesModel.seriesIndex,
  38181. seriesName: seriesModel.name,
  38182. seriesType: 'line'
  38183. };
  38184. };
  38185. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  38186. var data = seriesModel.getData();
  38187. var dataIndex = queryDataIndex(data, payload);
  38188. this._changePolyState('emphasis');
  38189. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  38190. var points = data.getLayout('points');
  38191. var symbol = data.getItemGraphicEl(dataIndex);
  38192. if (!symbol) {
  38193. // Create a temporary symbol if it is not exists
  38194. var x = points[dataIndex * 2];
  38195. var y = points[dataIndex * 2 + 1];
  38196. if (isNaN(x) || isNaN(y)) {
  38197. // Null data
  38198. return;
  38199. }
  38200. // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  38201. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  38202. return;
  38203. }
  38204. var zlevel = seriesModel.get('zlevel') || 0;
  38205. var z = seriesModel.get('z') || 0;
  38206. symbol = new Symbol(data, dataIndex);
  38207. symbol.x = x;
  38208. symbol.y = y;
  38209. symbol.setZ(zlevel, z);
  38210. // ensure label text of the temporary symbol is in front of line and area polygon
  38211. var symbolLabel = symbol.getSymbolPath().getTextContent();
  38212. if (symbolLabel) {
  38213. symbolLabel.zlevel = zlevel;
  38214. symbolLabel.z = z;
  38215. symbolLabel.z2 = this._polyline.z2 + 1;
  38216. }
  38217. symbol.__temp = true;
  38218. data.setItemGraphicEl(dataIndex, symbol);
  38219. // Stop scale animation
  38220. symbol.stopSymbolAnimation(true);
  38221. this.group.add(symbol);
  38222. }
  38223. symbol.highlight();
  38224. } else {
  38225. // Highlight whole series
  38226. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  38227. }
  38228. };
  38229. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  38230. var data = seriesModel.getData();
  38231. var dataIndex = queryDataIndex(data, payload);
  38232. this._changePolyState('normal');
  38233. if (dataIndex != null && dataIndex >= 0) {
  38234. var symbol = data.getItemGraphicEl(dataIndex);
  38235. if (symbol) {
  38236. if (symbol.__temp) {
  38237. data.setItemGraphicEl(dataIndex, null);
  38238. this.group.remove(symbol);
  38239. } else {
  38240. symbol.downplay();
  38241. }
  38242. }
  38243. } else {
  38244. // FIXME
  38245. // can not downplay completely.
  38246. // Downplay whole series
  38247. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  38248. }
  38249. };
  38250. LineView.prototype._changePolyState = function (toState) {
  38251. var polygon = this._polygon;
  38252. setStatesFlag(this._polyline, toState);
  38253. polygon && setStatesFlag(polygon, toState);
  38254. };
  38255. LineView.prototype._newPolyline = function (points) {
  38256. var polyline = this._polyline;
  38257. // Remove previous created polyline
  38258. if (polyline) {
  38259. this._lineGroup.remove(polyline);
  38260. }
  38261. polyline = new ECPolyline({
  38262. shape: {
  38263. points: points
  38264. },
  38265. segmentIgnoreThreshold: 2,
  38266. z2: 10
  38267. });
  38268. this._lineGroup.add(polyline);
  38269. this._polyline = polyline;
  38270. return polyline;
  38271. };
  38272. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  38273. var polygon = this._polygon;
  38274. // Remove previous created polygon
  38275. if (polygon) {
  38276. this._lineGroup.remove(polygon);
  38277. }
  38278. polygon = new ECPolygon({
  38279. shape: {
  38280. points: points,
  38281. stackedOnPoints: stackedOnPoints
  38282. },
  38283. segmentIgnoreThreshold: 2
  38284. });
  38285. this._lineGroup.add(polygon);
  38286. this._polygon = polygon;
  38287. return polygon;
  38288. };
  38289. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  38290. var isHorizontalOrRadial;
  38291. var isCoordSysPolar;
  38292. var baseAxis = coordSys.getBaseAxis();
  38293. var isAxisInverse = baseAxis.inverse;
  38294. if (coordSys.type === 'cartesian2d') {
  38295. isHorizontalOrRadial = baseAxis.isHorizontal();
  38296. isCoordSysPolar = false;
  38297. } else if (coordSys.type === 'polar') {
  38298. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38299. isCoordSysPolar = true;
  38300. }
  38301. var seriesModel = data.hostModel;
  38302. var seriesDuration = seriesModel.get('animationDuration');
  38303. if (isFunction(seriesDuration)) {
  38304. seriesDuration = seriesDuration(null);
  38305. }
  38306. var seriesDelay = seriesModel.get('animationDelay') || 0;
  38307. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  38308. data.eachItemGraphicEl(function (symbol, idx) {
  38309. var el = symbol;
  38310. if (el) {
  38311. var point = [symbol.x, symbol.y];
  38312. var start = void 0;
  38313. var end = void 0;
  38314. var current = void 0;
  38315. if (clipShape) {
  38316. if (isCoordSysPolar) {
  38317. var polarClip = clipShape;
  38318. var coord = coordSys.pointToCoord(point);
  38319. if (isHorizontalOrRadial) {
  38320. start = polarClip.startAngle;
  38321. end = polarClip.endAngle;
  38322. current = -coord[1] / 180 * Math.PI;
  38323. } else {
  38324. start = polarClip.r0;
  38325. end = polarClip.r;
  38326. current = coord[0];
  38327. }
  38328. } else {
  38329. var gridClip = clipShape;
  38330. if (isHorizontalOrRadial) {
  38331. start = gridClip.x;
  38332. end = gridClip.x + gridClip.width;
  38333. current = symbol.x;
  38334. } else {
  38335. start = gridClip.y + gridClip.height;
  38336. end = gridClip.y;
  38337. current = symbol.y;
  38338. }
  38339. }
  38340. }
  38341. var ratio = end === start ? 0 : (current - start) / (end - start);
  38342. if (isAxisInverse) {
  38343. ratio = 1 - ratio;
  38344. }
  38345. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  38346. var symbolPath = el.getSymbolPath();
  38347. var text = symbolPath.getTextContent();
  38348. el.attr({
  38349. scaleX: 0,
  38350. scaleY: 0
  38351. });
  38352. el.animateTo({
  38353. scaleX: 1,
  38354. scaleY: 1
  38355. }, {
  38356. duration: 200,
  38357. setToFinal: true,
  38358. delay: delay
  38359. });
  38360. if (text) {
  38361. text.animateFrom({
  38362. style: {
  38363. opacity: 0
  38364. }
  38365. }, {
  38366. duration: 300,
  38367. delay: delay
  38368. });
  38369. }
  38370. symbolPath.disableLabelAnimation = true;
  38371. }
  38372. });
  38373. };
  38374. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  38375. var endLabelModel = seriesModel.getModel('endLabel');
  38376. if (anyStateShowEndLabel(seriesModel)) {
  38377. var data_2 = seriesModel.getData();
  38378. var polyline = this._polyline;
  38379. // series may be filtered.
  38380. var points = data_2.getLayout('points');
  38381. if (!points) {
  38382. polyline.removeTextContent();
  38383. this._endLabel = null;
  38384. return;
  38385. }
  38386. var endLabel = this._endLabel;
  38387. if (!endLabel) {
  38388. endLabel = this._endLabel = new ZRText({
  38389. z2: 200 // should be higher than item symbol
  38390. });
  38391. endLabel.ignoreClip = true;
  38392. polyline.setTextContent(this._endLabel);
  38393. polyline.disableLabelAnimation = true;
  38394. }
  38395. // Find last non-NaN data to display data
  38396. var dataIndex = getLastIndexNotNull(points);
  38397. if (dataIndex >= 0) {
  38398. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  38399. inheritColor: inheritColor,
  38400. labelFetcher: seriesModel,
  38401. labelDataIndex: dataIndex,
  38402. defaultText: function (dataIndex, opt, interpolatedValue) {
  38403. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  38404. },
  38405. enableTextSetter: true
  38406. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  38407. polyline.textConfig.position = null;
  38408. }
  38409. } else if (this._endLabel) {
  38410. this._polyline.removeTextContent();
  38411. this._endLabel = null;
  38412. }
  38413. };
  38414. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  38415. var endLabel = this._endLabel;
  38416. var polyline = this._polyline;
  38417. if (endLabel) {
  38418. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  38419. // The label is not prepared at this time.
  38420. if (percent < 1 && animationRecord.originalX == null) {
  38421. animationRecord.originalX = endLabel.x;
  38422. animationRecord.originalY = endLabel.y;
  38423. }
  38424. var points = data.getLayout('points');
  38425. var seriesModel = data.hostModel;
  38426. var connectNulls = seriesModel.get('connectNulls');
  38427. var precision = endLabelModel.get('precision');
  38428. var distance = endLabelModel.get('distance') || 0;
  38429. var baseAxis = coordSys.getBaseAxis();
  38430. var isHorizontal = baseAxis.isHorizontal();
  38431. var isBaseInversed = baseAxis.inverse;
  38432. var clipShape = clipRect.shape;
  38433. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  38434. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  38435. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  38436. var dim = isHorizontal ? 'x' : 'y';
  38437. var dataIndexRange = getIndexRange(points, xOrY, dim);
  38438. var indices = dataIndexRange.range;
  38439. var diff = indices[1] - indices[0];
  38440. var value = void 0;
  38441. if (diff >= 1) {
  38442. // diff > 1 && connectNulls, which is on the null data.
  38443. if (diff > 1 && !connectNulls) {
  38444. var pt = getPointAtIndex(points, indices[0]);
  38445. endLabel.attr({
  38446. x: pt[0] + distanceX,
  38447. y: pt[1] + distanceY
  38448. });
  38449. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  38450. } else {
  38451. var pt = polyline.getPointOn(xOrY, dim);
  38452. pt && endLabel.attr({
  38453. x: pt[0] + distanceX,
  38454. y: pt[1] + distanceY
  38455. });
  38456. var startValue = seriesModel.getRawValue(indices[0]);
  38457. var endValue = seriesModel.getRawValue(indices[1]);
  38458. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  38459. }
  38460. animationRecord.lastFrameIndex = indices[0];
  38461. } else {
  38462. // If diff <= 0, which is the range is not found(Include NaN)
  38463. // Choose the first point or last point.
  38464. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  38465. var pt = getPointAtIndex(points, idx);
  38466. valueAnimation && (value = seriesModel.getRawValue(idx));
  38467. endLabel.attr({
  38468. x: pt[0] + distanceX,
  38469. y: pt[1] + distanceY
  38470. });
  38471. }
  38472. if (valueAnimation) {
  38473. var inner = labelInner(endLabel);
  38474. if (typeof inner.setLabelText === 'function') {
  38475. inner.setLabelText(value);
  38476. }
  38477. }
  38478. }
  38479. };
  38480. /**
  38481. * @private
  38482. */
  38483. // FIXME Two value axis
  38484. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  38485. var polyline = this._polyline;
  38486. var polygon = this._polygon;
  38487. var seriesModel = data.hostModel;
  38488. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  38489. var current = diff.current;
  38490. var stackedOnCurrent = diff.stackedOnCurrent;
  38491. var next = diff.next;
  38492. var stackedOnNext = diff.stackedOnNext;
  38493. if (step) {
  38494. // TODO If stacked series is not step
  38495. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  38496. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  38497. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  38498. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  38499. }
  38500. // Don't apply animation if diff is large.
  38501. // For better result and avoid memory explosion problems like
  38502. // https://github.com/apache/incubator-echarts/issues/12229
  38503. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  38504. polyline.stopAnimation();
  38505. polyline.setShape({
  38506. points: next
  38507. });
  38508. if (polygon) {
  38509. polygon.stopAnimation();
  38510. polygon.setShape({
  38511. points: next,
  38512. stackedOnPoints: stackedOnNext
  38513. });
  38514. }
  38515. return;
  38516. }
  38517. polyline.shape.__points = diff.current;
  38518. polyline.shape.points = current;
  38519. var target = {
  38520. shape: {
  38521. points: next
  38522. }
  38523. };
  38524. // Also animate the original points.
  38525. // If points reference is changed when turning into step line.
  38526. if (diff.current !== current) {
  38527. target.shape.__points = diff.next;
  38528. }
  38529. // Stop previous animation.
  38530. polyline.stopAnimation();
  38531. updateProps(polyline, target, seriesModel);
  38532. if (polygon) {
  38533. polygon.setShape({
  38534. // Reuse the points with polyline.
  38535. points: current,
  38536. stackedOnPoints: stackedOnCurrent
  38537. });
  38538. polygon.stopAnimation();
  38539. updateProps(polygon, {
  38540. shape: {
  38541. stackedOnPoints: stackedOnNext
  38542. }
  38543. }, seriesModel);
  38544. // If use attr directly in updateProps.
  38545. if (polyline.shape.points !== polygon.shape.points) {
  38546. polygon.shape.points = polyline.shape.points;
  38547. }
  38548. }
  38549. var updatedDataInfo = [];
  38550. var diffStatus = diff.status;
  38551. for (var i = 0; i < diffStatus.length; i++) {
  38552. var cmd = diffStatus[i].cmd;
  38553. if (cmd === '=') {
  38554. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  38555. if (el) {
  38556. updatedDataInfo.push({
  38557. el: el,
  38558. ptIdx: i // Index of points
  38559. });
  38560. }
  38561. }
  38562. }
  38563. if (polyline.animators && polyline.animators.length) {
  38564. polyline.animators[0].during(function () {
  38565. polygon && polygon.dirtyShape();
  38566. var points = polyline.shape.__points;
  38567. for (var i = 0; i < updatedDataInfo.length; i++) {
  38568. var el = updatedDataInfo[i].el;
  38569. var offset = updatedDataInfo[i].ptIdx * 2;
  38570. el.x = points[offset];
  38571. el.y = points[offset + 1];
  38572. el.markRedraw();
  38573. }
  38574. });
  38575. }
  38576. };
  38577. LineView.prototype.remove = function (ecModel) {
  38578. var group = this.group;
  38579. var oldData = this._data;
  38580. this._lineGroup.removeAll();
  38581. this._symbolDraw.remove(true);
  38582. // Remove temporary created elements when highlighting
  38583. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38584. if (el.__temp) {
  38585. group.remove(el);
  38586. oldData.setItemGraphicEl(idx, null);
  38587. }
  38588. });
  38589. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  38590. };
  38591. LineView.type = 'line';
  38592. return LineView;
  38593. }(ChartView);
  38594. function pointsLayout(seriesType, forceStoreInTypedArray) {
  38595. return {
  38596. seriesType: seriesType,
  38597. plan: createRenderPlanner(),
  38598. reset: function (seriesModel) {
  38599. var data = seriesModel.getData();
  38600. var coordSys = seriesModel.coordinateSystem;
  38601. var pipelineContext = seriesModel.pipelineContext;
  38602. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  38603. if (!coordSys) {
  38604. return;
  38605. }
  38606. var dims = map(coordSys.dimensions, function (dim) {
  38607. return data.mapDimension(dim);
  38608. }).slice(0, 2);
  38609. var dimLen = dims.length;
  38610. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  38611. if (isDimensionStacked(data, dims[0])) {
  38612. dims[0] = stackResultDim;
  38613. }
  38614. if (isDimensionStacked(data, dims[1])) {
  38615. dims[1] = stackResultDim;
  38616. }
  38617. var store = data.getStore();
  38618. var dimIdx0 = data.getDimensionIndex(dims[0]);
  38619. var dimIdx1 = data.getDimensionIndex(dims[1]);
  38620. return dimLen && {
  38621. progress: function (params, data) {
  38622. var segCount = params.end - params.start;
  38623. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  38624. var tmpIn = [];
  38625. var tmpOut = [];
  38626. for (var i = params.start, offset = 0; i < params.end; i++) {
  38627. var point = void 0;
  38628. if (dimLen === 1) {
  38629. var x = store.get(dimIdx0, i);
  38630. // NOTE: Make sure the second parameter is null to use default strategy.
  38631. point = coordSys.dataToPoint(x, null, tmpOut);
  38632. } else {
  38633. tmpIn[0] = store.get(dimIdx0, i);
  38634. tmpIn[1] = store.get(dimIdx1, i);
  38635. // Let coordinate system to handle the NaN data.
  38636. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  38637. }
  38638. if (useTypedArray) {
  38639. points[offset++] = point[0];
  38640. points[offset++] = point[1];
  38641. } else {
  38642. data.setItemLayout(i, point.slice());
  38643. }
  38644. }
  38645. useTypedArray && data.setLayout('points', points);
  38646. }
  38647. };
  38648. }
  38649. };
  38650. }
  38651. var samplers = {
  38652. average: function (frame) {
  38653. var sum = 0;
  38654. var count = 0;
  38655. for (var i = 0; i < frame.length; i++) {
  38656. if (!isNaN(frame[i])) {
  38657. sum += frame[i];
  38658. count++;
  38659. }
  38660. }
  38661. // Return NaN if count is 0
  38662. return count === 0 ? NaN : sum / count;
  38663. },
  38664. sum: function (frame) {
  38665. var sum = 0;
  38666. for (var i = 0; i < frame.length; i++) {
  38667. // Ignore NaN
  38668. sum += frame[i] || 0;
  38669. }
  38670. return sum;
  38671. },
  38672. max: function (frame) {
  38673. var max = -Infinity;
  38674. for (var i = 0; i < frame.length; i++) {
  38675. frame[i] > max && (max = frame[i]);
  38676. }
  38677. // NaN will cause illegal axis extent.
  38678. return isFinite(max) ? max : NaN;
  38679. },
  38680. min: function (frame) {
  38681. var min = Infinity;
  38682. for (var i = 0; i < frame.length; i++) {
  38683. frame[i] < min && (min = frame[i]);
  38684. }
  38685. // NaN will cause illegal axis extent.
  38686. return isFinite(min) ? min : NaN;
  38687. },
  38688. minmax: function (frame) {
  38689. var turningPointAbsoluteValue = -Infinity;
  38690. var turningPointOriginalValue = -Infinity;
  38691. for (var i = 0; i < frame.length; i++) {
  38692. var originalValue = frame[i];
  38693. var absoluteValue = Math.abs(originalValue);
  38694. if (absoluteValue > turningPointAbsoluteValue) {
  38695. turningPointAbsoluteValue = absoluteValue;
  38696. turningPointOriginalValue = originalValue;
  38697. }
  38698. }
  38699. return isFinite(turningPointOriginalValue) ? turningPointOriginalValue : NaN;
  38700. },
  38701. // TODO
  38702. // Median
  38703. nearest: function (frame) {
  38704. return frame[0];
  38705. }
  38706. };
  38707. var indexSampler = function (frame) {
  38708. return Math.round(frame.length / 2);
  38709. };
  38710. function dataSample(seriesType) {
  38711. return {
  38712. seriesType: seriesType,
  38713. // FIXME:TS never used, so comment it
  38714. // modifyOutputEnd: true,
  38715. reset: function (seriesModel, ecModel, api) {
  38716. var data = seriesModel.getData();
  38717. var sampling = seriesModel.get('sampling');
  38718. var coordSys = seriesModel.coordinateSystem;
  38719. var count = data.count();
  38720. // Only cartesian2d support down sampling. Disable it when there is few data.
  38721. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  38722. var baseAxis = coordSys.getBaseAxis();
  38723. var valueAxis = coordSys.getOtherAxis(baseAxis);
  38724. var extent = baseAxis.getExtent();
  38725. var dpr = api.getDevicePixelRatio();
  38726. // Coordinste system has been resized
  38727. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  38728. var rate = Math.round(count / size);
  38729. if (isFinite(rate) && rate > 1) {
  38730. if (sampling === 'lttb') {
  38731. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  38732. }
  38733. var sampler = void 0;
  38734. if (isString(sampling)) {
  38735. sampler = samplers[sampling];
  38736. } else if (isFunction(sampling)) {
  38737. sampler = sampling;
  38738. }
  38739. if (sampler) {
  38740. // Only support sample the first dim mapped from value axis.
  38741. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  38742. }
  38743. }
  38744. }
  38745. }
  38746. };
  38747. }
  38748. function install$2(registers) {
  38749. registers.registerChartView(LineView);
  38750. registers.registerSeriesModel(LineSeriesModel);
  38751. registers.registerLayout(pointsLayout('line', true));
  38752. registers.registerVisual({
  38753. seriesType: 'line',
  38754. reset: function (seriesModel) {
  38755. var data = seriesModel.getData();
  38756. // Visual coding for legend
  38757. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  38758. if (lineStyle && !lineStyle.stroke) {
  38759. // Fill in visual should be palette color if
  38760. // has color callback
  38761. lineStyle.stroke = data.getVisual('style').fill;
  38762. }
  38763. data.setVisual('legendLineStyle', lineStyle);
  38764. }
  38765. });
  38766. // Down sample after filter
  38767. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  38768. }
  38769. var BaseBarSeriesModel = /** @class */function (_super) {
  38770. __extends(BaseBarSeriesModel, _super);
  38771. function BaseBarSeriesModel() {
  38772. var _this = _super !== null && _super.apply(this, arguments) || this;
  38773. _this.type = BaseBarSeriesModel.type;
  38774. return _this;
  38775. }
  38776. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38777. return createSeriesData(null, this, {
  38778. useEncodeDefaulter: true
  38779. });
  38780. };
  38781. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  38782. var coordSys = this.coordinateSystem;
  38783. if (coordSys && coordSys.clampData) {
  38784. // PENDING if clamp ?
  38785. var clampData_1 = coordSys.clampData(value);
  38786. var pt_1 = coordSys.dataToPoint(clampData_1);
  38787. if (startingAtTick) {
  38788. each(coordSys.getAxes(), function (axis, idx) {
  38789. // If axis type is category, use tick coords instead
  38790. if (axis.type === 'category' && dims != null) {
  38791. var tickCoords = axis.getTicksCoords();
  38792. var alignTicksWithLabel = axis.getTickModel().get('alignWithLabel');
  38793. var targetTickId = clampData_1[idx];
  38794. // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  38795. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  38796. if (isEnd && !alignTicksWithLabel) {
  38797. targetTickId += 1;
  38798. }
  38799. // The only contains one tick, tickCoords is
  38800. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  38801. // to the length should always be larger than 1
  38802. if (tickCoords.length < 2) {
  38803. return;
  38804. } else if (tickCoords.length === 2) {
  38805. // The left value and right value of the axis are
  38806. // the same. coord is 0 in both items. Use the max
  38807. // value of the axis as the coord
  38808. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  38809. return;
  38810. }
  38811. var leftCoord = void 0;
  38812. var coord = void 0;
  38813. var stepTickValue = 1;
  38814. for (var i = 0; i < tickCoords.length; i++) {
  38815. var tickCoord = tickCoords[i].coord;
  38816. // The last item of tickCoords doesn't contain
  38817. // tickValue
  38818. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  38819. if (tickValue === targetTickId) {
  38820. coord = tickCoord;
  38821. break;
  38822. } else if (tickValue < targetTickId) {
  38823. leftCoord = tickCoord;
  38824. } else if (leftCoord != null && tickValue > targetTickId) {
  38825. coord = (tickCoord + leftCoord) / 2;
  38826. break;
  38827. }
  38828. if (i === 1) {
  38829. // Here we assume the step of category axes is
  38830. // the same
  38831. stepTickValue = tickValue - tickCoords[0].tickValue;
  38832. }
  38833. }
  38834. if (coord == null) {
  38835. if (!leftCoord) {
  38836. // targetTickId is smaller than all tick ids in the
  38837. // visible area, use the leftmost tick coord
  38838. coord = tickCoords[0].coord;
  38839. } else if (leftCoord) {
  38840. // targetTickId is larger than all tick ids in the
  38841. // visible area, use the rightmost tick coord
  38842. coord = tickCoords[tickCoords.length - 1].coord;
  38843. }
  38844. }
  38845. pt_1[idx] = axis.toGlobalCoord(coord);
  38846. }
  38847. });
  38848. } else {
  38849. var data = this.getData();
  38850. var offset = data.getLayout('offset');
  38851. var size = data.getLayout('size');
  38852. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  38853. pt_1[offsetIndex] += offset + size / 2;
  38854. }
  38855. return pt_1;
  38856. }
  38857. return [NaN, NaN];
  38858. };
  38859. BaseBarSeriesModel.type = 'series.__base_bar__';
  38860. BaseBarSeriesModel.defaultOption = {
  38861. // zlevel: 0,
  38862. z: 2,
  38863. coordinateSystem: 'cartesian2d',
  38864. legendHoverLink: true,
  38865. // stack: null
  38866. // Cartesian coordinate system
  38867. // xAxisIndex: 0,
  38868. // yAxisIndex: 0,
  38869. barMinHeight: 0,
  38870. barMinAngle: 0,
  38871. // cursor: null,
  38872. large: false,
  38873. largeThreshold: 400,
  38874. progressive: 3e3,
  38875. progressiveChunkMode: 'mod'
  38876. };
  38877. return BaseBarSeriesModel;
  38878. }(SeriesModel);
  38879. SeriesModel.registerClass(BaseBarSeriesModel);
  38880. var BarSeriesModel = /** @class */function (_super) {
  38881. __extends(BarSeriesModel, _super);
  38882. function BarSeriesModel() {
  38883. var _this = _super !== null && _super.apply(this, arguments) || this;
  38884. _this.type = BarSeriesModel.type;
  38885. return _this;
  38886. }
  38887. BarSeriesModel.prototype.getInitialData = function () {
  38888. return createSeriesData(null, this, {
  38889. useEncodeDefaulter: true,
  38890. createInvertedIndices: !!this.get('realtimeSort', true) || null
  38891. });
  38892. };
  38893. /**
  38894. * @override
  38895. */
  38896. BarSeriesModel.prototype.getProgressive = function () {
  38897. // Do not support progressive in normal mode.
  38898. return this.get('large') ? this.get('progressive') : false;
  38899. };
  38900. /**
  38901. * @override
  38902. */
  38903. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  38904. // Do not support progressive in normal mode.
  38905. var progressiveThreshold = this.get('progressiveThreshold');
  38906. var largeThreshold = this.get('largeThreshold');
  38907. if (largeThreshold > progressiveThreshold) {
  38908. progressiveThreshold = largeThreshold;
  38909. }
  38910. return progressiveThreshold;
  38911. };
  38912. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  38913. return selectors.rect(data.getItemLayout(dataIndex));
  38914. };
  38915. BarSeriesModel.type = 'series.bar';
  38916. BarSeriesModel.dependencies = ['grid', 'polar'];
  38917. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  38918. // If clipped
  38919. // Only available on cartesian2d
  38920. clip: true,
  38921. roundCap: false,
  38922. showBackground: false,
  38923. backgroundStyle: {
  38924. color: 'rgba(180, 180, 180, 0.2)',
  38925. borderColor: null,
  38926. borderWidth: 0,
  38927. borderType: 'solid',
  38928. borderRadius: 0,
  38929. shadowBlur: 0,
  38930. shadowColor: null,
  38931. shadowOffsetX: 0,
  38932. shadowOffsetY: 0,
  38933. opacity: 1
  38934. },
  38935. select: {
  38936. itemStyle: {
  38937. borderColor: '#212121'
  38938. }
  38939. },
  38940. realtimeSort: false
  38941. });
  38942. return BarSeriesModel;
  38943. }(BaseBarSeriesModel);
  38944. /**
  38945. * Sausage: similar to sector, but have half circle on both sides
  38946. */
  38947. var SausageShape = /** @class */function () {
  38948. function SausageShape() {
  38949. this.cx = 0;
  38950. this.cy = 0;
  38951. this.r0 = 0;
  38952. this.r = 0;
  38953. this.startAngle = 0;
  38954. this.endAngle = Math.PI * 2;
  38955. this.clockwise = true;
  38956. }
  38957. return SausageShape;
  38958. }();
  38959. var SausagePath = /** @class */function (_super) {
  38960. __extends(SausagePath, _super);
  38961. function SausagePath(opts) {
  38962. var _this = _super.call(this, opts) || this;
  38963. _this.type = 'sausage';
  38964. return _this;
  38965. }
  38966. SausagePath.prototype.getDefaultShape = function () {
  38967. return new SausageShape();
  38968. };
  38969. SausagePath.prototype.buildPath = function (ctx, shape) {
  38970. var cx = shape.cx;
  38971. var cy = shape.cy;
  38972. var r0 = Math.max(shape.r0 || 0, 0);
  38973. var r = Math.max(shape.r, 0);
  38974. var dr = (r - r0) * 0.5;
  38975. var rCenter = r0 + dr;
  38976. var startAngle = shape.startAngle;
  38977. var endAngle = shape.endAngle;
  38978. var clockwise = shape.clockwise;
  38979. var PI2 = Math.PI * 2;
  38980. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  38981. if (!lessThanCircle) {
  38982. // Normalize angles
  38983. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  38984. }
  38985. var unitStartX = Math.cos(startAngle);
  38986. var unitStartY = Math.sin(startAngle);
  38987. var unitEndX = Math.cos(endAngle);
  38988. var unitEndY = Math.sin(endAngle);
  38989. if (lessThanCircle) {
  38990. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  38991. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  38992. } else {
  38993. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  38994. }
  38995. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  38996. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  38997. if (r0 !== 0) {
  38998. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  38999. }
  39000. // ctx.closePath();
  39001. };
  39002. return SausagePath;
  39003. }(Path);
  39004. function createSectorCalculateTextPosition(positionMapping, opts) {
  39005. opts = opts || {};
  39006. var isRoundCap = opts.isRoundCap;
  39007. return function (out, opts, boundingRect) {
  39008. var textPosition = opts.position;
  39009. if (!textPosition || textPosition instanceof Array) {
  39010. return calculateTextPosition(out, opts, boundingRect);
  39011. }
  39012. var mappedSectorPosition = positionMapping(textPosition);
  39013. var distance = opts.distance != null ? opts.distance : 5;
  39014. var sector = this.shape;
  39015. var cx = sector.cx;
  39016. var cy = sector.cy;
  39017. var r = sector.r;
  39018. var r0 = sector.r0;
  39019. var middleR = (r + r0) / 2;
  39020. var startAngle = sector.startAngle;
  39021. var endAngle = sector.endAngle;
  39022. var middleAngle = (startAngle + endAngle) / 2;
  39023. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  39024. var mathCos = Math.cos;
  39025. var mathSin = Math.sin;
  39026. // base position: top-left
  39027. var x = cx + r * mathCos(startAngle);
  39028. var y = cy + r * mathSin(startAngle);
  39029. var textAlign = 'left';
  39030. var textVerticalAlign = 'top';
  39031. switch (mappedSectorPosition) {
  39032. case 'startArc':
  39033. x = cx + (r0 - distance) * mathCos(middleAngle);
  39034. y = cy + (r0 - distance) * mathSin(middleAngle);
  39035. textAlign = 'center';
  39036. textVerticalAlign = 'top';
  39037. break;
  39038. case 'insideStartArc':
  39039. x = cx + (r0 + distance) * mathCos(middleAngle);
  39040. y = cy + (r0 + distance) * mathSin(middleAngle);
  39041. textAlign = 'center';
  39042. textVerticalAlign = 'bottom';
  39043. break;
  39044. case 'startAngle':
  39045. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  39046. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  39047. textAlign = 'right';
  39048. textVerticalAlign = 'middle';
  39049. break;
  39050. case 'insideStartAngle':
  39051. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  39052. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  39053. textAlign = 'left';
  39054. textVerticalAlign = 'middle';
  39055. break;
  39056. case 'middle':
  39057. x = cx + middleR * mathCos(middleAngle);
  39058. y = cy + middleR * mathSin(middleAngle);
  39059. textAlign = 'center';
  39060. textVerticalAlign = 'middle';
  39061. break;
  39062. case 'endArc':
  39063. x = cx + (r + distance) * mathCos(middleAngle);
  39064. y = cy + (r + distance) * mathSin(middleAngle);
  39065. textAlign = 'center';
  39066. textVerticalAlign = 'bottom';
  39067. break;
  39068. case 'insideEndArc':
  39069. x = cx + (r - distance) * mathCos(middleAngle);
  39070. y = cy + (r - distance) * mathSin(middleAngle);
  39071. textAlign = 'center';
  39072. textVerticalAlign = 'top';
  39073. break;
  39074. case 'endAngle':
  39075. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  39076. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  39077. textAlign = 'left';
  39078. textVerticalAlign = 'middle';
  39079. break;
  39080. case 'insideEndAngle':
  39081. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  39082. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  39083. textAlign = 'right';
  39084. textVerticalAlign = 'middle';
  39085. break;
  39086. default:
  39087. return calculateTextPosition(out, opts, boundingRect);
  39088. }
  39089. out = out || {};
  39090. out.x = x;
  39091. out.y = y;
  39092. out.align = textAlign;
  39093. out.verticalAlign = textVerticalAlign;
  39094. return out;
  39095. };
  39096. }
  39097. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  39098. if (isNumber(rotateType)) {
  39099. // user-set rotation
  39100. sector.setTextConfig({
  39101. rotation: rotateType
  39102. });
  39103. return;
  39104. } else if (isArray(textPosition)) {
  39105. // user-set position, use 0 as auto rotation
  39106. sector.setTextConfig({
  39107. rotation: 0
  39108. });
  39109. return;
  39110. }
  39111. var shape = sector.shape;
  39112. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  39113. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  39114. var middleAngle = (startAngle + endAngle) / 2;
  39115. var anchorAngle;
  39116. var mappedSectorPosition = positionMapping(textPosition);
  39117. switch (mappedSectorPosition) {
  39118. case 'startArc':
  39119. case 'insideStartArc':
  39120. case 'middle':
  39121. case 'insideEndArc':
  39122. case 'endArc':
  39123. anchorAngle = middleAngle;
  39124. break;
  39125. case 'startAngle':
  39126. case 'insideStartAngle':
  39127. anchorAngle = startAngle;
  39128. break;
  39129. case 'endAngle':
  39130. case 'insideEndAngle':
  39131. anchorAngle = endAngle;
  39132. break;
  39133. default:
  39134. sector.setTextConfig({
  39135. rotation: 0
  39136. });
  39137. return;
  39138. }
  39139. var rotate = Math.PI * 1.5 - anchorAngle;
  39140. /**
  39141. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  39142. * half round flipped to increase readability. However, only middle
  39143. * position supports this for now, because in other positions, the
  39144. * anchor point is not at the center of the text, so the positions
  39145. * after rotating is not as expected.
  39146. */
  39147. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  39148. rotate -= Math.PI;
  39149. }
  39150. sector.setTextConfig({
  39151. rotation: rotate
  39152. });
  39153. }
  39154. function adjustAngleDistanceX(angle, distance, isEnd) {
  39155. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  39156. }
  39157. function adjustAngleDistanceY(angle, distance, isEnd) {
  39158. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  39159. }
  39160. function getSectorCornerRadius(model, shape, zeroIfNull) {
  39161. var cornerRadius = model.get('borderRadius');
  39162. if (cornerRadius == null) {
  39163. return zeroIfNull ? {
  39164. cornerRadius: 0
  39165. } : null;
  39166. }
  39167. if (!isArray(cornerRadius)) {
  39168. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  39169. }
  39170. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  39171. return {
  39172. cornerRadius: map(cornerRadius, function (cr) {
  39173. return parsePercent(cr, dr);
  39174. })
  39175. };
  39176. }
  39177. var mathMax$6 = Math.max;
  39178. var mathMin$6 = Math.min;
  39179. function getClipArea(coord, data) {
  39180. var coordSysClipArea = coord.getArea && coord.getArea();
  39181. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39182. var baseAxis = coord.getBaseAxis();
  39183. // When boundaryGap is false or using time axis. bar may exceed the grid.
  39184. // We should not clip this part.
  39185. // See test/bar2.html
  39186. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  39187. var expandWidth = data.getLayout('bandWidth');
  39188. if (baseAxis.isHorizontal()) {
  39189. coordSysClipArea.x -= expandWidth;
  39190. coordSysClipArea.width += expandWidth * 2;
  39191. } else {
  39192. coordSysClipArea.y -= expandWidth;
  39193. coordSysClipArea.height += expandWidth * 2;
  39194. }
  39195. }
  39196. }
  39197. return coordSysClipArea;
  39198. }
  39199. var BarView = /** @class */function (_super) {
  39200. __extends(BarView, _super);
  39201. function BarView() {
  39202. var _this = _super.call(this) || this;
  39203. _this.type = BarView.type;
  39204. _this._isFirstFrame = true;
  39205. return _this;
  39206. }
  39207. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39208. this._model = seriesModel;
  39209. this._removeOnRenderedListener(api);
  39210. this._updateDrawMode(seriesModel);
  39211. var coordinateSystemType = seriesModel.get('coordinateSystem');
  39212. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  39213. // Clear previously rendered progressive elements.
  39214. this._progressiveEls = null;
  39215. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  39216. } else if ("development" !== 'production') {
  39217. warn('Only cartesian2d and polar supported for bar.');
  39218. }
  39219. };
  39220. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  39221. this._clear();
  39222. this._updateDrawMode(seriesModel);
  39223. // incremental also need to clip, otherwise might be overlow.
  39224. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  39225. this._updateLargeClip(seriesModel);
  39226. };
  39227. BarView.prototype.incrementalRender = function (params, seriesModel) {
  39228. // Reset
  39229. this._progressiveEls = [];
  39230. // Do not support progressive in normal mode.
  39231. this._incrementalRenderLarge(params, seriesModel);
  39232. };
  39233. BarView.prototype.eachRendered = function (cb) {
  39234. traverseElements(this._progressiveEls || this.group, cb);
  39235. };
  39236. BarView.prototype._updateDrawMode = function (seriesModel) {
  39237. var isLargeDraw = seriesModel.pipelineContext.large;
  39238. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  39239. this._isLargeDraw = isLargeDraw;
  39240. this._clear();
  39241. }
  39242. };
  39243. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  39244. var group = this.group;
  39245. var data = seriesModel.getData();
  39246. var oldData = this._data;
  39247. var coord = seriesModel.coordinateSystem;
  39248. var baseAxis = coord.getBaseAxis();
  39249. var isHorizontalOrRadial;
  39250. if (coord.type === 'cartesian2d') {
  39251. isHorizontalOrRadial = baseAxis.isHorizontal();
  39252. } else if (coord.type === 'polar') {
  39253. isHorizontalOrRadial = baseAxis.dim === 'angle';
  39254. }
  39255. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  39256. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  39257. if (realtimeSortCfg) {
  39258. this._enableRealtimeSort(realtimeSortCfg, data, api);
  39259. }
  39260. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  39261. var coordSysClipArea = getClipArea(coord, data);
  39262. // If there is clipPath created in large mode. Remove it.
  39263. group.removeClipPath();
  39264. // We don't use clipPath in normal mode because we needs a perfect animation
  39265. // And don't want the label are clipped.
  39266. var roundCap = seriesModel.get('roundCap', true);
  39267. var drawBackground = seriesModel.get('showBackground', true);
  39268. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39269. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  39270. var bgEls = [];
  39271. var oldBgEls = this._backgroundEls;
  39272. var isInitSort = payload && payload.isInitSort;
  39273. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  39274. function createBackground(dataIndex) {
  39275. var bgLayout = getLayout[coord.type](data, dataIndex);
  39276. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  39277. bgEl.useStyle(backgroundModel.getItemStyle());
  39278. // Only cartesian2d support borderRadius.
  39279. if (coord.type === 'cartesian2d') {
  39280. bgEl.setShape('r', barBorderRadius);
  39281. } else {
  39282. bgEl.setShape('cornerRadius', barBorderRadius);
  39283. }
  39284. bgEls[dataIndex] = bgEl;
  39285. return bgEl;
  39286. }
  39287. data.diff(oldData).add(function (dataIndex) {
  39288. var itemModel = data.getItemModel(dataIndex);
  39289. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  39290. if (drawBackground) {
  39291. createBackground(dataIndex);
  39292. }
  39293. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  39294. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  39295. return;
  39296. }
  39297. var isClipped = false;
  39298. if (needsClip) {
  39299. // Clip will modify the layout params.
  39300. // And return a boolean to determine if the shape are fully clipped.
  39301. isClipped = clip[coord.type](coordSysClipArea, layout);
  39302. }
  39303. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  39304. if (realtimeSortCfg) {
  39305. /**
  39306. * Force label animation because even if the element is
  39307. * ignored because it's clipped, it may not be clipped after
  39308. * changing order. Then, if not using forceLabelAnimation,
  39309. * the label animation was never started, in which case,
  39310. * the label will be the final value and doesn't have label
  39311. * animation.
  39312. */
  39313. el.forceLabelAnimation = true;
  39314. }
  39315. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39316. if (isInitSort) {
  39317. el.attr({
  39318. shape: layout
  39319. });
  39320. } else if (realtimeSortCfg) {
  39321. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  39322. } else {
  39323. initProps(el, {
  39324. shape: layout
  39325. }, seriesModel, dataIndex);
  39326. }
  39327. data.setItemGraphicEl(dataIndex, el);
  39328. group.add(el);
  39329. el.ignore = isClipped;
  39330. }).update(function (newIndex, oldIndex) {
  39331. var itemModel = data.getItemModel(newIndex);
  39332. var layout = getLayout[coord.type](data, newIndex, itemModel);
  39333. if (drawBackground) {
  39334. var bgEl = void 0;
  39335. if (oldBgEls.length === 0) {
  39336. bgEl = createBackground(oldIndex);
  39337. } else {
  39338. bgEl = oldBgEls[oldIndex];
  39339. bgEl.useStyle(backgroundModel.getItemStyle());
  39340. // Only cartesian2d support borderRadius.
  39341. if (coord.type === 'cartesian2d') {
  39342. bgEl.setShape('r', barBorderRadius);
  39343. } else {
  39344. bgEl.setShape('cornerRadius', barBorderRadius);
  39345. }
  39346. bgEls[newIndex] = bgEl;
  39347. }
  39348. var bgLayout = getLayout[coord.type](data, newIndex);
  39349. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  39350. updateProps(bgEl, {
  39351. shape: shape
  39352. }, animationModel, newIndex);
  39353. }
  39354. var el = oldData.getItemGraphicEl(oldIndex);
  39355. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  39356. group.remove(el);
  39357. return;
  39358. }
  39359. var isClipped = false;
  39360. if (needsClip) {
  39361. isClipped = clip[coord.type](coordSysClipArea, layout);
  39362. if (isClipped) {
  39363. group.remove(el);
  39364. }
  39365. }
  39366. if (!el) {
  39367. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  39368. } else {
  39369. saveOldStyle(el);
  39370. }
  39371. if (realtimeSortCfg) {
  39372. el.forceLabelAnimation = true;
  39373. }
  39374. if (isChangeOrder) {
  39375. var textEl = el.getTextContent();
  39376. if (textEl) {
  39377. var labelInnerStore = labelInner(textEl);
  39378. if (labelInnerStore.prevValue != null) {
  39379. /**
  39380. * Set preValue to be value so that no new label
  39381. * should be started, otherwise, it will take a full
  39382. * `animationDurationUpdate` time to finish the
  39383. * animation, which is not expected.
  39384. */
  39385. labelInnerStore.prevValue = labelInnerStore.value;
  39386. }
  39387. }
  39388. }
  39389. // Not change anything if only order changed.
  39390. // Especially not change label.
  39391. else {
  39392. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39393. }
  39394. if (isInitSort) {
  39395. el.attr({
  39396. shape: layout
  39397. });
  39398. } else if (realtimeSortCfg) {
  39399. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  39400. } else {
  39401. updateProps(el, {
  39402. shape: layout
  39403. }, seriesModel, newIndex, null);
  39404. }
  39405. data.setItemGraphicEl(newIndex, el);
  39406. el.ignore = isClipped;
  39407. group.add(el);
  39408. }).remove(function (dataIndex) {
  39409. var el = oldData.getItemGraphicEl(dataIndex);
  39410. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  39411. }).execute();
  39412. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  39413. bgGroup.removeAll();
  39414. for (var i = 0; i < bgEls.length; ++i) {
  39415. bgGroup.add(bgEls[i]);
  39416. }
  39417. group.add(bgGroup);
  39418. this._backgroundEls = bgEls;
  39419. this._data = data;
  39420. };
  39421. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  39422. this._clear();
  39423. createLarge(seriesModel, this.group);
  39424. this._updateLargeClip(seriesModel);
  39425. };
  39426. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  39427. this._removeBackground();
  39428. createLarge(seriesModel, this.group, this._progressiveEls, true);
  39429. };
  39430. BarView.prototype._updateLargeClip = function (seriesModel) {
  39431. // Use clipPath in large mode.
  39432. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  39433. var group = this.group;
  39434. if (clipPath) {
  39435. group.setClipPath(clipPath);
  39436. } else {
  39437. group.removeClipPath();
  39438. }
  39439. };
  39440. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  39441. var _this = this;
  39442. // If no data in the first frame, wait for data to initSort
  39443. if (!data.count()) {
  39444. return;
  39445. }
  39446. var baseAxis = realtimeSortCfg.baseAxis;
  39447. if (this._isFirstFrame) {
  39448. this._dispatchInitSort(data, realtimeSortCfg, api);
  39449. this._isFirstFrame = false;
  39450. } else {
  39451. var orderMapping_1 = function (idx) {
  39452. var el = data.getItemGraphicEl(idx);
  39453. var shape = el && el.shape;
  39454. return shape &&
  39455. // The result should be consistent with the initial sort by data value.
  39456. // Do not support the case that both positive and negative exist.
  39457. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width)
  39458. // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  39459. || 0;
  39460. };
  39461. this._onRendered = function () {
  39462. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  39463. };
  39464. api.getZr().on('rendered', this._onRendered);
  39465. }
  39466. };
  39467. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  39468. var info = [];
  39469. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  39470. var mappedValue = orderMapping(dataIdx);
  39471. mappedValue = mappedValue == null ? NaN : mappedValue;
  39472. info.push({
  39473. dataIndex: dataIdx,
  39474. mappedValue: mappedValue,
  39475. ordinalNumber: ordinalNumber
  39476. });
  39477. });
  39478. info.sort(function (a, b) {
  39479. // If NaN, it will be treated as min val.
  39480. return b.mappedValue - a.mappedValue;
  39481. });
  39482. return {
  39483. ordinalNumbers: map(info, function (item) {
  39484. return item.ordinalNumber;
  39485. })
  39486. };
  39487. };
  39488. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  39489. var scale = baseAxis.scale;
  39490. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  39491. var lastValue = Number.MAX_VALUE;
  39492. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  39493. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  39494. var value = rawIdx < 0
  39495. // If some tick have no bar, the tick will be treated as min.
  39496. ? Number.MIN_VALUE
  39497. // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  39498. : orderMapping(data.indexOfRawIndex(rawIdx));
  39499. if (value > lastValue) {
  39500. return true;
  39501. }
  39502. lastValue = value;
  39503. }
  39504. return false;
  39505. };
  39506. /*
  39507. * Consider the case when A and B changed order, whose representing
  39508. * bars are both out of sight, we don't wish to trigger reorder action
  39509. * as long as the order in the view doesn't change.
  39510. */
  39511. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  39512. var scale = baseAxis.scale;
  39513. var extent = scale.getExtent();
  39514. var tickNum = Math.max(0, extent[0]);
  39515. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  39516. for (; tickNum <= tickMax; ++tickNum) {
  39517. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  39518. return true;
  39519. }
  39520. }
  39521. };
  39522. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  39523. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  39524. return;
  39525. }
  39526. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  39527. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  39528. this._removeOnRenderedListener(api);
  39529. api.dispatchAction({
  39530. type: 'changeAxisOrder',
  39531. componentType: baseAxis.dim + 'Axis',
  39532. axisId: baseAxis.index,
  39533. sortInfo: sortInfo
  39534. });
  39535. }
  39536. };
  39537. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  39538. var baseAxis = realtimeSortCfg.baseAxis;
  39539. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  39540. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  39541. });
  39542. api.dispatchAction({
  39543. type: 'changeAxisOrder',
  39544. componentType: baseAxis.dim + 'Axis',
  39545. isInitSort: true,
  39546. axisId: baseAxis.index,
  39547. sortInfo: sortResult
  39548. });
  39549. };
  39550. BarView.prototype.remove = function (ecModel, api) {
  39551. this._clear(this._model);
  39552. this._removeOnRenderedListener(api);
  39553. };
  39554. BarView.prototype.dispose = function (ecModel, api) {
  39555. this._removeOnRenderedListener(api);
  39556. };
  39557. BarView.prototype._removeOnRenderedListener = function (api) {
  39558. if (this._onRendered) {
  39559. api.getZr().off('rendered', this._onRendered);
  39560. this._onRendered = null;
  39561. }
  39562. };
  39563. BarView.prototype._clear = function (model) {
  39564. var group = this.group;
  39565. var data = this._data;
  39566. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  39567. this._removeBackground();
  39568. this._backgroundEls = [];
  39569. data.eachItemGraphicEl(function (el) {
  39570. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  39571. });
  39572. } else {
  39573. group.removeAll();
  39574. }
  39575. this._data = null;
  39576. this._isFirstFrame = true;
  39577. };
  39578. BarView.prototype._removeBackground = function () {
  39579. this.group.remove(this._backgroundGroup);
  39580. this._backgroundGroup = null;
  39581. };
  39582. BarView.type = 'bar';
  39583. return BarView;
  39584. }(ChartView);
  39585. var clip = {
  39586. cartesian2d: function (coordSysBoundingRect, layout) {
  39587. var signWidth = layout.width < 0 ? -1 : 1;
  39588. var signHeight = layout.height < 0 ? -1 : 1;
  39589. // Needs positive width and height
  39590. if (signWidth < 0) {
  39591. layout.x += layout.width;
  39592. layout.width = -layout.width;
  39593. }
  39594. if (signHeight < 0) {
  39595. layout.y += layout.height;
  39596. layout.height = -layout.height;
  39597. }
  39598. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  39599. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  39600. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  39601. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  39602. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  39603. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  39604. var xClipped = x2 < x;
  39605. var yClipped = y2 < y;
  39606. // When xClipped or yClipped, the element will be marked as `ignore`.
  39607. // But we should also place the element at the edge of the coord sys bounding rect.
  39608. // Because if data changed and the bar shows again, its transition animation
  39609. // will begin at this place.
  39610. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  39611. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  39612. layout.width = xClipped ? 0 : x2 - x;
  39613. layout.height = yClipped ? 0 : y2 - y;
  39614. // Reverse back
  39615. if (signWidth < 0) {
  39616. layout.x += layout.width;
  39617. layout.width = -layout.width;
  39618. }
  39619. if (signHeight < 0) {
  39620. layout.y += layout.height;
  39621. layout.height = -layout.height;
  39622. }
  39623. return xClipped || yClipped;
  39624. },
  39625. polar: function (coordSysClipArea, layout) {
  39626. var signR = layout.r0 <= layout.r ? 1 : -1;
  39627. // Make sure r is larger than r0
  39628. if (signR < 0) {
  39629. var tmp = layout.r;
  39630. layout.r = layout.r0;
  39631. layout.r0 = tmp;
  39632. }
  39633. var r = mathMin$6(layout.r, coordSysClipArea.r);
  39634. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  39635. layout.r = r;
  39636. layout.r0 = r0;
  39637. var clipped = r - r0 < 0;
  39638. // Reverse back
  39639. if (signR < 0) {
  39640. var tmp = layout.r;
  39641. layout.r = layout.r0;
  39642. layout.r0 = tmp;
  39643. }
  39644. return clipped;
  39645. }
  39646. };
  39647. var elementCreator = {
  39648. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  39649. var rect = new Rect({
  39650. shape: extend({}, layout),
  39651. z2: 1
  39652. });
  39653. rect.__dataIndex = newIndex;
  39654. rect.name = 'item';
  39655. if (animationModel) {
  39656. var rectShape = rect.shape;
  39657. var animateProperty = isHorizontal ? 'height' : 'width';
  39658. rectShape[animateProperty] = 0;
  39659. }
  39660. return rect;
  39661. },
  39662. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  39663. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  39664. var sector = new ShapeClass({
  39665. shape: layout,
  39666. z2: 1
  39667. });
  39668. sector.name = 'item';
  39669. var positionMap = createPolarPositionMapping(isRadial);
  39670. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  39671. isRoundCap: ShapeClass === SausagePath
  39672. });
  39673. // Animation
  39674. if (animationModel) {
  39675. var sectorShape = sector.shape;
  39676. var animateProperty = isRadial ? 'r' : 'endAngle';
  39677. var animateTarget = {};
  39678. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  39679. animateTarget[animateProperty] = layout[animateProperty];
  39680. (isUpdate ? updateProps : initProps)(sector, {
  39681. shape: animateTarget
  39682. // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  39683. }, animationModel);
  39684. }
  39685. return sector;
  39686. }
  39687. };
  39688. function shouldRealtimeSort(seriesModel, coordSys) {
  39689. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  39690. var baseAxis = coordSys.getBaseAxis();
  39691. if ("development" !== 'production') {
  39692. if (realtimeSortOption) {
  39693. if (baseAxis.type !== 'category') {
  39694. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  39695. }
  39696. if (coordSys.type !== 'cartesian2d') {
  39697. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  39698. }
  39699. }
  39700. }
  39701. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  39702. return {
  39703. baseAxis: baseAxis,
  39704. otherAxis: coordSys.getOtherAxis(baseAxis)
  39705. };
  39706. }
  39707. }
  39708. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  39709. var seriesTarget;
  39710. var axisTarget;
  39711. if (isHorizontal) {
  39712. axisTarget = {
  39713. x: layout.x,
  39714. width: layout.width
  39715. };
  39716. seriesTarget = {
  39717. y: layout.y,
  39718. height: layout.height
  39719. };
  39720. } else {
  39721. axisTarget = {
  39722. y: layout.y,
  39723. height: layout.height
  39724. };
  39725. seriesTarget = {
  39726. x: layout.x,
  39727. width: layout.width
  39728. };
  39729. }
  39730. if (!isChangeOrder) {
  39731. // Keep the original growth animation if only axis order changed.
  39732. // Not start a new animation.
  39733. (isUpdate ? updateProps : initProps)(el, {
  39734. shape: seriesTarget
  39735. }, seriesAnimationModel, newIndex, null);
  39736. }
  39737. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  39738. (isUpdate ? updateProps : initProps)(el, {
  39739. shape: axisTarget
  39740. }, axisAnimationModel, newIndex);
  39741. }
  39742. function checkPropertiesNotValid(obj, props) {
  39743. for (var i = 0; i < props.length; i++) {
  39744. if (!isFinite(obj[props[i]])) {
  39745. return true;
  39746. }
  39747. }
  39748. return false;
  39749. }
  39750. var rectPropties = ['x', 'y', 'width', 'height'];
  39751. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  39752. var isValidLayout = {
  39753. cartesian2d: function (layout) {
  39754. return !checkPropertiesNotValid(layout, rectPropties);
  39755. },
  39756. polar: function (layout) {
  39757. return !checkPropertiesNotValid(layout, polarPropties);
  39758. }
  39759. };
  39760. var getLayout = {
  39761. // itemModel is only used to get borderWidth, which is not needed
  39762. // when calculating bar background layout.
  39763. cartesian2d: function (data, dataIndex, itemModel) {
  39764. var layout = data.getItemLayout(dataIndex);
  39765. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  39766. // fix layout with lineWidth
  39767. var signX = layout.width > 0 ? 1 : -1;
  39768. var signY = layout.height > 0 ? 1 : -1;
  39769. return {
  39770. x: layout.x + signX * fixedLineWidth / 2,
  39771. y: layout.y + signY * fixedLineWidth / 2,
  39772. width: layout.width - signX * fixedLineWidth,
  39773. height: layout.height - signY * fixedLineWidth
  39774. };
  39775. },
  39776. polar: function (data, dataIndex, itemModel) {
  39777. var layout = data.getItemLayout(dataIndex);
  39778. return {
  39779. cx: layout.cx,
  39780. cy: layout.cy,
  39781. r0: layout.r0,
  39782. r: layout.r,
  39783. startAngle: layout.startAngle,
  39784. endAngle: layout.endAngle,
  39785. clockwise: layout.clockwise
  39786. };
  39787. }
  39788. };
  39789. function isZeroOnPolar(layout) {
  39790. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  39791. }
  39792. function createPolarPositionMapping(isRadial) {
  39793. return function (isRadial) {
  39794. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  39795. return function (position) {
  39796. switch (position) {
  39797. case 'start':
  39798. case 'insideStart':
  39799. case 'end':
  39800. case 'insideEnd':
  39801. return position + arcOrAngle;
  39802. default:
  39803. return position;
  39804. }
  39805. };
  39806. }(isRadial);
  39807. }
  39808. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  39809. var style = data.getItemVisual(dataIndex, 'style');
  39810. if (!isPolar) {
  39811. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  39812. el.setShape('r', borderRadius);
  39813. } else if (!seriesModel.get('roundCap')) {
  39814. var sectorShape = el.shape;
  39815. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  39816. extend(sectorShape, cornerRadius);
  39817. el.setShape(sectorShape);
  39818. }
  39819. el.useStyle(style);
  39820. var cursorStyle = itemModel.getShallow('cursor');
  39821. cursorStyle && el.attr('cursor', cursorStyle);
  39822. 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';
  39823. var labelStatesModels = getLabelStatesModels(itemModel);
  39824. setLabelStyle(el, labelStatesModels, {
  39825. labelFetcher: seriesModel,
  39826. labelDataIndex: dataIndex,
  39827. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  39828. inheritColor: style.fill,
  39829. defaultOpacity: style.opacity,
  39830. defaultOutsidePosition: labelPositionOutside
  39831. });
  39832. var label = el.getTextContent();
  39833. if (isPolar && label) {
  39834. var position = itemModel.get(['label', 'position']);
  39835. el.textConfig.inside = position === 'middle' ? true : null;
  39836. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  39837. }
  39838. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  39839. return getDefaultInterpolatedLabel(data, value);
  39840. });
  39841. var emphasisModel = itemModel.getModel(['emphasis']);
  39842. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39843. setStatesStylesFromModel(el, itemModel);
  39844. if (isZeroOnPolar(layout)) {
  39845. el.style.fill = 'none';
  39846. el.style.stroke = 'none';
  39847. each(el.states, function (state) {
  39848. if (state.style) {
  39849. state.style.fill = state.style.stroke = 'none';
  39850. }
  39851. });
  39852. }
  39853. }
  39854. // In case width or height are too small.
  39855. function getLineWidth(itemModel, rawLayout) {
  39856. // Has no border.
  39857. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  39858. if (!borderColor || borderColor === 'none') {
  39859. return 0;
  39860. }
  39861. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0;
  39862. // width or height may be NaN for empty data
  39863. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  39864. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  39865. return Math.min(lineWidth, width, height);
  39866. }
  39867. var LagePathShape = /** @class */function () {
  39868. function LagePathShape() {}
  39869. return LagePathShape;
  39870. }();
  39871. var LargePath = /** @class */function (_super) {
  39872. __extends(LargePath, _super);
  39873. function LargePath(opts) {
  39874. var _this = _super.call(this, opts) || this;
  39875. _this.type = 'largeBar';
  39876. return _this;
  39877. }
  39878. LargePath.prototype.getDefaultShape = function () {
  39879. return new LagePathShape();
  39880. };
  39881. LargePath.prototype.buildPath = function (ctx, shape) {
  39882. // Drawing lines is more efficient than drawing
  39883. // a whole line or drawing rects.
  39884. var points = shape.points;
  39885. var baseDimIdx = this.baseDimIdx;
  39886. var valueDimIdx = 1 - this.baseDimIdx;
  39887. var startPoint = [];
  39888. var size = [];
  39889. var barWidth = this.barWidth;
  39890. for (var i = 0; i < points.length; i += 3) {
  39891. size[baseDimIdx] = barWidth;
  39892. size[valueDimIdx] = points[i + 2];
  39893. startPoint[baseDimIdx] = points[i + baseDimIdx];
  39894. startPoint[valueDimIdx] = points[i + valueDimIdx];
  39895. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  39896. }
  39897. };
  39898. return LargePath;
  39899. }(Path);
  39900. function createLarge(seriesModel, group, progressiveEls, incremental) {
  39901. // TODO support polar
  39902. var data = seriesModel.getData();
  39903. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  39904. var largeDataIndices = data.getLayout('largeDataIndices');
  39905. var barWidth = data.getLayout('size');
  39906. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39907. var bgPoints = data.getLayout('largeBackgroundPoints');
  39908. if (bgPoints) {
  39909. var bgEl = new LargePath({
  39910. shape: {
  39911. points: bgPoints
  39912. },
  39913. incremental: !!incremental,
  39914. silent: true,
  39915. z2: 0
  39916. });
  39917. bgEl.baseDimIdx = baseDimIdx;
  39918. bgEl.largeDataIndices = largeDataIndices;
  39919. bgEl.barWidth = barWidth;
  39920. bgEl.useStyle(backgroundModel.getItemStyle());
  39921. group.add(bgEl);
  39922. progressiveEls && progressiveEls.push(bgEl);
  39923. }
  39924. var el = new LargePath({
  39925. shape: {
  39926. points: data.getLayout('largePoints')
  39927. },
  39928. incremental: !!incremental,
  39929. ignoreCoarsePointer: true,
  39930. z2: 1
  39931. });
  39932. el.baseDimIdx = baseDimIdx;
  39933. el.largeDataIndices = largeDataIndices;
  39934. el.barWidth = barWidth;
  39935. group.add(el);
  39936. el.useStyle(data.getVisual('style'));
  39937. // Enable tooltip and user mouse/touch event handlers.
  39938. getECData(el).seriesIndex = seriesModel.seriesIndex;
  39939. if (!seriesModel.get('silent')) {
  39940. el.on('mousedown', largePathUpdateDataIndex);
  39941. el.on('mousemove', largePathUpdateDataIndex);
  39942. }
  39943. progressiveEls && progressiveEls.push(el);
  39944. }
  39945. // Use throttle to avoid frequently traverse to find dataIndex.
  39946. var largePathUpdateDataIndex = throttle(function (event) {
  39947. var largePath = this;
  39948. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  39949. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  39950. }, 30, false);
  39951. function largePathFindDataIndex(largePath, x, y) {
  39952. var baseDimIdx = largePath.baseDimIdx;
  39953. var valueDimIdx = 1 - baseDimIdx;
  39954. var points = largePath.shape.points;
  39955. var largeDataIndices = largePath.largeDataIndices;
  39956. var startPoint = [];
  39957. var size = [];
  39958. var barWidth = largePath.barWidth;
  39959. for (var i = 0, len = points.length / 3; i < len; i++) {
  39960. var ii = i * 3;
  39961. size[baseDimIdx] = barWidth;
  39962. size[valueDimIdx] = points[ii + 2];
  39963. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  39964. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  39965. if (size[valueDimIdx] < 0) {
  39966. startPoint[valueDimIdx] += size[valueDimIdx];
  39967. size[valueDimIdx] = -size[valueDimIdx];
  39968. }
  39969. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  39970. return largeDataIndices[i];
  39971. }
  39972. }
  39973. return -1;
  39974. }
  39975. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  39976. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39977. var rectShape = layout;
  39978. var coordLayout = coord.getArea();
  39979. return {
  39980. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  39981. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  39982. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  39983. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  39984. };
  39985. } else {
  39986. var coordLayout = coord.getArea();
  39987. var sectorShape = layout;
  39988. return {
  39989. cx: coordLayout.cx,
  39990. cy: coordLayout.cy,
  39991. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  39992. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  39993. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  39994. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  39995. };
  39996. }
  39997. }
  39998. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  39999. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  40000. return new ElementClz({
  40001. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  40002. silent: true,
  40003. z2: 0
  40004. });
  40005. }
  40006. function install$3(registers) {
  40007. registers.registerChartView(BarView);
  40008. registers.registerSeriesModel(BarSeriesModel);
  40009. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  40010. // Do layout after other overall layout, which can prepare some information.
  40011. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar'));
  40012. // Down sample after filter
  40013. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  40014. /**
  40015. * @payload
  40016. * @property {string} [componentType=series]
  40017. * @property {number} [dx]
  40018. * @property {number} [dy]
  40019. * @property {number} [zoom]
  40020. * @property {number} [originX]
  40021. * @property {number} [originY]
  40022. */
  40023. registers.registerAction({
  40024. type: 'changeAxisOrder',
  40025. event: 'changeAxisOrder',
  40026. update: 'update'
  40027. }, function (payload, ecModel) {
  40028. var componentType = payload.componentType || 'series';
  40029. ecModel.eachComponent({
  40030. mainType: componentType,
  40031. query: payload
  40032. }, function (componentModel) {
  40033. if (payload.sortInfo) {
  40034. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  40035. }
  40036. });
  40037. });
  40038. }
  40039. var PI2$7 = Math.PI * 2;
  40040. var RADIAN = Math.PI / 180;
  40041. function getViewRect(seriesModel, api) {
  40042. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40043. width: api.getWidth(),
  40044. height: api.getHeight()
  40045. });
  40046. }
  40047. function getBasicPieLayout(seriesModel, api) {
  40048. var viewRect = getViewRect(seriesModel, api);
  40049. // center can be string or number when coordinateSystem is specified
  40050. var center = seriesModel.get('center');
  40051. var radius = seriesModel.get('radius');
  40052. if (!isArray(radius)) {
  40053. radius = [0, radius];
  40054. }
  40055. var width = parsePercent$1(viewRect.width, api.getWidth());
  40056. var height = parsePercent$1(viewRect.height, api.getHeight());
  40057. var size = Math.min(width, height);
  40058. var r0 = parsePercent$1(radius[0], size / 2);
  40059. var r = parsePercent$1(radius[1], size / 2);
  40060. var cx;
  40061. var cy;
  40062. var coordSys = seriesModel.coordinateSystem;
  40063. if (coordSys) {
  40064. // percentage is not allowed when coordinate system is specified
  40065. var point = coordSys.dataToPoint(center);
  40066. cx = point[0] || 0;
  40067. cy = point[1] || 0;
  40068. } else {
  40069. if (!isArray(center)) {
  40070. center = [center, center];
  40071. }
  40072. cx = parsePercent$1(center[0], width) + viewRect.x;
  40073. cy = parsePercent$1(center[1], height) + viewRect.y;
  40074. }
  40075. return {
  40076. cx: cx,
  40077. cy: cy,
  40078. r0: r0,
  40079. r: r
  40080. };
  40081. }
  40082. function pieLayout(seriesType, ecModel, api) {
  40083. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  40084. var data = seriesModel.getData();
  40085. var valueDim = data.mapDimension('value');
  40086. var viewRect = getViewRect(seriesModel, api);
  40087. var _a = getBasicPieLayout(seriesModel, api),
  40088. cx = _a.cx,
  40089. cy = _a.cy,
  40090. r = _a.r,
  40091. r0 = _a.r0;
  40092. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  40093. var endAngle = seriesModel.get('endAngle');
  40094. var padAngle = seriesModel.get('padAngle') * RADIAN;
  40095. endAngle = endAngle === 'auto' ? startAngle - PI2$7 : -endAngle * RADIAN;
  40096. var minAngle = seriesModel.get('minAngle') * RADIAN;
  40097. var minAndPadAngle = minAngle + padAngle;
  40098. var validDataCount = 0;
  40099. data.each(valueDim, function (value) {
  40100. !isNaN(value) && validDataCount++;
  40101. });
  40102. var sum = data.getSum(valueDim);
  40103. // Sum may be 0
  40104. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  40105. var clockwise = seriesModel.get('clockwise');
  40106. var roseType = seriesModel.get('roseType');
  40107. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  40108. // [0...max]
  40109. var extent = data.getDataExtent(valueDim);
  40110. extent[0] = 0;
  40111. var dir = clockwise ? 1 : -1;
  40112. var angles = [startAngle, endAngle];
  40113. var halfPadAngle = dir * padAngle / 2;
  40114. normalizeArcAngles(angles, !clockwise);
  40115. startAngle = angles[0], endAngle = angles[1];
  40116. var layoutData = getSeriesLayoutData(seriesModel);
  40117. layoutData.startAngle = startAngle;
  40118. layoutData.endAngle = endAngle;
  40119. layoutData.clockwise = clockwise;
  40120. var angleRange = Math.abs(endAngle - startAngle);
  40121. // In the case some sector angle is smaller than minAngle
  40122. var restAngle = angleRange;
  40123. var valueSumLargerThanMinAngle = 0;
  40124. var currentAngle = startAngle;
  40125. data.setLayout({
  40126. viewRect: viewRect,
  40127. r: r
  40128. });
  40129. data.each(valueDim, function (value, idx) {
  40130. var angle;
  40131. if (isNaN(value)) {
  40132. data.setItemLayout(idx, {
  40133. angle: NaN,
  40134. startAngle: NaN,
  40135. endAngle: NaN,
  40136. clockwise: clockwise,
  40137. cx: cx,
  40138. cy: cy,
  40139. r0: r0,
  40140. r: roseType ? NaN : r
  40141. });
  40142. return;
  40143. }
  40144. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  40145. if (roseType !== 'area') {
  40146. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  40147. } else {
  40148. angle = angleRange / validDataCount;
  40149. }
  40150. if (angle < minAndPadAngle) {
  40151. angle = minAndPadAngle;
  40152. restAngle -= minAndPadAngle;
  40153. } else {
  40154. valueSumLargerThanMinAngle += value;
  40155. }
  40156. var endAngle = currentAngle + dir * angle;
  40157. // calculate display angle
  40158. var actualStartAngle = 0;
  40159. var actualEndAngle = 0;
  40160. if (padAngle > angle) {
  40161. actualStartAngle = currentAngle + dir * angle / 2;
  40162. actualEndAngle = actualStartAngle;
  40163. } else {
  40164. actualStartAngle = currentAngle + halfPadAngle;
  40165. actualEndAngle = endAngle - halfPadAngle;
  40166. }
  40167. data.setItemLayout(idx, {
  40168. angle: angle,
  40169. startAngle: actualStartAngle,
  40170. endAngle: actualEndAngle,
  40171. clockwise: clockwise,
  40172. cx: cx,
  40173. cy: cy,
  40174. r0: r0,
  40175. r: roseType ? linearMap(value, extent, [r0, r]) : r
  40176. });
  40177. currentAngle = endAngle;
  40178. });
  40179. // Some sector is constrained by minAngle and padAngle
  40180. // Rest sectors needs recalculate angle
  40181. if (restAngle < PI2$7 && validDataCount) {
  40182. // Average the angle if rest angle is not enough after all angles is
  40183. // Constrained by minAngle and padAngle
  40184. if (restAngle <= 1e-3) {
  40185. var angle_1 = angleRange / validDataCount;
  40186. data.each(valueDim, function (value, idx) {
  40187. if (!isNaN(value)) {
  40188. var layout_1 = data.getItemLayout(idx);
  40189. layout_1.angle = angle_1;
  40190. var actualStartAngle = 0;
  40191. var actualEndAngle = 0;
  40192. if (angle_1 < padAngle) {
  40193. actualStartAngle = startAngle + dir * (idx + 1 / 2) * angle_1;
  40194. actualEndAngle = actualStartAngle;
  40195. } else {
  40196. actualStartAngle = startAngle + dir * idx * angle_1 + halfPadAngle;
  40197. actualEndAngle = startAngle + dir * (idx + 1) * angle_1 - halfPadAngle;
  40198. }
  40199. layout_1.startAngle = actualStartAngle;
  40200. layout_1.endAngle = actualEndAngle;
  40201. }
  40202. });
  40203. } else {
  40204. unitRadian = restAngle / valueSumLargerThanMinAngle;
  40205. currentAngle = startAngle;
  40206. data.each(valueDim, function (value, idx) {
  40207. if (!isNaN(value)) {
  40208. var layout_2 = data.getItemLayout(idx);
  40209. var angle = layout_2.angle === minAndPadAngle ? minAndPadAngle : value * unitRadian;
  40210. var actualStartAngle = 0;
  40211. var actualEndAngle = 0;
  40212. if (angle < padAngle) {
  40213. actualStartAngle = currentAngle + dir * angle / 2;
  40214. actualEndAngle = actualStartAngle;
  40215. } else {
  40216. actualStartAngle = currentAngle + halfPadAngle;
  40217. actualEndAngle = currentAngle + dir * angle - halfPadAngle;
  40218. }
  40219. layout_2.startAngle = actualStartAngle;
  40220. layout_2.endAngle = actualEndAngle;
  40221. currentAngle += dir * angle;
  40222. }
  40223. });
  40224. }
  40225. }
  40226. });
  40227. }
  40228. var getSeriesLayoutData = makeInner();
  40229. /*
  40230. * Licensed to the Apache Software Foundation (ASF) under one
  40231. * or more contributor license agreements. See the NOTICE file
  40232. * distributed with this work for additional information
  40233. * regarding copyright ownership. The ASF licenses this file
  40234. * to you under the Apache License, Version 2.0 (the
  40235. * "License"); you may not use this file except in compliance
  40236. * with the License. You may obtain a copy of the License at
  40237. *
  40238. * http://www.apache.org/licenses/LICENSE-2.0
  40239. *
  40240. * Unless required by applicable law or agreed to in writing,
  40241. * software distributed under the License is distributed on an
  40242. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40243. * KIND, either express or implied. See the License for the
  40244. * specific language governing permissions and limitations
  40245. * under the License.
  40246. */
  40247. /**
  40248. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40249. */
  40250. /*
  40251. * Licensed to the Apache Software Foundation (ASF) under one
  40252. * or more contributor license agreements. See the NOTICE file
  40253. * distributed with this work for additional information
  40254. * regarding copyright ownership. The ASF licenses this file
  40255. * to you under the Apache License, Version 2.0 (the
  40256. * "License"); you may not use this file except in compliance
  40257. * with the License. You may obtain a copy of the License at
  40258. *
  40259. * http://www.apache.org/licenses/LICENSE-2.0
  40260. *
  40261. * Unless required by applicable law or agreed to in writing,
  40262. * software distributed under the License is distributed on an
  40263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40264. * KIND, either express or implied. See the License for the
  40265. * specific language governing permissions and limitations
  40266. * under the License.
  40267. */
  40268. function dataFilter(seriesType) {
  40269. return {
  40270. seriesType: seriesType,
  40271. reset: function (seriesModel, ecModel) {
  40272. var legendModels = ecModel.findComponents({
  40273. mainType: 'legend'
  40274. });
  40275. if (!legendModels || !legendModels.length) {
  40276. return;
  40277. }
  40278. var data = seriesModel.getData();
  40279. data.filterSelf(function (idx) {
  40280. var name = data.getName(idx);
  40281. // If in any legend component the status is not selected.
  40282. for (var i = 0; i < legendModels.length; i++) {
  40283. // @ts-ignore FIXME: LegendModel
  40284. if (!legendModels[i].isSelected(name)) {
  40285. return false;
  40286. }
  40287. }
  40288. return true;
  40289. });
  40290. }
  40291. };
  40292. }
  40293. var RADIAN$1 = Math.PI / 180;
  40294. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  40295. if (list.length < 2) {
  40296. return;
  40297. }
  40298. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  40299. var rB = semi.rB;
  40300. var rB2 = rB * rB;
  40301. for (var i = 0; i < semi.list.length; i++) {
  40302. var item = semi.list[i];
  40303. var dy = Math.abs(item.label.y - cy);
  40304. // horizontal r is always same with original r because x is not changed.
  40305. var rA = r + item.len;
  40306. var rA2 = rA * rA;
  40307. // Use ellipse implicit function to calculate x
  40308. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  40309. var newX = cx + (dx + item.len2) * dir;
  40310. var deltaX = newX - item.label.x;
  40311. var newTargetWidth = item.targetTextWidth - deltaX * dir;
  40312. // text x is changed, so need to recalculate width.
  40313. constrainTextWidth(item, newTargetWidth, true);
  40314. item.label.x = newX;
  40315. }
  40316. }
  40317. // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  40318. function recalculateX(items) {
  40319. // Extremes of
  40320. var topSemi = {
  40321. list: [],
  40322. maxY: 0
  40323. };
  40324. var bottomSemi = {
  40325. list: [],
  40326. maxY: 0
  40327. };
  40328. for (var i = 0; i < items.length; i++) {
  40329. if (items[i].labelAlignTo !== 'none') {
  40330. continue;
  40331. }
  40332. var item = items[i];
  40333. var semi = item.label.y > cy ? bottomSemi : topSemi;
  40334. var dy = Math.abs(item.label.y - cy);
  40335. if (dy >= semi.maxY) {
  40336. var dx = item.label.x - cx - item.len2 * dir;
  40337. // horizontal r is always same with original r because x is not changed.
  40338. var rA = r + item.len;
  40339. // Canculate rB based on the topest / bottemest label.
  40340. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  40341. semi.rB = rB;
  40342. semi.maxY = dy;
  40343. }
  40344. semi.list.push(item);
  40345. }
  40346. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  40347. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  40348. }
  40349. var len = list.length;
  40350. for (var i = 0; i < len; i++) {
  40351. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  40352. var dx = list[i].label.x - farthestX;
  40353. list[i].linePoints[1][0] += dx;
  40354. list[i].label.x = farthestX;
  40355. }
  40356. }
  40357. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  40358. recalculateX(list);
  40359. }
  40360. }
  40361. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  40362. var leftList = [];
  40363. var rightList = [];
  40364. var leftmostX = Number.MAX_VALUE;
  40365. var rightmostX = -Number.MAX_VALUE;
  40366. for (var i = 0; i < labelLayoutList.length; i++) {
  40367. var label = labelLayoutList[i].label;
  40368. if (isPositionCenter(labelLayoutList[i])) {
  40369. continue;
  40370. }
  40371. if (label.x < cx) {
  40372. leftmostX = Math.min(leftmostX, label.x);
  40373. leftList.push(labelLayoutList[i]);
  40374. } else {
  40375. rightmostX = Math.max(rightmostX, label.x);
  40376. rightList.push(labelLayoutList[i]);
  40377. }
  40378. }
  40379. for (var i = 0; i < labelLayoutList.length; i++) {
  40380. var layout = labelLayoutList[i];
  40381. if (!isPositionCenter(layout) && layout.linePoints) {
  40382. if (layout.labelStyleWidth != null) {
  40383. continue;
  40384. }
  40385. var label = layout.label;
  40386. var linePoints = layout.linePoints;
  40387. var targetTextWidth = void 0;
  40388. if (layout.labelAlignTo === 'edge') {
  40389. if (label.x < cx) {
  40390. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  40391. } else {
  40392. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  40393. }
  40394. } else if (layout.labelAlignTo === 'labelLine') {
  40395. if (label.x < cx) {
  40396. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  40397. } else {
  40398. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  40399. }
  40400. } else {
  40401. if (label.x < cx) {
  40402. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  40403. } else {
  40404. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  40405. }
  40406. }
  40407. layout.targetTextWidth = targetTextWidth;
  40408. constrainTextWidth(layout, targetTextWidth);
  40409. }
  40410. }
  40411. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  40412. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  40413. for (var i = 0; i < labelLayoutList.length; i++) {
  40414. var layout = labelLayoutList[i];
  40415. if (!isPositionCenter(layout) && layout.linePoints) {
  40416. var label = layout.label;
  40417. var linePoints = layout.linePoints;
  40418. var isAlignToEdge = layout.labelAlignTo === 'edge';
  40419. var padding = label.style.padding;
  40420. var paddingH = padding ? padding[1] + padding[3] : 0;
  40421. // textRect.width already contains paddingH if bgColor is set
  40422. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  40423. var realTextWidth = layout.rect.width + extraPaddingH;
  40424. var dist = linePoints[1][0] - linePoints[2][0];
  40425. if (isAlignToEdge) {
  40426. if (label.x < cx) {
  40427. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  40428. } else {
  40429. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  40430. }
  40431. } else {
  40432. if (label.x < cx) {
  40433. linePoints[2][0] = label.x + layout.labelDistance;
  40434. } else {
  40435. linePoints[2][0] = label.x - layout.labelDistance;
  40436. }
  40437. linePoints[1][0] = linePoints[2][0] + dist;
  40438. }
  40439. linePoints[1][1] = linePoints[2][1] = label.y;
  40440. }
  40441. }
  40442. }
  40443. /**
  40444. * Set max width of each label, and then wrap each label to the max width.
  40445. *
  40446. * @param layout label layout
  40447. * @param availableWidth max width for the label to display
  40448. * @param forceRecalculate recaculate the text layout even if the current width
  40449. * is smaller than `availableWidth`. This is useful when the text was previously
  40450. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  40451. * which case, previous wrapping should be redo.
  40452. */
  40453. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  40454. if (forceRecalculate === void 0) {
  40455. forceRecalculate = false;
  40456. }
  40457. if (layout.labelStyleWidth != null) {
  40458. // User-defined style.width has the highest priority.
  40459. return;
  40460. }
  40461. var label = layout.label;
  40462. var style = label.style;
  40463. var textRect = layout.rect;
  40464. var bgColor = style.backgroundColor;
  40465. var padding = style.padding;
  40466. var paddingH = padding ? padding[1] + padding[3] : 0;
  40467. var overflow = style.overflow;
  40468. // textRect.width already contains paddingH if bgColor is set
  40469. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  40470. if (availableWidth < oldOuterWidth || forceRecalculate) {
  40471. var oldHeight = textRect.height;
  40472. if (overflow && overflow.match('break')) {
  40473. // Temporarily set background to be null to calculate
  40474. // the bounding box without background.
  40475. label.setStyle('backgroundColor', null);
  40476. // Set constraining width
  40477. label.setStyle('width', availableWidth - paddingH);
  40478. // This is the real bounding box of the text without padding.
  40479. var innerRect = label.getBoundingRect();
  40480. label.setStyle('width', Math.ceil(innerRect.width));
  40481. label.setStyle('backgroundColor', bgColor);
  40482. } else {
  40483. var availableInnerWidth = availableWidth - paddingH;
  40484. var newWidth = availableWidth < oldOuterWidth
  40485. // Current text is too wide, use `availableWidth` as max width.
  40486. ? availableInnerWidth :
  40487. // Current available width is enough, but the text may have
  40488. // already been wrapped with a smaller available width.
  40489. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth
  40490. // Current available is larger than text width,
  40491. // so don't constrain width (otherwise it may have
  40492. // empty space in the background).
  40493. ? null
  40494. // Current available is smaller than text width, so
  40495. // use the current available width as constraining
  40496. // width.
  40497. : availableInnerWidth
  40498. // Current available width is enough, so no need to
  40499. // constrain.
  40500. : null;
  40501. label.setStyle('width', newWidth);
  40502. }
  40503. var newRect = label.getBoundingRect();
  40504. textRect.width = newRect.width;
  40505. var margin = (label.style.margin || 0) + 2.1;
  40506. textRect.height = newRect.height + margin;
  40507. textRect.y -= (textRect.height - oldHeight) / 2;
  40508. }
  40509. }
  40510. function isPositionCenter(sectorShape) {
  40511. // Not change x for center label
  40512. return sectorShape.position === 'center';
  40513. }
  40514. function pieLabelLayout(seriesModel) {
  40515. var data = seriesModel.getData();
  40516. var labelLayoutList = [];
  40517. var cx;
  40518. var cy;
  40519. var hasLabelRotate = false;
  40520. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  40521. var viewRect = data.getLayout('viewRect');
  40522. var r = data.getLayout('r');
  40523. var viewWidth = viewRect.width;
  40524. var viewLeft = viewRect.x;
  40525. var viewTop = viewRect.y;
  40526. var viewHeight = viewRect.height;
  40527. function setNotShow(el) {
  40528. el.ignore = true;
  40529. }
  40530. function isLabelShown(label) {
  40531. if (!label.ignore) {
  40532. return true;
  40533. }
  40534. for (var key in label.states) {
  40535. if (label.states[key].ignore === false) {
  40536. return true;
  40537. }
  40538. }
  40539. return false;
  40540. }
  40541. data.each(function (idx) {
  40542. var sector = data.getItemGraphicEl(idx);
  40543. var sectorShape = sector.shape;
  40544. var label = sector.getTextContent();
  40545. var labelLine = sector.getTextGuideLine();
  40546. var itemModel = data.getItemModel(idx);
  40547. var labelModel = itemModel.getModel('label');
  40548. // Use position in normal or emphasis
  40549. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  40550. var labelDistance = labelModel.get('distanceToLabelLine');
  40551. var labelAlignTo = labelModel.get('alignTo');
  40552. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  40553. var bleedMargin = labelModel.get('bleedMargin');
  40554. var labelLineModel = itemModel.getModel('labelLine');
  40555. var labelLineLen = labelLineModel.get('length');
  40556. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  40557. var labelLineLen2 = labelLineModel.get('length2');
  40558. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  40559. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  40560. each(label.states, setNotShow);
  40561. label.ignore = true;
  40562. if (labelLine) {
  40563. each(labelLine.states, setNotShow);
  40564. labelLine.ignore = true;
  40565. }
  40566. return;
  40567. }
  40568. if (!isLabelShown(label)) {
  40569. return;
  40570. }
  40571. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  40572. var nx = Math.cos(midAngle);
  40573. var ny = Math.sin(midAngle);
  40574. var textX;
  40575. var textY;
  40576. var linePoints;
  40577. var textAlign;
  40578. cx = sectorShape.cx;
  40579. cy = sectorShape.cy;
  40580. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  40581. if (labelPosition === 'center') {
  40582. textX = sectorShape.cx;
  40583. textY = sectorShape.cy;
  40584. textAlign = 'center';
  40585. } else {
  40586. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  40587. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  40588. textX = x1 + nx * 3;
  40589. textY = y1 + ny * 3;
  40590. if (!isLabelInside) {
  40591. // For roseType
  40592. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  40593. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  40594. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  40595. var y3 = y2;
  40596. if (labelAlignTo === 'edge') {
  40597. // Adjust textX because text align of edge is opposite
  40598. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  40599. } else {
  40600. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  40601. }
  40602. textY = y3;
  40603. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  40604. }
  40605. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  40606. }
  40607. var PI = Math.PI;
  40608. var labelRotate = 0;
  40609. var rotate = labelModel.get('rotate');
  40610. if (isNumber(rotate)) {
  40611. labelRotate = rotate * (PI / 180);
  40612. } else if (labelPosition === 'center') {
  40613. labelRotate = 0;
  40614. } else if (rotate === 'radial' || rotate === true) {
  40615. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  40616. labelRotate = radialAngle;
  40617. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  40618. var rad = Math.atan2(nx, ny);
  40619. if (rad < 0) {
  40620. rad = PI * 2 + rad;
  40621. }
  40622. var isDown = ny > 0;
  40623. if (isDown) {
  40624. rad = PI + rad;
  40625. }
  40626. labelRotate = rad - PI;
  40627. }
  40628. hasLabelRotate = !!labelRotate;
  40629. label.x = textX;
  40630. label.y = textY;
  40631. label.rotation = labelRotate;
  40632. label.setStyle({
  40633. verticalAlign: 'middle'
  40634. });
  40635. // Not sectorShape the inside label
  40636. if (!isLabelInside) {
  40637. var textRect = label.getBoundingRect().clone();
  40638. textRect.applyTransform(label.getComputedTransform());
  40639. // Text has a default 1px stroke. Exclude this.
  40640. var margin = (label.style.margin || 0) + 2.1;
  40641. textRect.y -= margin / 2;
  40642. textRect.height += margin;
  40643. labelLayoutList.push({
  40644. label: label,
  40645. labelLine: labelLine,
  40646. position: labelPosition,
  40647. len: labelLineLen,
  40648. len2: labelLineLen2,
  40649. minTurnAngle: labelLineModel.get('minTurnAngle'),
  40650. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  40651. surfaceNormal: new Point(nx, ny),
  40652. linePoints: linePoints,
  40653. textAlign: textAlign,
  40654. labelDistance: labelDistance,
  40655. labelAlignTo: labelAlignTo,
  40656. edgeDistance: edgeDistance,
  40657. bleedMargin: bleedMargin,
  40658. rect: textRect,
  40659. unconstrainedWidth: textRect.width,
  40660. labelStyleWidth: label.style.width
  40661. });
  40662. } else {
  40663. label.setStyle({
  40664. align: textAlign
  40665. });
  40666. var selectState = label.states.select;
  40667. if (selectState) {
  40668. selectState.x += label.x;
  40669. selectState.y += label.y;
  40670. }
  40671. }
  40672. sector.setTextConfig({
  40673. inside: isLabelInside
  40674. });
  40675. });
  40676. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  40677. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  40678. }
  40679. for (var i = 0; i < labelLayoutList.length; i++) {
  40680. var layout = labelLayoutList[i];
  40681. var label = layout.label;
  40682. var labelLine = layout.labelLine;
  40683. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  40684. if (label) {
  40685. label.setStyle({
  40686. align: layout.textAlign
  40687. });
  40688. if (notShowLabel) {
  40689. each(label.states, setNotShow);
  40690. label.ignore = true;
  40691. }
  40692. var selectState = label.states.select;
  40693. if (selectState) {
  40694. selectState.x += label.x;
  40695. selectState.y += label.y;
  40696. }
  40697. }
  40698. if (labelLine) {
  40699. var linePoints = layout.linePoints;
  40700. if (notShowLabel || !linePoints) {
  40701. each(labelLine.states, setNotShow);
  40702. labelLine.ignore = true;
  40703. } else {
  40704. limitTurnAngle(linePoints, layout.minTurnAngle);
  40705. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  40706. labelLine.setShape({
  40707. points: linePoints
  40708. });
  40709. // Set the anchor to the midpoint of sector
  40710. label.__hostTarget.textGuideLineConfig = {
  40711. anchor: new Point(linePoints[0][0], linePoints[0][1])
  40712. };
  40713. }
  40714. }
  40715. }
  40716. }
  40717. /**
  40718. * Piece of pie including Sector, Label, LabelLine
  40719. */
  40720. var PiePiece = /** @class */function (_super) {
  40721. __extends(PiePiece, _super);
  40722. function PiePiece(data, idx, startAngle) {
  40723. var _this = _super.call(this) || this;
  40724. _this.z2 = 2;
  40725. var text = new ZRText();
  40726. _this.setTextContent(text);
  40727. _this.updateData(data, idx, startAngle, true);
  40728. return _this;
  40729. }
  40730. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  40731. var sector = this;
  40732. var seriesModel = data.hostModel;
  40733. var itemModel = data.getItemModel(idx);
  40734. var emphasisModel = itemModel.getModel('emphasis');
  40735. var layout = data.getItemLayout(idx);
  40736. // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  40737. // see `setItemLayout` in `pieLayout.ts`.
  40738. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout);
  40739. // Ignore NaN data.
  40740. if (isNaN(sectorShape.startAngle)) {
  40741. // Use NaN shape to avoid drawing shape.
  40742. sector.setShape(sectorShape);
  40743. return;
  40744. }
  40745. if (firstCreate) {
  40746. sector.setShape(sectorShape);
  40747. var animationType = seriesModel.getShallow('animationType');
  40748. if (seriesModel.ecModel.ssr) {
  40749. // Use scale animation in SSR mode(opacity?)
  40750. // Because CSS SVG animation doesn't support very customized shape animation.
  40751. initProps(sector, {
  40752. scaleX: 0,
  40753. scaleY: 0
  40754. }, seriesModel, {
  40755. dataIndex: idx,
  40756. isFrom: true
  40757. });
  40758. sector.originX = sectorShape.cx;
  40759. sector.originY = sectorShape.cy;
  40760. } else if (animationType === 'scale') {
  40761. sector.shape.r = layout.r0;
  40762. initProps(sector, {
  40763. shape: {
  40764. r: layout.r
  40765. }
  40766. }, seriesModel, idx);
  40767. }
  40768. // Expansion
  40769. else {
  40770. if (startAngle != null) {
  40771. sector.setShape({
  40772. startAngle: startAngle,
  40773. endAngle: startAngle
  40774. });
  40775. initProps(sector, {
  40776. shape: {
  40777. startAngle: layout.startAngle,
  40778. endAngle: layout.endAngle
  40779. }
  40780. }, seriesModel, idx);
  40781. } else {
  40782. sector.shape.endAngle = layout.startAngle;
  40783. updateProps(sector, {
  40784. shape: {
  40785. endAngle: layout.endAngle
  40786. }
  40787. }, seriesModel, idx);
  40788. }
  40789. }
  40790. } else {
  40791. saveOldStyle(sector);
  40792. // Transition animation from the old shape
  40793. updateProps(sector, {
  40794. shape: sectorShape
  40795. }, seriesModel, idx);
  40796. }
  40797. sector.useStyle(data.getItemVisual(idx, 'style'));
  40798. setStatesStylesFromModel(sector, itemModel);
  40799. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  40800. var offset = seriesModel.get('selectedOffset');
  40801. var dx = Math.cos(midAngle) * offset;
  40802. var dy = Math.sin(midAngle) * offset;
  40803. var cursorStyle = itemModel.getShallow('cursor');
  40804. cursorStyle && sector.attr('cursor', cursorStyle);
  40805. this._updateLabel(seriesModel, data, idx);
  40806. sector.ensureState('emphasis').shape = extend({
  40807. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  40808. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  40809. extend(sector.ensureState('select'), {
  40810. x: dx,
  40811. y: dy,
  40812. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  40813. });
  40814. extend(sector.ensureState('blur'), {
  40815. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  40816. });
  40817. var labelLine = sector.getTextGuideLine();
  40818. var labelText = sector.getTextContent();
  40819. labelLine && extend(labelLine.ensureState('select'), {
  40820. x: dx,
  40821. y: dy
  40822. });
  40823. // TODO: needs dx, dy in zrender?
  40824. extend(labelText.ensureState('select'), {
  40825. x: dx,
  40826. y: dy
  40827. });
  40828. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  40829. };
  40830. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  40831. var sector = this;
  40832. var itemModel = data.getItemModel(idx);
  40833. var labelLineModel = itemModel.getModel('labelLine');
  40834. var style = data.getItemVisual(idx, 'style');
  40835. var visualColor = style && style.fill;
  40836. var visualOpacity = style && style.opacity;
  40837. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  40838. labelFetcher: data.hostModel,
  40839. labelDataIndex: idx,
  40840. inheritColor: visualColor,
  40841. defaultOpacity: visualOpacity,
  40842. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  40843. });
  40844. var labelText = sector.getTextContent();
  40845. // Set textConfig on sector.
  40846. sector.setTextConfig({
  40847. // reset position, rotation
  40848. position: null,
  40849. rotation: null
  40850. });
  40851. // Make sure update style on labelText after setLabelStyle.
  40852. // Because setLabelStyle will replace a new style on it.
  40853. labelText.attr({
  40854. z2: 10
  40855. });
  40856. var labelPosition = seriesModel.get(['label', 'position']);
  40857. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  40858. sector.removeTextGuideLine();
  40859. } else {
  40860. var polyline = this.getTextGuideLine();
  40861. if (!polyline) {
  40862. polyline = new Polyline();
  40863. this.setTextGuideLine(polyline);
  40864. }
  40865. // Default use item visual color
  40866. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  40867. stroke: visualColor,
  40868. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  40869. });
  40870. }
  40871. };
  40872. return PiePiece;
  40873. }(Sector);
  40874. // Pie view
  40875. var PieView = /** @class */function (_super) {
  40876. __extends(PieView, _super);
  40877. function PieView() {
  40878. var _this = _super !== null && _super.apply(this, arguments) || this;
  40879. _this.ignoreLabelLineUpdate = true;
  40880. return _this;
  40881. }
  40882. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  40883. var data = seriesModel.getData();
  40884. var oldData = this._data;
  40885. var group = this.group;
  40886. var startAngle;
  40887. // First render
  40888. if (!oldData && data.count() > 0) {
  40889. var shape = data.getItemLayout(0);
  40890. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  40891. shape = data.getItemLayout(s);
  40892. }
  40893. if (shape) {
  40894. startAngle = shape.startAngle;
  40895. }
  40896. }
  40897. // remove empty-circle if it exists
  40898. if (this._emptyCircleSector) {
  40899. group.remove(this._emptyCircleSector);
  40900. }
  40901. // when all data are filtered, show lightgray empty circle
  40902. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  40903. var layoutData = getSeriesLayoutData(seriesModel);
  40904. var sector = new Sector({
  40905. shape: extend(getBasicPieLayout(seriesModel, api), layoutData)
  40906. });
  40907. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  40908. this._emptyCircleSector = sector;
  40909. group.add(sector);
  40910. }
  40911. data.diff(oldData).add(function (idx) {
  40912. var piePiece = new PiePiece(data, idx, startAngle);
  40913. data.setItemGraphicEl(idx, piePiece);
  40914. group.add(piePiece);
  40915. }).update(function (newIdx, oldIdx) {
  40916. var piePiece = oldData.getItemGraphicEl(oldIdx);
  40917. piePiece.updateData(data, newIdx, startAngle);
  40918. piePiece.off('click');
  40919. group.add(piePiece);
  40920. data.setItemGraphicEl(newIdx, piePiece);
  40921. }).remove(function (idx) {
  40922. var piePiece = oldData.getItemGraphicEl(idx);
  40923. removeElementWithFadeOut(piePiece, seriesModel, idx);
  40924. }).execute();
  40925. pieLabelLayout(seriesModel);
  40926. // Always use initial animation.
  40927. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  40928. this._data = data;
  40929. }
  40930. };
  40931. PieView.prototype.dispose = function () {};
  40932. PieView.prototype.containPoint = function (point, seriesModel) {
  40933. var data = seriesModel.getData();
  40934. var itemLayout = data.getItemLayout(0);
  40935. if (itemLayout) {
  40936. var dx = point[0] - itemLayout.cx;
  40937. var dy = point[1] - itemLayout.cy;
  40938. var radius = Math.sqrt(dx * dx + dy * dy);
  40939. return radius <= itemLayout.r && radius >= itemLayout.r0;
  40940. }
  40941. };
  40942. PieView.type = 'pie';
  40943. return PieView;
  40944. }(ChartView);
  40945. /**
  40946. * [Usage]:
  40947. * (1)
  40948. * createListSimply(seriesModel, ['value']);
  40949. * (2)
  40950. * createListSimply(seriesModel, {
  40951. * coordDimensions: ['value'],
  40952. * dimensionsCount: 5
  40953. * });
  40954. */
  40955. function createSeriesDataSimply(seriesModel, opt, nameList) {
  40956. opt = isArray(opt) && {
  40957. coordDimensions: opt
  40958. } || extend({
  40959. encodeDefine: seriesModel.getEncode()
  40960. }, opt);
  40961. var source = seriesModel.getSource();
  40962. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  40963. var list = new SeriesData(dimensions, seriesModel);
  40964. list.initData(source, nameList);
  40965. return list;
  40966. }
  40967. /*
  40968. * Licensed to the Apache Software Foundation (ASF) under one
  40969. * or more contributor license agreements. See the NOTICE file
  40970. * distributed with this work for additional information
  40971. * regarding copyright ownership. The ASF licenses this file
  40972. * to you under the Apache License, Version 2.0 (the
  40973. * "License"); you may not use this file except in compliance
  40974. * with the License. You may obtain a copy of the License at
  40975. *
  40976. * http://www.apache.org/licenses/LICENSE-2.0
  40977. *
  40978. * Unless required by applicable law or agreed to in writing,
  40979. * software distributed under the License is distributed on an
  40980. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40981. * KIND, either express or implied. See the License for the
  40982. * specific language governing permissions and limitations
  40983. * under the License.
  40984. */
  40985. /**
  40986. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40987. */
  40988. /*
  40989. * Licensed to the Apache Software Foundation (ASF) under one
  40990. * or more contributor license agreements. See the NOTICE file
  40991. * distributed with this work for additional information
  40992. * regarding copyright ownership. The ASF licenses this file
  40993. * to you under the Apache License, Version 2.0 (the
  40994. * "License"); you may not use this file except in compliance
  40995. * with the License. You may obtain a copy of the License at
  40996. *
  40997. * http://www.apache.org/licenses/LICENSE-2.0
  40998. *
  40999. * Unless required by applicable law or agreed to in writing,
  41000. * software distributed under the License is distributed on an
  41001. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41002. * KIND, either express or implied. See the License for the
  41003. * specific language governing permissions and limitations
  41004. * under the License.
  41005. */
  41006. /**
  41007. * LegendVisualProvider is an bridge that pick encoded color from data and
  41008. * provide to the legend component.
  41009. */
  41010. var LegendVisualProvider = /** @class */function () {
  41011. function LegendVisualProvider(
  41012. // Function to get data after filtered. It stores all the encoding info
  41013. getDataWithEncodedVisual,
  41014. // Function to get raw data before filtered.
  41015. getRawData) {
  41016. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  41017. this._getRawData = getRawData;
  41018. }
  41019. LegendVisualProvider.prototype.getAllNames = function () {
  41020. var rawData = this._getRawData();
  41021. // We find the name from the raw data. In case it's filtered by the legend component.
  41022. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  41023. return rawData.mapArray(rawData.getName);
  41024. };
  41025. LegendVisualProvider.prototype.containName = function (name) {
  41026. var rawData = this._getRawData();
  41027. return rawData.indexOfName(name) >= 0;
  41028. };
  41029. LegendVisualProvider.prototype.indexOfName = function (name) {
  41030. // Only get data when necessary.
  41031. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  41032. // Invoking Series#getData immediately will throw an error.
  41033. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  41034. return dataWithEncodedVisual.indexOfName(name);
  41035. };
  41036. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  41037. // Get encoded visual properties from final filtered data.
  41038. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  41039. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  41040. };
  41041. return LegendVisualProvider;
  41042. }();
  41043. var innerData = makeInner();
  41044. var PieSeriesModel = /** @class */function (_super) {
  41045. __extends(PieSeriesModel, _super);
  41046. function PieSeriesModel() {
  41047. return _super !== null && _super.apply(this, arguments) || this;
  41048. }
  41049. /**
  41050. * @overwrite
  41051. */
  41052. PieSeriesModel.prototype.init = function (option) {
  41053. _super.prototype.init.apply(this, arguments);
  41054. // Enable legend selection for each data item
  41055. // Use a function instead of direct access because data reference may changed
  41056. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  41057. this._defaultLabelLine(option);
  41058. };
  41059. /**
  41060. * @overwrite
  41061. */
  41062. PieSeriesModel.prototype.mergeOption = function () {
  41063. _super.prototype.mergeOption.apply(this, arguments);
  41064. };
  41065. /**
  41066. * @overwrite
  41067. */
  41068. PieSeriesModel.prototype.getInitialData = function () {
  41069. return createSeriesDataSimply(this, {
  41070. coordDimensions: ['value'],
  41071. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  41072. });
  41073. };
  41074. /**
  41075. * @overwrite
  41076. */
  41077. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  41078. var data = this.getData();
  41079. // update seats when data is changed
  41080. var dataInner = innerData(data);
  41081. var seats = dataInner.seats;
  41082. if (!seats) {
  41083. var valueList_1 = [];
  41084. data.each(data.mapDimension('value'), function (value) {
  41085. valueList_1.push(value);
  41086. });
  41087. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  41088. }
  41089. var params = _super.prototype.getDataParams.call(this, dataIndex);
  41090. // seats may be empty when sum is 0
  41091. params.percent = seats[dataIndex] || 0;
  41092. params.$vars.push('percent');
  41093. return params;
  41094. };
  41095. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  41096. // Extend labelLine emphasis
  41097. defaultEmphasis(option, 'labelLine', ['show']);
  41098. var labelLineNormalOpt = option.labelLine;
  41099. var labelLineEmphasisOpt = option.emphasis.labelLine;
  41100. // Not show label line if `label.normal.show = false`
  41101. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  41102. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  41103. };
  41104. PieSeriesModel.type = 'series.pie';
  41105. PieSeriesModel.defaultOption = {
  41106. // zlevel: 0,
  41107. z: 2,
  41108. legendHoverLink: true,
  41109. colorBy: 'data',
  41110. // 默认全局居中
  41111. center: ['50%', '50%'],
  41112. radius: [0, '75%'],
  41113. // 默认顺时针
  41114. clockwise: true,
  41115. startAngle: 90,
  41116. endAngle: 'auto',
  41117. padAngle: 0,
  41118. // 最小角度改为0
  41119. minAngle: 0,
  41120. // If the angle of a sector less than `minShowLabelAngle`,
  41121. // the label will not be displayed.
  41122. minShowLabelAngle: 0,
  41123. // 选中时扇区偏移量
  41124. selectedOffset: 10,
  41125. // 选择模式,默认关闭,可选single,multiple
  41126. // selectedMode: false,
  41127. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  41128. // roseType: null,
  41129. percentPrecision: 2,
  41130. // If still show when all data zero.
  41131. stillShowZeroSum: true,
  41132. // cursor: null,
  41133. left: 0,
  41134. top: 0,
  41135. right: 0,
  41136. bottom: 0,
  41137. width: null,
  41138. height: null,
  41139. label: {
  41140. // color: 'inherit',
  41141. // If rotate around circle
  41142. rotate: 0,
  41143. show: true,
  41144. overflow: 'truncate',
  41145. // 'outer', 'inside', 'center'
  41146. position: 'outer',
  41147. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  41148. alignTo: 'none',
  41149. // Closest distance between label and chart edge.
  41150. // Works only position is 'outer' and alignTo is 'edge'.
  41151. edgeDistance: '25%',
  41152. // Works only position is 'outer' and alignTo is not 'edge'.
  41153. bleedMargin: 10,
  41154. // Distance between text and label line.
  41155. distanceToLabelLine: 5
  41156. // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  41157. // 默认使用全局文本样式,详见 textStyle
  41158. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  41159. },
  41160. // Enabled when label.normal.position is 'outer'
  41161. labelLine: {
  41162. show: true,
  41163. // 引导线两段中的第一段长度
  41164. length: 15,
  41165. // 引导线两段中的第二段长度
  41166. length2: 15,
  41167. smooth: false,
  41168. minTurnAngle: 90,
  41169. maxSurfaceAngle: 90,
  41170. lineStyle: {
  41171. // color: 各异,
  41172. width: 1,
  41173. type: 'solid'
  41174. }
  41175. },
  41176. itemStyle: {
  41177. borderWidth: 1,
  41178. borderJoin: 'round'
  41179. },
  41180. showEmptyCircle: true,
  41181. emptyCircleStyle: {
  41182. color: 'lightgray',
  41183. opacity: 1
  41184. },
  41185. labelLayout: {
  41186. // Hide the overlapped label.
  41187. hideOverlap: true
  41188. },
  41189. emphasis: {
  41190. scale: true,
  41191. scaleSize: 5
  41192. },
  41193. // If use strategy to avoid label overlapping
  41194. avoidLabelOverlap: true,
  41195. // Animation type. Valid values: expansion, scale
  41196. animationType: 'expansion',
  41197. animationDuration: 1000,
  41198. // Animation type when update. Valid values: transition, expansion
  41199. animationTypeUpdate: 'transition',
  41200. animationEasingUpdate: 'cubicInOut',
  41201. animationDurationUpdate: 500,
  41202. animationEasing: 'cubicInOut'
  41203. };
  41204. return PieSeriesModel;
  41205. }(SeriesModel);
  41206. function negativeDataFilter(seriesType) {
  41207. return {
  41208. seriesType: seriesType,
  41209. reset: function (seriesModel, ecModel) {
  41210. var data = seriesModel.getData();
  41211. data.filterSelf(function (idx) {
  41212. // handle negative value condition
  41213. var valueDim = data.mapDimension('value');
  41214. var curValue = data.get(valueDim, idx);
  41215. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  41216. return false;
  41217. }
  41218. return true;
  41219. });
  41220. }
  41221. };
  41222. }
  41223. function install$4(registers) {
  41224. registers.registerChartView(PieView);
  41225. registers.registerSeriesModel(PieSeriesModel);
  41226. createLegacyDataSelectAction('pie', registers.registerAction);
  41227. registers.registerLayout(curry(pieLayout, 'pie'));
  41228. registers.registerProcessor(dataFilter('pie'));
  41229. registers.registerProcessor(negativeDataFilter('pie'));
  41230. }
  41231. var ScatterSeriesModel = /** @class */function (_super) {
  41232. __extends(ScatterSeriesModel, _super);
  41233. function ScatterSeriesModel() {
  41234. var _this = _super !== null && _super.apply(this, arguments) || this;
  41235. _this.type = ScatterSeriesModel.type;
  41236. _this.hasSymbolVisual = true;
  41237. return _this;
  41238. }
  41239. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41240. return createSeriesData(null, this, {
  41241. useEncodeDefaulter: true
  41242. });
  41243. };
  41244. ScatterSeriesModel.prototype.getProgressive = function () {
  41245. var progressive = this.option.progressive;
  41246. if (progressive == null) {
  41247. // PENDING
  41248. return this.option.large ? 5e3 : this.get('progressive');
  41249. }
  41250. return progressive;
  41251. };
  41252. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  41253. var progressiveThreshold = this.option.progressiveThreshold;
  41254. if (progressiveThreshold == null) {
  41255. // PENDING
  41256. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  41257. }
  41258. return progressiveThreshold;
  41259. };
  41260. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  41261. return selectors.point(data.getItemLayout(dataIndex));
  41262. };
  41263. ScatterSeriesModel.prototype.getZLevelKey = function () {
  41264. // Each progressive series has individual key.
  41265. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  41266. };
  41267. ScatterSeriesModel.type = 'series.scatter';
  41268. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  41269. ScatterSeriesModel.defaultOption = {
  41270. coordinateSystem: 'cartesian2d',
  41271. // zlevel: 0,
  41272. z: 2,
  41273. legendHoverLink: true,
  41274. symbolSize: 10,
  41275. // symbolRotate: null, // 图形旋转控制
  41276. large: false,
  41277. // Available when large is true
  41278. largeThreshold: 2000,
  41279. // cursor: null,
  41280. itemStyle: {
  41281. opacity: 0.8
  41282. // color: 各异
  41283. },
  41284. emphasis: {
  41285. scale: true
  41286. },
  41287. // If clip the overflow graphics
  41288. // Works on cartesian / polar series
  41289. clip: true,
  41290. select: {
  41291. itemStyle: {
  41292. borderColor: '#212121'
  41293. }
  41294. },
  41295. universalTransition: {
  41296. divideShape: 'clone'
  41297. }
  41298. // progressive: null
  41299. };
  41300. return ScatterSeriesModel;
  41301. }(SeriesModel);
  41302. var BOOST_SIZE_THRESHOLD = 4;
  41303. var LargeSymbolPathShape = /** @class */function () {
  41304. function LargeSymbolPathShape() {}
  41305. return LargeSymbolPathShape;
  41306. }();
  41307. var LargeSymbolPath = /** @class */function (_super) {
  41308. __extends(LargeSymbolPath, _super);
  41309. function LargeSymbolPath(opts) {
  41310. var _this = _super.call(this, opts) || this;
  41311. _this._off = 0;
  41312. _this.hoverDataIdx = -1;
  41313. return _this;
  41314. }
  41315. LargeSymbolPath.prototype.getDefaultShape = function () {
  41316. return new LargeSymbolPathShape();
  41317. };
  41318. LargeSymbolPath.prototype.reset = function () {
  41319. this.notClear = false;
  41320. this._off = 0;
  41321. };
  41322. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  41323. var points = shape.points;
  41324. var size = shape.size;
  41325. var symbolProxy = this.symbolProxy;
  41326. var symbolProxyShape = symbolProxy.shape;
  41327. var ctx = path.getContext ? path.getContext() : path;
  41328. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  41329. var softClipShape = this.softClipShape;
  41330. var i;
  41331. // Do draw in afterBrush.
  41332. if (canBoost) {
  41333. this._ctx = ctx;
  41334. return;
  41335. }
  41336. this._ctx = null;
  41337. for (i = this._off; i < points.length;) {
  41338. var x = points[i++];
  41339. var y = points[i++];
  41340. if (isNaN(x) || isNaN(y)) {
  41341. continue;
  41342. }
  41343. if (softClipShape && !softClipShape.contain(x, y)) {
  41344. continue;
  41345. }
  41346. symbolProxyShape.x = x - size[0] / 2;
  41347. symbolProxyShape.y = y - size[1] / 2;
  41348. symbolProxyShape.width = size[0];
  41349. symbolProxyShape.height = size[1];
  41350. symbolProxy.buildPath(path, symbolProxyShape, true);
  41351. }
  41352. if (this.incremental) {
  41353. this._off = i;
  41354. this.notClear = true;
  41355. }
  41356. };
  41357. LargeSymbolPath.prototype.afterBrush = function () {
  41358. var shape = this.shape;
  41359. var points = shape.points;
  41360. var size = shape.size;
  41361. var ctx = this._ctx;
  41362. var softClipShape = this.softClipShape;
  41363. var i;
  41364. if (!ctx) {
  41365. return;
  41366. }
  41367. // PENDING If style or other canvas status changed?
  41368. for (i = this._off; i < points.length;) {
  41369. var x = points[i++];
  41370. var y = points[i++];
  41371. if (isNaN(x) || isNaN(y)) {
  41372. continue;
  41373. }
  41374. if (softClipShape && !softClipShape.contain(x, y)) {
  41375. continue;
  41376. }
  41377. // fillRect is faster than building a rect path and draw.
  41378. // And it support light globalCompositeOperation.
  41379. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  41380. }
  41381. if (this.incremental) {
  41382. this._off = i;
  41383. this.notClear = true;
  41384. }
  41385. };
  41386. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  41387. // TODO ???
  41388. // Consider transform
  41389. var shape = this.shape;
  41390. var points = shape.points;
  41391. var size = shape.size;
  41392. var w = Math.max(size[0], 4);
  41393. var h = Math.max(size[1], 4);
  41394. // Not consider transform
  41395. // Treat each element as a rect
  41396. // top down traverse
  41397. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  41398. var i = idx * 2;
  41399. var x0 = points[i] - w / 2;
  41400. var y0 = points[i + 1] - h / 2;
  41401. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  41402. return idx;
  41403. }
  41404. }
  41405. return -1;
  41406. };
  41407. LargeSymbolPath.prototype.contain = function (x, y) {
  41408. var localPos = this.transformCoordToLocal(x, y);
  41409. var rect = this.getBoundingRect();
  41410. x = localPos[0];
  41411. y = localPos[1];
  41412. if (rect.contain(x, y)) {
  41413. // Cache found data index.
  41414. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  41415. return dataIdx >= 0;
  41416. }
  41417. this.hoverDataIdx = -1;
  41418. return false;
  41419. };
  41420. LargeSymbolPath.prototype.getBoundingRect = function () {
  41421. // Ignore stroke for large symbol draw.
  41422. var rect = this._rect;
  41423. if (!rect) {
  41424. var shape = this.shape;
  41425. var points = shape.points;
  41426. var size = shape.size;
  41427. var w = size[0];
  41428. var h = size[1];
  41429. var minX = Infinity;
  41430. var minY = Infinity;
  41431. var maxX = -Infinity;
  41432. var maxY = -Infinity;
  41433. for (var i = 0; i < points.length;) {
  41434. var x = points[i++];
  41435. var y = points[i++];
  41436. minX = Math.min(x, minX);
  41437. maxX = Math.max(x, maxX);
  41438. minY = Math.min(y, minY);
  41439. maxY = Math.max(y, maxY);
  41440. }
  41441. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  41442. }
  41443. return rect;
  41444. };
  41445. return LargeSymbolPath;
  41446. }(Path);
  41447. var LargeSymbolDraw = /** @class */function () {
  41448. function LargeSymbolDraw() {
  41449. this.group = new Group();
  41450. }
  41451. /**
  41452. * Update symbols draw by new data
  41453. */
  41454. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  41455. this._clear();
  41456. var symbolEl = this._create();
  41457. symbolEl.setShape({
  41458. points: data.getLayout('points')
  41459. });
  41460. this._setCommon(symbolEl, data, opt);
  41461. };
  41462. LargeSymbolDraw.prototype.updateLayout = function (data) {
  41463. var points = data.getLayout('points');
  41464. this.group.eachChild(function (child) {
  41465. if (child.startIndex != null) {
  41466. var len = (child.endIndex - child.startIndex) * 2;
  41467. var byteOffset = child.startIndex * 4 * 2;
  41468. points = new Float32Array(points.buffer, byteOffset, len);
  41469. }
  41470. child.setShape('points', points);
  41471. // Reset draw cursor.
  41472. child.reset();
  41473. });
  41474. };
  41475. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  41476. this._clear();
  41477. };
  41478. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  41479. var lastAdded = this._newAdded[0];
  41480. var points = data.getLayout('points');
  41481. var oldPoints = lastAdded && lastAdded.shape.points;
  41482. // Merging the exists. Each element has 1e4 points.
  41483. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  41484. if (oldPoints && oldPoints.length < 2e4) {
  41485. var oldLen = oldPoints.length;
  41486. var newPoints = new Float32Array(oldLen + points.length);
  41487. // Concat two array
  41488. newPoints.set(oldPoints);
  41489. newPoints.set(points, oldLen);
  41490. // Update endIndex
  41491. lastAdded.endIndex = taskParams.end;
  41492. lastAdded.setShape({
  41493. points: newPoints
  41494. });
  41495. } else {
  41496. // Clear
  41497. this._newAdded = [];
  41498. var symbolEl = this._create();
  41499. symbolEl.startIndex = taskParams.start;
  41500. symbolEl.endIndex = taskParams.end;
  41501. symbolEl.incremental = true;
  41502. symbolEl.setShape({
  41503. points: points
  41504. });
  41505. this._setCommon(symbolEl, data, opt);
  41506. }
  41507. };
  41508. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  41509. this._newAdded[0] && cb(this._newAdded[0]);
  41510. };
  41511. LargeSymbolDraw.prototype._create = function () {
  41512. var symbolEl = new LargeSymbolPath({
  41513. cursor: 'default'
  41514. });
  41515. symbolEl.ignoreCoarsePointer = true;
  41516. this.group.add(symbolEl);
  41517. this._newAdded.push(symbolEl);
  41518. return symbolEl;
  41519. };
  41520. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  41521. var hostModel = data.hostModel;
  41522. opt = opt || {};
  41523. var size = data.getVisual('symbolSize');
  41524. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  41525. symbolEl.softClipShape = opt.clipShape || null;
  41526. // Create symbolProxy to build path for each data
  41527. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0);
  41528. // Use symbolProxy setColor method
  41529. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  41530. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  41531. symbolEl.useStyle(
  41532. // Draw shadow when doing fillRect is extremely slow.
  41533. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  41534. var globalStyle = data.getVisual('style');
  41535. var visualColor = globalStyle && globalStyle.fill;
  41536. if (visualColor) {
  41537. symbolEl.setColor(visualColor);
  41538. }
  41539. var ecData = getECData(symbolEl);
  41540. // Enable tooltip
  41541. // PENDING May have performance issue when path is extremely large
  41542. ecData.seriesIndex = hostModel.seriesIndex;
  41543. symbolEl.on('mousemove', function (e) {
  41544. ecData.dataIndex = null;
  41545. var dataIndex = symbolEl.hoverDataIdx;
  41546. if (dataIndex >= 0) {
  41547. // Provide dataIndex for tooltip
  41548. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  41549. }
  41550. });
  41551. };
  41552. LargeSymbolDraw.prototype.remove = function () {
  41553. this._clear();
  41554. };
  41555. LargeSymbolDraw.prototype._clear = function () {
  41556. this._newAdded = [];
  41557. this.group.removeAll();
  41558. };
  41559. return LargeSymbolDraw;
  41560. }();
  41561. var ScatterView = /** @class */function (_super) {
  41562. __extends(ScatterView, _super);
  41563. function ScatterView() {
  41564. var _this = _super !== null && _super.apply(this, arguments) || this;
  41565. _this.type = ScatterView.type;
  41566. return _this;
  41567. }
  41568. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  41569. var data = seriesModel.getData();
  41570. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41571. symbolDraw.updateData(data, {
  41572. // TODO
  41573. // If this parameter should be a shape or a bounding volume
  41574. // shape will be more general.
  41575. // But bounding volume like bounding rect will be much faster in the contain calculation
  41576. clipShape: this._getClipShape(seriesModel)
  41577. });
  41578. this._finished = true;
  41579. };
  41580. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  41581. var data = seriesModel.getData();
  41582. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41583. symbolDraw.incrementalPrepareUpdate(data);
  41584. this._finished = false;
  41585. };
  41586. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  41587. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  41588. clipShape: this._getClipShape(seriesModel)
  41589. });
  41590. this._finished = taskParams.end === seriesModel.getData().count();
  41591. };
  41592. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  41593. var data = seriesModel.getData();
  41594. // Must mark group dirty and make sure the incremental layer will be cleared
  41595. // PENDING
  41596. this.group.dirty();
  41597. if (!this._finished || data.count() > 1e4) {
  41598. return {
  41599. update: true
  41600. };
  41601. } else {
  41602. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  41603. if (res.progress) {
  41604. res.progress({
  41605. start: 0,
  41606. end: data.count(),
  41607. count: data.count()
  41608. }, data);
  41609. }
  41610. this._symbolDraw.updateLayout(data);
  41611. }
  41612. };
  41613. ScatterView.prototype.eachRendered = function (cb) {
  41614. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  41615. };
  41616. ScatterView.prototype._getClipShape = function (seriesModel) {
  41617. if (!seriesModel.get('clip', true)) {
  41618. return;
  41619. }
  41620. var coordSys = seriesModel.coordinateSystem;
  41621. // PENDING make `0.1` configurable, for example, `clipTolerance`?
  41622. return coordSys && coordSys.getArea && coordSys.getArea(.1);
  41623. };
  41624. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  41625. var symbolDraw = this._symbolDraw;
  41626. var pipelineContext = seriesModel.pipelineContext;
  41627. var isLargeDraw = pipelineContext.large;
  41628. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  41629. symbolDraw && symbolDraw.remove();
  41630. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  41631. this._isLargeDraw = isLargeDraw;
  41632. this.group.removeAll();
  41633. }
  41634. this.group.add(symbolDraw.group);
  41635. return symbolDraw;
  41636. };
  41637. ScatterView.prototype.remove = function (ecModel, api) {
  41638. this._symbolDraw && this._symbolDraw.remove(true);
  41639. this._symbolDraw = null;
  41640. };
  41641. ScatterView.prototype.dispose = function () {};
  41642. ScatterView.type = 'scatter';
  41643. return ScatterView;
  41644. }(ChartView);
  41645. var GridModel = /** @class */function (_super) {
  41646. __extends(GridModel, _super);
  41647. function GridModel() {
  41648. return _super !== null && _super.apply(this, arguments) || this;
  41649. }
  41650. GridModel.type = 'grid';
  41651. GridModel.dependencies = ['xAxis', 'yAxis'];
  41652. GridModel.layoutMode = 'box';
  41653. GridModel.defaultOption = {
  41654. show: false,
  41655. // zlevel: 0,
  41656. z: 0,
  41657. left: '10%',
  41658. top: 60,
  41659. right: '10%',
  41660. bottom: 70,
  41661. // If grid size contain label
  41662. containLabel: false,
  41663. // width: {totalWidth} - left - right,
  41664. // height: {totalHeight} - top - bottom,
  41665. backgroundColor: 'rgba(0,0,0,0)',
  41666. borderWidth: 1,
  41667. borderColor: '#ccc'
  41668. };
  41669. return GridModel;
  41670. }(ComponentModel);
  41671. var CartesianAxisModel = /** @class */function (_super) {
  41672. __extends(CartesianAxisModel, _super);
  41673. function CartesianAxisModel() {
  41674. return _super !== null && _super.apply(this, arguments) || this;
  41675. }
  41676. CartesianAxisModel.prototype.getCoordSysModel = function () {
  41677. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  41678. };
  41679. CartesianAxisModel.type = 'cartesian2dAxis';
  41680. return CartesianAxisModel;
  41681. }(ComponentModel);
  41682. mixin(CartesianAxisModel, AxisModelCommonMixin);
  41683. var defaultOption = {
  41684. show: true,
  41685. // zlevel: 0,
  41686. z: 0,
  41687. // Inverse the axis.
  41688. inverse: false,
  41689. // Axis name displayed.
  41690. name: '',
  41691. // 'start' | 'middle' | 'end'
  41692. nameLocation: 'end',
  41693. // By degree. By default auto rotate by nameLocation.
  41694. nameRotate: null,
  41695. nameTruncate: {
  41696. maxWidth: null,
  41697. ellipsis: '...',
  41698. placeholder: '.'
  41699. },
  41700. // Use global text style by default.
  41701. nameTextStyle: {},
  41702. // The gap between axisName and axisLine.
  41703. nameGap: 15,
  41704. // Default `false` to support tooltip.
  41705. silent: false,
  41706. // Default `false` to avoid legacy user event listener fail.
  41707. triggerEvent: false,
  41708. tooltip: {
  41709. show: false
  41710. },
  41711. axisPointer: {},
  41712. axisLine: {
  41713. show: true,
  41714. onZero: true,
  41715. onZeroAxisIndex: null,
  41716. lineStyle: {
  41717. color: '#6E7079',
  41718. width: 1,
  41719. type: 'solid'
  41720. },
  41721. // The arrow at both ends the the axis.
  41722. symbol: ['none', 'none'],
  41723. symbolSize: [10, 15]
  41724. },
  41725. axisTick: {
  41726. show: true,
  41727. // Whether axisTick is inside the grid or outside the grid.
  41728. inside: false,
  41729. // The length of axisTick.
  41730. length: 5,
  41731. lineStyle: {
  41732. width: 1
  41733. }
  41734. },
  41735. axisLabel: {
  41736. show: true,
  41737. // Whether axisLabel is inside the grid or outside the grid.
  41738. inside: false,
  41739. rotate: 0,
  41740. // true | false | null/undefined (auto)
  41741. showMinLabel: null,
  41742. // true | false | null/undefined (auto)
  41743. showMaxLabel: null,
  41744. margin: 8,
  41745. // formatter: null,
  41746. fontSize: 12
  41747. },
  41748. splitLine: {
  41749. show: true,
  41750. lineStyle: {
  41751. color: ['#E0E6F1'],
  41752. width: 1,
  41753. type: 'solid'
  41754. }
  41755. },
  41756. splitArea: {
  41757. show: false,
  41758. areaStyle: {
  41759. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  41760. }
  41761. }
  41762. };
  41763. var categoryAxis = merge({
  41764. // The gap at both ends of the axis. For categoryAxis, boolean.
  41765. boundaryGap: true,
  41766. // Set false to faster category collection.
  41767. deduplication: null,
  41768. // splitArea: {
  41769. // show: false
  41770. // },
  41771. splitLine: {
  41772. show: false
  41773. },
  41774. axisTick: {
  41775. // If tick is align with label when boundaryGap is true
  41776. alignWithLabel: false,
  41777. interval: 'auto'
  41778. },
  41779. axisLabel: {
  41780. interval: 'auto'
  41781. }
  41782. }, defaultOption);
  41783. var valueAxis = merge({
  41784. boundaryGap: [0, 0],
  41785. axisLine: {
  41786. // Not shown when other axis is categoryAxis in cartesian
  41787. show: 'auto'
  41788. },
  41789. axisTick: {
  41790. // Not shown when other axis is categoryAxis in cartesian
  41791. show: 'auto'
  41792. },
  41793. // TODO
  41794. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  41795. splitNumber: 5,
  41796. minorTick: {
  41797. // Minor tick, not available for cateogry axis.
  41798. show: false,
  41799. // Split number of minor ticks. The value should be in range of (0, 100)
  41800. splitNumber: 5,
  41801. // Length of minor tick
  41802. length: 3,
  41803. // Line style
  41804. lineStyle: {
  41805. // Default to be same with axisTick
  41806. }
  41807. },
  41808. minorSplitLine: {
  41809. show: false,
  41810. lineStyle: {
  41811. color: '#F4F7FD',
  41812. width: 1
  41813. }
  41814. }
  41815. }, defaultOption);
  41816. var timeAxis = merge({
  41817. splitNumber: 6,
  41818. axisLabel: {
  41819. // To eliminate labels that are not nice
  41820. showMinLabel: false,
  41821. showMaxLabel: false,
  41822. rich: {
  41823. primary: {
  41824. fontWeight: 'bold'
  41825. }
  41826. }
  41827. },
  41828. splitLine: {
  41829. show: false
  41830. }
  41831. }, valueAxis);
  41832. var logAxis = defaults({
  41833. logBase: 10
  41834. }, valueAxis);
  41835. var axisDefault = {
  41836. category: categoryAxis,
  41837. value: valueAxis,
  41838. time: timeAxis,
  41839. log: logAxis
  41840. };
  41841. /*
  41842. * Licensed to the Apache Software Foundation (ASF) under one
  41843. * or more contributor license agreements. See the NOTICE file
  41844. * distributed with this work for additional information
  41845. * regarding copyright ownership. The ASF licenses this file
  41846. * to you under the Apache License, Version 2.0 (the
  41847. * "License"); you may not use this file except in compliance
  41848. * with the License. You may obtain a copy of the License at
  41849. *
  41850. * http://www.apache.org/licenses/LICENSE-2.0
  41851. *
  41852. * Unless required by applicable law or agreed to in writing,
  41853. * software distributed under the License is distributed on an
  41854. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41855. * KIND, either express or implied. See the License for the
  41856. * specific language governing permissions and limitations
  41857. * under the License.
  41858. */
  41859. /**
  41860. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41861. */
  41862. /*
  41863. * Licensed to the Apache Software Foundation (ASF) under one
  41864. * or more contributor license agreements. See the NOTICE file
  41865. * distributed with this work for additional information
  41866. * regarding copyright ownership. The ASF licenses this file
  41867. * to you under the Apache License, Version 2.0 (the
  41868. * "License"); you may not use this file except in compliance
  41869. * with the License. You may obtain a copy of the License at
  41870. *
  41871. * http://www.apache.org/licenses/LICENSE-2.0
  41872. *
  41873. * Unless required by applicable law or agreed to in writing,
  41874. * software distributed under the License is distributed on an
  41875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41876. * KIND, either express or implied. See the License for the
  41877. * specific language governing permissions and limitations
  41878. * under the License.
  41879. */
  41880. var AXIS_TYPES = {
  41881. value: 1,
  41882. category: 1,
  41883. time: 1,
  41884. log: 1
  41885. };
  41886. /**
  41887. * Generate sub axis model class
  41888. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  41889. */
  41890. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  41891. each(AXIS_TYPES, function (v, axisType) {
  41892. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  41893. var AxisModel = /** @class */function (_super) {
  41894. __extends(AxisModel, _super);
  41895. function AxisModel() {
  41896. var _this = _super !== null && _super.apply(this, arguments) || this;
  41897. _this.type = axisName + 'Axis.' + axisType;
  41898. return _this;
  41899. }
  41900. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  41901. var layoutMode = fetchLayoutMode(this);
  41902. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  41903. var themeModel = ecModel.getTheme();
  41904. merge(option, themeModel.get(axisType + 'Axis'));
  41905. merge(option, this.getDefaultOption());
  41906. option.type = getAxisType(option);
  41907. if (layoutMode) {
  41908. mergeLayoutParam(option, inputPositionParams, layoutMode);
  41909. }
  41910. };
  41911. AxisModel.prototype.optionUpdated = function () {
  41912. var thisOption = this.option;
  41913. if (thisOption.type === 'category') {
  41914. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  41915. }
  41916. };
  41917. /**
  41918. * Should not be called before all of 'getInitailData' finished.
  41919. * Because categories are collected during initializing data.
  41920. */
  41921. AxisModel.prototype.getCategories = function (rawData) {
  41922. var option = this.option;
  41923. // FIXME
  41924. // warning if called before all of 'getInitailData' finished.
  41925. if (option.type === 'category') {
  41926. if (rawData) {
  41927. return option.data;
  41928. }
  41929. return this.__ordinalMeta.categories;
  41930. }
  41931. };
  41932. AxisModel.prototype.getOrdinalMeta = function () {
  41933. return this.__ordinalMeta;
  41934. };
  41935. AxisModel.type = axisName + 'Axis.' + axisType;
  41936. AxisModel.defaultOption = defaultOption;
  41937. return AxisModel;
  41938. }(BaseAxisModelClass);
  41939. registers.registerComponentModel(AxisModel);
  41940. });
  41941. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  41942. }
  41943. function getAxisType(option) {
  41944. // Default axis with data is category axis
  41945. return option.type || (option.data ? 'category' : 'value');
  41946. }
  41947. var Cartesian = /** @class */function () {
  41948. function Cartesian(name) {
  41949. this.type = 'cartesian';
  41950. this._dimList = [];
  41951. this._axes = {};
  41952. this.name = name || '';
  41953. }
  41954. Cartesian.prototype.getAxis = function (dim) {
  41955. return this._axes[dim];
  41956. };
  41957. Cartesian.prototype.getAxes = function () {
  41958. return map(this._dimList, function (dim) {
  41959. return this._axes[dim];
  41960. }, this);
  41961. };
  41962. Cartesian.prototype.getAxesByScale = function (scaleType) {
  41963. scaleType = scaleType.toLowerCase();
  41964. return filter(this.getAxes(), function (axis) {
  41965. return axis.scale.type === scaleType;
  41966. });
  41967. };
  41968. Cartesian.prototype.addAxis = function (axis) {
  41969. var dim = axis.dim;
  41970. this._axes[dim] = axis;
  41971. this._dimList.push(dim);
  41972. };
  41973. return Cartesian;
  41974. }();
  41975. var cartesian2DDimensions = ['x', 'y'];
  41976. function canCalculateAffineTransform(scale) {
  41977. return scale.type === 'interval' || scale.type === 'time';
  41978. }
  41979. var Cartesian2D = /** @class */function (_super) {
  41980. __extends(Cartesian2D, _super);
  41981. function Cartesian2D() {
  41982. var _this = _super !== null && _super.apply(this, arguments) || this;
  41983. _this.type = 'cartesian2d';
  41984. _this.dimensions = cartesian2DDimensions;
  41985. return _this;
  41986. }
  41987. /**
  41988. * Calculate an affine transform matrix if two axes are time or value.
  41989. * It's mainly for accelartion on the large time series data.
  41990. */
  41991. Cartesian2D.prototype.calcAffineTransform = function () {
  41992. this._transform = this._invTransform = null;
  41993. var xAxisScale = this.getAxis('x').scale;
  41994. var yAxisScale = this.getAxis('y').scale;
  41995. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  41996. return;
  41997. }
  41998. var xScaleExtent = xAxisScale.getExtent();
  41999. var yScaleExtent = yAxisScale.getExtent();
  42000. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  42001. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  42002. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  42003. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  42004. if (!xScaleSpan || !yScaleSpan) {
  42005. return;
  42006. }
  42007. // Accelerate data to point calculation on the special large time series data.
  42008. var scaleX = (end[0] - start[0]) / xScaleSpan;
  42009. var scaleY = (end[1] - start[1]) / yScaleSpan;
  42010. var translateX = start[0] - xScaleExtent[0] * scaleX;
  42011. var translateY = start[1] - yScaleExtent[0] * scaleY;
  42012. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  42013. this._invTransform = invert([], m);
  42014. };
  42015. /**
  42016. * Base axis will be used on stacking.
  42017. */
  42018. Cartesian2D.prototype.getBaseAxis = function () {
  42019. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  42020. };
  42021. Cartesian2D.prototype.containPoint = function (point) {
  42022. var axisX = this.getAxis('x');
  42023. var axisY = this.getAxis('y');
  42024. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  42025. };
  42026. Cartesian2D.prototype.containData = function (data) {
  42027. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  42028. };
  42029. Cartesian2D.prototype.containZone = function (data1, data2) {
  42030. var zoneDiag1 = this.dataToPoint(data1);
  42031. var zoneDiag2 = this.dataToPoint(data2);
  42032. var area = this.getArea();
  42033. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  42034. return area.intersect(zone);
  42035. };
  42036. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  42037. out = out || [];
  42038. var xVal = data[0];
  42039. var yVal = data[1];
  42040. // Fast path
  42041. if (this._transform
  42042. // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  42043. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  42044. return applyTransform(out, data, this._transform);
  42045. }
  42046. var xAxis = this.getAxis('x');
  42047. var yAxis = this.getAxis('y');
  42048. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  42049. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  42050. return out;
  42051. };
  42052. Cartesian2D.prototype.clampData = function (data, out) {
  42053. var xScale = this.getAxis('x').scale;
  42054. var yScale = this.getAxis('y').scale;
  42055. var xAxisExtent = xScale.getExtent();
  42056. var yAxisExtent = yScale.getExtent();
  42057. var x = xScale.parse(data[0]);
  42058. var y = yScale.parse(data[1]);
  42059. out = out || [];
  42060. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  42061. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  42062. return out;
  42063. };
  42064. Cartesian2D.prototype.pointToData = function (point, clamp) {
  42065. var out = [];
  42066. if (this._invTransform) {
  42067. return applyTransform(out, point, this._invTransform);
  42068. }
  42069. var xAxis = this.getAxis('x');
  42070. var yAxis = this.getAxis('y');
  42071. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  42072. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  42073. return out;
  42074. };
  42075. Cartesian2D.prototype.getOtherAxis = function (axis) {
  42076. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  42077. };
  42078. /**
  42079. * Get rect area of cartesian.
  42080. * Area will have a contain function to determine if a point is in the coordinate system.
  42081. */
  42082. Cartesian2D.prototype.getArea = function (tolerance) {
  42083. tolerance = tolerance || 0;
  42084. var xExtent = this.getAxis('x').getGlobalExtent();
  42085. var yExtent = this.getAxis('y').getGlobalExtent();
  42086. var x = Math.min(xExtent[0], xExtent[1]) - tolerance;
  42087. var y = Math.min(yExtent[0], yExtent[1]) - tolerance;
  42088. var width = Math.max(xExtent[0], xExtent[1]) - x + tolerance;
  42089. var height = Math.max(yExtent[0], yExtent[1]) - y + tolerance;
  42090. return new BoundingRect(x, y, width, height);
  42091. };
  42092. return Cartesian2D;
  42093. }(Cartesian);
  42094. var Axis2D = /** @class */function (_super) {
  42095. __extends(Axis2D, _super);
  42096. function Axis2D(dim, scale, coordExtent, axisType, position) {
  42097. var _this = _super.call(this, dim, scale, coordExtent) || this;
  42098. /**
  42099. * Index of axis, can be used as key
  42100. * Injected outside.
  42101. */
  42102. _this.index = 0;
  42103. _this.type = axisType || 'value';
  42104. _this.position = position || 'bottom';
  42105. return _this;
  42106. }
  42107. Axis2D.prototype.isHorizontal = function () {
  42108. var position = this.position;
  42109. return position === 'top' || position === 'bottom';
  42110. };
  42111. /**
  42112. * Each item cooresponds to this.getExtent(), which
  42113. * means globalExtent[0] may greater than globalExtent[1],
  42114. * unless `asc` is input.
  42115. *
  42116. * @param {boolean} [asc]
  42117. * @return {Array.<number>}
  42118. */
  42119. Axis2D.prototype.getGlobalExtent = function (asc) {
  42120. var ret = this.getExtent();
  42121. ret[0] = this.toGlobalCoord(ret[0]);
  42122. ret[1] = this.toGlobalCoord(ret[1]);
  42123. asc && ret[0] > ret[1] && ret.reverse();
  42124. return ret;
  42125. };
  42126. Axis2D.prototype.pointToData = function (point, clamp) {
  42127. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  42128. };
  42129. /**
  42130. * Set ordinalSortInfo
  42131. * @param info new OrdinalSortInfo
  42132. */
  42133. Axis2D.prototype.setCategorySortInfo = function (info) {
  42134. if (this.type !== 'category') {
  42135. return false;
  42136. }
  42137. this.model.option.categorySortInfo = info;
  42138. this.scale.setSortInfo(info);
  42139. };
  42140. return Axis2D;
  42141. }(Axis);
  42142. /**
  42143. * Can only be called after coordinate system creation stage.
  42144. * (Can be called before coordinate system update stage).
  42145. */
  42146. function layout$1(gridModel, axisModel, opt) {
  42147. opt = opt || {};
  42148. var grid = gridModel.coordinateSystem;
  42149. var axis = axisModel.axis;
  42150. var layout = {};
  42151. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  42152. var rawAxisPosition = axis.position;
  42153. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  42154. var axisDim = axis.dim;
  42155. var rect = grid.getRect();
  42156. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  42157. var idx = {
  42158. left: 0,
  42159. right: 1,
  42160. top: 0,
  42161. bottom: 1,
  42162. onZero: 2
  42163. };
  42164. var axisOffset = axisModel.get('offset') || 0;
  42165. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  42166. if (otherAxisOnZeroOf) {
  42167. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  42168. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  42169. }
  42170. // Axis position
  42171. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]];
  42172. // Axis rotation
  42173. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  42174. // Tick and label direction, x y is axisDim
  42175. var dirMap = {
  42176. top: -1,
  42177. bottom: 1,
  42178. left: -1,
  42179. right: 1
  42180. };
  42181. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  42182. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  42183. if (axisModel.get(['axisTick', 'inside'])) {
  42184. layout.tickDirection = -layout.tickDirection;
  42185. }
  42186. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  42187. layout.labelDirection = -layout.labelDirection;
  42188. }
  42189. // Special label rotation
  42190. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  42191. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  42192. // Over splitLine and splitArea
  42193. layout.z2 = 1;
  42194. return layout;
  42195. }
  42196. function isCartesian2DSeries(seriesModel) {
  42197. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  42198. }
  42199. function findAxisModels(seriesModel) {
  42200. var axisModelMap = {
  42201. xAxisModel: null,
  42202. yAxisModel: null
  42203. };
  42204. each(axisModelMap, function (v, key) {
  42205. var axisType = key.replace(/Model$/, '');
  42206. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  42207. if ("development" !== 'production') {
  42208. if (!axisModel) {
  42209. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  42210. }
  42211. }
  42212. axisModelMap[key] = axisModel;
  42213. });
  42214. return axisModelMap;
  42215. }
  42216. var mathLog$1 = Math.log;
  42217. function alignScaleTicks(scale, axisModel, alignToScale) {
  42218. var intervalScaleProto = IntervalScale.prototype;
  42219. // NOTE: There is a precondition for log scale here:
  42220. // In log scale we store _interval and _extent of exponent value.
  42221. // So if we use the method of InternalScale to set/get these data.
  42222. // It process the exponent value, which is linear and what we want here.
  42223. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  42224. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  42225. var alignToSplitNumber = alignToTicks.length - 1;
  42226. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  42227. var scaleExtent = getScaleExtent(scale, axisModel);
  42228. var rawExtent = scaleExtent.extent;
  42229. var isMinFixed = scaleExtent.fixMin;
  42230. var isMaxFixed = scaleExtent.fixMax;
  42231. if (scale.type === 'log') {
  42232. var logBase = mathLog$1(scale.base);
  42233. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  42234. }
  42235. scale.setExtent(rawExtent[0], rawExtent[1]);
  42236. scale.calcNiceExtent({
  42237. splitNumber: alignToSplitNumber,
  42238. fixMin: isMinFixed,
  42239. fixMax: isMaxFixed
  42240. });
  42241. var extent = intervalScaleProto.getExtent.call(scale);
  42242. // Need to update the rawExtent.
  42243. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  42244. if (isMinFixed) {
  42245. rawExtent[0] = extent[0];
  42246. }
  42247. if (isMaxFixed) {
  42248. rawExtent[1] = extent[1];
  42249. }
  42250. var interval = intervalScaleProto.getInterval.call(scale);
  42251. var min = rawExtent[0];
  42252. var max = rawExtent[1];
  42253. if (isMinFixed && isMaxFixed) {
  42254. // User set min, max, divide to get new interval
  42255. interval = (max - min) / alignToSplitNumber;
  42256. } else if (isMinFixed) {
  42257. max = rawExtent[0] + interval * alignToSplitNumber;
  42258. // User set min, expand extent on the other side
  42259. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  42260. interval = increaseInterval(interval);
  42261. max = rawExtent[0] + interval * alignToSplitNumber;
  42262. }
  42263. } else if (isMaxFixed) {
  42264. // User set max, expand extent on the other side
  42265. min = rawExtent[1] - interval * alignToSplitNumber;
  42266. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  42267. interval = increaseInterval(interval);
  42268. min = rawExtent[1] - interval * alignToSplitNumber;
  42269. }
  42270. } else {
  42271. var nicedSplitNumber = scale.getTicks().length - 1;
  42272. if (nicedSplitNumber > alignToSplitNumber) {
  42273. interval = increaseInterval(interval);
  42274. }
  42275. var range = interval * alignToSplitNumber;
  42276. max = Math.ceil(rawExtent[1] / interval) * interval;
  42277. min = round(max - range);
  42278. // Not change the result that crossing zero.
  42279. if (min < 0 && rawExtent[0] >= 0) {
  42280. min = 0;
  42281. max = round(range);
  42282. } else if (max > 0 && rawExtent[1] <= 0) {
  42283. max = 0;
  42284. min = -round(range);
  42285. }
  42286. }
  42287. // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  42288. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  42289. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval;
  42290. // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  42291. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  42292. intervalScaleProto.setInterval.call(scale, interval);
  42293. if (t0 || t1) {
  42294. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  42295. }
  42296. if ("development" !== 'production') {
  42297. var ticks = intervalScaleProto.getTicks.call(scale);
  42298. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  42299. warn(
  42300. // eslint-disable-next-line
  42301. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  42302. }
  42303. }
  42304. }
  42305. var Grid = /** @class */function () {
  42306. function Grid(gridModel, ecModel, api) {
  42307. // FIXME:TS where used (different from registered type 'cartesian2d')?
  42308. this.type = 'grid';
  42309. this._coordsMap = {};
  42310. this._coordsList = [];
  42311. this._axesMap = {};
  42312. this._axesList = [];
  42313. this.axisPointerEnabled = true;
  42314. this.dimensions = cartesian2DDimensions;
  42315. this._initCartesian(gridModel, ecModel, api);
  42316. this.model = gridModel;
  42317. }
  42318. Grid.prototype.getRect = function () {
  42319. return this._rect;
  42320. };
  42321. Grid.prototype.update = function (ecModel, api) {
  42322. var axesMap = this._axesMap;
  42323. this._updateScale(ecModel, this.model);
  42324. function updateAxisTicks(axes) {
  42325. var alignTo;
  42326. // Axis is added in order of axisIndex.
  42327. var axesIndices = keys(axes);
  42328. var len = axesIndices.length;
  42329. if (!len) {
  42330. return;
  42331. }
  42332. var axisNeedsAlign = [];
  42333. // Process once and calculate the ticks for those don't use alignTicks.
  42334. for (var i = len - 1; i >= 0; i--) {
  42335. var idx = +axesIndices[i]; // Convert to number.
  42336. var axis = axes[idx];
  42337. var model = axis.model;
  42338. var scale = axis.scale;
  42339. if (
  42340. // Only value and log axis without interval support alignTicks.
  42341. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  42342. axisNeedsAlign.push(axis);
  42343. } else {
  42344. niceScaleExtent(scale, model);
  42345. if (isIntervalOrLogScale(scale)) {
  42346. // Can only align to interval or log axis.
  42347. alignTo = axis;
  42348. }
  42349. }
  42350. }
  42351. // All axes has set alignTicks. Pick the first one.
  42352. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  42353. if (axisNeedsAlign.length) {
  42354. if (!alignTo) {
  42355. alignTo = axisNeedsAlign.pop();
  42356. niceScaleExtent(alignTo.scale, alignTo.model);
  42357. }
  42358. each(axisNeedsAlign, function (axis) {
  42359. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  42360. });
  42361. }
  42362. }
  42363. updateAxisTicks(axesMap.x);
  42364. updateAxisTicks(axesMap.y);
  42365. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  42366. var onZeroRecords = {};
  42367. each(axesMap.x, function (xAxis) {
  42368. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  42369. });
  42370. each(axesMap.y, function (yAxis) {
  42371. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  42372. });
  42373. // Resize again if containLabel is enabled
  42374. // FIXME It may cause getting wrong grid size in data processing stage
  42375. this.resize(this.model, api);
  42376. };
  42377. /**
  42378. * Resize the grid
  42379. */
  42380. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  42381. var boxLayoutParams = gridModel.getBoxLayoutParams();
  42382. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  42383. var gridRect = getLayoutRect(boxLayoutParams, {
  42384. width: api.getWidth(),
  42385. height: api.getHeight()
  42386. });
  42387. this._rect = gridRect;
  42388. var axesList = this._axesList;
  42389. adjustAxes();
  42390. // Minus label size
  42391. if (isContainLabel) {
  42392. each(axesList, function (axis) {
  42393. if (!axis.model.get(['axisLabel', 'inside'])) {
  42394. var labelUnionRect = estimateLabelUnionRect(axis);
  42395. if (labelUnionRect) {
  42396. var dim = axis.isHorizontal() ? 'height' : 'width';
  42397. var margin = axis.model.get(['axisLabel', 'margin']);
  42398. gridRect[dim] -= labelUnionRect[dim] + margin;
  42399. if (axis.position === 'top') {
  42400. gridRect.y += labelUnionRect.height + margin;
  42401. } else if (axis.position === 'left') {
  42402. gridRect.x += labelUnionRect.width + margin;
  42403. }
  42404. }
  42405. }
  42406. });
  42407. adjustAxes();
  42408. }
  42409. each(this._coordsList, function (coord) {
  42410. // Calculate affine matrix to accelerate the data to point transform.
  42411. // If all the axes scales are time or value.
  42412. coord.calcAffineTransform();
  42413. });
  42414. function adjustAxes() {
  42415. each(axesList, function (axis) {
  42416. var isHorizontal = axis.isHorizontal();
  42417. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  42418. var idx = axis.inverse ? 1 : 0;
  42419. axis.setExtent(extent[idx], extent[1 - idx]);
  42420. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  42421. });
  42422. }
  42423. };
  42424. Grid.prototype.getAxis = function (dim, axisIndex) {
  42425. var axesMapOnDim = this._axesMap[dim];
  42426. if (axesMapOnDim != null) {
  42427. return axesMapOnDim[axisIndex || 0];
  42428. }
  42429. };
  42430. Grid.prototype.getAxes = function () {
  42431. return this._axesList.slice();
  42432. };
  42433. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  42434. if (xAxisIndex != null && yAxisIndex != null) {
  42435. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42436. return this._coordsMap[key];
  42437. }
  42438. if (isObject(xAxisIndex)) {
  42439. yAxisIndex = xAxisIndex.yAxisIndex;
  42440. xAxisIndex = xAxisIndex.xAxisIndex;
  42441. }
  42442. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  42443. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  42444. return coordList[i];
  42445. }
  42446. }
  42447. };
  42448. Grid.prototype.getCartesians = function () {
  42449. return this._coordsList.slice();
  42450. };
  42451. /**
  42452. * @implements
  42453. */
  42454. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  42455. var target = this._findConvertTarget(finder);
  42456. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  42457. };
  42458. /**
  42459. * @implements
  42460. */
  42461. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  42462. var target = this._findConvertTarget(finder);
  42463. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  42464. };
  42465. Grid.prototype._findConvertTarget = function (finder) {
  42466. var seriesModel = finder.seriesModel;
  42467. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  42468. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  42469. var gridModel = finder.gridModel;
  42470. var coordsList = this._coordsList;
  42471. var cartesian;
  42472. var axis;
  42473. if (seriesModel) {
  42474. cartesian = seriesModel.coordinateSystem;
  42475. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  42476. } else if (xAxisModel && yAxisModel) {
  42477. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42478. } else if (xAxisModel) {
  42479. axis = this.getAxis('x', xAxisModel.componentIndex);
  42480. } else if (yAxisModel) {
  42481. axis = this.getAxis('y', yAxisModel.componentIndex);
  42482. }
  42483. // Lowest priority.
  42484. else if (gridModel) {
  42485. var grid = gridModel.coordinateSystem;
  42486. if (grid === this) {
  42487. cartesian = this._coordsList[0];
  42488. }
  42489. }
  42490. return {
  42491. cartesian: cartesian,
  42492. axis: axis
  42493. };
  42494. };
  42495. /**
  42496. * @implements
  42497. */
  42498. Grid.prototype.containPoint = function (point) {
  42499. var coord = this._coordsList[0];
  42500. if (coord) {
  42501. return coord.containPoint(point);
  42502. }
  42503. };
  42504. /**
  42505. * Initialize cartesian coordinate systems
  42506. */
  42507. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  42508. var _this = this;
  42509. var grid = this;
  42510. var axisPositionUsed = {
  42511. left: false,
  42512. right: false,
  42513. top: false,
  42514. bottom: false
  42515. };
  42516. var axesMap = {
  42517. x: {},
  42518. y: {}
  42519. };
  42520. var axesCount = {
  42521. x: 0,
  42522. y: 0
  42523. };
  42524. // Create axis
  42525. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  42526. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  42527. if (!axesCount.x || !axesCount.y) {
  42528. // Roll back when there no either x or y axis
  42529. this._axesMap = {};
  42530. this._axesList = [];
  42531. return;
  42532. }
  42533. this._axesMap = axesMap;
  42534. // Create cartesian2d
  42535. each(axesMap.x, function (xAxis, xAxisIndex) {
  42536. each(axesMap.y, function (yAxis, yAxisIndex) {
  42537. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42538. var cartesian = new Cartesian2D(key);
  42539. cartesian.master = _this;
  42540. cartesian.model = gridModel;
  42541. _this._coordsMap[key] = cartesian;
  42542. _this._coordsList.push(cartesian);
  42543. cartesian.addAxis(xAxis);
  42544. cartesian.addAxis(yAxis);
  42545. });
  42546. });
  42547. function createAxisCreator(dimName) {
  42548. return function (axisModel, idx) {
  42549. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  42550. return;
  42551. }
  42552. var axisPosition = axisModel.get('position');
  42553. if (dimName === 'x') {
  42554. // Fix position
  42555. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  42556. // Default bottom of X
  42557. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  42558. }
  42559. } else {
  42560. // Fix position
  42561. if (axisPosition !== 'left' && axisPosition !== 'right') {
  42562. // Default left of Y
  42563. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  42564. }
  42565. }
  42566. axisPositionUsed[axisPosition] = true;
  42567. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  42568. var isCategory = axis.type === 'category';
  42569. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42570. axis.inverse = axisModel.get('inverse');
  42571. // Inject axis into axisModel
  42572. axisModel.axis = axis;
  42573. // Inject axisModel into axis
  42574. axis.model = axisModel;
  42575. // Inject grid info axis
  42576. axis.grid = grid;
  42577. // Index of axis, can be used as key
  42578. axis.index = idx;
  42579. grid._axesList.push(axis);
  42580. axesMap[dimName][idx] = axis;
  42581. axesCount[dimName]++;
  42582. };
  42583. }
  42584. };
  42585. /**
  42586. * Update cartesian properties from series.
  42587. */
  42588. Grid.prototype._updateScale = function (ecModel, gridModel) {
  42589. // Reset scale
  42590. each(this._axesList, function (axis) {
  42591. axis.scale.setExtent(Infinity, -Infinity);
  42592. if (axis.type === 'category') {
  42593. var categorySortInfo = axis.model.get('categorySortInfo');
  42594. axis.scale.setSortInfo(categorySortInfo);
  42595. }
  42596. });
  42597. ecModel.eachSeries(function (seriesModel) {
  42598. if (isCartesian2DSeries(seriesModel)) {
  42599. var axesModelMap = findAxisModels(seriesModel);
  42600. var xAxisModel = axesModelMap.xAxisModel;
  42601. var yAxisModel = axesModelMap.yAxisModel;
  42602. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  42603. return;
  42604. }
  42605. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42606. var data = seriesModel.getData();
  42607. var xAxis = cartesian.getAxis('x');
  42608. var yAxis = cartesian.getAxis('y');
  42609. unionExtent(data, xAxis);
  42610. unionExtent(data, yAxis);
  42611. }
  42612. }, this);
  42613. function unionExtent(data, axis) {
  42614. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  42615. axis.scale.unionExtentFromData(data, dim);
  42616. });
  42617. }
  42618. };
  42619. /**
  42620. * @param dim 'x' or 'y' or 'auto' or null/undefined
  42621. */
  42622. Grid.prototype.getTooltipAxes = function (dim) {
  42623. var baseAxes = [];
  42624. var otherAxes = [];
  42625. each(this.getCartesians(), function (cartesian) {
  42626. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  42627. var otherAxis = cartesian.getOtherAxis(baseAxis);
  42628. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  42629. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  42630. });
  42631. return {
  42632. baseAxes: baseAxes,
  42633. otherAxes: otherAxes
  42634. };
  42635. };
  42636. Grid.create = function (ecModel, api) {
  42637. var grids = [];
  42638. ecModel.eachComponent('grid', function (gridModel, idx) {
  42639. var grid = new Grid(gridModel, ecModel, api);
  42640. grid.name = 'grid_' + idx;
  42641. // dataSampling requires axis extent, so resize
  42642. // should be performed in create stage.
  42643. grid.resize(gridModel, api, true);
  42644. gridModel.coordinateSystem = grid;
  42645. grids.push(grid);
  42646. });
  42647. // Inject the coordinateSystems into seriesModel
  42648. ecModel.eachSeries(function (seriesModel) {
  42649. if (!isCartesian2DSeries(seriesModel)) {
  42650. return;
  42651. }
  42652. var axesModelMap = findAxisModels(seriesModel);
  42653. var xAxisModel = axesModelMap.xAxisModel;
  42654. var yAxisModel = axesModelMap.yAxisModel;
  42655. var gridModel = xAxisModel.getCoordSysModel();
  42656. if ("development" !== 'production') {
  42657. if (!gridModel) {
  42658. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  42659. }
  42660. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  42661. throw new Error('xAxis and yAxis must use the same grid');
  42662. }
  42663. }
  42664. var grid = gridModel.coordinateSystem;
  42665. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42666. });
  42667. return grids;
  42668. };
  42669. // For deciding which dimensions to use when creating list data
  42670. Grid.dimensions = cartesian2DDimensions;
  42671. return Grid;
  42672. }();
  42673. /**
  42674. * Check if the axis is used in the specified grid.
  42675. */
  42676. function isAxisUsedInTheGrid(axisModel, gridModel) {
  42677. return axisModel.getCoordSysModel() === gridModel;
  42678. }
  42679. function fixAxisOnZero(axesMap, otherAxisDim, axis,
  42680. // Key: see `getOnZeroRecordKey`
  42681. onZeroRecords) {
  42682. axis.getAxesOnZeroOf = function () {
  42683. // TODO: onZero of multiple axes.
  42684. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  42685. };
  42686. // onZero can not be enabled in these two situations:
  42687. // 1. When any other axis is a category axis.
  42688. // 2. When no axis is cross 0 point.
  42689. var otherAxes = axesMap[otherAxisDim];
  42690. var otherAxisOnZeroOf;
  42691. var axisModel = axis.model;
  42692. var onZero = axisModel.get(['axisLine', 'onZero']);
  42693. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  42694. if (!onZero) {
  42695. return;
  42696. }
  42697. // If target axis is specified.
  42698. if (onZeroAxisIndex != null) {
  42699. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  42700. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  42701. }
  42702. } else {
  42703. // Find the first available other axis.
  42704. for (var idx in otherAxes) {
  42705. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])
  42706. // Consider that two Y axes on one value axis,
  42707. // if both onZero, the two Y axes overlap.
  42708. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  42709. otherAxisOnZeroOf = otherAxes[idx];
  42710. break;
  42711. }
  42712. }
  42713. }
  42714. if (otherAxisOnZeroOf) {
  42715. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  42716. }
  42717. function getOnZeroRecordKey(axis) {
  42718. return axis.dim + '_' + axis.index;
  42719. }
  42720. }
  42721. function canOnZeroToAxis(axis) {
  42722. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  42723. }
  42724. function updateAxisTransform(axis, coordBase) {
  42725. var axisExtent = axis.getExtent();
  42726. var axisExtentSum = axisExtent[0] + axisExtent[1];
  42727. // Fast transform
  42728. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  42729. return coord + coordBase;
  42730. } : function (coord) {
  42731. return axisExtentSum - coord + coordBase;
  42732. };
  42733. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  42734. return coord - coordBase;
  42735. } : function (coord) {
  42736. return axisExtentSum - coord + coordBase;
  42737. };
  42738. }
  42739. var PI$5 = Math.PI;
  42740. /**
  42741. * A final axis is translated and rotated from a "standard axis".
  42742. * So opt.position and opt.rotation is required.
  42743. *
  42744. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  42745. * for example: (0, 0) ------------> (0, 50)
  42746. *
  42747. * nameDirection or tickDirection or labelDirection is 1 means tick
  42748. * or label is below the standard axis, whereas is -1 means above
  42749. * the standard axis. labelOffset means offset between label and axis,
  42750. * which is useful when 'onZero', where axisLabel is in the grid and
  42751. * label in outside grid.
  42752. *
  42753. * Tips: like always,
  42754. * positive rotation represents anticlockwise, and negative rotation
  42755. * represents clockwise.
  42756. * The direction of position coordinate is the same as the direction
  42757. * of screen coordinate.
  42758. *
  42759. * Do not need to consider axis 'inverse', which is auto processed by
  42760. * axis extent.
  42761. */
  42762. var AxisBuilder = /** @class */function () {
  42763. function AxisBuilder(axisModel, opt) {
  42764. this.group = new Group();
  42765. this.opt = opt;
  42766. this.axisModel = axisModel;
  42767. // Default value
  42768. defaults(opt, {
  42769. labelOffset: 0,
  42770. nameDirection: 1,
  42771. tickDirection: 1,
  42772. labelDirection: 1,
  42773. silent: true,
  42774. handleAutoShown: function () {
  42775. return true;
  42776. }
  42777. });
  42778. // FIXME Not use a separate text group?
  42779. var transformGroup = new Group({
  42780. x: opt.position[0],
  42781. y: opt.position[1],
  42782. rotation: opt.rotation
  42783. });
  42784. // this.group.add(transformGroup);
  42785. // this._transformGroup = transformGroup;
  42786. transformGroup.updateTransform();
  42787. this._transformGroup = transformGroup;
  42788. }
  42789. AxisBuilder.prototype.hasBuilder = function (name) {
  42790. return !!builders[name];
  42791. };
  42792. AxisBuilder.prototype.add = function (name) {
  42793. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  42794. };
  42795. AxisBuilder.prototype.getGroup = function () {
  42796. return this.group;
  42797. };
  42798. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  42799. var rotationDiff = remRadian(textRotation - axisRotation);
  42800. var textAlign;
  42801. var textVerticalAlign;
  42802. if (isRadianAroundZero(rotationDiff)) {
  42803. // Label is parallel with axis line.
  42804. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  42805. textAlign = 'center';
  42806. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  42807. // Label is inverse parallel with axis line.
  42808. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  42809. textAlign = 'center';
  42810. } else {
  42811. textVerticalAlign = 'middle';
  42812. if (rotationDiff > 0 && rotationDiff < PI$5) {
  42813. textAlign = direction > 0 ? 'right' : 'left';
  42814. } else {
  42815. textAlign = direction > 0 ? 'left' : 'right';
  42816. }
  42817. }
  42818. return {
  42819. rotation: rotationDiff,
  42820. textAlign: textAlign,
  42821. textVerticalAlign: textVerticalAlign
  42822. };
  42823. };
  42824. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  42825. var eventData = {
  42826. componentType: axisModel.mainType,
  42827. componentIndex: axisModel.componentIndex
  42828. };
  42829. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  42830. return eventData;
  42831. };
  42832. AxisBuilder.isLabelSilent = function (axisModel) {
  42833. var tooltipOpt = axisModel.get('tooltip');
  42834. return axisModel.get('silent')
  42835. // Consider mouse cursor, add these restrictions.
  42836. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  42837. };
  42838. return AxisBuilder;
  42839. }();
  42840. var builders = {
  42841. axisLine: function (opt, axisModel, group, transformGroup) {
  42842. var shown = axisModel.get(['axisLine', 'show']);
  42843. if (shown === 'auto' && opt.handleAutoShown) {
  42844. shown = opt.handleAutoShown('axisLine');
  42845. }
  42846. if (!shown) {
  42847. return;
  42848. }
  42849. var extent = axisModel.axis.getExtent();
  42850. var matrix = transformGroup.transform;
  42851. var pt1 = [extent[0], 0];
  42852. var pt2 = [extent[1], 0];
  42853. var inverse = pt1[0] > pt2[0];
  42854. if (matrix) {
  42855. applyTransform(pt1, pt1, matrix);
  42856. applyTransform(pt2, pt2, matrix);
  42857. }
  42858. var lineStyle = extend({
  42859. lineCap: 'round'
  42860. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  42861. var line = new Line({
  42862. shape: {
  42863. x1: pt1[0],
  42864. y1: pt1[1],
  42865. x2: pt2[0],
  42866. y2: pt2[1]
  42867. },
  42868. style: lineStyle,
  42869. strokeContainThreshold: opt.strokeContainThreshold || 5,
  42870. silent: true,
  42871. z2: 1
  42872. });
  42873. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  42874. line.anid = 'line';
  42875. group.add(line);
  42876. var arrows = axisModel.get(['axisLine', 'symbol']);
  42877. if (arrows != null) {
  42878. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  42879. if (isString(arrows)) {
  42880. // Use the same arrow for start and end point
  42881. arrows = [arrows, arrows];
  42882. }
  42883. if (isString(arrowSize) || isNumber(arrowSize)) {
  42884. // Use the same size for width and height
  42885. arrowSize = [arrowSize, arrowSize];
  42886. }
  42887. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  42888. var symbolWidth_1 = arrowSize[0];
  42889. var symbolHeight_1 = arrowSize[1];
  42890. each([{
  42891. rotate: opt.rotation + Math.PI / 2,
  42892. offset: arrowOffset[0],
  42893. r: 0
  42894. }, {
  42895. rotate: opt.rotation - Math.PI / 2,
  42896. offset: arrowOffset[1],
  42897. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  42898. }], function (point, index) {
  42899. if (arrows[index] !== 'none' && arrows[index] != null) {
  42900. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true);
  42901. // Calculate arrow position with offset
  42902. var r = point.r + point.offset;
  42903. var pt = inverse ? pt2 : pt1;
  42904. symbol.attr({
  42905. rotation: point.rotate,
  42906. x: pt[0] + r * Math.cos(opt.rotation),
  42907. y: pt[1] - r * Math.sin(opt.rotation),
  42908. silent: true,
  42909. z2: 11
  42910. });
  42911. group.add(symbol);
  42912. }
  42913. });
  42914. }
  42915. },
  42916. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  42917. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  42918. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  42919. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  42920. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  42921. // This bit fixes the label overlap issue for the time chart.
  42922. // See https://github.com/apache/echarts/issues/14266 for more.
  42923. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  42924. var labelList = prepareLayoutList(map(labelEls, function (label) {
  42925. return {
  42926. label: label,
  42927. priority: label.z2,
  42928. defaultAttr: {
  42929. ignore: label.ignore
  42930. }
  42931. };
  42932. }));
  42933. hideOverlap(labelList);
  42934. }
  42935. },
  42936. axisName: function (opt, axisModel, group, transformGroup) {
  42937. var name = retrieve(opt.axisName, axisModel.get('name'));
  42938. if (!name) {
  42939. return;
  42940. }
  42941. var nameLocation = axisModel.get('nameLocation');
  42942. var nameDirection = opt.nameDirection;
  42943. var textStyleModel = axisModel.getModel('nameTextStyle');
  42944. var gap = axisModel.get('nameGap') || 0;
  42945. var extent = axisModel.axis.getExtent();
  42946. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  42947. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2,
  42948. // Reuse labelOffset.
  42949. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  42950. var labelLayout;
  42951. var nameRotation = axisModel.get('nameRotate');
  42952. if (nameRotation != null) {
  42953. nameRotation = nameRotation * PI$5 / 180; // To radian.
  42954. }
  42955. var axisNameAvailableWidth;
  42956. if (isNameLocationCenter(nameLocation)) {
  42957. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation,
  42958. // Adapt to axis.
  42959. nameDirection);
  42960. } else {
  42961. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  42962. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  42963. if (axisNameAvailableWidth != null) {
  42964. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  42965. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  42966. }
  42967. }
  42968. var textFont = textStyleModel.getFont();
  42969. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  42970. var ellipsis = truncateOpt.ellipsis;
  42971. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  42972. var textEl = new ZRText({
  42973. x: pos[0],
  42974. y: pos[1],
  42975. rotation: labelLayout.rotation,
  42976. silent: AxisBuilder.isLabelSilent(axisModel),
  42977. style: createTextStyle(textStyleModel, {
  42978. text: name,
  42979. font: textFont,
  42980. overflow: 'truncate',
  42981. width: maxWidth,
  42982. ellipsis: ellipsis,
  42983. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  42984. align: textStyleModel.get('align') || labelLayout.textAlign,
  42985. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  42986. }),
  42987. z2: 1
  42988. });
  42989. setTooltipConfig({
  42990. el: textEl,
  42991. componentModel: axisModel,
  42992. itemName: name
  42993. });
  42994. textEl.__fullText = name;
  42995. // Id for animation
  42996. textEl.anid = 'name';
  42997. if (axisModel.get('triggerEvent')) {
  42998. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  42999. eventData.targetType = 'axisName';
  43000. eventData.name = name;
  43001. getECData(textEl).eventData = eventData;
  43002. }
  43003. // FIXME
  43004. transformGroup.add(textEl);
  43005. textEl.updateTransform();
  43006. group.add(textEl);
  43007. textEl.decomposeTransform();
  43008. }
  43009. };
  43010. function endTextLayout(rotation, textPosition, textRotate, extent) {
  43011. var rotationDiff = remRadian(textRotate - rotation);
  43012. var textAlign;
  43013. var textVerticalAlign;
  43014. var inverse = extent[0] > extent[1];
  43015. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  43016. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  43017. textVerticalAlign = onLeft ? 'bottom' : 'top';
  43018. textAlign = 'center';
  43019. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  43020. textVerticalAlign = onLeft ? 'top' : 'bottom';
  43021. textAlign = 'center';
  43022. } else {
  43023. textVerticalAlign = 'middle';
  43024. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  43025. textAlign = onLeft ? 'left' : 'right';
  43026. } else {
  43027. textAlign = onLeft ? 'right' : 'left';
  43028. }
  43029. }
  43030. return {
  43031. rotation: rotationDiff,
  43032. textAlign: textAlign,
  43033. textVerticalAlign: textVerticalAlign
  43034. };
  43035. }
  43036. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  43037. if (shouldShowAllLabels(axisModel.axis)) {
  43038. return;
  43039. }
  43040. // If min or max are user set, we need to check
  43041. // If the tick on min(max) are overlap on their neighbour tick
  43042. // If they are overlapped, we need to hide the min(max) tick label
  43043. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  43044. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']);
  43045. // FIXME
  43046. // Have not consider onBand yet, where tick els is more than label els.
  43047. labelEls = labelEls || [];
  43048. tickEls = tickEls || [];
  43049. var firstLabel = labelEls[0];
  43050. var nextLabel = labelEls[1];
  43051. var lastLabel = labelEls[labelEls.length - 1];
  43052. var prevLabel = labelEls[labelEls.length - 2];
  43053. var firstTick = tickEls[0];
  43054. var nextTick = tickEls[1];
  43055. var lastTick = tickEls[tickEls.length - 1];
  43056. var prevTick = tickEls[tickEls.length - 2];
  43057. if (showMinLabel === false) {
  43058. ignoreEl(firstLabel);
  43059. ignoreEl(firstTick);
  43060. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  43061. if (showMinLabel) {
  43062. ignoreEl(nextLabel);
  43063. ignoreEl(nextTick);
  43064. } else {
  43065. ignoreEl(firstLabel);
  43066. ignoreEl(firstTick);
  43067. }
  43068. }
  43069. if (showMaxLabel === false) {
  43070. ignoreEl(lastLabel);
  43071. ignoreEl(lastTick);
  43072. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  43073. if (showMaxLabel) {
  43074. ignoreEl(prevLabel);
  43075. ignoreEl(prevTick);
  43076. } else {
  43077. ignoreEl(lastLabel);
  43078. ignoreEl(lastTick);
  43079. }
  43080. }
  43081. }
  43082. function ignoreEl(el) {
  43083. el && (el.ignore = true);
  43084. }
  43085. function isTwoLabelOverlapped(current, next) {
  43086. // current and next has the same rotation.
  43087. var firstRect = current && current.getBoundingRect().clone();
  43088. var nextRect = next && next.getBoundingRect().clone();
  43089. if (!firstRect || !nextRect) {
  43090. return;
  43091. }
  43092. // When checking intersect of two rotated labels, we use mRotationBack
  43093. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  43094. var mRotationBack = identity([]);
  43095. rotate(mRotationBack, mRotationBack, -current.rotation);
  43096. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  43097. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  43098. return firstRect.intersect(nextRect);
  43099. }
  43100. function isNameLocationCenter(nameLocation) {
  43101. return nameLocation === 'middle' || nameLocation === 'center';
  43102. }
  43103. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  43104. var tickEls = [];
  43105. var pt1 = [];
  43106. var pt2 = [];
  43107. for (var i = 0; i < ticksCoords.length; i++) {
  43108. var tickCoord = ticksCoords[i].coord;
  43109. pt1[0] = tickCoord;
  43110. pt1[1] = 0;
  43111. pt2[0] = tickCoord;
  43112. pt2[1] = tickEndCoord;
  43113. if (tickTransform) {
  43114. applyTransform(pt1, pt1, tickTransform);
  43115. applyTransform(pt2, pt2, tickTransform);
  43116. }
  43117. // Tick line, Not use group transform to have better line draw
  43118. var tickEl = new Line({
  43119. shape: {
  43120. x1: pt1[0],
  43121. y1: pt1[1],
  43122. x2: pt2[0],
  43123. y2: pt2[1]
  43124. },
  43125. style: tickLineStyle,
  43126. z2: 2,
  43127. autoBatch: true,
  43128. silent: true
  43129. });
  43130. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  43131. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  43132. tickEls.push(tickEl);
  43133. }
  43134. return tickEls;
  43135. }
  43136. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  43137. var axis = axisModel.axis;
  43138. var tickModel = axisModel.getModel('axisTick');
  43139. var shown = tickModel.get('show');
  43140. if (shown === 'auto' && opt.handleAutoShown) {
  43141. shown = opt.handleAutoShown('axisTick');
  43142. }
  43143. if (!shown || axis.scale.isBlank()) {
  43144. return;
  43145. }
  43146. var lineStyleModel = tickModel.getModel('lineStyle');
  43147. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  43148. var ticksCoords = axis.getTicksCoords();
  43149. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  43150. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43151. }), 'ticks');
  43152. for (var i = 0; i < ticksEls.length; i++) {
  43153. group.add(ticksEls[i]);
  43154. }
  43155. return ticksEls;
  43156. }
  43157. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  43158. var axis = axisModel.axis;
  43159. var minorTickModel = axisModel.getModel('minorTick');
  43160. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  43161. return;
  43162. }
  43163. var minorTicksCoords = axis.getMinorTicksCoords();
  43164. if (!minorTicksCoords.length) {
  43165. return;
  43166. }
  43167. var lineStyleModel = minorTickModel.getModel('lineStyle');
  43168. var tickEndCoord = tickDirection * minorTickModel.get('length');
  43169. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  43170. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43171. }));
  43172. for (var i = 0; i < minorTicksCoords.length; i++) {
  43173. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  43174. for (var k = 0; k < minorTicksEls.length; k++) {
  43175. group.add(minorTicksEls[k]);
  43176. }
  43177. }
  43178. }
  43179. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  43180. var axis = axisModel.axis;
  43181. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  43182. if (!show || axis.scale.isBlank()) {
  43183. return;
  43184. }
  43185. var labelModel = axisModel.getModel('axisLabel');
  43186. var labelMargin = labelModel.get('margin');
  43187. var labels = axis.getViewLabels();
  43188. // Special label rotate.
  43189. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  43190. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  43191. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  43192. var labelEls = [];
  43193. var silent = AxisBuilder.isLabelSilent(axisModel);
  43194. var triggerEvent = axisModel.get('triggerEvent');
  43195. each(labels, function (labelItem, index) {
  43196. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  43197. var formattedLabel = labelItem.formattedLabel;
  43198. var rawLabel = labelItem.rawLabel;
  43199. var itemLabelModel = labelModel;
  43200. if (rawCategoryData && rawCategoryData[tickValue]) {
  43201. var rawCategoryItem = rawCategoryData[tickValue];
  43202. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  43203. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  43204. }
  43205. }
  43206. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  43207. var tickCoord = axis.dataToCoord(tickValue);
  43208. var align = itemLabelModel.getShallow('align', true) || labelLayout.textAlign;
  43209. var alignMin = retrieve2(itemLabelModel.getShallow('alignMinLabel', true), align);
  43210. var alignMax = retrieve2(itemLabelModel.getShallow('alignMaxLabel', true), align);
  43211. var verticalAlign = itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign;
  43212. var verticalAlignMin = retrieve2(itemLabelModel.getShallow('verticalAlignMinLabel', true), verticalAlign);
  43213. var verticalAlignMax = retrieve2(itemLabelModel.getShallow('verticalAlignMaxLabel', true), verticalAlign);
  43214. var textEl = new ZRText({
  43215. x: tickCoord,
  43216. y: opt.labelOffset + opt.labelDirection * labelMargin,
  43217. rotation: labelLayout.rotation,
  43218. silent: silent,
  43219. z2: 10 + (labelItem.level || 0),
  43220. style: createTextStyle(itemLabelModel, {
  43221. text: formattedLabel,
  43222. align: index === 0 ? alignMin : index === labels.length - 1 ? alignMax : align,
  43223. verticalAlign: index === 0 ? verticalAlignMin : index === labels.length - 1 ? verticalAlignMax : verticalAlign,
  43224. fill: isFunction(textColor) ? textColor(
  43225. // (1) In category axis with data zoom, tick is not the original
  43226. // index of axis.data. So tick should not be exposed to user
  43227. // in category axis.
  43228. // (2) Compatible with previous version, which always use formatted label as
  43229. // input. But in interval scale the formatted label is like '223,445', which
  43230. // maked user replace ','. So we modify it to return original val but remain
  43231. // it as 'string' to avoid error in replacing.
  43232. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  43233. })
  43234. });
  43235. textEl.anid = 'label_' + tickValue;
  43236. // Pack data for mouse event
  43237. if (triggerEvent) {
  43238. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43239. eventData.targetType = 'axisLabel';
  43240. eventData.value = rawLabel;
  43241. eventData.tickIndex = index;
  43242. if (axis.type === 'category') {
  43243. eventData.dataIndex = tickValue;
  43244. }
  43245. getECData(textEl).eventData = eventData;
  43246. }
  43247. // FIXME
  43248. transformGroup.add(textEl);
  43249. textEl.updateTransform();
  43250. labelEls.push(textEl);
  43251. group.add(textEl);
  43252. textEl.decomposeTransform();
  43253. });
  43254. return labelEls;
  43255. }
  43256. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  43257. // allAxesInfo should be updated when setOption performed.
  43258. function collect(ecModel, api) {
  43259. var result = {
  43260. /**
  43261. * key: makeKey(axis.model)
  43262. * value: {
  43263. * axis,
  43264. * coordSys,
  43265. * axisPointerModel,
  43266. * triggerTooltip,
  43267. * triggerEmphasis,
  43268. * involveSeries,
  43269. * snap,
  43270. * seriesModels,
  43271. * seriesDataCount
  43272. * }
  43273. */
  43274. axesInfo: {},
  43275. seriesInvolved: false,
  43276. /**
  43277. * key: makeKey(coordSys.model)
  43278. * value: Object: key makeKey(axis.model), value: axisInfo
  43279. */
  43280. coordSysAxesInfo: {},
  43281. coordSysMap: {}
  43282. };
  43283. collectAxesInfo(result, ecModel, api);
  43284. // Check seriesInvolved for performance, in case too many series in some chart.
  43285. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  43286. return result;
  43287. }
  43288. function collectAxesInfo(result, ecModel, api) {
  43289. var globalTooltipModel = ecModel.getComponent('tooltip');
  43290. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  43291. // links can only be set on global.
  43292. var linksOption = globalAxisPointerModel.get('link', true) || [];
  43293. var linkGroups = [];
  43294. // Collect axes info.
  43295. each(api.getCoordinateSystems(), function (coordSys) {
  43296. // Some coordinate system do not support axes, like geo.
  43297. if (!coordSys.axisPointerEnabled) {
  43298. return;
  43299. }
  43300. var coordSysKey = makeKey(coordSys.model);
  43301. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  43302. result.coordSysMap[coordSysKey] = coordSys;
  43303. // Set tooltip (like 'cross') is a convenient way to show axisPointer
  43304. // for user. So we enable setting tooltip on coordSys model.
  43305. var coordSysModel = coordSys.model;
  43306. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  43307. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null));
  43308. // If axis tooltip used, choose tooltip axis for each coordSys.
  43309. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  43310. if (coordSys.getTooltipAxes && globalTooltipModel
  43311. // If tooltip.showContent is set as false, tooltip will not
  43312. // show but axisPointer will show as normal.
  43313. && baseTooltipModel.get('show')) {
  43314. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  43315. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  43316. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  43317. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  43318. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  43319. if (triggerAxis || cross) {
  43320. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  43321. }
  43322. if (cross) {
  43323. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  43324. }
  43325. }
  43326. // fromTooltip: true | false | 'cross'
  43327. // triggerTooltip: true | false | null
  43328. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  43329. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  43330. var axisPointerShow = axisPointerModel.get('show');
  43331. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  43332. return;
  43333. }
  43334. if (triggerTooltip == null) {
  43335. triggerTooltip = axisPointerModel.get('triggerTooltip');
  43336. }
  43337. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  43338. var snap = axisPointerModel.get('snap');
  43339. var triggerEmphasis = axisPointerModel.get('triggerEmphasis');
  43340. var axisKey = makeKey(axis.model);
  43341. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  43342. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  43343. var axisInfo = result.axesInfo[axisKey] = {
  43344. key: axisKey,
  43345. axis: axis,
  43346. coordSys: coordSys,
  43347. axisPointerModel: axisPointerModel,
  43348. triggerTooltip: triggerTooltip,
  43349. triggerEmphasis: triggerEmphasis,
  43350. involveSeries: involveSeries,
  43351. snap: snap,
  43352. useHandle: isHandleTrigger(axisPointerModel),
  43353. seriesModels: [],
  43354. linkGroup: null
  43355. };
  43356. axesInfoInCoordSys[axisKey] = axisInfo;
  43357. result.seriesInvolved = result.seriesInvolved || involveSeries;
  43358. var groupIndex = getLinkGroupIndex(linksOption, axis);
  43359. if (groupIndex != null) {
  43360. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  43361. axesInfo: {}
  43362. });
  43363. linkGroup.axesInfo[axisKey] = axisInfo;
  43364. linkGroup.mapper = linksOption[groupIndex].mapper;
  43365. axisInfo.linkGroup = linkGroup;
  43366. }
  43367. }
  43368. });
  43369. }
  43370. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  43371. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  43372. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  43373. var volatileOption = {};
  43374. each(fields, function (field) {
  43375. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  43376. });
  43377. // category axis do not auto snap, otherwise some tick that do not
  43378. // has value can not be hovered. value/time/log axis default snap if
  43379. // triggered from tooltip and trigger tooltip.
  43380. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  43381. // Compatible with previous behavior, tooltip axis does not show label by default.
  43382. // Only these properties can be overridden from tooltip to axisPointer.
  43383. if (tooltipAxisPointerModel.get('type') === 'cross') {
  43384. volatileOption.type = 'line';
  43385. }
  43386. var labelOption = volatileOption.label || (volatileOption.label = {});
  43387. // Follow the convention, do not show label when triggered by tooltip by default.
  43388. labelOption.show == null && (labelOption.show = false);
  43389. if (fromTooltip === 'cross') {
  43390. // When 'cross', both axes show labels.
  43391. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  43392. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  43393. // If triggerTooltip, this is a base axis, which should better not use cross style
  43394. // (cross style is dashed by default)
  43395. if (!triggerTooltip) {
  43396. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  43397. crossStyle && defaults(labelOption, crossStyle.textStyle);
  43398. }
  43399. }
  43400. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  43401. }
  43402. function collectSeriesInfo(result, ecModel) {
  43403. // Prepare data for axis trigger
  43404. ecModel.eachSeries(function (seriesModel) {
  43405. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  43406. var coordSys = seriesModel.coordinateSystem;
  43407. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  43408. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  43409. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  43410. return;
  43411. }
  43412. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  43413. var axis = axisInfo.axis;
  43414. if (coordSys.getAxis(axis.dim) === axis) {
  43415. axisInfo.seriesModels.push(seriesModel);
  43416. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  43417. axisInfo.seriesDataCount += seriesModel.getData().count();
  43418. }
  43419. });
  43420. });
  43421. }
  43422. /**
  43423. * For example:
  43424. * {
  43425. * axisPointer: {
  43426. * links: [{
  43427. * xAxisIndex: [2, 4],
  43428. * yAxisIndex: 'all'
  43429. * }, {
  43430. * xAxisId: ['a5', 'a7'],
  43431. * xAxisName: 'xxx'
  43432. * }]
  43433. * }
  43434. * }
  43435. */
  43436. function getLinkGroupIndex(linksOption, axis) {
  43437. var axisModel = axis.model;
  43438. var dim = axis.dim;
  43439. for (var i = 0; i < linksOption.length; i++) {
  43440. var linkOption = linksOption[i] || {};
  43441. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  43442. return i;
  43443. }
  43444. }
  43445. }
  43446. function checkPropInLink(linkPropValue, axisPropValue) {
  43447. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  43448. }
  43449. function fixValue(axisModel) {
  43450. var axisInfo = getAxisInfo(axisModel);
  43451. if (!axisInfo) {
  43452. return;
  43453. }
  43454. var axisPointerModel = axisInfo.axisPointerModel;
  43455. var scale = axisInfo.axis.scale;
  43456. var option = axisPointerModel.option;
  43457. var status = axisPointerModel.get('status');
  43458. var value = axisPointerModel.get('value');
  43459. // Parse init value for category and time axis.
  43460. if (value != null) {
  43461. value = scale.parse(value);
  43462. }
  43463. var useHandle = isHandleTrigger(axisPointerModel);
  43464. // If `handle` used, `axisPointer` will always be displayed, so value
  43465. // and status should be initialized.
  43466. if (status == null) {
  43467. option.status = useHandle ? 'show' : 'hide';
  43468. }
  43469. var extent = scale.getExtent().slice();
  43470. extent[0] > extent[1] && extent.reverse();
  43471. if (
  43472. // Pick a value on axis when initializing.
  43473. value == null
  43474. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  43475. // where we should re-pick a value to keep `handle` displaying normally.
  43476. || value > extent[1]) {
  43477. // Make handle displayed on the end of the axis when init, which looks better.
  43478. value = extent[1];
  43479. }
  43480. if (value < extent[0]) {
  43481. value = extent[0];
  43482. }
  43483. option.value = value;
  43484. if (useHandle) {
  43485. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  43486. }
  43487. }
  43488. function getAxisInfo(axisModel) {
  43489. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  43490. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  43491. }
  43492. function getAxisPointerModel(axisModel) {
  43493. var axisInfo = getAxisInfo(axisModel);
  43494. return axisInfo && axisInfo.axisPointerModel;
  43495. }
  43496. function isHandleTrigger(axisPointerModel) {
  43497. return !!axisPointerModel.get(['handle', 'show']);
  43498. }
  43499. /**
  43500. * @param {module:echarts/model/Model} model
  43501. * @return {string} unique key
  43502. */
  43503. function makeKey(model) {
  43504. return model.type + '||' + model.id;
  43505. }
  43506. var axisPointerClazz = {};
  43507. /**
  43508. * Base class of AxisView.
  43509. */
  43510. var AxisView = /** @class */function (_super) {
  43511. __extends(AxisView, _super);
  43512. function AxisView() {
  43513. var _this = _super !== null && _super.apply(this, arguments) || this;
  43514. _this.type = AxisView.type;
  43515. return _this;
  43516. }
  43517. /**
  43518. * @override
  43519. */
  43520. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43521. // FIXME
  43522. // This process should proformed after coordinate systems updated
  43523. // (axis scale updated), and should be performed each time update.
  43524. // So put it here temporarily, although it is not appropriate to
  43525. // put a model-writing procedure in `view`.
  43526. this.axisPointerClass && fixValue(axisModel);
  43527. _super.prototype.render.apply(this, arguments);
  43528. this._doUpdateAxisPointerClass(axisModel, api, true);
  43529. };
  43530. /**
  43531. * Action handler.
  43532. */
  43533. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  43534. this._doUpdateAxisPointerClass(axisModel, api, false);
  43535. };
  43536. /**
  43537. * @override
  43538. */
  43539. AxisView.prototype.remove = function (ecModel, api) {
  43540. var axisPointer = this._axisPointer;
  43541. axisPointer && axisPointer.remove(api);
  43542. };
  43543. /**
  43544. * @override
  43545. */
  43546. AxisView.prototype.dispose = function (ecModel, api) {
  43547. this._disposeAxisPointer(api);
  43548. _super.prototype.dispose.apply(this, arguments);
  43549. };
  43550. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  43551. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  43552. if (!Clazz) {
  43553. return;
  43554. }
  43555. var axisPointerModel = getAxisPointerModel(axisModel);
  43556. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  43557. };
  43558. AxisView.prototype._disposeAxisPointer = function (api) {
  43559. this._axisPointer && this._axisPointer.dispose(api);
  43560. this._axisPointer = null;
  43561. };
  43562. AxisView.registerAxisPointerClass = function (type, clazz) {
  43563. if ("development" !== 'production') {
  43564. if (axisPointerClazz[type]) {
  43565. throw new Error('axisPointer ' + type + ' exists');
  43566. }
  43567. }
  43568. axisPointerClazz[type] = clazz;
  43569. };
  43570. AxisView.getAxisPointerClass = function (type) {
  43571. return type && axisPointerClazz[type];
  43572. };
  43573. AxisView.type = 'axis';
  43574. return AxisView;
  43575. }(ComponentView);
  43576. var inner$6 = makeInner();
  43577. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  43578. var axis = axisModel.axis;
  43579. if (axis.scale.isBlank()) {
  43580. return;
  43581. }
  43582. // TODO: TYPE
  43583. var splitAreaModel = axisModel.getModel('splitArea');
  43584. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  43585. var areaColors = areaStyleModel.get('color');
  43586. var gridRect = gridModel.coordinateSystem.getRect();
  43587. var ticksCoords = axis.getTicksCoords({
  43588. tickModel: splitAreaModel,
  43589. clamp: true
  43590. });
  43591. if (!ticksCoords.length) {
  43592. return;
  43593. }
  43594. // For Making appropriate splitArea animation, the color and anid
  43595. // should be corresponding to previous one if possible.
  43596. var areaColorsLen = areaColors.length;
  43597. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  43598. var newSplitAreaColors = createHashMap();
  43599. var colorIndex = 0;
  43600. if (lastSplitAreaColors) {
  43601. for (var i = 0; i < ticksCoords.length; i++) {
  43602. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  43603. if (cIndex != null) {
  43604. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  43605. break;
  43606. }
  43607. }
  43608. }
  43609. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  43610. var areaStyle = areaStyleModel.getAreaStyle();
  43611. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  43612. for (var i = 1; i < ticksCoords.length; i++) {
  43613. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43614. var x = void 0;
  43615. var y = void 0;
  43616. var width = void 0;
  43617. var height = void 0;
  43618. if (axis.isHorizontal()) {
  43619. x = prev;
  43620. y = gridRect.y;
  43621. width = tickCoord - x;
  43622. height = gridRect.height;
  43623. prev = x + width;
  43624. } else {
  43625. x = gridRect.x;
  43626. y = prev;
  43627. width = gridRect.width;
  43628. height = tickCoord - y;
  43629. prev = y + height;
  43630. }
  43631. var tickValue = ticksCoords[i - 1].tickValue;
  43632. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  43633. axisGroup.add(new Rect({
  43634. anid: tickValue != null ? 'area_' + tickValue : null,
  43635. shape: {
  43636. x: x,
  43637. y: y,
  43638. width: width,
  43639. height: height
  43640. },
  43641. style: defaults({
  43642. fill: areaColors[colorIndex]
  43643. }, areaStyle),
  43644. autoBatch: true,
  43645. silent: true
  43646. }));
  43647. colorIndex = (colorIndex + 1) % areaColorsLen;
  43648. }
  43649. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  43650. }
  43651. function rectCoordAxisHandleRemove(axisView) {
  43652. inner$6(axisView).splitAreaColors = null;
  43653. }
  43654. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  43655. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  43656. var CartesianAxisView = /** @class */function (_super) {
  43657. __extends(CartesianAxisView, _super);
  43658. function CartesianAxisView() {
  43659. var _this = _super !== null && _super.apply(this, arguments) || this;
  43660. _this.type = CartesianAxisView.type;
  43661. _this.axisPointerClass = 'CartesianAxisPointer';
  43662. return _this;
  43663. }
  43664. /**
  43665. * @override
  43666. */
  43667. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43668. this.group.removeAll();
  43669. var oldAxisGroup = this._axisGroup;
  43670. this._axisGroup = new Group();
  43671. this.group.add(this._axisGroup);
  43672. if (!axisModel.get('show')) {
  43673. return;
  43674. }
  43675. var gridModel = axisModel.getCoordSysModel();
  43676. var layout = layout$1(gridModel, axisModel);
  43677. var axisBuilder = new AxisBuilder(axisModel, extend({
  43678. handleAutoShown: function (elementType) {
  43679. var cartesians = gridModel.coordinateSystem.getCartesians();
  43680. for (var i = 0; i < cartesians.length; i++) {
  43681. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  43682. // Still show axis tick or axisLine if other axis is value / log
  43683. return true;
  43684. }
  43685. }
  43686. // Not show axisTick or axisLine if other axis is category / time
  43687. return false;
  43688. }
  43689. }, layout));
  43690. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  43691. this._axisGroup.add(axisBuilder.getGroup());
  43692. each(selfBuilderAttrs, function (name) {
  43693. if (axisModel.get([name, 'show'])) {
  43694. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  43695. }
  43696. }, this);
  43697. // THIS is a special case for bar racing chart.
  43698. // Update the axis label from the natural initial layout to
  43699. // sorted layout should has no animation.
  43700. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  43701. if (!isInitialSortFromBarRacing) {
  43702. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  43703. }
  43704. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  43705. };
  43706. CartesianAxisView.prototype.remove = function () {
  43707. rectCoordAxisHandleRemove(this);
  43708. };
  43709. CartesianAxisView.type = 'cartesianAxis';
  43710. return CartesianAxisView;
  43711. }(AxisView);
  43712. var axisElementBuilders = {
  43713. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43714. var axis = axisModel.axis;
  43715. if (axis.scale.isBlank()) {
  43716. return;
  43717. }
  43718. var splitLineModel = axisModel.getModel('splitLine');
  43719. var lineStyleModel = splitLineModel.getModel('lineStyle');
  43720. var lineColors = lineStyleModel.get('color');
  43721. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  43722. var gridRect = gridModel.coordinateSystem.getRect();
  43723. var isHorizontal = axis.isHorizontal();
  43724. var lineCount = 0;
  43725. var ticksCoords = axis.getTicksCoords({
  43726. tickModel: splitLineModel
  43727. });
  43728. var p1 = [];
  43729. var p2 = [];
  43730. var lineStyle = lineStyleModel.getLineStyle();
  43731. for (var i = 0; i < ticksCoords.length; i++) {
  43732. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43733. if (isHorizontal) {
  43734. p1[0] = tickCoord;
  43735. p1[1] = gridRect.y;
  43736. p2[0] = tickCoord;
  43737. p2[1] = gridRect.y + gridRect.height;
  43738. } else {
  43739. p1[0] = gridRect.x;
  43740. p1[1] = tickCoord;
  43741. p2[0] = gridRect.x + gridRect.width;
  43742. p2[1] = tickCoord;
  43743. }
  43744. var colorIndex = lineCount++ % lineColors.length;
  43745. var tickValue = ticksCoords[i].tickValue;
  43746. var line = new Line({
  43747. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  43748. autoBatch: true,
  43749. shape: {
  43750. x1: p1[0],
  43751. y1: p1[1],
  43752. x2: p2[0],
  43753. y2: p2[1]
  43754. },
  43755. style: defaults({
  43756. stroke: lineColors[colorIndex]
  43757. }, lineStyle),
  43758. silent: true
  43759. });
  43760. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43761. axisGroup.add(line);
  43762. }
  43763. },
  43764. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43765. var axis = axisModel.axis;
  43766. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  43767. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  43768. var gridRect = gridModel.coordinateSystem.getRect();
  43769. var isHorizontal = axis.isHorizontal();
  43770. var minorTicksCoords = axis.getMinorTicksCoords();
  43771. if (!minorTicksCoords.length) {
  43772. return;
  43773. }
  43774. var p1 = [];
  43775. var p2 = [];
  43776. var lineStyle = lineStyleModel.getLineStyle();
  43777. for (var i = 0; i < minorTicksCoords.length; i++) {
  43778. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  43779. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  43780. if (isHorizontal) {
  43781. p1[0] = tickCoord;
  43782. p1[1] = gridRect.y;
  43783. p2[0] = tickCoord;
  43784. p2[1] = gridRect.y + gridRect.height;
  43785. } else {
  43786. p1[0] = gridRect.x;
  43787. p1[1] = tickCoord;
  43788. p2[0] = gridRect.x + gridRect.width;
  43789. p2[1] = tickCoord;
  43790. }
  43791. var line = new Line({
  43792. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  43793. autoBatch: true,
  43794. shape: {
  43795. x1: p1[0],
  43796. y1: p1[1],
  43797. x2: p2[0],
  43798. y2: p2[1]
  43799. },
  43800. style: lineStyle,
  43801. silent: true
  43802. });
  43803. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43804. axisGroup.add(line);
  43805. }
  43806. }
  43807. },
  43808. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  43809. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  43810. }
  43811. };
  43812. var CartesianXAxisView = /** @class */function (_super) {
  43813. __extends(CartesianXAxisView, _super);
  43814. function CartesianXAxisView() {
  43815. var _this = _super !== null && _super.apply(this, arguments) || this;
  43816. _this.type = CartesianXAxisView.type;
  43817. return _this;
  43818. }
  43819. CartesianXAxisView.type = 'xAxis';
  43820. return CartesianXAxisView;
  43821. }(CartesianAxisView);
  43822. var CartesianYAxisView = /** @class */function (_super) {
  43823. __extends(CartesianYAxisView, _super);
  43824. function CartesianYAxisView() {
  43825. var _this = _super !== null && _super.apply(this, arguments) || this;
  43826. _this.type = CartesianXAxisView.type;
  43827. return _this;
  43828. }
  43829. CartesianYAxisView.type = 'yAxis';
  43830. return CartesianYAxisView;
  43831. }(CartesianAxisView);
  43832. // Grid view
  43833. var GridView = /** @class */function (_super) {
  43834. __extends(GridView, _super);
  43835. function GridView() {
  43836. var _this = _super !== null && _super.apply(this, arguments) || this;
  43837. _this.type = 'grid';
  43838. return _this;
  43839. }
  43840. GridView.prototype.render = function (gridModel, ecModel) {
  43841. this.group.removeAll();
  43842. if (gridModel.get('show')) {
  43843. this.group.add(new Rect({
  43844. shape: gridModel.coordinateSystem.getRect(),
  43845. style: defaults({
  43846. fill: gridModel.get('backgroundColor')
  43847. }, gridModel.getItemStyle()),
  43848. silent: true,
  43849. z2: -1
  43850. }));
  43851. }
  43852. };
  43853. GridView.type = 'grid';
  43854. return GridView;
  43855. }(ComponentView);
  43856. var extraOption = {
  43857. // gridIndex: 0,
  43858. // gridId: '',
  43859. offset: 0
  43860. };
  43861. function install$5(registers) {
  43862. registers.registerComponentView(GridView);
  43863. registers.registerComponentModel(GridModel);
  43864. registers.registerCoordinateSystem('cartesian2d', Grid);
  43865. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  43866. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  43867. registers.registerComponentView(CartesianXAxisView);
  43868. registers.registerComponentView(CartesianYAxisView);
  43869. registers.registerPreprocessor(function (option) {
  43870. // Only create grid when need
  43871. if (option.xAxis && option.yAxis && !option.grid) {
  43872. option.grid = {};
  43873. }
  43874. });
  43875. }
  43876. function install$6(registers) {
  43877. // In case developer forget to include grid component
  43878. use(install$5);
  43879. registers.registerSeriesModel(ScatterSeriesModel);
  43880. registers.registerChartView(ScatterView);
  43881. registers.registerLayout(pointsLayout('scatter'));
  43882. }
  43883. var inner$7 = makeInner();
  43884. var clone$3 = clone;
  43885. var bind$1 = bind;
  43886. /**
  43887. * Base axis pointer class in 2D.
  43888. */
  43889. var BaseAxisPointer = /** @class */function () {
  43890. function BaseAxisPointer() {
  43891. this._dragging = false;
  43892. /**
  43893. * In px, arbitrary value. Do not set too small,
  43894. * no animation is ok for most cases.
  43895. */
  43896. this.animationThreshold = 15;
  43897. }
  43898. /**
  43899. * @implement
  43900. */
  43901. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  43902. var value = axisPointerModel.get('value');
  43903. var status = axisPointerModel.get('status');
  43904. // Bind them to `this`, not in closure, otherwise they will not
  43905. // be replaced when user calling setOption in not merge mode.
  43906. this._axisModel = axisModel;
  43907. this._axisPointerModel = axisPointerModel;
  43908. this._api = api;
  43909. // Optimize: `render` will be called repeatedly during mouse move.
  43910. // So it is power consuming if performing `render` each time,
  43911. // especially on mobile device.
  43912. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  43913. return;
  43914. }
  43915. this._lastValue = value;
  43916. this._lastStatus = status;
  43917. var group = this._group;
  43918. var handle = this._handle;
  43919. if (!status || status === 'hide') {
  43920. // Do not clear here, for animation better.
  43921. group && group.hide();
  43922. handle && handle.hide();
  43923. return;
  43924. }
  43925. group && group.show();
  43926. handle && handle.show();
  43927. // Otherwise status is 'show'
  43928. var elOption = {};
  43929. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  43930. // Enable change axis pointer type.
  43931. var graphicKey = elOption.graphicKey;
  43932. if (graphicKey !== this._lastGraphicKey) {
  43933. this.clear(api);
  43934. }
  43935. this._lastGraphicKey = graphicKey;
  43936. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  43937. if (!group) {
  43938. group = this._group = new Group();
  43939. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  43940. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  43941. api.getZr().add(group);
  43942. } else {
  43943. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  43944. this.updatePointerEl(group, elOption, doUpdateProps);
  43945. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  43946. }
  43947. updateMandatoryProps(group, axisPointerModel, true);
  43948. this._renderHandle(value);
  43949. };
  43950. /**
  43951. * @implement
  43952. */
  43953. BaseAxisPointer.prototype.remove = function (api) {
  43954. this.clear(api);
  43955. };
  43956. /**
  43957. * @implement
  43958. */
  43959. BaseAxisPointer.prototype.dispose = function (api) {
  43960. this.clear(api);
  43961. };
  43962. /**
  43963. * @protected
  43964. */
  43965. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  43966. var animation = axisPointerModel.get('animation');
  43967. var axis = axisModel.axis;
  43968. var isCategoryAxis = axis.type === 'category';
  43969. var useSnap = axisPointerModel.get('snap');
  43970. // Value axis without snap always do not snap.
  43971. if (!useSnap && !isCategoryAxis) {
  43972. return false;
  43973. }
  43974. if (animation === 'auto' || animation == null) {
  43975. var animationThreshold = this.animationThreshold;
  43976. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  43977. return true;
  43978. }
  43979. // It is important to auto animation when snap used. Consider if there is
  43980. // a dataZoom, animation will be disabled when too many points exist, while
  43981. // it will be enabled for better visual effect when little points exist.
  43982. if (useSnap) {
  43983. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  43984. var axisExtent = axis.getExtent();
  43985. // Approximate band width
  43986. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  43987. }
  43988. return false;
  43989. }
  43990. return animation === true;
  43991. };
  43992. /**
  43993. * add {pointer, label, graphicKey} to elOption
  43994. * @protected
  43995. */
  43996. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  43997. // Should be implemenented by sub-class.
  43998. };
  43999. /**
  44000. * @protected
  44001. */
  44002. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  44003. var pointerOption = elOption.pointer;
  44004. if (pointerOption) {
  44005. var pointerEl = inner$7(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  44006. group.add(pointerEl);
  44007. }
  44008. };
  44009. /**
  44010. * @protected
  44011. */
  44012. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  44013. if (elOption.label) {
  44014. var labelEl = inner$7(group).labelEl = new ZRText(clone$3(elOption.label));
  44015. group.add(labelEl);
  44016. updateLabelShowHide(labelEl, axisPointerModel);
  44017. }
  44018. };
  44019. /**
  44020. * @protected
  44021. */
  44022. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  44023. var pointerEl = inner$7(group).pointerEl;
  44024. if (pointerEl && elOption.pointer) {
  44025. pointerEl.setStyle(elOption.pointer.style);
  44026. updateProps(pointerEl, {
  44027. shape: elOption.pointer.shape
  44028. });
  44029. }
  44030. };
  44031. /**
  44032. * @protected
  44033. */
  44034. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  44035. var labelEl = inner$7(group).labelEl;
  44036. if (labelEl) {
  44037. labelEl.setStyle(elOption.label.style);
  44038. updateProps(labelEl, {
  44039. // Consider text length change in vertical axis, animation should
  44040. // be used on shape, otherwise the effect will be weird.
  44041. // TODOTODO
  44042. // shape: elOption.label.shape,
  44043. x: elOption.label.x,
  44044. y: elOption.label.y
  44045. });
  44046. updateLabelShowHide(labelEl, axisPointerModel);
  44047. }
  44048. };
  44049. /**
  44050. * @private
  44051. */
  44052. BaseAxisPointer.prototype._renderHandle = function (value) {
  44053. if (this._dragging || !this.updateHandleTransform) {
  44054. return;
  44055. }
  44056. var axisPointerModel = this._axisPointerModel;
  44057. var zr = this._api.getZr();
  44058. var handle = this._handle;
  44059. var handleModel = axisPointerModel.getModel('handle');
  44060. var status = axisPointerModel.get('status');
  44061. if (!handleModel.get('show') || !status || status === 'hide') {
  44062. handle && zr.remove(handle);
  44063. this._handle = null;
  44064. return;
  44065. }
  44066. var isInit;
  44067. if (!this._handle) {
  44068. isInit = true;
  44069. handle = this._handle = createIcon(handleModel.get('icon'), {
  44070. cursor: 'move',
  44071. draggable: true,
  44072. onmousemove: function (e) {
  44073. // For mobile device, prevent screen slider on the button.
  44074. stop(e.event);
  44075. },
  44076. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  44077. drift: bind$1(this._onHandleDragMove, this),
  44078. ondragend: bind$1(this._onHandleDragEnd, this)
  44079. });
  44080. zr.add(handle);
  44081. }
  44082. updateMandatoryProps(handle, axisPointerModel, false);
  44083. // update style
  44084. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY']));
  44085. // update position
  44086. var handleSize = handleModel.get('size');
  44087. if (!isArray(handleSize)) {
  44088. handleSize = [handleSize, handleSize];
  44089. }
  44090. handle.scaleX = handleSize[0] / 2;
  44091. handle.scaleY = handleSize[1] / 2;
  44092. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  44093. this._moveHandleToValue(value, isInit);
  44094. };
  44095. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  44096. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  44097. };
  44098. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  44099. var handle = this._handle;
  44100. if (!handle) {
  44101. return;
  44102. }
  44103. this._dragging = true;
  44104. // Persistent for throttle.
  44105. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  44106. this._payloadInfo = trans;
  44107. handle.stopAnimation();
  44108. handle.attr(getHandleTransProps(trans));
  44109. inner$7(handle).lastProp = null;
  44110. this._doDispatchAxisPointer();
  44111. };
  44112. /**
  44113. * Throttled method.
  44114. */
  44115. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  44116. var handle = this._handle;
  44117. if (!handle) {
  44118. return;
  44119. }
  44120. var payloadInfo = this._payloadInfo;
  44121. var axisModel = this._axisModel;
  44122. this._api.dispatchAction({
  44123. type: 'updateAxisPointer',
  44124. x: payloadInfo.cursorPoint[0],
  44125. y: payloadInfo.cursorPoint[1],
  44126. tooltipOption: payloadInfo.tooltipOption,
  44127. axesInfo: [{
  44128. axisDim: axisModel.axis.dim,
  44129. axisIndex: axisModel.componentIndex
  44130. }]
  44131. });
  44132. };
  44133. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  44134. this._dragging = false;
  44135. var handle = this._handle;
  44136. if (!handle) {
  44137. return;
  44138. }
  44139. var value = this._axisPointerModel.get('value');
  44140. // Consider snap or categroy axis, handle may be not consistent with
  44141. // axisPointer. So move handle to align the exact value position when
  44142. // drag ended.
  44143. this._moveHandleToValue(value);
  44144. // For the effect: tooltip will be shown when finger holding on handle
  44145. // button, and will be hidden after finger left handle button.
  44146. this._api.dispatchAction({
  44147. type: 'hideTip'
  44148. });
  44149. };
  44150. /**
  44151. * @private
  44152. */
  44153. BaseAxisPointer.prototype.clear = function (api) {
  44154. this._lastValue = null;
  44155. this._lastStatus = null;
  44156. var zr = api.getZr();
  44157. var group = this._group;
  44158. var handle = this._handle;
  44159. if (zr && group) {
  44160. this._lastGraphicKey = null;
  44161. group && zr.remove(group);
  44162. handle && zr.remove(handle);
  44163. this._group = null;
  44164. this._handle = null;
  44165. this._payloadInfo = null;
  44166. }
  44167. clear(this, '_doDispatchAxisPointer');
  44168. };
  44169. /**
  44170. * @protected
  44171. */
  44172. BaseAxisPointer.prototype.doClear = function () {
  44173. // Implemented by sub-class if necessary.
  44174. };
  44175. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  44176. xDimIndex = xDimIndex || 0;
  44177. return {
  44178. x: xy[xDimIndex],
  44179. y: xy[1 - xDimIndex],
  44180. width: wh[xDimIndex],
  44181. height: wh[1 - xDimIndex]
  44182. };
  44183. };
  44184. return BaseAxisPointer;
  44185. }();
  44186. function updateProps$1(animationModel, moveAnimation, el, props) {
  44187. // Animation optimize.
  44188. if (!propsEqual(inner$7(el).lastProp, props)) {
  44189. inner$7(el).lastProp = props;
  44190. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  44191. }
  44192. }
  44193. function propsEqual(lastProps, newProps) {
  44194. if (isObject(lastProps) && isObject(newProps)) {
  44195. var equals_1 = true;
  44196. each(newProps, function (item, key) {
  44197. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  44198. });
  44199. return !!equals_1;
  44200. } else {
  44201. return lastProps === newProps;
  44202. }
  44203. }
  44204. function updateLabelShowHide(labelEl, axisPointerModel) {
  44205. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  44206. }
  44207. function getHandleTransProps(trans) {
  44208. return {
  44209. x: trans.x || 0,
  44210. y: trans.y || 0,
  44211. rotation: trans.rotation || 0
  44212. };
  44213. }
  44214. function updateMandatoryProps(group, axisPointerModel, silent) {
  44215. var z = axisPointerModel.get('z');
  44216. var zlevel = axisPointerModel.get('zlevel');
  44217. group && group.traverse(function (el) {
  44218. if (el.type !== 'group') {
  44219. z != null && (el.z = z);
  44220. zlevel != null && (el.zlevel = zlevel);
  44221. el.silent = silent;
  44222. }
  44223. });
  44224. }
  44225. function buildElStyle(axisPointerModel) {
  44226. var axisPointerType = axisPointerModel.get('type');
  44227. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  44228. var style;
  44229. if (axisPointerType === 'line') {
  44230. style = styleModel.getLineStyle();
  44231. style.fill = null;
  44232. } else if (axisPointerType === 'shadow') {
  44233. style = styleModel.getAreaStyle();
  44234. style.stroke = null;
  44235. }
  44236. return style;
  44237. }
  44238. /**
  44239. * @param {Function} labelPos {align, verticalAlign, position}
  44240. */
  44241. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  44242. var value = axisPointerModel.get('value');
  44243. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  44244. precision: axisPointerModel.get(['label', 'precision']),
  44245. formatter: axisPointerModel.get(['label', 'formatter'])
  44246. });
  44247. var labelModel = axisPointerModel.getModel('label');
  44248. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  44249. var font = labelModel.getFont();
  44250. var textRect = getBoundingRect(text, font);
  44251. var position = labelPos.position;
  44252. var width = textRect.width + paddings[1] + paddings[3];
  44253. var height = textRect.height + paddings[0] + paddings[2];
  44254. // Adjust by align.
  44255. var align = labelPos.align;
  44256. align === 'right' && (position[0] -= width);
  44257. align === 'center' && (position[0] -= width / 2);
  44258. var verticalAlign = labelPos.verticalAlign;
  44259. verticalAlign === 'bottom' && (position[1] -= height);
  44260. verticalAlign === 'middle' && (position[1] -= height / 2);
  44261. // Not overflow ec container
  44262. confineInContainer(position, width, height, api);
  44263. var bgColor = labelModel.get('backgroundColor');
  44264. if (!bgColor || bgColor === 'auto') {
  44265. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  44266. }
  44267. elOption.label = {
  44268. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  44269. x: position[0],
  44270. y: position[1],
  44271. style: createTextStyle(labelModel, {
  44272. text: text,
  44273. font: font,
  44274. fill: labelModel.getTextColor(),
  44275. padding: paddings,
  44276. backgroundColor: bgColor
  44277. }),
  44278. // Label should be over axisPointer.
  44279. z2: 10
  44280. };
  44281. }
  44282. // Do not overflow ec container
  44283. function confineInContainer(position, width, height, api) {
  44284. var viewWidth = api.getWidth();
  44285. var viewHeight = api.getHeight();
  44286. position[0] = Math.min(position[0] + width, viewWidth) - width;
  44287. position[1] = Math.min(position[1] + height, viewHeight) - height;
  44288. position[0] = Math.max(position[0], 0);
  44289. position[1] = Math.max(position[1], 0);
  44290. }
  44291. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  44292. value = axis.scale.parse(value);
  44293. var text = axis.scale.getLabel({
  44294. value: value
  44295. }, {
  44296. // If `precision` is set, width can be fixed (like '12.00500'), which
  44297. // helps to debounce when when moving label.
  44298. precision: opt.precision
  44299. });
  44300. var formatter = opt.formatter;
  44301. if (formatter) {
  44302. var params_1 = {
  44303. value: getAxisRawValue(axis, {
  44304. value: value
  44305. }),
  44306. axisDimension: axis.dim,
  44307. axisIndex: axis.index,
  44308. seriesData: []
  44309. };
  44310. each(seriesDataIndices, function (idxItem) {
  44311. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  44312. var dataIndex = idxItem.dataIndexInside;
  44313. var dataParams = series && series.getDataParams(dataIndex);
  44314. dataParams && params_1.seriesData.push(dataParams);
  44315. });
  44316. if (isString(formatter)) {
  44317. text = formatter.replace('{value}', text);
  44318. } else if (isFunction(formatter)) {
  44319. text = formatter(params_1);
  44320. }
  44321. }
  44322. return text;
  44323. }
  44324. function getTransformedPosition(axis, value, layoutInfo) {
  44325. var transform = create$1();
  44326. rotate(transform, transform, layoutInfo.rotation);
  44327. translate(transform, transform, layoutInfo.position);
  44328. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  44329. }
  44330. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  44331. // @ts-ignore
  44332. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  44333. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  44334. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  44335. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  44336. align: textLayout.textAlign,
  44337. verticalAlign: textLayout.textVerticalAlign
  44338. });
  44339. }
  44340. function makeLineShape(p1, p2, xDimIndex) {
  44341. xDimIndex = xDimIndex || 0;
  44342. return {
  44343. x1: p1[xDimIndex],
  44344. y1: p1[1 - xDimIndex],
  44345. x2: p2[xDimIndex],
  44346. y2: p2[1 - xDimIndex]
  44347. };
  44348. }
  44349. function makeRectShape(xy, wh, xDimIndex) {
  44350. xDimIndex = xDimIndex || 0;
  44351. return {
  44352. x: xy[xDimIndex],
  44353. y: xy[1 - xDimIndex],
  44354. width: wh[xDimIndex],
  44355. height: wh[1 - xDimIndex]
  44356. };
  44357. }
  44358. var CartesianAxisPointer = /** @class */function (_super) {
  44359. __extends(CartesianAxisPointer, _super);
  44360. function CartesianAxisPointer() {
  44361. return _super !== null && _super.apply(this, arguments) || this;
  44362. }
  44363. /**
  44364. * @override
  44365. */
  44366. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  44367. var axis = axisModel.axis;
  44368. var grid = axis.grid;
  44369. var axisPointerType = axisPointerModel.get('type');
  44370. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  44371. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  44372. if (axisPointerType && axisPointerType !== 'none') {
  44373. var elStyle = buildElStyle(axisPointerModel);
  44374. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  44375. pointerOption.style = elStyle;
  44376. elOption.graphicKey = pointerOption.type;
  44377. elOption.pointer = pointerOption;
  44378. }
  44379. var layoutInfo = layout$1(grid.model, axisModel);
  44380. buildCartesianSingleLabelElOption(
  44381. // @ts-ignore
  44382. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  44383. };
  44384. /**
  44385. * @override
  44386. */
  44387. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  44388. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  44389. labelInside: false
  44390. });
  44391. // @ts-ignore
  44392. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  44393. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  44394. return {
  44395. x: pos[0],
  44396. y: pos[1],
  44397. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  44398. };
  44399. };
  44400. /**
  44401. * @override
  44402. */
  44403. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  44404. var axis = axisModel.axis;
  44405. var grid = axis.grid;
  44406. var axisExtent = axis.getGlobalExtent(true);
  44407. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  44408. var dimIndex = axis.dim === 'x' ? 0 : 1;
  44409. var currPosition = [transform.x, transform.y];
  44410. currPosition[dimIndex] += delta[dimIndex];
  44411. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  44412. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  44413. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  44414. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  44415. cursorPoint[dimIndex] = currPosition[dimIndex];
  44416. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  44417. var tooltipOptions = [{
  44418. verticalAlign: 'middle'
  44419. }, {
  44420. align: 'center'
  44421. }];
  44422. return {
  44423. x: currPosition[0],
  44424. y: currPosition[1],
  44425. rotation: transform.rotation,
  44426. cursorPoint: cursorPoint,
  44427. tooltipOption: tooltipOptions[dimIndex]
  44428. };
  44429. };
  44430. return CartesianAxisPointer;
  44431. }(BaseAxisPointer);
  44432. function getCartesian(grid, axis) {
  44433. var opt = {};
  44434. opt[axis.dim + 'AxisIndex'] = axis.index;
  44435. return grid.getCartesian(opt);
  44436. }
  44437. var pointerShapeBuilder = {
  44438. line: function (axis, pixelValue, otherExtent) {
  44439. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  44440. return {
  44441. type: 'Line',
  44442. subPixelOptimize: true,
  44443. shape: targetShape
  44444. };
  44445. },
  44446. shadow: function (axis, pixelValue, otherExtent) {
  44447. var bandWidth = Math.max(1, axis.getBandWidth());
  44448. var span = otherExtent[1] - otherExtent[0];
  44449. return {
  44450. type: 'Rect',
  44451. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  44452. };
  44453. }
  44454. };
  44455. function getAxisDimIndex(axis) {
  44456. return axis.dim === 'x' ? 0 : 1;
  44457. }
  44458. var AxisPointerModel = /** @class */function (_super) {
  44459. __extends(AxisPointerModel, _super);
  44460. function AxisPointerModel() {
  44461. var _this = _super !== null && _super.apply(this, arguments) || this;
  44462. _this.type = AxisPointerModel.type;
  44463. return _this;
  44464. }
  44465. AxisPointerModel.type = 'axisPointer';
  44466. AxisPointerModel.defaultOption = {
  44467. // 'auto' means that show when triggered by tooltip or handle.
  44468. show: 'auto',
  44469. // zlevel: 0,
  44470. z: 50,
  44471. type: 'line',
  44472. // axispointer triggered by tootip determine snap automatically,
  44473. // see `modelHelper`.
  44474. snap: false,
  44475. triggerTooltip: true,
  44476. triggerEmphasis: true,
  44477. value: null,
  44478. status: null,
  44479. link: [],
  44480. // Do not set 'auto' here, otherwise global animation: false
  44481. // will not effect at this axispointer.
  44482. animation: null,
  44483. animationDurationUpdate: 200,
  44484. lineStyle: {
  44485. color: '#B9BEC9',
  44486. width: 1,
  44487. type: 'dashed'
  44488. },
  44489. shadowStyle: {
  44490. color: 'rgba(210,219,238,0.2)'
  44491. },
  44492. label: {
  44493. show: true,
  44494. formatter: null,
  44495. precision: 'auto',
  44496. margin: 3,
  44497. color: '#fff',
  44498. padding: [5, 7, 5, 7],
  44499. backgroundColor: 'auto',
  44500. borderColor: null,
  44501. borderWidth: 0,
  44502. borderRadius: 3
  44503. },
  44504. handle: {
  44505. show: false,
  44506. // eslint-disable-next-line
  44507. 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',
  44508. size: 45,
  44509. // handle margin is from symbol center to axis, which is stable when circular move.
  44510. margin: 50,
  44511. // color: '#1b8bbd'
  44512. // color: '#2f4554'
  44513. color: '#333',
  44514. shadowBlur: 3,
  44515. shadowColor: '#aaa',
  44516. shadowOffsetX: 0,
  44517. shadowOffsetY: 2,
  44518. // For mobile performance
  44519. throttle: 40
  44520. }
  44521. };
  44522. return AxisPointerModel;
  44523. }(ComponentModel);
  44524. var inner$8 = makeInner();
  44525. var each$3 = each;
  44526. /**
  44527. * @param {string} key
  44528. * @param {module:echarts/ExtensionAPI} api
  44529. * @param {Function} handler
  44530. * param: {string} currTrigger
  44531. * param: {Array.<number>} point
  44532. */
  44533. function register(key, api, handler) {
  44534. if (env.node) {
  44535. return;
  44536. }
  44537. var zr = api.getZr();
  44538. inner$8(zr).records || (inner$8(zr).records = {});
  44539. initGlobalListeners(zr, api);
  44540. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  44541. record.handler = handler;
  44542. }
  44543. function initGlobalListeners(zr, api) {
  44544. if (inner$8(zr).initialized) {
  44545. return;
  44546. }
  44547. inner$8(zr).initialized = true;
  44548. useHandler('click', curry(doEnter, 'click'));
  44549. useHandler('mousemove', curry(doEnter, 'mousemove'));
  44550. // useHandler('mouseout', onLeave);
  44551. useHandler('globalout', onLeave);
  44552. function useHandler(eventType, cb) {
  44553. zr.on(eventType, function (e) {
  44554. var dis = makeDispatchAction(api);
  44555. each$3(inner$8(zr).records, function (record) {
  44556. record && cb(record, e, dis.dispatchAction);
  44557. });
  44558. dispatchTooltipFinally(dis.pendings, api);
  44559. });
  44560. }
  44561. }
  44562. function dispatchTooltipFinally(pendings, api) {
  44563. var showLen = pendings.showTip.length;
  44564. var hideLen = pendings.hideTip.length;
  44565. var actuallyPayload;
  44566. if (showLen) {
  44567. actuallyPayload = pendings.showTip[showLen - 1];
  44568. } else if (hideLen) {
  44569. actuallyPayload = pendings.hideTip[hideLen - 1];
  44570. }
  44571. if (actuallyPayload) {
  44572. actuallyPayload.dispatchAction = null;
  44573. api.dispatchAction(actuallyPayload);
  44574. }
  44575. }
  44576. function onLeave(record, e, dispatchAction) {
  44577. record.handler('leave', null, dispatchAction);
  44578. }
  44579. function doEnter(currTrigger, record, e, dispatchAction) {
  44580. record.handler(currTrigger, e, dispatchAction);
  44581. }
  44582. function makeDispatchAction(api) {
  44583. var pendings = {
  44584. showTip: [],
  44585. hideTip: []
  44586. };
  44587. // FIXME
  44588. // better approach?
  44589. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  44590. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  44591. // So we have to add "final stage" to merge those dispatched actions.
  44592. var dispatchAction = function (payload) {
  44593. var pendingList = pendings[payload.type];
  44594. if (pendingList) {
  44595. pendingList.push(payload);
  44596. } else {
  44597. payload.dispatchAction = dispatchAction;
  44598. api.dispatchAction(payload);
  44599. }
  44600. };
  44601. return {
  44602. dispatchAction: dispatchAction,
  44603. pendings: pendings
  44604. };
  44605. }
  44606. function unregister(key, api) {
  44607. if (env.node) {
  44608. return;
  44609. }
  44610. var zr = api.getZr();
  44611. var record = (inner$8(zr).records || {})[key];
  44612. if (record) {
  44613. inner$8(zr).records[key] = null;
  44614. }
  44615. }
  44616. var AxisPointerView = /** @class */function (_super) {
  44617. __extends(AxisPointerView, _super);
  44618. function AxisPointerView() {
  44619. var _this = _super !== null && _super.apply(this, arguments) || this;
  44620. _this.type = AxisPointerView.type;
  44621. return _this;
  44622. }
  44623. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  44624. var globalTooltipModel = ecModel.getComponent('tooltip');
  44625. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click';
  44626. // Register global listener in AxisPointerView to enable
  44627. // AxisPointerView to be independent to Tooltip.
  44628. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  44629. // If 'none', it is not controlled by mouse totally.
  44630. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  44631. dispatchAction({
  44632. type: 'updateAxisPointer',
  44633. currTrigger: currTrigger,
  44634. x: e && e.offsetX,
  44635. y: e && e.offsetY
  44636. });
  44637. }
  44638. });
  44639. };
  44640. AxisPointerView.prototype.remove = function (ecModel, api) {
  44641. unregister('axisPointer', api);
  44642. };
  44643. AxisPointerView.prototype.dispose = function (ecModel, api) {
  44644. unregister('axisPointer', api);
  44645. };
  44646. AxisPointerView.type = 'axisPointer';
  44647. return AxisPointerView;
  44648. }(ComponentView);
  44649. /**
  44650. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  44651. * @param ecModel
  44652. * @return {point: [x, y], el: ...} point Will not be null.
  44653. */
  44654. function findPointFromSeries(finder, ecModel) {
  44655. var point = [];
  44656. var seriesIndex = finder.seriesIndex;
  44657. var seriesModel;
  44658. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  44659. return {
  44660. point: []
  44661. };
  44662. }
  44663. var data = seriesModel.getData();
  44664. var dataIndex = queryDataIndex(data, finder);
  44665. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  44666. return {
  44667. point: []
  44668. };
  44669. }
  44670. var el = data.getItemGraphicEl(dataIndex);
  44671. var coordSys = seriesModel.coordinateSystem;
  44672. if (seriesModel.getTooltipPosition) {
  44673. point = seriesModel.getTooltipPosition(dataIndex) || [];
  44674. } else if (coordSys && coordSys.dataToPoint) {
  44675. if (finder.isStacked) {
  44676. var baseAxis = coordSys.getBaseAxis();
  44677. var valueAxis = coordSys.getOtherAxis(baseAxis);
  44678. var valueAxisDim = valueAxis.dim;
  44679. var baseAxisDim = baseAxis.dim;
  44680. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  44681. var baseDim = data.mapDimension(baseAxisDim);
  44682. var stackedData = [];
  44683. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  44684. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  44685. point = coordSys.dataToPoint(stackedData) || [];
  44686. } else {
  44687. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  44688. return data.mapDimension(dim);
  44689. }), dataIndex)) || [];
  44690. }
  44691. } else if (el) {
  44692. // Use graphic bounding rect
  44693. var rect = el.getBoundingRect().clone();
  44694. rect.applyTransform(el.transform);
  44695. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  44696. }
  44697. return {
  44698. point: point,
  44699. el: el
  44700. };
  44701. }
  44702. var inner$9 = makeInner();
  44703. /**
  44704. * Basic logic: check all axis, if they do not demand show/highlight,
  44705. * then hide/downplay them.
  44706. *
  44707. * @return content of event obj for echarts.connect.
  44708. */
  44709. function axisTrigger(payload, ecModel, api) {
  44710. var currTrigger = payload.currTrigger;
  44711. var point = [payload.x, payload.y];
  44712. var finder = payload;
  44713. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  44714. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  44715. // Pending
  44716. // See #6121. But we are not able to reproduce it yet.
  44717. if (!coordSysAxesInfo) {
  44718. return;
  44719. }
  44720. if (illegalPoint(point)) {
  44721. // Used in the default behavior of `connection`: use the sample seriesIndex
  44722. // and dataIndex. And also used in the tooltipView trigger.
  44723. point = findPointFromSeries({
  44724. seriesIndex: finder.seriesIndex,
  44725. // Do not use dataIndexInside from other ec instance.
  44726. // FIXME: auto detect it?
  44727. dataIndex: finder.dataIndex
  44728. }, ecModel).point;
  44729. }
  44730. var isIllegalPoint = illegalPoint(point);
  44731. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  44732. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  44733. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  44734. // and dataIndex.
  44735. var inputAxesInfo = finder.axesInfo;
  44736. var axesInfo = coordSysAxesInfo.axesInfo;
  44737. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  44738. var outputPayload = {};
  44739. var showValueMap = {};
  44740. var dataByCoordSys = {
  44741. list: [],
  44742. map: {}
  44743. };
  44744. var updaters = {
  44745. showPointer: curry(showPointer, showValueMap),
  44746. showTooltip: curry(showTooltip, dataByCoordSys)
  44747. };
  44748. // Process for triggered axes.
  44749. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  44750. // If a point given, it must be contained by the coordinate system.
  44751. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  44752. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  44753. var axis = axisInfo.axis;
  44754. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  44755. // If no inputAxesInfo, no axis is restricted.
  44756. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  44757. var val = inputAxisInfo && inputAxisInfo.value;
  44758. if (val == null && !isIllegalPoint) {
  44759. val = axis.pointToData(point);
  44760. }
  44761. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  44762. }
  44763. });
  44764. });
  44765. // Process for linked axes.
  44766. var linkTriggers = {};
  44767. each(axesInfo, function (tarAxisInfo, tarKey) {
  44768. var linkGroup = tarAxisInfo.linkGroup;
  44769. // If axis has been triggered in the previous stage, it should not be triggered by link.
  44770. if (linkGroup && !showValueMap[tarKey]) {
  44771. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  44772. var srcValItem = showValueMap[srcKey];
  44773. // If srcValItem exist, source axis is triggered, so link to target axis.
  44774. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  44775. var val = srcValItem.value;
  44776. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  44777. linkTriggers[tarAxisInfo.key] = val;
  44778. }
  44779. });
  44780. }
  44781. });
  44782. each(linkTriggers, function (val, tarKey) {
  44783. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  44784. });
  44785. updateModelActually(showValueMap, axesInfo, outputPayload);
  44786. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  44787. dispatchHighDownActually(axesInfo, dispatchAction, api);
  44788. return outputPayload;
  44789. }
  44790. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  44791. var axis = axisInfo.axis;
  44792. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  44793. return;
  44794. }
  44795. if (!axisInfo.involveSeries) {
  44796. updaters.showPointer(axisInfo, newValue);
  44797. return;
  44798. }
  44799. // Heavy calculation. So put it after axis.containData checking.
  44800. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  44801. var payloadBatch = payloadInfo.payloadBatch;
  44802. var snapToValue = payloadInfo.snapToValue;
  44803. // Fill content of event obj for echarts.connect.
  44804. // By default use the first involved series data as a sample to connect.
  44805. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  44806. extend(outputFinder, payloadBatch[0]);
  44807. }
  44808. // If no linkSource input, this process is for collecting link
  44809. // target, where snap should not be accepted.
  44810. if (!noSnap && axisInfo.snap) {
  44811. if (axis.containData(snapToValue) && snapToValue != null) {
  44812. newValue = snapToValue;
  44813. }
  44814. }
  44815. updaters.showPointer(axisInfo, newValue, payloadBatch);
  44816. // Tooltip should always be snapToValue, otherwise there will be
  44817. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  44818. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  44819. }
  44820. function buildPayloadsBySeries(value, axisInfo) {
  44821. var axis = axisInfo.axis;
  44822. var dim = axis.dim;
  44823. var snapToValue = value;
  44824. var payloadBatch = [];
  44825. var minDist = Number.MAX_VALUE;
  44826. var minDiff = -1;
  44827. each(axisInfo.seriesModels, function (series, idx) {
  44828. var dataDim = series.getData().mapDimensionsAll(dim);
  44829. var seriesNestestValue;
  44830. var dataIndices;
  44831. if (series.getAxisTooltipData) {
  44832. var result = series.getAxisTooltipData(dataDim, value, axis);
  44833. dataIndices = result.dataIndices;
  44834. seriesNestestValue = result.nestestValue;
  44835. } else {
  44836. dataIndices = series.getData().indicesOfNearest(dataDim[0], value,
  44837. // Add a threshold to avoid find the wrong dataIndex
  44838. // when data length is not same.
  44839. // false,
  44840. axis.type === 'category' ? 0.5 : null);
  44841. if (!dataIndices.length) {
  44842. return;
  44843. }
  44844. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  44845. }
  44846. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  44847. return;
  44848. }
  44849. var diff = value - seriesNestestValue;
  44850. var dist = Math.abs(diff);
  44851. // Consider category case
  44852. if (dist <= minDist) {
  44853. if (dist < minDist || diff >= 0 && minDiff < 0) {
  44854. minDist = dist;
  44855. minDiff = diff;
  44856. snapToValue = seriesNestestValue;
  44857. payloadBatch.length = 0;
  44858. }
  44859. each(dataIndices, function (dataIndex) {
  44860. payloadBatch.push({
  44861. seriesIndex: series.seriesIndex,
  44862. dataIndexInside: dataIndex,
  44863. dataIndex: series.getData().getRawIndex(dataIndex)
  44864. });
  44865. });
  44866. }
  44867. });
  44868. return {
  44869. payloadBatch: payloadBatch,
  44870. snapToValue: snapToValue
  44871. };
  44872. }
  44873. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  44874. showValueMap[axisInfo.key] = {
  44875. value: value,
  44876. payloadBatch: payloadBatch
  44877. };
  44878. }
  44879. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  44880. var payloadBatch = payloadInfo.payloadBatch;
  44881. var axis = axisInfo.axis;
  44882. var axisModel = axis.model;
  44883. var axisPointerModel = axisInfo.axisPointerModel;
  44884. // If no data, do not create anything in dataByCoordSys,
  44885. // whose length will be used to judge whether dispatch action.
  44886. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  44887. return;
  44888. }
  44889. var coordSysModel = axisInfo.coordSys.model;
  44890. var coordSysKey = makeKey(coordSysModel);
  44891. var coordSysItem = dataByCoordSys.map[coordSysKey];
  44892. if (!coordSysItem) {
  44893. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  44894. coordSysId: coordSysModel.id,
  44895. coordSysIndex: coordSysModel.componentIndex,
  44896. coordSysType: coordSysModel.type,
  44897. coordSysMainType: coordSysModel.mainType,
  44898. dataByAxis: []
  44899. };
  44900. dataByCoordSys.list.push(coordSysItem);
  44901. }
  44902. coordSysItem.dataByAxis.push({
  44903. axisDim: axis.dim,
  44904. axisIndex: axisModel.componentIndex,
  44905. axisType: axisModel.type,
  44906. axisId: axisModel.id,
  44907. value: value,
  44908. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  44909. // depends that all models have been updated. So it should not be performed
  44910. // here. Considering axisPointerModel used here is volatile, which is hard
  44911. // to be retrieve in TooltipView, we prepare parameters here.
  44912. valueLabelOpt: {
  44913. precision: axisPointerModel.get(['label', 'precision']),
  44914. formatter: axisPointerModel.get(['label', 'formatter'])
  44915. },
  44916. seriesDataIndices: payloadBatch.slice()
  44917. });
  44918. }
  44919. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  44920. var outputAxesInfo = outputPayload.axesInfo = [];
  44921. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  44922. each(axesInfo, function (axisInfo, key) {
  44923. var option = axisInfo.axisPointerModel.option;
  44924. var valItem = showValueMap[key];
  44925. if (valItem) {
  44926. !axisInfo.useHandle && (option.status = 'show');
  44927. option.value = valItem.value;
  44928. // For label formatter param and highlight.
  44929. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  44930. }
  44931. // When always show (e.g., handle used), remain
  44932. // original value and status.
  44933. else {
  44934. // If hide, value still need to be set, consider
  44935. // click legend to toggle axis blank.
  44936. !axisInfo.useHandle && (option.status = 'hide');
  44937. }
  44938. // If status is 'hide', should be no info in payload.
  44939. option.status === 'show' && outputAxesInfo.push({
  44940. axisDim: axisInfo.axis.dim,
  44941. axisIndex: axisInfo.axis.model.componentIndex,
  44942. value: option.value
  44943. });
  44944. });
  44945. }
  44946. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  44947. // Basic logic: If no showTip required, hideTip will be dispatched.
  44948. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  44949. dispatchAction({
  44950. type: 'hideTip'
  44951. });
  44952. return;
  44953. }
  44954. // In most case only one axis (or event one series is used). It is
  44955. // convenient to fetch payload.seriesIndex and payload.dataIndex
  44956. // directly. So put the first seriesIndex and dataIndex of the first
  44957. // axis on the payload.
  44958. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  44959. dispatchAction({
  44960. type: 'showTip',
  44961. escapeConnect: true,
  44962. x: point[0],
  44963. y: point[1],
  44964. tooltipOption: payload.tooltipOption,
  44965. position: payload.position,
  44966. dataIndexInside: sampleItem.dataIndexInside,
  44967. dataIndex: sampleItem.dataIndex,
  44968. seriesIndex: sampleItem.seriesIndex,
  44969. dataByCoordSys: dataByCoordSys.list
  44970. });
  44971. }
  44972. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  44973. // FIXME
  44974. // highlight status modification should be a stage of main process?
  44975. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  44976. var zr = api.getZr();
  44977. var highDownKey = 'axisPointerLastHighlights';
  44978. var lastHighlights = inner$9(zr)[highDownKey] || {};
  44979. var newHighlights = inner$9(zr)[highDownKey] = {};
  44980. // Update highlight/downplay status according to axisPointer model.
  44981. // Build hash map and remove duplicate incidentally.
  44982. each(axesInfo, function (axisInfo, key) {
  44983. var option = axisInfo.axisPointerModel.option;
  44984. option.status === 'show' && axisInfo.triggerEmphasis && each(option.seriesDataIndices, function (batchItem) {
  44985. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  44986. newHighlights[key] = batchItem;
  44987. });
  44988. });
  44989. // Diff.
  44990. var toHighlight = [];
  44991. var toDownplay = [];
  44992. each(lastHighlights, function (batchItem, key) {
  44993. !newHighlights[key] && toDownplay.push(batchItem);
  44994. });
  44995. each(newHighlights, function (batchItem, key) {
  44996. !lastHighlights[key] && toHighlight.push(batchItem);
  44997. });
  44998. toDownplay.length && api.dispatchAction({
  44999. type: 'downplay',
  45000. escapeConnect: true,
  45001. // Not blur others when highlight in axisPointer.
  45002. notBlur: true,
  45003. batch: toDownplay
  45004. });
  45005. toHighlight.length && api.dispatchAction({
  45006. type: 'highlight',
  45007. escapeConnect: true,
  45008. // Not blur others when highlight in axisPointer.
  45009. notBlur: true,
  45010. batch: toHighlight
  45011. });
  45012. }
  45013. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  45014. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  45015. var inputAxisInfo = inputAxesInfo[i];
  45016. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  45017. return inputAxisInfo;
  45018. }
  45019. }
  45020. }
  45021. function makeMapperParam(axisInfo) {
  45022. var axisModel = axisInfo.axis.model;
  45023. var item = {};
  45024. var dim = item.axisDim = axisInfo.axis.dim;
  45025. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  45026. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  45027. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  45028. return item;
  45029. }
  45030. function illegalPoint(point) {
  45031. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  45032. }
  45033. function install$7(registers) {
  45034. // CartesianAxisPointer is not supposed to be required here. But consider
  45035. // echarts.simple.js and online build tooltip, which only require gridSimple,
  45036. // CartesianAxisPointer should be able to required somewhere.
  45037. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  45038. registers.registerComponentModel(AxisPointerModel);
  45039. registers.registerComponentView(AxisPointerView);
  45040. registers.registerPreprocessor(function (option) {
  45041. // Always has a global axisPointerModel for default setting.
  45042. if (option) {
  45043. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  45044. var link = option.axisPointer.link;
  45045. // Normalize to array to avoid object mergin. But if link
  45046. // is not set, remain null/undefined, otherwise it will
  45047. // override existent link setting.
  45048. if (link && !isArray(link)) {
  45049. option.axisPointer.link = [link];
  45050. }
  45051. }
  45052. });
  45053. // This process should proformed after coordinate systems created
  45054. // and series data processed. So put it on statistic processing stage.
  45055. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  45056. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  45057. // allAxesInfo should be updated when setOption performed.
  45058. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  45059. });
  45060. // Broadcast to all views.
  45061. registers.registerAction({
  45062. type: 'updateAxisPointer',
  45063. event: 'updateAxisPointer',
  45064. update: ':updateAxisPointer'
  45065. }, axisTrigger);
  45066. }
  45067. function install$8(registers) {
  45068. use(install$5);
  45069. use(install$7);
  45070. }
  45071. function setKeyInfoToNewElOption(resultItem, newElOption) {
  45072. var existElOption = resultItem.existing;
  45073. // Set id and type after id assigned.
  45074. newElOption.id = resultItem.keyInfo.id;
  45075. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  45076. // Set parent id if not specified
  45077. if (newElOption.parentId == null) {
  45078. var newElParentOption = newElOption.parentOption;
  45079. if (newElParentOption) {
  45080. newElOption.parentId = newElParentOption.id;
  45081. } else if (existElOption) {
  45082. newElOption.parentId = existElOption.parentId;
  45083. }
  45084. }
  45085. // Clear
  45086. newElOption.parentOption = null;
  45087. }
  45088. function isSetLoc(obj, props) {
  45089. var isSet;
  45090. each(props, function (prop) {
  45091. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  45092. });
  45093. return isSet;
  45094. }
  45095. function mergeNewElOptionToExist(existList, index, newElOption) {
  45096. // Update existing options, for `getOption` feature.
  45097. var newElOptCopy = extend({}, newElOption);
  45098. var existElOption = existList[index];
  45099. var $action = newElOption.$action || 'merge';
  45100. if ($action === 'merge') {
  45101. if (existElOption) {
  45102. if ("development" !== 'production') {
  45103. var newType = newElOption.type;
  45104. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  45105. }
  45106. // We can ensure that newElOptCopy and existElOption are not
  45107. // the same object, so `merge` will not change newElOptCopy.
  45108. merge(existElOption, newElOptCopy, true);
  45109. // Rigid body, use ignoreSize.
  45110. mergeLayoutParam(existElOption, newElOptCopy, {
  45111. ignoreSize: true
  45112. });
  45113. // Will be used in render.
  45114. copyLayoutParams(newElOption, existElOption);
  45115. // Copy transition info to new option so it can be used in the transition.
  45116. // DO IT AFTER merge
  45117. copyTransitionInfo(newElOption, existElOption);
  45118. copyTransitionInfo(newElOption, existElOption, 'shape');
  45119. copyTransitionInfo(newElOption, existElOption, 'style');
  45120. copyTransitionInfo(newElOption, existElOption, 'extra');
  45121. // Copy clipPath
  45122. newElOption.clipPath = existElOption.clipPath;
  45123. } else {
  45124. existList[index] = newElOptCopy;
  45125. }
  45126. } else if ($action === 'replace') {
  45127. existList[index] = newElOptCopy;
  45128. } else if ($action === 'remove') {
  45129. // null will be cleaned later.
  45130. existElOption && (existList[index] = null);
  45131. }
  45132. }
  45133. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  45134. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  45135. function copyTransitionInfo(target, source, targetProp) {
  45136. if (targetProp) {
  45137. if (!target[targetProp] && source[targetProp]) {
  45138. // TODO avoid creating this empty object when there is no transition configuration.
  45139. target[targetProp] = {};
  45140. }
  45141. target = target[targetProp];
  45142. source = source[targetProp];
  45143. }
  45144. if (!target || !source) {
  45145. return;
  45146. }
  45147. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  45148. for (var i = 0; i < props.length; i++) {
  45149. var prop = props[i];
  45150. if (target[prop] == null && source[prop] != null) {
  45151. target[prop] = source[prop];
  45152. }
  45153. }
  45154. }
  45155. function setLayoutInfoToExist(existItem, newElOption) {
  45156. if (!existItem) {
  45157. return;
  45158. }
  45159. existItem.hv = newElOption.hv = [
  45160. // Rigid body, don't care about `width`.
  45161. isSetLoc(newElOption, ['left', 'right']),
  45162. // Rigid body, don't care about `height`.
  45163. isSetLoc(newElOption, ['top', 'bottom'])];
  45164. // Give default group size. Otherwise layout error may occur.
  45165. if (existItem.type === 'group') {
  45166. var existingGroupOpt = existItem;
  45167. var newGroupOpt = newElOption;
  45168. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  45169. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  45170. }
  45171. }
  45172. var GraphicComponentModel = /** @class */function (_super) {
  45173. __extends(GraphicComponentModel, _super);
  45174. function GraphicComponentModel() {
  45175. var _this = _super !== null && _super.apply(this, arguments) || this;
  45176. _this.type = GraphicComponentModel.type;
  45177. _this.preventAutoZ = true;
  45178. return _this;
  45179. }
  45180. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  45181. // Prevent default merge to elements
  45182. var elements = this.option.elements;
  45183. this.option.elements = null;
  45184. _super.prototype.mergeOption.call(this, option, ecModel);
  45185. this.option.elements = elements;
  45186. };
  45187. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  45188. var thisOption = this.option;
  45189. var newList = (isInit ? thisOption : newOption).elements;
  45190. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  45191. var flattenedList = [];
  45192. this._flatten(newList, flattenedList, null);
  45193. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge');
  45194. // Clear elOptionsToUpdate
  45195. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  45196. each(mappingResult, function (resultItem, index) {
  45197. var newElOption = resultItem.newOption;
  45198. if ("development" !== 'production') {
  45199. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  45200. }
  45201. if (!newElOption) {
  45202. return;
  45203. }
  45204. elOptionsToUpdate.push(newElOption);
  45205. setKeyInfoToNewElOption(resultItem, newElOption);
  45206. mergeNewElOptionToExist(existList, index, newElOption);
  45207. setLayoutInfoToExist(existList[index], newElOption);
  45208. }, this);
  45209. // Clean
  45210. thisOption.elements = filter(existList, function (item) {
  45211. // $action should be volatile, otherwise option gotten from
  45212. // `getOption` will contain unexpected $action.
  45213. item && delete item.$action;
  45214. return item != null;
  45215. });
  45216. };
  45217. /**
  45218. * Convert
  45219. * [{
  45220. * type: 'group',
  45221. * id: 'xx',
  45222. * children: [{type: 'circle'}, {type: 'polygon'}]
  45223. * }]
  45224. * to
  45225. * [
  45226. * {type: 'group', id: 'xx'},
  45227. * {type: 'circle', parentId: 'xx'},
  45228. * {type: 'polygon', parentId: 'xx'}
  45229. * ]
  45230. */
  45231. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  45232. each(optionList, function (option) {
  45233. if (!option) {
  45234. return;
  45235. }
  45236. if (parentOption) {
  45237. option.parentOption = parentOption;
  45238. }
  45239. result.push(option);
  45240. var children = option.children;
  45241. // here we don't judge if option.type is `group`
  45242. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  45243. if (children && children.length) {
  45244. this._flatten(children, result, option);
  45245. }
  45246. // Deleting for JSON output, and for not affecting group creation.
  45247. delete option.children;
  45248. }, this);
  45249. };
  45250. // FIXME
  45251. // Pass to view using payload? setOption has a payload?
  45252. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  45253. var els = this._elOptionsToUpdate;
  45254. // Clear to avoid render duplicately when zooming.
  45255. this._elOptionsToUpdate = null;
  45256. return els;
  45257. };
  45258. GraphicComponentModel.type = 'graphic';
  45259. GraphicComponentModel.defaultOption = {
  45260. elements: []
  45261. // parentId: null
  45262. };
  45263. return GraphicComponentModel;
  45264. }(ComponentModel);
  45265. /**
  45266. * Whether need to call `convertEC4CompatibleStyle`.
  45267. */
  45268. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  45269. // Since echarts5, `RectText` is separated from its host element and style.text
  45270. // does not exist any more. The compat work brings some extra burden on performance.
  45271. // So we provide:
  45272. // `legacy: true` force make compat.
  45273. // `legacy: false`, force do not compat.
  45274. // `legacy` not set: auto detect whether legacy.
  45275. // But in this case we do not compat (difficult to detect and rare case):
  45276. // Becuse custom series and graphic component support "merge", users may firstly
  45277. // only set `textStrokeWidth` style or secondly only set `text`.
  45278. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan'
  45279. // Difficult to detect whether legacy for a "text" el.
  45280. && (elType === 'text' || hasOwn(style, 'text')));
  45281. }
  45282. /**
  45283. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  45284. * @param hostStyle The properties might be modified.
  45285. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  45286. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  45287. * retried from the `hostStyle`.
  45288. */
  45289. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  45290. var srcStyle = hostStyle;
  45291. var textConfig;
  45292. var textContent;
  45293. var textContentStyle;
  45294. if (elType === 'text') {
  45295. textContentStyle = srcStyle;
  45296. } else {
  45297. textContentStyle = {};
  45298. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  45299. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  45300. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  45301. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  45302. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  45303. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  45304. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  45305. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  45306. textContent = {
  45307. type: 'text',
  45308. style: textContentStyle,
  45309. // ec4 does not support rectText trigger.
  45310. // And when text position is different in normal and emphasis
  45311. // => hover text trigger emphasis;
  45312. // => text position changed, leave mouse pointer immediately;
  45313. // That might cause incorrect state.
  45314. silent: true
  45315. };
  45316. textConfig = {};
  45317. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  45318. if (isNormal) {
  45319. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  45320. } else {
  45321. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  45322. }
  45323. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  45324. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  45325. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  45326. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  45327. }
  45328. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  45329. each(textContentStyle.rich, function (richItem) {
  45330. convertEC4CompatibleRichItem(richItem, richItem);
  45331. });
  45332. return {
  45333. textConfig: textConfig,
  45334. textContent: textContent
  45335. };
  45336. }
  45337. /**
  45338. * The result will be set to `out`.
  45339. */
  45340. function convertEC4CompatibleRichItem(out, richItem) {
  45341. if (!richItem) {
  45342. return;
  45343. }
  45344. // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  45345. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  45346. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  45347. // richText in ec5.
  45348. // (2) `out === richItem` if and only if `out` is text el or rich item.
  45349. // So we can overwrite existing props in `out` since textXXX has higher priority.
  45350. richItem.font = richItem.textFont || richItem.font;
  45351. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  45352. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  45353. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  45354. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  45355. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  45356. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  45357. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  45358. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  45359. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  45360. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  45361. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  45362. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  45363. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  45364. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  45365. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  45366. }
  45367. var LEGACY_TRANSFORM_PROPS_MAP = {
  45368. position: ['x', 'y'],
  45369. scale: ['scaleX', 'scaleY'],
  45370. origin: ['originX', 'originY']
  45371. };
  45372. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  45373. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  45374. obj[key] = 1;
  45375. return obj;
  45376. }, {});
  45377. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', ');
  45378. // '' means root
  45379. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  45380. var transitionInnerStore = makeInner();
  45381. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  45382. var animationProp = animationType + "Animation";
  45383. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  45384. var userDuring = transitionInnerStore(el).userDuring;
  45385. // Only set when duration is > 0 and it's need to be animated.
  45386. if (config.duration > 0) {
  45387. // For simplicity, if during not specified, the previous during will not work any more.
  45388. config.during = userDuring ? bind(duringCall, {
  45389. el: el,
  45390. userDuring: userDuring
  45391. }) : null;
  45392. config.setToFinal = true;
  45393. config.scope = animationType;
  45394. }
  45395. extend(config, elOption[animationProp]);
  45396. return config;
  45397. }
  45398. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  45399. opts = opts || {};
  45400. var dataIndex = opts.dataIndex,
  45401. isInit = opts.isInit,
  45402. clearStyle = opts.clearStyle;
  45403. var hasAnimation = animatableModel.isAnimationEnabled();
  45404. // Save the meta info for further morphing. Like apply on the sub morphing elements.
  45405. var store = transitionInnerStore(el);
  45406. var styleOpt = elOption.style;
  45407. store.userDuring = elOption.during;
  45408. var transFromProps = {};
  45409. var propsToSet = {};
  45410. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  45411. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  45412. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  45413. if (!isInit && hasAnimation) {
  45414. prepareTransformTransitionFrom(el, elOption, transFromProps);
  45415. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  45416. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  45417. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  45418. }
  45419. propsToSet.style = styleOpt;
  45420. applyPropsDirectly(el, propsToSet, clearStyle);
  45421. applyMiscProps(el, elOption);
  45422. if (hasAnimation) {
  45423. if (isInit) {
  45424. var enterFromProps_1 = {};
  45425. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  45426. var prop = propName ? elOption[propName] : elOption;
  45427. if (prop && prop.enterFrom) {
  45428. if (propName) {
  45429. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  45430. }
  45431. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  45432. }
  45433. });
  45434. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  45435. if (config.duration > 0) {
  45436. el.animateFrom(enterFromProps_1, config);
  45437. }
  45438. } else {
  45439. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  45440. }
  45441. }
  45442. // Store leave to be used in leave transition.
  45443. updateLeaveTo(el, elOption);
  45444. styleOpt ? el.dirty() : el.markRedraw();
  45445. }
  45446. function updateLeaveTo(el, elOption) {
  45447. // Try merge to previous set leaveTo
  45448. var leaveToProps = transitionInnerStore(el).leaveToProps;
  45449. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  45450. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  45451. var prop = propName ? elOption[propName] : elOption;
  45452. if (prop && prop.leaveTo) {
  45453. if (!leaveToProps) {
  45454. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  45455. }
  45456. if (propName) {
  45457. leaveToProps[propName] = leaveToProps[propName] || {};
  45458. }
  45459. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  45460. }
  45461. }
  45462. }
  45463. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  45464. if (el) {
  45465. var parent_1 = el.parent;
  45466. var leaveToProps = transitionInnerStore(el).leaveToProps;
  45467. if (leaveToProps) {
  45468. // TODO TODO use leave after leaveAnimation in series is introduced
  45469. // TODO Data index?
  45470. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  45471. config.done = function () {
  45472. parent_1.remove(el);
  45473. onRemove && onRemove();
  45474. };
  45475. el.animateTo(leaveToProps, config);
  45476. } else {
  45477. parent_1.remove(el);
  45478. onRemove && onRemove();
  45479. }
  45480. }
  45481. }
  45482. function isTransitionAll(transition) {
  45483. return transition === 'all';
  45484. }
  45485. function applyPropsDirectly(el,
  45486. // Can be null/undefined
  45487. allPropsFinal, clearStyle) {
  45488. var styleOpt = allPropsFinal.style;
  45489. if (!el.isGroup && styleOpt) {
  45490. if (clearStyle) {
  45491. el.useStyle({});
  45492. // When style object changed, how to trade the existing animation?
  45493. // It is probably complicated and not needed to cover all the cases.
  45494. // But still need consider the case:
  45495. // (1) When using init animation on `style.opacity`, and before the animation
  45496. // ended users triggers an update by mousewhel. At that time the init
  45497. // animation should better be continued rather than terminated.
  45498. // So after `useStyle` called, we should change the animation target manually
  45499. // to continue the effect of the init animation.
  45500. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  45501. // to update the value to `val2` and no animation declared, should be terminate
  45502. // the previous animation or just modify the target of the animation?
  45503. // Therotically That will happen not only on `style` but also on `shape` and
  45504. // `transfrom` props. But we haven't handle this case at present yet.
  45505. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  45506. var animators = el.animators;
  45507. for (var i = 0; i < animators.length; i++) {
  45508. var animator = animators[i];
  45509. // targetName is the "topKey".
  45510. if (animator.targetName === 'style') {
  45511. animator.changeTarget(el.style);
  45512. }
  45513. }
  45514. }
  45515. el.setStyle(styleOpt);
  45516. }
  45517. if (allPropsFinal) {
  45518. // Not set style here.
  45519. allPropsFinal.style = null;
  45520. // Set el to the final state firstly.
  45521. allPropsFinal && el.attr(allPropsFinal);
  45522. allPropsFinal.style = styleOpt;
  45523. }
  45524. }
  45525. function applyPropsTransition(el, elOption, dataIndex, model,
  45526. // Can be null/undefined
  45527. transFromProps) {
  45528. if (transFromProps) {
  45529. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  45530. if (config.duration > 0) {
  45531. el.animateFrom(transFromProps, config);
  45532. }
  45533. }
  45534. }
  45535. function applyMiscProps(el, elOption) {
  45536. // Merge by default.
  45537. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  45538. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  45539. if (el instanceof Displayable) {
  45540. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  45541. }
  45542. if (el instanceof Path) {
  45543. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  45544. }
  45545. }
  45546. // Use it to avoid it be exposed to user.
  45547. var tmpDuringScope = {};
  45548. var transitionDuringAPI = {
  45549. // Usually other props do not need to be changed in animation during.
  45550. setTransform: function (key, val) {
  45551. if ("development" !== 'production') {
  45552. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  45553. }
  45554. tmpDuringScope.el[key] = val;
  45555. return this;
  45556. },
  45557. getTransform: function (key) {
  45558. if ("development" !== 'production') {
  45559. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  45560. }
  45561. return tmpDuringScope.el[key];
  45562. },
  45563. setShape: function (key, val) {
  45564. if ("development" !== 'production') {
  45565. assertNotReserved(key);
  45566. }
  45567. var el = tmpDuringScope.el;
  45568. var shape = el.shape || (el.shape = {});
  45569. shape[key] = val;
  45570. el.dirtyShape && el.dirtyShape();
  45571. return this;
  45572. },
  45573. getShape: function (key) {
  45574. if ("development" !== 'production') {
  45575. assertNotReserved(key);
  45576. }
  45577. var shape = tmpDuringScope.el.shape;
  45578. if (shape) {
  45579. return shape[key];
  45580. }
  45581. },
  45582. setStyle: function (key, val) {
  45583. if ("development" !== 'production') {
  45584. assertNotReserved(key);
  45585. }
  45586. var el = tmpDuringScope.el;
  45587. var style = el.style;
  45588. if (style) {
  45589. if ("development" !== 'production') {
  45590. if (eqNaN(val)) {
  45591. warn('style.' + key + ' must not be assigned with NaN.');
  45592. }
  45593. }
  45594. style[key] = val;
  45595. el.dirtyStyle && el.dirtyStyle();
  45596. }
  45597. return this;
  45598. },
  45599. getStyle: function (key) {
  45600. if ("development" !== 'production') {
  45601. assertNotReserved(key);
  45602. }
  45603. var style = tmpDuringScope.el.style;
  45604. if (style) {
  45605. return style[key];
  45606. }
  45607. },
  45608. setExtra: function (key, val) {
  45609. if ("development" !== 'production') {
  45610. assertNotReserved(key);
  45611. }
  45612. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  45613. extra[key] = val;
  45614. return this;
  45615. },
  45616. getExtra: function (key) {
  45617. if ("development" !== 'production') {
  45618. assertNotReserved(key);
  45619. }
  45620. var extra = tmpDuringScope.el.extra;
  45621. if (extra) {
  45622. return extra[key];
  45623. }
  45624. }
  45625. };
  45626. function assertNotReserved(key) {
  45627. if ("development" !== 'production') {
  45628. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  45629. throw new Error('key must not be "' + key + '"');
  45630. }
  45631. }
  45632. }
  45633. function duringCall() {
  45634. // Do not provide "percent" until some requirements come.
  45635. // Because consider thies case:
  45636. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  45637. // And enter duration is different from update duration.
  45638. // Thus it might be confused about the meaning of "percent" in during callback.
  45639. var scope = this;
  45640. var el = scope.el;
  45641. if (!el) {
  45642. return;
  45643. }
  45644. // If el is remove from zr by reason like legend, during still need to called,
  45645. // because el will be added back to zr and the prop value should not be incorrect.
  45646. var latestUserDuring = transitionInnerStore(el).userDuring;
  45647. var scopeUserDuring = scope.userDuring;
  45648. // Ensured a during is only called once in each animation frame.
  45649. // If a during is called multiple times in one frame, maybe some users' calculation logic
  45650. // might be wrong (not sure whether this usage exists).
  45651. // The case of a during might be called twice can be: by default there is a animator for
  45652. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  45653. // another animators for 'style'/'shape'/'extra'.
  45654. if (latestUserDuring !== scopeUserDuring) {
  45655. // release
  45656. scope.el = scope.userDuring = null;
  45657. return;
  45658. }
  45659. tmpDuringScope.el = el;
  45660. // Give no `this` to user in "during" calling.
  45661. scopeUserDuring(transitionDuringAPI);
  45662. // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  45663. // consider the issue that the prop might be incorrect when return to "normal" state.
  45664. }
  45665. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  45666. var attrOpt = elOption[mainAttr];
  45667. if (!attrOpt) {
  45668. return;
  45669. }
  45670. var elPropsInAttr = fromEl[mainAttr];
  45671. var transFromPropsInAttr;
  45672. if (elPropsInAttr) {
  45673. var transition = elOption.transition;
  45674. var attrTransition = attrOpt.transition;
  45675. if (attrTransition) {
  45676. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  45677. if (isTransitionAll(attrTransition)) {
  45678. extend(transFromPropsInAttr, elPropsInAttr);
  45679. } else {
  45680. var transitionKeys = normalizeToArray(attrTransition);
  45681. for (var i = 0; i < transitionKeys.length; i++) {
  45682. var key = transitionKeys[i];
  45683. var elVal = elPropsInAttr[key];
  45684. transFromPropsInAttr[key] = elVal;
  45685. }
  45686. }
  45687. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  45688. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  45689. var elPropsInAttrKeys = keys(elPropsInAttr);
  45690. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  45691. var key = elPropsInAttrKeys[i];
  45692. var elVal = elPropsInAttr[key];
  45693. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  45694. transFromPropsInAttr[key] = elVal;
  45695. }
  45696. }
  45697. }
  45698. }
  45699. }
  45700. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  45701. var attrOpt = elOption[mainAttr];
  45702. if (!attrOpt) {
  45703. return;
  45704. }
  45705. var allPropsInAttr = allProps[mainAttr] = {};
  45706. var keysInAttr = keys(attrOpt);
  45707. for (var i = 0; i < keysInAttr.length; i++) {
  45708. var key = keysInAttr[i];
  45709. // To avoid share one object with different element, and
  45710. // to avoid user modify the object inexpectedly, have to clone.
  45711. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  45712. }
  45713. }
  45714. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  45715. var transition = elOption.transition;
  45716. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  45717. for (var i = 0; i < transitionKeys.length; i++) {
  45718. var key = transitionKeys[i];
  45719. if (key === 'style' || key === 'shape' || key === 'extra') {
  45720. continue;
  45721. }
  45722. var elVal = el[key];
  45723. if ("development" !== 'production') {
  45724. checkTransformPropRefer(key, 'el.transition');
  45725. }
  45726. // Do not clone, animator will perform that clone.
  45727. transFromProps[key] = elVal;
  45728. }
  45729. }
  45730. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  45731. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  45732. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  45733. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  45734. var legacyArr = elOption[legacyName];
  45735. if (legacyArr) {
  45736. allProps[xyName[0]] = legacyArr[0];
  45737. allProps[xyName[1]] = legacyArr[1];
  45738. }
  45739. }
  45740. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  45741. var key = TRANSFORMABLE_PROPS[i];
  45742. if (elOption[key] != null) {
  45743. allProps[key] = elOption[key];
  45744. }
  45745. }
  45746. }
  45747. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  45748. if (!styleOpt) {
  45749. return;
  45750. }
  45751. var fromElStyle = fromEl.style;
  45752. var transFromStyleProps;
  45753. if (fromElStyle) {
  45754. var styleTransition = styleOpt.transition;
  45755. var elTransition = elOption.transition;
  45756. if (styleTransition && !isTransitionAll(styleTransition)) {
  45757. var transitionKeys = normalizeToArray(styleTransition);
  45758. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  45759. for (var i = 0; i < transitionKeys.length; i++) {
  45760. var key = transitionKeys[i];
  45761. var elVal = fromElStyle[key];
  45762. // Do not clone, see `checkNonStyleTansitionRefer`.
  45763. transFromStyleProps[key] = elVal;
  45764. }
  45765. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  45766. var animationProps = fromEl.getAnimationStyleProps();
  45767. var animationStyleProps = animationProps ? animationProps.style : null;
  45768. if (animationStyleProps) {
  45769. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  45770. var styleKeys = keys(styleOpt);
  45771. for (var i = 0; i < styleKeys.length; i++) {
  45772. var key = styleKeys[i];
  45773. if (animationStyleProps[key]) {
  45774. var elVal = fromElStyle[key];
  45775. transFromStyleProps[key] = elVal;
  45776. }
  45777. }
  45778. }
  45779. }
  45780. }
  45781. }
  45782. function isNonStyleTransitionEnabled(optVal, elVal) {
  45783. // The same as `checkNonStyleTansitionRefer`.
  45784. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  45785. }
  45786. var checkTransformPropRefer;
  45787. if ("development" !== 'production') {
  45788. checkTransformPropRefer = function (key, usedIn) {
  45789. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  45790. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  45791. }
  45792. };
  45793. }
  45794. var getStateToRestore = makeInner();
  45795. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  45796. /**
  45797. * Stop previous keyframe animation and restore the attributes.
  45798. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  45799. */
  45800. function stopPreviousKeyframeAnimationAndRestore(el) {
  45801. // Stop previous keyframe animation.
  45802. el.stopAnimation('keyframe');
  45803. // Restore
  45804. el.attr(getStateToRestore(el));
  45805. }
  45806. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  45807. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  45808. return;
  45809. }
  45810. if (isArray(animationOpts)) {
  45811. each(animationOpts, function (singleAnimationOpts) {
  45812. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  45813. });
  45814. return;
  45815. }
  45816. var keyframes = animationOpts.keyframes;
  45817. var duration = animationOpts.duration;
  45818. if (animatableModel && duration == null) {
  45819. // Default to use duration of config.
  45820. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  45821. var config = getAnimationConfig('enter', animatableModel, 0);
  45822. duration = config && config.duration;
  45823. }
  45824. if (!keyframes || !duration) {
  45825. return;
  45826. }
  45827. var stateToRestore = getStateToRestore(el);
  45828. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  45829. if (targetPropName && !el[targetPropName]) {
  45830. return;
  45831. }
  45832. var animator;
  45833. var endFrameIsSet = false;
  45834. // Sort keyframes by percent.
  45835. keyframes.sort(function (a, b) {
  45836. return a.percent - b.percent;
  45837. });
  45838. each(keyframes, function (kf) {
  45839. // Stop current animation.
  45840. var animators = el.animators;
  45841. var kfValues = targetPropName ? kf[targetPropName] : kf;
  45842. if ("development" !== 'production') {
  45843. if (kf.percent >= 1) {
  45844. endFrameIsSet = true;
  45845. }
  45846. }
  45847. if (!kfValues) {
  45848. return;
  45849. }
  45850. var propKeys = keys(kfValues);
  45851. if (!targetPropName) {
  45852. // PENDING performance?
  45853. propKeys = filter(propKeys, function (key) {
  45854. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  45855. });
  45856. }
  45857. if (!propKeys.length) {
  45858. return;
  45859. }
  45860. if (!animator) {
  45861. animator = el.animate(targetPropName, animationOpts.loop, true);
  45862. animator.scope = 'keyframe';
  45863. }
  45864. for (var i = 0; i < animators.length; i++) {
  45865. // Stop all other animation that is not keyframe.
  45866. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  45867. animators[i].stopTracks(propKeys);
  45868. }
  45869. }
  45870. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  45871. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  45872. each(propKeys, function (key) {
  45873. // Save original value.
  45874. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  45875. });
  45876. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  45877. });
  45878. if (!animator) {
  45879. return;
  45880. }
  45881. if ("development" !== 'production') {
  45882. if (!endFrameIsSet) {
  45883. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  45884. }
  45885. }
  45886. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  45887. });
  45888. }
  45889. var nonShapeGraphicElements = {
  45890. // Reserved but not supported in graphic component.
  45891. path: null,
  45892. compoundPath: null,
  45893. // Supported in graphic component.
  45894. group: Group,
  45895. image: ZRImage,
  45896. text: ZRText
  45897. };
  45898. var inner$a = makeInner();
  45899. // ------------------------
  45900. // View
  45901. // ------------------------
  45902. var GraphicComponentView = /** @class */function (_super) {
  45903. __extends(GraphicComponentView, _super);
  45904. function GraphicComponentView() {
  45905. var _this = _super !== null && _super.apply(this, arguments) || this;
  45906. _this.type = GraphicComponentView.type;
  45907. return _this;
  45908. }
  45909. GraphicComponentView.prototype.init = function () {
  45910. this._elMap = createHashMap();
  45911. };
  45912. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  45913. // Having leveraged between use cases and algorithm complexity, a very
  45914. // simple layout mechanism is used:
  45915. // The size(width/height) can be determined by itself or its parent (not
  45916. // implemented yet), but can not by its children. (Top-down travel)
  45917. // The location(x/y) can be determined by the bounding rect of itself
  45918. // (can including its descendants or not) and the size of its parent.
  45919. // (Bottom-up travel)
  45920. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  45921. // view will be reused.
  45922. if (graphicModel !== this._lastGraphicModel) {
  45923. this._clear();
  45924. }
  45925. this._lastGraphicModel = graphicModel;
  45926. this._updateElements(graphicModel);
  45927. this._relocate(graphicModel, api);
  45928. };
  45929. /**
  45930. * Update graphic elements.
  45931. */
  45932. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  45933. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  45934. if (!elOptionsToUpdate) {
  45935. return;
  45936. }
  45937. var elMap = this._elMap;
  45938. var rootGroup = this.group;
  45939. var globalZ = graphicModel.get('z');
  45940. var globalZLevel = graphicModel.get('zlevel');
  45941. // Top-down tranverse to assign graphic settings to each elements.
  45942. each(elOptionsToUpdate, function (elOption) {
  45943. var id = convertOptionIdName(elOption.id, null);
  45944. var elExisting = id != null ? elMap.get(id) : null;
  45945. var parentId = convertOptionIdName(elOption.parentId, null);
  45946. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  45947. var elType = elOption.type;
  45948. var elOptionStyle = elOption.style;
  45949. if (elType === 'text' && elOptionStyle) {
  45950. // In top/bottom mode, textVerticalAlign should not be used, which cause
  45951. // inaccurately locating.
  45952. if (elOption.hv && elOption.hv[1]) {
  45953. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  45954. }
  45955. }
  45956. var textContentOption = elOption.textContent;
  45957. var textConfig = elOption.textConfig;
  45958. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  45959. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  45960. if (!textConfig && convertResult.textConfig) {
  45961. textConfig = elOption.textConfig = convertResult.textConfig;
  45962. }
  45963. if (!textContentOption && convertResult.textContent) {
  45964. textContentOption = convertResult.textContent;
  45965. }
  45966. }
  45967. // Remove unnecessary props to avoid potential problems.
  45968. var elOptionCleaned = getCleanedElOption(elOption);
  45969. // For simple, do not support parent change, otherwise reorder is needed.
  45970. if ("development" !== 'production') {
  45971. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  45972. }
  45973. var $action = elOption.$action || 'merge';
  45974. var isMerge = $action === 'merge';
  45975. var isReplace = $action === 'replace';
  45976. if (isMerge) {
  45977. var isInit = !elExisting;
  45978. var el_1 = elExisting;
  45979. if (isInit) {
  45980. el_1 = createEl(id, targetElParent, elOption.type, elMap);
  45981. } else {
  45982. el_1 && (inner$a(el_1).isNew = false);
  45983. // Stop and restore before update any other attributes.
  45984. stopPreviousKeyframeAnimationAndRestore(el_1);
  45985. }
  45986. if (el_1) {
  45987. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  45988. isInit: isInit
  45989. });
  45990. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  45991. }
  45992. } else if (isReplace) {
  45993. removeEl(elExisting, elOption, elMap, graphicModel);
  45994. var el_2 = createEl(id, targetElParent, elOption.type, elMap);
  45995. if (el_2) {
  45996. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  45997. isInit: true
  45998. });
  45999. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  46000. }
  46001. } else if ($action === 'remove') {
  46002. updateLeaveTo(elExisting, elOption);
  46003. removeEl(elExisting, elOption, elMap, graphicModel);
  46004. }
  46005. var el = elMap.get(id);
  46006. if (el && textContentOption) {
  46007. if (isMerge) {
  46008. var textContentExisting = el.getTextContent();
  46009. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  46010. } else if (isReplace) {
  46011. el.setTextContent(new ZRText(textContentOption));
  46012. }
  46013. }
  46014. if (el) {
  46015. var clipPathOption = elOption.clipPath;
  46016. if (clipPathOption) {
  46017. var clipPathType = clipPathOption.type;
  46018. var clipPath = void 0;
  46019. var isInit = false;
  46020. if (isMerge) {
  46021. var oldClipPath = el.getClipPath();
  46022. isInit = !oldClipPath || inner$a(oldClipPath).type !== clipPathType;
  46023. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  46024. } else if (isReplace) {
  46025. isInit = true;
  46026. clipPath = newEl(clipPathType);
  46027. }
  46028. el.setClipPath(clipPath);
  46029. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  46030. isInit: isInit
  46031. });
  46032. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  46033. }
  46034. var elInner = inner$a(el);
  46035. el.setTextConfig(textConfig);
  46036. elInner.option = elOption;
  46037. setEventData(el, graphicModel, elOption);
  46038. setTooltipConfig({
  46039. el: el,
  46040. componentModel: graphicModel,
  46041. itemName: el.name,
  46042. itemTooltipOption: elOption.tooltip
  46043. });
  46044. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  46045. }
  46046. });
  46047. };
  46048. /**
  46049. * Locate graphic elements.
  46050. */
  46051. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  46052. var elOptions = graphicModel.option.elements;
  46053. var rootGroup = this.group;
  46054. var elMap = this._elMap;
  46055. var apiWidth = api.getWidth();
  46056. var apiHeight = api.getHeight();
  46057. var xy = ['x', 'y'];
  46058. // Top-down to calculate percentage width/height of group
  46059. for (var i = 0; i < elOptions.length; i++) {
  46060. var elOption = elOptions[i];
  46061. var id = convertOptionIdName(elOption.id, null);
  46062. var el = id != null ? elMap.get(id) : null;
  46063. if (!el || !el.isGroup) {
  46064. continue;
  46065. }
  46066. var parentEl = el.parent;
  46067. var isParentRoot = parentEl === rootGroup;
  46068. // Like 'position:absolut' in css, default 0.
  46069. var elInner = inner$a(el);
  46070. var parentElInner = inner$a(parentEl);
  46071. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  46072. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  46073. }
  46074. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  46075. for (var i = elOptions.length - 1; i >= 0; i--) {
  46076. var elOption = elOptions[i];
  46077. var id = convertOptionIdName(elOption.id, null);
  46078. var el = id != null ? elMap.get(id) : null;
  46079. if (!el) {
  46080. continue;
  46081. }
  46082. var parentEl = el.parent;
  46083. var parentElInner = inner$a(parentEl);
  46084. var containerInfo = parentEl === rootGroup ? {
  46085. width: apiWidth,
  46086. height: apiHeight
  46087. } : {
  46088. width: parentElInner.width,
  46089. height: parentElInner.height
  46090. };
  46091. // PENDING
  46092. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  46093. // does not include the rect of [0, 0, group.width, group.height], which
  46094. // is probably weird for users. Should we make a break change for it?
  46095. var layoutPos = {};
  46096. var layouted = positionElement(el, elOption, containerInfo, null, {
  46097. hv: elOption.hv,
  46098. boundingMode: elOption.bounding
  46099. }, layoutPos);
  46100. if (!inner$a(el).isNew && layouted) {
  46101. var transition = elOption.transition;
  46102. var animatePos = {};
  46103. for (var k = 0; k < xy.length; k++) {
  46104. var key = xy[k];
  46105. var val = layoutPos[key];
  46106. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  46107. animatePos[key] = val;
  46108. } else {
  46109. el[key] = val;
  46110. }
  46111. }
  46112. updateProps(el, animatePos, graphicModel, 0);
  46113. } else {
  46114. el.attr(layoutPos);
  46115. }
  46116. }
  46117. };
  46118. /**
  46119. * Clear all elements.
  46120. */
  46121. GraphicComponentView.prototype._clear = function () {
  46122. var _this = this;
  46123. var elMap = this._elMap;
  46124. elMap.each(function (el) {
  46125. removeEl(el, inner$a(el).option, elMap, _this._lastGraphicModel);
  46126. });
  46127. this._elMap = createHashMap();
  46128. };
  46129. GraphicComponentView.prototype.dispose = function () {
  46130. this._clear();
  46131. };
  46132. GraphicComponentView.type = 'graphic';
  46133. return GraphicComponentView;
  46134. }(ComponentView);
  46135. function newEl(graphicType) {
  46136. if ("development" !== 'production') {
  46137. assert(graphicType, 'graphic type MUST be set');
  46138. }
  46139. var Clz = hasOwn(nonShapeGraphicElements, graphicType)
  46140. // Those graphic elements are not shapes. They should not be
  46141. // overwritten by users, so do them first.
  46142. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  46143. if ("development" !== 'production') {
  46144. assert(Clz, "graphic type " + graphicType + " can not be found");
  46145. }
  46146. var el = new Clz({});
  46147. inner$a(el).type = graphicType;
  46148. return el;
  46149. }
  46150. function createEl(id, targetElParent, graphicType, elMap) {
  46151. var el = newEl(graphicType);
  46152. targetElParent.add(el);
  46153. elMap.set(id, el);
  46154. inner$a(el).id = id;
  46155. inner$a(el).isNew = true;
  46156. return el;
  46157. }
  46158. function removeEl(elExisting, elOption, elMap, graphicModel) {
  46159. var existElParent = elExisting && elExisting.parent;
  46160. if (existElParent) {
  46161. elExisting.type === 'group' && elExisting.traverse(function (el) {
  46162. removeEl(el, elOption, elMap, graphicModel);
  46163. });
  46164. applyLeaveTransition(elExisting, elOption, graphicModel);
  46165. elMap.removeKey(inner$a(elExisting).id);
  46166. }
  46167. }
  46168. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  46169. if (!el.isGroup) {
  46170. each([['cursor', Displayable.prototype.cursor],
  46171. // We should not support configure z and zlevel in the element level.
  46172. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  46173. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0],
  46174. // z2 must not be null/undefined, otherwise sort error may occur.
  46175. ['z2', 0]], function (item) {
  46176. var prop = item[0];
  46177. if (hasOwn(elOption, prop)) {
  46178. el[prop] = retrieve2(elOption[prop], item[1]);
  46179. } else if (el[prop] == null) {
  46180. el[prop] = item[1];
  46181. }
  46182. });
  46183. }
  46184. each(keys(elOption), function (key) {
  46185. // Assign event handlers.
  46186. // PENDING: should enumerate all event names or use pattern matching?
  46187. if (key.indexOf('on') === 0) {
  46188. var val = elOption[key];
  46189. el[key] = isFunction(val) ? val : null;
  46190. }
  46191. });
  46192. if (hasOwn(elOption, 'draggable')) {
  46193. el.draggable = elOption.draggable;
  46194. }
  46195. // Other attributes
  46196. elOption.name != null && (el.name = elOption.name);
  46197. elOption.id != null && (el.id = elOption.id);
  46198. }
  46199. // Remove unnecessary props to avoid potential problems.
  46200. function getCleanedElOption(elOption) {
  46201. elOption = extend({}, elOption);
  46202. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  46203. delete elOption[name];
  46204. });
  46205. return elOption;
  46206. }
  46207. function setEventData(el, graphicModel, elOption) {
  46208. var eventData = getECData(el).eventData;
  46209. // Simple optimize for large amount of elements that no need event.
  46210. if (!el.silent && !el.ignore && !eventData) {
  46211. eventData = getECData(el).eventData = {
  46212. componentType: 'graphic',
  46213. componentIndex: graphicModel.componentIndex,
  46214. name: el.name
  46215. };
  46216. }
  46217. // `elOption.info` enables user to mount some info on
  46218. // elements and use them in event handlers.
  46219. if (eventData) {
  46220. eventData.info = elOption.info;
  46221. }
  46222. }
  46223. function install$9(registers) {
  46224. registers.registerComponentModel(GraphicComponentModel);
  46225. registers.registerComponentView(GraphicComponentView);
  46226. registers.registerPreprocessor(function (option) {
  46227. var graphicOption = option.graphic;
  46228. // Convert
  46229. // {graphic: [{left: 10, type: 'circle'}, ...]}
  46230. // or
  46231. // {graphic: {left: 10, type: 'circle'}}
  46232. // to
  46233. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  46234. if (isArray(graphicOption)) {
  46235. if (!graphicOption[0] || !graphicOption[0].elements) {
  46236. option.graphic = [{
  46237. elements: graphicOption
  46238. }];
  46239. } else {
  46240. // Only one graphic instance can be instantiated. (We don't
  46241. // want that too many views are created in echarts._viewMap.)
  46242. option.graphic = [option.graphic[0]];
  46243. }
  46244. } else if (graphicOption && !graphicOption.elements) {
  46245. option.graphic = [{
  46246. elements: [graphicOption]
  46247. }];
  46248. }
  46249. });
  46250. }
  46251. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single'];
  46252. // Supported coords.
  46253. // FIXME: polar has been broken (but rarely used).
  46254. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  46255. function isCoordSupported(seriesModel) {
  46256. var coordType = seriesModel.get('coordinateSystem');
  46257. return indexOf(SERIES_COORDS, coordType) >= 0;
  46258. }
  46259. function getAxisMainType(axisDim) {
  46260. if ("development" !== 'production') {
  46261. assert(axisDim);
  46262. }
  46263. return axisDim + 'Axis';
  46264. }
  46265. /**
  46266. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  46267. * This function finds all linked dataZoomModels start from the given payload.
  46268. */
  46269. function findEffectedDataZooms(ecModel, payload) {
  46270. // Key: `DataZoomAxisDimension`
  46271. var axisRecords = createHashMap();
  46272. var effectedModels = [];
  46273. // Key: uid of dataZoomModel
  46274. var effectedModelMap = createHashMap();
  46275. // Find the dataZooms specified by payload.
  46276. ecModel.eachComponent({
  46277. mainType: 'dataZoom',
  46278. query: payload
  46279. }, function (dataZoomModel) {
  46280. if (!effectedModelMap.get(dataZoomModel.uid)) {
  46281. addToEffected(dataZoomModel);
  46282. }
  46283. });
  46284. // Start from the given dataZoomModels, travel the graph to find
  46285. // all of the linked dataZoom models.
  46286. var foundNewLink;
  46287. do {
  46288. foundNewLink = false;
  46289. ecModel.eachComponent('dataZoom', processSingle);
  46290. } while (foundNewLink);
  46291. function processSingle(dataZoomModel) {
  46292. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  46293. addToEffected(dataZoomModel);
  46294. foundNewLink = true;
  46295. }
  46296. }
  46297. function addToEffected(dataZoom) {
  46298. effectedModelMap.set(dataZoom.uid, true);
  46299. effectedModels.push(dataZoom);
  46300. markAxisControlled(dataZoom);
  46301. }
  46302. function isLinked(dataZoomModel) {
  46303. var isLink = false;
  46304. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  46305. var axisIdxArr = axisRecords.get(axisDim);
  46306. if (axisIdxArr && axisIdxArr[axisIndex]) {
  46307. isLink = true;
  46308. }
  46309. });
  46310. return isLink;
  46311. }
  46312. function markAxisControlled(dataZoomModel) {
  46313. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  46314. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  46315. });
  46316. }
  46317. return effectedModels;
  46318. }
  46319. /**
  46320. * Find the first target coordinate system.
  46321. * Available after model built.
  46322. *
  46323. * @return Like {
  46324. * grid: [
  46325. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  46326. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  46327. * ...
  46328. * ], // cartesians must not be null/undefined.
  46329. * polar: [
  46330. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  46331. * ...
  46332. * ], // polars must not be null/undefined.
  46333. * singleAxis: [
  46334. * {model: coord0, axisModels: [], coordIndex: 0}
  46335. * ]
  46336. * }
  46337. */
  46338. function collectReferCoordSysModelInfo(dataZoomModel) {
  46339. var ecModel = dataZoomModel.ecModel;
  46340. var coordSysInfoWrap = {
  46341. infoList: [],
  46342. infoMap: createHashMap()
  46343. };
  46344. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  46345. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  46346. if (!axisModel) {
  46347. return;
  46348. }
  46349. var coordSysModel = axisModel.getCoordSysModel();
  46350. if (!coordSysModel) {
  46351. return;
  46352. }
  46353. var coordSysUid = coordSysModel.uid;
  46354. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  46355. if (!coordSysInfo) {
  46356. coordSysInfo = {
  46357. model: coordSysModel,
  46358. axisModels: []
  46359. };
  46360. coordSysInfoWrap.infoList.push(coordSysInfo);
  46361. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  46362. }
  46363. coordSysInfo.axisModels.push(axisModel);
  46364. });
  46365. return coordSysInfoWrap;
  46366. }
  46367. var DataZoomAxisInfo = /** @class */function () {
  46368. function DataZoomAxisInfo() {
  46369. this.indexList = [];
  46370. this.indexMap = [];
  46371. }
  46372. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  46373. // Remove duplication.
  46374. if (!this.indexMap[axisCmptIdx]) {
  46375. this.indexList.push(axisCmptIdx);
  46376. this.indexMap[axisCmptIdx] = true;
  46377. }
  46378. };
  46379. return DataZoomAxisInfo;
  46380. }();
  46381. var DataZoomModel = /** @class */function (_super) {
  46382. __extends(DataZoomModel, _super);
  46383. function DataZoomModel() {
  46384. var _this = _super !== null && _super.apply(this, arguments) || this;
  46385. _this.type = DataZoomModel.type;
  46386. _this._autoThrottle = true;
  46387. _this._noTarget = true;
  46388. /**
  46389. * It is `[rangeModeForMin, rangeModeForMax]`.
  46390. * The optional values for `rangeMode`:
  46391. * + `'value'` mode: the axis extent will always be determined by
  46392. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  46393. * how data like and how `axis.min` and `axis.max` are.
  46394. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  46395. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  46396. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  46397. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  46398. *
  46399. * For example, when users are using dynamic data (update data periodically via `setOption`),
  46400. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  46401. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  46402. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  46403. */
  46404. _this._rangePropMode = ['percent', 'percent'];
  46405. return _this;
  46406. }
  46407. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  46408. var inputRawOption = retrieveRawOption(option);
  46409. /**
  46410. * Suppose a "main process" start at the point that model prepared (that is,
  46411. * model initialized or merged or method called in `action`).
  46412. * We should keep the `main process` idempotent, that is, given a set of values
  46413. * on `option`, we get the same result.
  46414. *
  46415. * But sometimes, values on `option` will be updated for providing users
  46416. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  46417. * should not be the base/input of the `main process`.
  46418. *
  46419. * So in that case we should save and keep the input of the `main process`
  46420. * separately, called `settledOption`.
  46421. *
  46422. * For example, consider the case:
  46423. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  46424. * where the original input `option.startValue`, `option.endValue` are earsed by
  46425. * calculated value.
  46426. * (Step)2) click the legend to hide and show a series,
  46427. * where the new range is calculated by the earsed `startValue` and `endValue`,
  46428. * which brings incorrect result.
  46429. */
  46430. this.settledOption = inputRawOption;
  46431. this.mergeDefaultAndTheme(option, ecModel);
  46432. this._doInit(inputRawOption);
  46433. };
  46434. DataZoomModel.prototype.mergeOption = function (newOption) {
  46435. var inputRawOption = retrieveRawOption(newOption);
  46436. // FIX #2591
  46437. merge(this.option, newOption, true);
  46438. merge(this.settledOption, inputRawOption, true);
  46439. this._doInit(inputRawOption);
  46440. };
  46441. DataZoomModel.prototype._doInit = function (inputRawOption) {
  46442. var thisOption = this.option;
  46443. this._setDefaultThrottle(inputRawOption);
  46444. this._updateRangeUse(inputRawOption);
  46445. var settledOption = this.settledOption;
  46446. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  46447. // start/end has higher priority over startValue/endValue if they
  46448. // both set, but we should make chart.setOption({endValue: 1000})
  46449. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  46450. if (this._rangePropMode[index] === 'value') {
  46451. thisOption[names[0]] = settledOption[names[0]] = null;
  46452. }
  46453. // Otherwise do nothing and use the merge result.
  46454. }, this);
  46455. this._resetTarget();
  46456. };
  46457. DataZoomModel.prototype._resetTarget = function () {
  46458. var optionOrient = this.get('orient', true);
  46459. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  46460. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  46461. if (hasAxisSpecified) {
  46462. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  46463. } else {
  46464. this._orient = optionOrient || 'horizontal';
  46465. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  46466. }
  46467. this._noTarget = true;
  46468. targetAxisIndexMap.each(function (axisInfo) {
  46469. if (axisInfo.indexList.length) {
  46470. this._noTarget = false;
  46471. }
  46472. }, this);
  46473. };
  46474. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  46475. var hasAxisSpecified = false;
  46476. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  46477. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING);
  46478. // When user set axisIndex as a empty array, we think that user specify axisIndex
  46479. // but do not want use auto mode. Because empty array may be encountered when
  46480. // some error occurred.
  46481. if (!refering.specified) {
  46482. return;
  46483. }
  46484. hasAxisSpecified = true;
  46485. var axisInfo = new DataZoomAxisInfo();
  46486. each(refering.models, function (axisModel) {
  46487. axisInfo.add(axisModel.componentIndex);
  46488. });
  46489. targetAxisIndexMap.set(axisDim, axisInfo);
  46490. }, this);
  46491. return hasAxisSpecified;
  46492. };
  46493. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  46494. var ecModel = this.ecModel;
  46495. var needAuto = true;
  46496. // Find axis that parallel to dataZoom as default.
  46497. if (needAuto) {
  46498. var axisDim = orient === 'vertical' ? 'y' : 'x';
  46499. var axisModels = ecModel.findComponents({
  46500. mainType: axisDim + 'Axis'
  46501. });
  46502. setParallelAxis(axisModels, axisDim);
  46503. }
  46504. // Find axis that parallel to dataZoom as default.
  46505. if (needAuto) {
  46506. var axisModels = ecModel.findComponents({
  46507. mainType: 'singleAxis',
  46508. filter: function (axisModel) {
  46509. return axisModel.get('orient', true) === orient;
  46510. }
  46511. });
  46512. setParallelAxis(axisModels, 'single');
  46513. }
  46514. function setParallelAxis(axisModels, axisDim) {
  46515. // At least use the first parallel axis as the target axis.
  46516. var axisModel = axisModels[0];
  46517. if (!axisModel) {
  46518. return;
  46519. }
  46520. var axisInfo = new DataZoomAxisInfo();
  46521. axisInfo.add(axisModel.componentIndex);
  46522. targetAxisIndexMap.set(axisDim, axisInfo);
  46523. needAuto = false;
  46524. // Find parallel axes in the same grid.
  46525. if (axisDim === 'x' || axisDim === 'y') {
  46526. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  46527. gridModel_1 && each(axisModels, function (axModel) {
  46528. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  46529. axisInfo.add(axModel.componentIndex);
  46530. }
  46531. });
  46532. }
  46533. }
  46534. if (needAuto) {
  46535. // If no parallel axis, find the first category axis as default. (Also consider polar).
  46536. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  46537. if (!needAuto) {
  46538. return;
  46539. }
  46540. var axisModels = ecModel.findComponents({
  46541. mainType: getAxisMainType(axisDim),
  46542. filter: function (axisModel) {
  46543. return axisModel.get('type', true) === 'category';
  46544. }
  46545. });
  46546. if (axisModels[0]) {
  46547. var axisInfo = new DataZoomAxisInfo();
  46548. axisInfo.add(axisModels[0].componentIndex);
  46549. targetAxisIndexMap.set(axisDim, axisInfo);
  46550. needAuto = false;
  46551. }
  46552. }, this);
  46553. }
  46554. };
  46555. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  46556. var dim;
  46557. // Find the first axis
  46558. this.eachTargetAxis(function (axisDim) {
  46559. !dim && (dim = axisDim);
  46560. }, this);
  46561. return dim === 'y' ? 'vertical' : 'horizontal';
  46562. };
  46563. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  46564. // When first time user set throttle, auto throttle ends.
  46565. if (inputRawOption.hasOwnProperty('throttle')) {
  46566. this._autoThrottle = false;
  46567. }
  46568. if (this._autoThrottle) {
  46569. var globalOption = this.ecModel.option;
  46570. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  46571. }
  46572. };
  46573. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  46574. var rangePropMode = this._rangePropMode;
  46575. var rangeModeInOption = this.get('rangeMode');
  46576. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  46577. var percentSpecified = inputRawOption[names[0]] != null;
  46578. var valueSpecified = inputRawOption[names[1]] != null;
  46579. if (percentSpecified && !valueSpecified) {
  46580. rangePropMode[index] = 'percent';
  46581. } else if (!percentSpecified && valueSpecified) {
  46582. rangePropMode[index] = 'value';
  46583. } else if (rangeModeInOption) {
  46584. rangePropMode[index] = rangeModeInOption[index];
  46585. } else if (percentSpecified) {
  46586. // percentSpecified && valueSpecified
  46587. rangePropMode[index] = 'percent';
  46588. }
  46589. // else remain its original setting.
  46590. });
  46591. };
  46592. DataZoomModel.prototype.noTarget = function () {
  46593. return this._noTarget;
  46594. };
  46595. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  46596. var firstAxisModel;
  46597. this.eachTargetAxis(function (axisDim, axisIndex) {
  46598. if (firstAxisModel == null) {
  46599. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  46600. }
  46601. }, this);
  46602. return firstAxisModel;
  46603. };
  46604. /**
  46605. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  46606. */
  46607. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  46608. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  46609. each(axisInfo.indexList, function (axisIndex) {
  46610. callback.call(context, axisDim, axisIndex);
  46611. });
  46612. });
  46613. };
  46614. /**
  46615. * @return If not found, return null/undefined.
  46616. */
  46617. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  46618. var axisModel = this.getAxisModel(axisDim, axisIndex);
  46619. if (axisModel) {
  46620. return axisModel.__dzAxisProxy;
  46621. }
  46622. };
  46623. /**
  46624. * @return If not found, return null/undefined.
  46625. */
  46626. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  46627. if ("development" !== 'production') {
  46628. assert(axisDim && axisIndex != null);
  46629. }
  46630. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  46631. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  46632. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  46633. }
  46634. };
  46635. /**
  46636. * If not specified, set to undefined.
  46637. */
  46638. DataZoomModel.prototype.setRawRange = function (opt) {
  46639. var thisOption = this.option;
  46640. var settledOption = this.settledOption;
  46641. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  46642. // Consider the pair <start, startValue>:
  46643. // If one has value and the other one is `null/undefined`, we both set them
  46644. // to `settledOption`. This strategy enables the feature to clear the original
  46645. // value in `settledOption` to `null/undefined`.
  46646. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  46647. // and keep `settledOption` with the original value. This strategy enables users to
  46648. // only set <end or endValue> but not set <start or startValue> when calling
  46649. // `dispatchAction`.
  46650. // The pair <end, endValue> is treated in the same way.
  46651. if (opt[names[0]] != null || opt[names[1]] != null) {
  46652. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  46653. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  46654. }
  46655. }, this);
  46656. this._updateRangeUse(opt);
  46657. };
  46658. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  46659. var option = this.option;
  46660. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  46661. option[name] = opt[name];
  46662. });
  46663. };
  46664. DataZoomModel.prototype.getPercentRange = function () {
  46665. var axisProxy = this.findRepresentativeAxisProxy();
  46666. if (axisProxy) {
  46667. return axisProxy.getDataPercentWindow();
  46668. }
  46669. };
  46670. /**
  46671. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  46672. *
  46673. * @return [startValue, endValue] value can only be '-' or finite number.
  46674. */
  46675. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  46676. if (axisDim == null && axisIndex == null) {
  46677. var axisProxy = this.findRepresentativeAxisProxy();
  46678. if (axisProxy) {
  46679. return axisProxy.getDataValueWindow();
  46680. }
  46681. } else {
  46682. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  46683. }
  46684. };
  46685. /**
  46686. * @param axisModel If axisModel given, find axisProxy
  46687. * corresponding to the axisModel
  46688. */
  46689. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  46690. if (axisModel) {
  46691. return axisModel.__dzAxisProxy;
  46692. }
  46693. // Find the first hosted axisProxy
  46694. var firstProxy;
  46695. var axisDimList = this._targetAxisInfoMap.keys();
  46696. for (var i = 0; i < axisDimList.length; i++) {
  46697. var axisDim = axisDimList[i];
  46698. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  46699. for (var j = 0; j < axisInfo.indexList.length; j++) {
  46700. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  46701. if (proxy.hostedBy(this)) {
  46702. return proxy;
  46703. }
  46704. if (!firstProxy) {
  46705. firstProxy = proxy;
  46706. }
  46707. }
  46708. }
  46709. // If no hosted proxy found, still need to return a proxy.
  46710. // This case always happens in toolbox dataZoom, where axes are all hosted by
  46711. // other dataZooms.
  46712. return firstProxy;
  46713. };
  46714. DataZoomModel.prototype.getRangePropMode = function () {
  46715. return this._rangePropMode.slice();
  46716. };
  46717. DataZoomModel.prototype.getOrient = function () {
  46718. if ("development" !== 'production') {
  46719. // Should not be called before initialized.
  46720. assert(this._orient);
  46721. }
  46722. return this._orient;
  46723. };
  46724. DataZoomModel.type = 'dataZoom';
  46725. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  46726. DataZoomModel.defaultOption = {
  46727. // zlevel: 0,
  46728. z: 4,
  46729. filterMode: 'filter',
  46730. start: 0,
  46731. end: 100
  46732. };
  46733. return DataZoomModel;
  46734. }(ComponentModel);
  46735. /**
  46736. * Retrieve those raw params from option, which will be cached separately,
  46737. * because they will be overwritten by normalized/calculated values in the main
  46738. * process.
  46739. */
  46740. function retrieveRawOption(option) {
  46741. var ret = {};
  46742. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  46743. option.hasOwnProperty(name) && (ret[name] = option[name]);
  46744. });
  46745. return ret;
  46746. }
  46747. var SelectDataZoomModel = /** @class */function (_super) {
  46748. __extends(SelectDataZoomModel, _super);
  46749. function SelectDataZoomModel() {
  46750. var _this = _super !== null && _super.apply(this, arguments) || this;
  46751. _this.type = SelectDataZoomModel.type;
  46752. return _this;
  46753. }
  46754. SelectDataZoomModel.type = 'dataZoom.select';
  46755. return SelectDataZoomModel;
  46756. }(DataZoomModel);
  46757. var DataZoomView = /** @class */function (_super) {
  46758. __extends(DataZoomView, _super);
  46759. function DataZoomView() {
  46760. var _this = _super !== null && _super.apply(this, arguments) || this;
  46761. _this.type = DataZoomView.type;
  46762. return _this;
  46763. }
  46764. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  46765. this.dataZoomModel = dataZoomModel;
  46766. this.ecModel = ecModel;
  46767. this.api = api;
  46768. };
  46769. DataZoomView.type = 'dataZoom';
  46770. return DataZoomView;
  46771. }(ComponentView);
  46772. var SelectDataZoomView = /** @class */function (_super) {
  46773. __extends(SelectDataZoomView, _super);
  46774. function SelectDataZoomView() {
  46775. var _this = _super !== null && _super.apply(this, arguments) || this;
  46776. _this.type = SelectDataZoomView.type;
  46777. return _this;
  46778. }
  46779. SelectDataZoomView.type = 'dataZoom.select';
  46780. return SelectDataZoomView;
  46781. }(DataZoomView);
  46782. /*
  46783. * Licensed to the Apache Software Foundation (ASF) under one
  46784. * or more contributor license agreements. See the NOTICE file
  46785. * distributed with this work for additional information
  46786. * regarding copyright ownership. The ASF licenses this file
  46787. * to you under the Apache License, Version 2.0 (the
  46788. * "License"); you may not use this file except in compliance
  46789. * with the License. You may obtain a copy of the License at
  46790. *
  46791. * http://www.apache.org/licenses/LICENSE-2.0
  46792. *
  46793. * Unless required by applicable law or agreed to in writing,
  46794. * software distributed under the License is distributed on an
  46795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46796. * KIND, either express or implied. See the License for the
  46797. * specific language governing permissions and limitations
  46798. * under the License.
  46799. */
  46800. /**
  46801. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46802. */
  46803. /*
  46804. * Licensed to the Apache Software Foundation (ASF) under one
  46805. * or more contributor license agreements. See the NOTICE file
  46806. * distributed with this work for additional information
  46807. * regarding copyright ownership. The ASF licenses this file
  46808. * to you under the Apache License, Version 2.0 (the
  46809. * "License"); you may not use this file except in compliance
  46810. * with the License. You may obtain a copy of the License at
  46811. *
  46812. * http://www.apache.org/licenses/LICENSE-2.0
  46813. *
  46814. * Unless required by applicable law or agreed to in writing,
  46815. * software distributed under the License is distributed on an
  46816. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46817. * KIND, either express or implied. See the License for the
  46818. * specific language governing permissions and limitations
  46819. * under the License.
  46820. */
  46821. /**
  46822. * Calculate slider move result.
  46823. * Usage:
  46824. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  46825. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  46826. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  46827. *
  46828. * @param delta Move length.
  46829. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  46830. * handleEnds will be modified in this method.
  46831. * @param extent handleEnds is restricted by extent.
  46832. * extent[0] should less or equals than extent[1].
  46833. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  46834. * @param minSpan The range of dataZoom can not be smaller than that.
  46835. * If not set, handle0 and cross handle1. If set as a non-negative
  46836. * number (including `0`), handles will push each other when reaching
  46837. * the minSpan.
  46838. * @param maxSpan The range of dataZoom can not be larger than that.
  46839. * @return The input handleEnds.
  46840. */
  46841. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  46842. delta = delta || 0;
  46843. var extentSpan = extent[1] - extent[0];
  46844. // Notice maxSpan and minSpan can be null/undefined.
  46845. if (minSpan != null) {
  46846. minSpan = restrict(minSpan, [0, extentSpan]);
  46847. }
  46848. if (maxSpan != null) {
  46849. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  46850. }
  46851. if (handleIndex === 'all') {
  46852. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  46853. handleSpan = restrict(handleSpan, [0, extentSpan]);
  46854. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  46855. handleIndex = 0;
  46856. }
  46857. handleEnds[0] = restrict(handleEnds[0], extent);
  46858. handleEnds[1] = restrict(handleEnds[1], extent);
  46859. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  46860. handleEnds[handleIndex] += delta;
  46861. // Restrict in extent.
  46862. var extentMinSpan = minSpan || 0;
  46863. var realExtent = extent.slice();
  46864. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  46865. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  46866. // Expand span.
  46867. var currDistSign;
  46868. currDistSign = getSpanSign(handleEnds, handleIndex);
  46869. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  46870. // If minSpan exists, 'cross' is forbidden.
  46871. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  46872. }
  46873. // Shrink span.
  46874. currDistSign = getSpanSign(handleEnds, handleIndex);
  46875. if (maxSpan != null && currDistSign.span > maxSpan) {
  46876. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  46877. }
  46878. return handleEnds;
  46879. }
  46880. function getSpanSign(handleEnds, handleIndex) {
  46881. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  46882. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  46883. // is at left of handleEnds[1] for non-cross case.
  46884. return {
  46885. span: Math.abs(dist),
  46886. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  46887. };
  46888. }
  46889. function restrict(value, extend) {
  46890. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  46891. }
  46892. var each$4 = each;
  46893. var asc$1 = asc;
  46894. /**
  46895. * Operate single axis.
  46896. * One axis can only operated by one axis operator.
  46897. * Different dataZoomModels may be defined to operate the same axis.
  46898. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  46899. * So dataZoomModels share one axisProxy in that case.
  46900. */
  46901. var AxisProxy = /** @class */function () {
  46902. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  46903. this._dimName = dimName;
  46904. this._axisIndex = axisIndex;
  46905. this.ecModel = ecModel;
  46906. this._dataZoomModel = dataZoomModel;
  46907. // /**
  46908. // * @readOnly
  46909. // * @private
  46910. // */
  46911. // this.hasSeriesStacked;
  46912. }
  46913. /**
  46914. * Whether the axisProxy is hosted by dataZoomModel.
  46915. */
  46916. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  46917. return this._dataZoomModel === dataZoomModel;
  46918. };
  46919. /**
  46920. * @return Value can only be NaN or finite value.
  46921. */
  46922. AxisProxy.prototype.getDataValueWindow = function () {
  46923. return this._valueWindow.slice();
  46924. };
  46925. /**
  46926. * @return {Array.<number>}
  46927. */
  46928. AxisProxy.prototype.getDataPercentWindow = function () {
  46929. return this._percentWindow.slice();
  46930. };
  46931. AxisProxy.prototype.getTargetSeriesModels = function () {
  46932. var seriesModels = [];
  46933. this.ecModel.eachSeries(function (seriesModel) {
  46934. if (isCoordSupported(seriesModel)) {
  46935. var axisMainType = getAxisMainType(this._dimName);
  46936. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  46937. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  46938. seriesModels.push(seriesModel);
  46939. }
  46940. }
  46941. }, this);
  46942. return seriesModels;
  46943. };
  46944. AxisProxy.prototype.getAxisModel = function () {
  46945. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  46946. };
  46947. AxisProxy.prototype.getMinMaxSpan = function () {
  46948. return clone(this._minMaxSpan);
  46949. };
  46950. /**
  46951. * Only calculate by given range and this._dataExtent, do not change anything.
  46952. */
  46953. AxisProxy.prototype.calculateDataWindow = function (opt) {
  46954. var dataExtent = this._dataExtent;
  46955. var axisModel = this.getAxisModel();
  46956. var scale = axisModel.axis.scale;
  46957. var rangePropMode = this._dataZoomModel.getRangePropMode();
  46958. var percentExtent = [0, 100];
  46959. var percentWindow = [];
  46960. var valueWindow = [];
  46961. var hasPropModeValue;
  46962. each$4(['start', 'end'], function (prop, idx) {
  46963. var boundPercent = opt[prop];
  46964. var boundValue = opt[prop + 'Value'];
  46965. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  46966. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  46967. // but not min/max of axis, which will be calculated by data window then).
  46968. // The former one is suitable for cases that a dataZoom component controls multiple
  46969. // axes with different unit or extent, and the latter one is suitable for accurate
  46970. // zoom by pixel (e.g., in dataZoomSelect).
  46971. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  46972. // only when setOption or dispatchAction, otherwise it remains its original value.
  46973. // (Why not only record `percentProp` and always map to `valueProp`? Because
  46974. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  46975. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  46976. // data extent. All of values that are overflow the `dataExtent` will be calculated
  46977. // to percent '100%').
  46978. if (rangePropMode[idx] === 'percent') {
  46979. boundPercent == null && (boundPercent = percentExtent[idx]);
  46980. // Use scale.parse to math round for category or time axis.
  46981. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  46982. } else {
  46983. hasPropModeValue = true;
  46984. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  46985. // Calculating `percent` from `value` may be not accurate, because
  46986. // This calculation can not be inversed, because all of values that
  46987. // are overflow the `dataExtent` will be calculated to percent '100%'
  46988. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  46989. }
  46990. // valueWindow[idx] = round(boundValue);
  46991. // percentWindow[idx] = round(boundPercent);
  46992. // fallback to extent start/end when parsed value or percent is invalid
  46993. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  46994. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  46995. });
  46996. asc$1(valueWindow);
  46997. asc$1(percentWindow);
  46998. // The windows from user calling of `dispatchAction` might be out of the extent,
  46999. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  47000. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  47001. // where API is able to initialize/modify the window size even though `zoomLock`
  47002. // specified.
  47003. var spans = this._minMaxSpan;
  47004. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  47005. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  47006. var suffix = toValue ? 'Span' : 'ValueSpan';
  47007. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  47008. for (var i = 0; i < 2; i++) {
  47009. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  47010. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  47011. }
  47012. }
  47013. return {
  47014. valueWindow: valueWindow,
  47015. percentWindow: percentWindow
  47016. };
  47017. };
  47018. /**
  47019. * Notice: reset should not be called before series.restoreData() is called,
  47020. * so it is recommended to be called in "process stage" but not "model init
  47021. * stage".
  47022. */
  47023. AxisProxy.prototype.reset = function (dataZoomModel) {
  47024. if (dataZoomModel !== this._dataZoomModel) {
  47025. return;
  47026. }
  47027. var targetSeries = this.getTargetSeriesModels();
  47028. // Culculate data window and data extent, and record them.
  47029. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  47030. // `calculateDataWindow` uses min/maxSpan.
  47031. this._updateMinMaxSpan();
  47032. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  47033. this._valueWindow = dataWindow.valueWindow;
  47034. this._percentWindow = dataWindow.percentWindow;
  47035. // Update axis setting then.
  47036. this._setAxisModel();
  47037. };
  47038. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  47039. if (dataZoomModel !== this._dataZoomModel) {
  47040. return;
  47041. }
  47042. var axisDim = this._dimName;
  47043. var seriesModels = this.getTargetSeriesModels();
  47044. var filterMode = dataZoomModel.get('filterMode');
  47045. var valueWindow = this._valueWindow;
  47046. if (filterMode === 'none') {
  47047. return;
  47048. }
  47049. // FIXME
  47050. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  47051. // with NaN data, NaN will be filtered and stack will be wrong.
  47052. // So we need to force the mode to be set empty.
  47053. // In fect, it is not a big deal that do not support filterMode-'filter'
  47054. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  47055. // selection" some day, which might need "adapt to data extent on the
  47056. // otherAxis", which is disabled by filterMode-'empty'.
  47057. // But currently, stack has been fixed to based on value but not index,
  47058. // so this is not an issue any more.
  47059. // let otherAxisModel = this.getOtherAxisModel();
  47060. // if (dataZoomModel.get('$fromToolbox')
  47061. // && otherAxisModel
  47062. // && otherAxisModel.hasSeriesStacked
  47063. // ) {
  47064. // filterMode = 'empty';
  47065. // }
  47066. // TODO
  47067. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  47068. each$4(seriesModels, function (seriesModel) {
  47069. var seriesData = seriesModel.getData();
  47070. var dataDims = seriesData.mapDimensionsAll(axisDim);
  47071. if (!dataDims.length) {
  47072. return;
  47073. }
  47074. if (filterMode === 'weakFilter') {
  47075. var store_1 = seriesData.getStore();
  47076. var dataDimIndices_1 = map(dataDims, function (dim) {
  47077. return seriesData.getDimensionIndex(dim);
  47078. }, seriesData);
  47079. seriesData.filterSelf(function (dataIndex) {
  47080. var leftOut;
  47081. var rightOut;
  47082. var hasValue;
  47083. for (var i = 0; i < dataDims.length; i++) {
  47084. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  47085. var thisHasValue = !isNaN(value);
  47086. var thisLeftOut = value < valueWindow[0];
  47087. var thisRightOut = value > valueWindow[1];
  47088. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  47089. return true;
  47090. }
  47091. thisHasValue && (hasValue = true);
  47092. thisLeftOut && (leftOut = true);
  47093. thisRightOut && (rightOut = true);
  47094. }
  47095. // If both left out and right out, do not filter.
  47096. return hasValue && leftOut && rightOut;
  47097. });
  47098. } else {
  47099. each$4(dataDims, function (dim) {
  47100. if (filterMode === 'empty') {
  47101. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  47102. return !isInWindow(value) ? NaN : value;
  47103. }));
  47104. } else {
  47105. var range = {};
  47106. range[dim] = valueWindow;
  47107. // console.time('select');
  47108. seriesData.selectRange(range);
  47109. // console.timeEnd('select');
  47110. }
  47111. });
  47112. }
  47113. each$4(dataDims, function (dim) {
  47114. seriesData.setApproximateExtent(valueWindow, dim);
  47115. });
  47116. });
  47117. function isInWindow(value) {
  47118. return value >= valueWindow[0] && value <= valueWindow[1];
  47119. }
  47120. };
  47121. AxisProxy.prototype._updateMinMaxSpan = function () {
  47122. var minMaxSpan = this._minMaxSpan = {};
  47123. var dataZoomModel = this._dataZoomModel;
  47124. var dataExtent = this._dataExtent;
  47125. each$4(['min', 'max'], function (minMax) {
  47126. var percentSpan = dataZoomModel.get(minMax + 'Span');
  47127. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  47128. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan));
  47129. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  47130. if (valueSpan != null) {
  47131. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  47132. } else if (percentSpan != null) {
  47133. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  47134. }
  47135. minMaxSpan[minMax + 'Span'] = percentSpan;
  47136. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  47137. }, this);
  47138. };
  47139. AxisProxy.prototype._setAxisModel = function () {
  47140. var axisModel = this.getAxisModel();
  47141. var percentWindow = this._percentWindow;
  47142. var valueWindow = this._valueWindow;
  47143. if (!percentWindow) {
  47144. return;
  47145. }
  47146. // [0, 500]: arbitrary value, guess axis extent.
  47147. var precision = getPixelPrecision(valueWindow, [0, 500]);
  47148. precision = Math.min(precision, 20);
  47149. // For value axis, if min/max/scale are not set, we just use the extent obtained
  47150. // by series data, which may be a little different from the extent calculated by
  47151. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  47152. // little when zooming. So it will not be fixed until some users require it strongly.
  47153. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  47154. if (percentWindow[0] !== 0) {
  47155. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  47156. }
  47157. if (percentWindow[1] !== 100) {
  47158. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  47159. }
  47160. rawExtentInfo.freeze();
  47161. };
  47162. return AxisProxy;
  47163. }();
  47164. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  47165. var dataExtent = [Infinity, -Infinity];
  47166. each$4(seriesModels, function (seriesModel) {
  47167. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  47168. });
  47169. // It is important to get "consistent" extent when more then one axes is
  47170. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  47171. // when zooming. But it is difficult to know what is "consistent", considering
  47172. // axes have different type or even different meanings (For example, two
  47173. // time axes are used to compare data of the same date in different years).
  47174. // So basically dataZoom just obtains extent by series.data (in category axis
  47175. // extent can be obtained from axis.data).
  47176. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  47177. // consistent.
  47178. var axisModel = axisProxy.getAxisModel();
  47179. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  47180. return [rawExtentResult.min, rawExtentResult.max];
  47181. }
  47182. var dataZoomProcessor = {
  47183. // `dataZoomProcessor` will only be performed in needed series. Consider if
  47184. // there is a line series and a pie series, it is better not to update the
  47185. // line series if only pie series is needed to be updated.
  47186. getTargetSeries: function (ecModel) {
  47187. function eachAxisModel(cb) {
  47188. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47189. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  47190. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  47191. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  47192. });
  47193. });
  47194. }
  47195. // FIXME: it brings side-effect to `getTargetSeries`.
  47196. // Prepare axis proxies.
  47197. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  47198. // dispose all last axis proxy, in case that some axis are deleted.
  47199. axisModel.__dzAxisProxy = null;
  47200. });
  47201. var proxyList = [];
  47202. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  47203. // Different dataZooms may constrol the same axis. In that case,
  47204. // an axisProxy serves both of them.
  47205. if (!axisModel.__dzAxisProxy) {
  47206. // Use the first dataZoomModel as the main model of axisProxy.
  47207. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  47208. proxyList.push(axisModel.__dzAxisProxy);
  47209. }
  47210. });
  47211. var seriesModelMap = createHashMap();
  47212. each(proxyList, function (axisProxy) {
  47213. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  47214. seriesModelMap.set(seriesModel.uid, seriesModel);
  47215. });
  47216. });
  47217. return seriesModelMap;
  47218. },
  47219. // Consider appendData, where filter should be performed. Because data process is
  47220. // in block mode currently, it is not need to worry about that the overallProgress
  47221. // execute every frame.
  47222. overallReset: function (ecModel, api) {
  47223. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47224. // We calculate window and reset axis here but not in model
  47225. // init stage and not after action dispatch handler, because
  47226. // reset should be called after seriesData.restoreData.
  47227. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  47228. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  47229. });
  47230. // Caution: data zoom filtering is order sensitive when using
  47231. // percent range and no min/max/scale set on axis.
  47232. // For example, we have dataZoom definition:
  47233. // [
  47234. // {xAxisIndex: 0, start: 30, end: 70},
  47235. // {yAxisIndex: 0, start: 20, end: 80}
  47236. // ]
  47237. // In this case, [20, 80] of y-dataZoom should be based on data
  47238. // that have filtered by x-dataZoom using range of [30, 70],
  47239. // but should not be based on full raw data. Thus sliding
  47240. // x-dataZoom will change both ranges of xAxis and yAxis,
  47241. // while sliding y-dataZoom will only change the range of yAxis.
  47242. // So we should filter x-axis after reset x-axis immediately,
  47243. // and then reset y-axis and filter y-axis.
  47244. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  47245. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  47246. });
  47247. });
  47248. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  47249. // Fullfill all of the range props so that user
  47250. // is able to get them from chart.getOption().
  47251. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  47252. if (axisProxy) {
  47253. var percentRange = axisProxy.getDataPercentWindow();
  47254. var valueRange = axisProxy.getDataValueWindow();
  47255. dataZoomModel.setCalculatedRange({
  47256. start: percentRange[0],
  47257. end: percentRange[1],
  47258. startValue: valueRange[0],
  47259. endValue: valueRange[1]
  47260. });
  47261. }
  47262. });
  47263. }
  47264. };
  47265. function installDataZoomAction(registers) {
  47266. registers.registerAction('dataZoom', function (payload, ecModel) {
  47267. var effectedModels = findEffectedDataZooms(ecModel, payload);
  47268. each(effectedModels, function (dataZoomModel) {
  47269. dataZoomModel.setRawRange({
  47270. start: payload.start,
  47271. end: payload.end,
  47272. startValue: payload.startValue,
  47273. endValue: payload.endValue
  47274. });
  47275. });
  47276. });
  47277. }
  47278. var installed = false;
  47279. function installCommon(registers) {
  47280. if (installed) {
  47281. return;
  47282. }
  47283. installed = true;
  47284. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  47285. installDataZoomAction(registers);
  47286. registers.registerSubTypeDefaulter('dataZoom', function () {
  47287. // Default 'slider' when no type specified.
  47288. return 'slider';
  47289. });
  47290. }
  47291. function install$a(registers) {
  47292. registers.registerComponentModel(SelectDataZoomModel);
  47293. registers.registerComponentView(SelectDataZoomView);
  47294. installCommon(registers);
  47295. }
  47296. /*
  47297. * Licensed to the Apache Software Foundation (ASF) under one
  47298. * or more contributor license agreements. See the NOTICE file
  47299. * distributed with this work for additional information
  47300. * regarding copyright ownership. The ASF licenses this file
  47301. * to you under the Apache License, Version 2.0 (the
  47302. * "License"); you may not use this file except in compliance
  47303. * with the License. You may obtain a copy of the License at
  47304. *
  47305. * http://www.apache.org/licenses/LICENSE-2.0
  47306. *
  47307. * Unless required by applicable law or agreed to in writing,
  47308. * software distributed under the License is distributed on an
  47309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47310. * KIND, either express or implied. See the License for the
  47311. * specific language governing permissions and limitations
  47312. * under the License.
  47313. */
  47314. /**
  47315. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47316. */
  47317. var ToolboxFeature = /** @class */function () {
  47318. function ToolboxFeature() {}
  47319. return ToolboxFeature;
  47320. }();
  47321. var features = {};
  47322. function registerFeature(name, ctor) {
  47323. features[name] = ctor;
  47324. }
  47325. function getFeature(name) {
  47326. return features[name];
  47327. }
  47328. var ToolboxModel = /** @class */function (_super) {
  47329. __extends(ToolboxModel, _super);
  47330. function ToolboxModel() {
  47331. var _this = _super !== null && _super.apply(this, arguments) || this;
  47332. _this.type = ToolboxModel.type;
  47333. return _this;
  47334. }
  47335. ToolboxModel.prototype.optionUpdated = function () {
  47336. _super.prototype.optionUpdated.apply(this, arguments);
  47337. var ecModel = this.ecModel;
  47338. each(this.option.feature, function (featureOpt, featureName) {
  47339. var Feature = getFeature(featureName);
  47340. if (Feature) {
  47341. if (Feature.getDefaultOption) {
  47342. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  47343. }
  47344. merge(featureOpt, Feature.defaultOption);
  47345. }
  47346. });
  47347. };
  47348. ToolboxModel.type = 'toolbox';
  47349. ToolboxModel.layoutMode = {
  47350. type: 'box',
  47351. ignoreSize: true
  47352. };
  47353. ToolboxModel.defaultOption = {
  47354. show: true,
  47355. z: 6,
  47356. // zlevel: 0,
  47357. orient: 'horizontal',
  47358. left: 'right',
  47359. top: 'top',
  47360. // right
  47361. // bottom
  47362. backgroundColor: 'transparent',
  47363. borderColor: '#ccc',
  47364. borderRadius: 0,
  47365. borderWidth: 0,
  47366. padding: 5,
  47367. itemSize: 15,
  47368. itemGap: 8,
  47369. showTitle: true,
  47370. iconStyle: {
  47371. borderColor: '#666',
  47372. color: 'none'
  47373. },
  47374. emphasis: {
  47375. iconStyle: {
  47376. borderColor: '#3E98C5'
  47377. }
  47378. },
  47379. // textStyle: {},
  47380. // feature
  47381. tooltip: {
  47382. show: false,
  47383. position: 'bottom'
  47384. }
  47385. };
  47386. return ToolboxModel;
  47387. }(ComponentModel);
  47388. /**
  47389. * Layout list like component.
  47390. * It will box layout each items in group of component and then position the whole group in the viewport
  47391. * @param {module:zrender/group/Group} group
  47392. * @param {module:echarts/model/Component} componentModel
  47393. * @param {module:echarts/ExtensionAPI}
  47394. */
  47395. function layout$2(group, componentModel, api) {
  47396. var boxLayoutParams = componentModel.getBoxLayoutParams();
  47397. var padding = componentModel.get('padding');
  47398. var viewportSize = {
  47399. width: api.getWidth(),
  47400. height: api.getHeight()
  47401. };
  47402. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  47403. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  47404. positionElement(group, boxLayoutParams, viewportSize, padding);
  47405. }
  47406. function makeBackground(rect, componentModel) {
  47407. var padding = normalizeCssArray$1(componentModel.get('padding'));
  47408. var style = componentModel.getItemStyle(['color', 'opacity']);
  47409. style.fill = componentModel.get('backgroundColor');
  47410. rect = new Rect({
  47411. shape: {
  47412. x: rect.x - padding[3],
  47413. y: rect.y - padding[0],
  47414. width: rect.width + padding[1] + padding[3],
  47415. height: rect.height + padding[0] + padding[2],
  47416. r: componentModel.get('borderRadius')
  47417. },
  47418. style: style,
  47419. silent: true,
  47420. z2: -1
  47421. });
  47422. // FIXME
  47423. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  47424. // and background rect when setting like `left: 0`, `top: 0`.
  47425. // graphic.subPixelOptimizeRect(rect);
  47426. return rect;
  47427. }
  47428. var ToolboxView = /** @class */function (_super) {
  47429. __extends(ToolboxView, _super);
  47430. function ToolboxView() {
  47431. return _super !== null && _super.apply(this, arguments) || this;
  47432. }
  47433. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  47434. var group = this.group;
  47435. group.removeAll();
  47436. if (!toolboxModel.get('show')) {
  47437. return;
  47438. }
  47439. var itemSize = +toolboxModel.get('itemSize');
  47440. var isVertical = toolboxModel.get('orient') === 'vertical';
  47441. var featureOpts = toolboxModel.get('feature') || {};
  47442. var features = this._features || (this._features = {});
  47443. var featureNames = [];
  47444. each(featureOpts, function (opt, name) {
  47445. featureNames.push(name);
  47446. });
  47447. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute();
  47448. // Keep for diff.
  47449. this._featureNames = featureNames;
  47450. function processFeature(newIndex, oldIndex) {
  47451. var featureName = featureNames[newIndex];
  47452. var oldName = featureNames[oldIndex];
  47453. var featureOpt = featureOpts[featureName];
  47454. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  47455. var feature;
  47456. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  47457. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  47458. featureOpt.title = payload.newTitle;
  47459. }
  47460. if (featureName && !oldName) {
  47461. // Create
  47462. if (isUserFeatureName(featureName)) {
  47463. feature = {
  47464. onclick: featureModel.option.onclick,
  47465. featureName: featureName
  47466. };
  47467. } else {
  47468. var Feature = getFeature(featureName);
  47469. if (!Feature) {
  47470. return;
  47471. }
  47472. feature = new Feature();
  47473. }
  47474. features[featureName] = feature;
  47475. } else {
  47476. feature = features[oldName];
  47477. // If feature does not exist.
  47478. if (!feature) {
  47479. return;
  47480. }
  47481. }
  47482. feature.uid = getUID('toolbox-feature');
  47483. feature.model = featureModel;
  47484. feature.ecModel = ecModel;
  47485. feature.api = api;
  47486. var isToolboxFeature = feature instanceof ToolboxFeature;
  47487. if (!featureName && oldName) {
  47488. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  47489. return;
  47490. }
  47491. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  47492. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  47493. return;
  47494. }
  47495. createIconPaths(featureModel, feature, featureName);
  47496. featureModel.setIconStatus = function (iconName, status) {
  47497. var option = this.option;
  47498. var iconPaths = this.iconPaths;
  47499. option.iconStatus = option.iconStatus || {};
  47500. option.iconStatus[iconName] = status;
  47501. if (iconPaths[iconName]) {
  47502. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  47503. }
  47504. };
  47505. if (feature instanceof ToolboxFeature) {
  47506. if (feature.render) {
  47507. feature.render(featureModel, ecModel, api, payload);
  47508. }
  47509. }
  47510. }
  47511. function createIconPaths(featureModel, feature, featureName) {
  47512. var iconStyleModel = featureModel.getModel('iconStyle');
  47513. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']);
  47514. // If one feature has multiple icons, they are organized as
  47515. // {
  47516. // icon: {
  47517. // foo: '',
  47518. // bar: ''
  47519. // },
  47520. // title: {
  47521. // foo: '',
  47522. // bar: ''
  47523. // }
  47524. // }
  47525. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  47526. var titles = featureModel.get('title') || {};
  47527. var iconsMap;
  47528. var titlesMap;
  47529. if (isString(icons)) {
  47530. iconsMap = {};
  47531. iconsMap[featureName] = icons;
  47532. } else {
  47533. iconsMap = icons;
  47534. }
  47535. if (isString(titles)) {
  47536. titlesMap = {};
  47537. titlesMap[featureName] = titles;
  47538. } else {
  47539. titlesMap = titles;
  47540. }
  47541. var iconPaths = featureModel.iconPaths = {};
  47542. each(iconsMap, function (iconStr, iconName) {
  47543. var path = createIcon(iconStr, {}, {
  47544. x: -itemSize / 2,
  47545. y: -itemSize / 2,
  47546. width: itemSize,
  47547. height: itemSize
  47548. }); // TODO handling image
  47549. path.setStyle(iconStyleModel.getItemStyle());
  47550. var pathEmphasisState = path.ensureState('emphasis');
  47551. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle();
  47552. // Text position calculation
  47553. // TODO: extract `textStyle` from `iconStyle` and use `createTextStyle`
  47554. var textContent = new ZRText({
  47555. style: {
  47556. text: titlesMap[iconName],
  47557. align: iconStyleEmphasisModel.get('textAlign'),
  47558. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  47559. padding: iconStyleEmphasisModel.get('textPadding'),
  47560. fill: null,
  47561. font: getFont({
  47562. fontStyle: iconStyleEmphasisModel.get('textFontStyle'),
  47563. fontFamily: iconStyleEmphasisModel.get('textFontFamily'),
  47564. fontSize: iconStyleEmphasisModel.get('textFontSize'),
  47565. fontWeight: iconStyleEmphasisModel.get('textFontWeight')
  47566. }, ecModel)
  47567. },
  47568. ignore: true
  47569. });
  47570. path.setTextContent(textContent);
  47571. setTooltipConfig({
  47572. el: path,
  47573. componentModel: toolboxModel,
  47574. itemName: iconName,
  47575. formatterParamsExtra: {
  47576. title: titlesMap[iconName]
  47577. }
  47578. });
  47579. path.__title = titlesMap[iconName];
  47580. path.on('mouseover', function () {
  47581. // Should not reuse above hoverStyle, which might be modified.
  47582. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  47583. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  47584. textContent.setStyle({
  47585. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  47586. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  47587. });
  47588. path.setTextConfig({
  47589. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  47590. });
  47591. textContent.ignore = !toolboxModel.get('showTitle');
  47592. // Use enterEmphasis and leaveEmphasis provide by ec.
  47593. // There are flags managed by the echarts.
  47594. api.enterEmphasis(this);
  47595. }).on('mouseout', function () {
  47596. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  47597. api.leaveEmphasis(this);
  47598. }
  47599. textContent.hide();
  47600. });
  47601. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  47602. group.add(path);
  47603. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  47604. iconPaths[iconName] = path;
  47605. });
  47606. }
  47607. layout$2(group, toolboxModel, api);
  47608. // Render background after group is layout
  47609. // FIXME
  47610. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  47611. // Adjust icon title positions to avoid them out of screen
  47612. isVertical || group.eachChild(function (icon) {
  47613. var titleText = icon.__title;
  47614. // const hoverStyle = icon.hoverStyle;
  47615. // TODO simplify code?
  47616. var emphasisState = icon.ensureState('emphasis');
  47617. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  47618. var textContent = icon.getTextContent();
  47619. var emphasisTextState = textContent && textContent.ensureState('emphasis');
  47620. // May be background element
  47621. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  47622. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  47623. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  47624. var offsetX = icon.x + group.x;
  47625. var offsetY = icon.y + group.y + itemSize;
  47626. var needPutOnTop = false;
  47627. if (offsetY + rect.height > api.getHeight()) {
  47628. emphasisTextConfig.position = 'top';
  47629. needPutOnTop = true;
  47630. }
  47631. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  47632. if (offsetX + rect.width / 2 > api.getWidth()) {
  47633. emphasisTextConfig.position = ['100%', topOffset];
  47634. emphasisTextStyle.align = 'right';
  47635. } else if (offsetX - rect.width / 2 < 0) {
  47636. emphasisTextConfig.position = [0, topOffset];
  47637. emphasisTextStyle.align = 'left';
  47638. }
  47639. }
  47640. });
  47641. };
  47642. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  47643. each(this._features, function (feature) {
  47644. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  47645. });
  47646. };
  47647. // updateLayout(toolboxModel, ecModel, api, payload) {
  47648. // zrUtil.each(this._features, function (feature) {
  47649. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  47650. // });
  47651. // },
  47652. ToolboxView.prototype.remove = function (ecModel, api) {
  47653. each(this._features, function (feature) {
  47654. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  47655. });
  47656. this.group.removeAll();
  47657. };
  47658. ToolboxView.prototype.dispose = function (ecModel, api) {
  47659. each(this._features, function (feature) {
  47660. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  47661. });
  47662. };
  47663. ToolboxView.type = 'toolbox';
  47664. return ToolboxView;
  47665. }(ComponentView);
  47666. function isUserFeatureName(featureName) {
  47667. return featureName.indexOf('my') === 0;
  47668. }
  47669. var SaveAsImage = /** @class */function (_super) {
  47670. __extends(SaveAsImage, _super);
  47671. function SaveAsImage() {
  47672. return _super !== null && _super.apply(this, arguments) || this;
  47673. }
  47674. SaveAsImage.prototype.onclick = function (ecModel, api) {
  47675. var model = this.model;
  47676. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  47677. var isSvg = api.getZr().painter.getType() === 'svg';
  47678. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  47679. var url = api.getConnectedDataURL({
  47680. type: type,
  47681. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  47682. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  47683. excludeComponents: model.get('excludeComponents'),
  47684. pixelRatio: model.get('pixelRatio')
  47685. });
  47686. var browser = env.browser;
  47687. // Chrome, Firefox, New Edge
  47688. if (typeof MouseEvent === 'function' && (browser.newEdge || !browser.ie && !browser.edge)) {
  47689. var $a = document.createElement('a');
  47690. $a.download = title + '.' + type;
  47691. $a.target = '_blank';
  47692. $a.href = url;
  47693. var evt = new MouseEvent('click', {
  47694. // some micro front-end framework, window maybe is a Proxy
  47695. view: document.defaultView,
  47696. bubbles: true,
  47697. cancelable: false
  47698. });
  47699. $a.dispatchEvent(evt);
  47700. }
  47701. // IE or old Edge
  47702. else {
  47703. // @ts-ignore
  47704. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  47705. var parts = url.split(',');
  47706. // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  47707. var base64Encoded = parts[0].indexOf('base64') > -1;
  47708. var bstr = isSvg
  47709. // should decode the svg data uri first
  47710. ? decodeURIComponent(parts[1]) : parts[1];
  47711. // only `atob` when the data uri is encoded with base64
  47712. // otherwise, like `svg` data uri exported by zrender,
  47713. // there will be an error, for it's not encoded with base64.
  47714. // (just a url-encoded string through `encodeURIComponent`)
  47715. base64Encoded && (bstr = window.atob(bstr));
  47716. var filename = title + '.' + type;
  47717. // @ts-ignore
  47718. if (window.navigator.msSaveOrOpenBlob) {
  47719. var n = bstr.length;
  47720. var u8arr = new Uint8Array(n);
  47721. while (n--) {
  47722. u8arr[n] = bstr.charCodeAt(n);
  47723. }
  47724. var blob = new Blob([u8arr]); // @ts-ignore
  47725. window.navigator.msSaveOrOpenBlob(blob, filename);
  47726. } else {
  47727. var frame = document.createElement('iframe');
  47728. document.body.appendChild(frame);
  47729. var cw = frame.contentWindow;
  47730. var doc = cw.document;
  47731. doc.open('image/svg+xml', 'replace');
  47732. doc.write(bstr);
  47733. doc.close();
  47734. cw.focus();
  47735. doc.execCommand('SaveAs', true, filename);
  47736. document.body.removeChild(frame);
  47737. }
  47738. } else {
  47739. var lang = model.get('lang');
  47740. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  47741. var tab = window.open();
  47742. tab.document.write(html);
  47743. tab.document.title = title;
  47744. }
  47745. }
  47746. };
  47747. SaveAsImage.getDefaultOption = function (ecModel) {
  47748. var defaultOption = {
  47749. show: true,
  47750. 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',
  47751. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  47752. type: 'png',
  47753. // Default use option.backgroundColor
  47754. // backgroundColor: '#fff',
  47755. connectedBackgroundColor: '#fff',
  47756. name: '',
  47757. excludeComponents: ['toolbox'],
  47758. // use current pixel ratio of device by default
  47759. // pixelRatio: 1,
  47760. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  47761. };
  47762. return defaultOption;
  47763. };
  47764. return SaveAsImage;
  47765. }(ToolboxFeature);
  47766. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  47767. var radioTypes = [['line', 'bar'], ['stack']];
  47768. var MagicType = /** @class */function (_super) {
  47769. __extends(MagicType, _super);
  47770. function MagicType() {
  47771. return _super !== null && _super.apply(this, arguments) || this;
  47772. }
  47773. MagicType.prototype.getIcons = function () {
  47774. var model = this.model;
  47775. var availableIcons = model.get('icon');
  47776. var icons = {};
  47777. each(model.get('type'), function (type) {
  47778. if (availableIcons[type]) {
  47779. icons[type] = availableIcons[type];
  47780. }
  47781. });
  47782. return icons;
  47783. };
  47784. MagicType.getDefaultOption = function (ecModel) {
  47785. var defaultOption = {
  47786. show: true,
  47787. type: [],
  47788. // Icon group
  47789. icon: {
  47790. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  47791. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  47792. // eslint-disable-next-line
  47793. 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
  47794. },
  47795. // `line`, `bar`, `stack`, `tiled`
  47796. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  47797. option: {},
  47798. seriesIndex: {}
  47799. };
  47800. return defaultOption;
  47801. };
  47802. MagicType.prototype.onclick = function (ecModel, api, type) {
  47803. var model = this.model;
  47804. var seriesIndex = model.get(['seriesIndex', type]);
  47805. // Not supported magicType
  47806. if (!seriesOptGenreator[type]) {
  47807. return;
  47808. }
  47809. var newOption = {
  47810. series: []
  47811. };
  47812. var generateNewSeriesTypes = function (seriesModel) {
  47813. var seriesType = seriesModel.subType;
  47814. var seriesId = seriesModel.id;
  47815. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  47816. if (newSeriesOpt) {
  47817. // PENDING If merge original option?
  47818. defaults(newSeriesOpt, seriesModel.option);
  47819. newOption.series.push(newSeriesOpt);
  47820. }
  47821. // Modify boundaryGap
  47822. var coordSys = seriesModel.coordinateSystem;
  47823. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  47824. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  47825. if (categoryAxis) {
  47826. var axisDim = categoryAxis.dim;
  47827. var axisType = axisDim + 'Axis';
  47828. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  47829. var axisIndex = axisModel.componentIndex;
  47830. newOption[axisType] = newOption[axisType] || [];
  47831. for (var i = 0; i <= axisIndex; i++) {
  47832. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  47833. }
  47834. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  47835. }
  47836. }
  47837. };
  47838. each(radioTypes, function (radio) {
  47839. if (indexOf(radio, type) >= 0) {
  47840. each(radio, function (item) {
  47841. model.setIconStatus(item, 'normal');
  47842. });
  47843. }
  47844. });
  47845. model.setIconStatus(type, 'emphasis');
  47846. ecModel.eachComponent({
  47847. mainType: 'series',
  47848. query: seriesIndex == null ? null : {
  47849. seriesIndex: seriesIndex
  47850. }
  47851. }, generateNewSeriesTypes);
  47852. var newTitle;
  47853. var currentType = type;
  47854. // Change title of stack
  47855. if (type === 'stack') {
  47856. // use titles in model instead of ecModel
  47857. // as stack and tiled appears in pair, just flip them
  47858. // no need of checking stack state
  47859. newTitle = merge({
  47860. stack: model.option.title.tiled,
  47861. tiled: model.option.title.stack
  47862. }, model.option.title);
  47863. if (model.get(['iconStatus', type]) !== 'emphasis') {
  47864. currentType = 'tiled';
  47865. }
  47866. }
  47867. api.dispatchAction({
  47868. type: 'changeMagicType',
  47869. currentType: currentType,
  47870. newOption: newOption,
  47871. newTitle: newTitle,
  47872. featureName: 'magicType'
  47873. });
  47874. };
  47875. return MagicType;
  47876. }(ToolboxFeature);
  47877. var seriesOptGenreator = {
  47878. 'line': function (seriesType, seriesId, seriesModel, model) {
  47879. if (seriesType === 'bar') {
  47880. return merge({
  47881. id: seriesId,
  47882. type: 'line',
  47883. // Preserve data related option
  47884. data: seriesModel.get('data'),
  47885. stack: seriesModel.get('stack'),
  47886. markPoint: seriesModel.get('markPoint'),
  47887. markLine: seriesModel.get('markLine')
  47888. }, model.get(['option', 'line']) || {}, true);
  47889. }
  47890. },
  47891. 'bar': function (seriesType, seriesId, seriesModel, model) {
  47892. if (seriesType === 'line') {
  47893. return merge({
  47894. id: seriesId,
  47895. type: 'bar',
  47896. // Preserve data related option
  47897. data: seriesModel.get('data'),
  47898. stack: seriesModel.get('stack'),
  47899. markPoint: seriesModel.get('markPoint'),
  47900. markLine: seriesModel.get('markLine')
  47901. }, model.get(['option', 'bar']) || {}, true);
  47902. }
  47903. },
  47904. 'stack': function (seriesType, seriesId, seriesModel, model) {
  47905. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  47906. if (seriesType === 'line' || seriesType === 'bar') {
  47907. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  47908. return merge({
  47909. id: seriesId,
  47910. stack: isStack ? '' : INNER_STACK_KEYWORD
  47911. }, model.get(['option', 'stack']) || {}, true);
  47912. }
  47913. }
  47914. };
  47915. // TODO: SELF REGISTERED.
  47916. registerAction({
  47917. type: 'changeMagicType',
  47918. event: 'magicTypeChanged',
  47919. update: 'prepareAndUpdate'
  47920. }, function (payload, ecModel) {
  47921. ecModel.mergeOption(payload.newOption);
  47922. });
  47923. /* global document */
  47924. var BLOCK_SPLITER = new Array(60).join('-');
  47925. var ITEM_SPLITER = '\t';
  47926. /**
  47927. * Group series into two types
  47928. * 1. on category axis, like line, bar
  47929. * 2. others, like scatter, pie
  47930. */
  47931. function groupSeries(ecModel) {
  47932. var seriesGroupByCategoryAxis = {};
  47933. var otherSeries = [];
  47934. var meta = [];
  47935. ecModel.eachRawSeries(function (seriesModel) {
  47936. var coordSys = seriesModel.coordinateSystem;
  47937. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  47938. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  47939. var baseAxis = coordSys.getBaseAxis();
  47940. if (baseAxis.type === 'category') {
  47941. var key = baseAxis.dim + '_' + baseAxis.index;
  47942. if (!seriesGroupByCategoryAxis[key]) {
  47943. seriesGroupByCategoryAxis[key] = {
  47944. categoryAxis: baseAxis,
  47945. valueAxis: coordSys.getOtherAxis(baseAxis),
  47946. series: []
  47947. };
  47948. meta.push({
  47949. axisDim: baseAxis.dim,
  47950. axisIndex: baseAxis.index
  47951. });
  47952. }
  47953. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  47954. } else {
  47955. otherSeries.push(seriesModel);
  47956. }
  47957. } else {
  47958. otherSeries.push(seriesModel);
  47959. }
  47960. });
  47961. return {
  47962. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  47963. other: otherSeries,
  47964. meta: meta
  47965. };
  47966. }
  47967. /**
  47968. * Assemble content of series on cateogory axis
  47969. * @inner
  47970. */
  47971. function assembleSeriesWithCategoryAxis(groups) {
  47972. var tables = [];
  47973. each(groups, function (group, key) {
  47974. var categoryAxis = group.categoryAxis;
  47975. var valueAxis = group.valueAxis;
  47976. var valueAxisDim = valueAxis.dim;
  47977. var headers = [' '].concat(map(group.series, function (series) {
  47978. return series.name;
  47979. }));
  47980. // @ts-ignore TODO Polar
  47981. var columns = [categoryAxis.model.getCategories()];
  47982. each(group.series, function (series) {
  47983. var rawData = series.getRawData();
  47984. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  47985. return val;
  47986. }));
  47987. });
  47988. // Assemble table content
  47989. var lines = [headers.join(ITEM_SPLITER)];
  47990. for (var i = 0; i < columns[0].length; i++) {
  47991. var items = [];
  47992. for (var j = 0; j < columns.length; j++) {
  47993. items.push(columns[j][i]);
  47994. }
  47995. lines.push(items.join(ITEM_SPLITER));
  47996. }
  47997. tables.push(lines.join('\n'));
  47998. });
  47999. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  48000. }
  48001. /**
  48002. * Assemble content of other series
  48003. */
  48004. function assembleOtherSeries(series) {
  48005. return map(series, function (series) {
  48006. var data = series.getRawData();
  48007. var lines = [series.name];
  48008. var vals = [];
  48009. data.each(data.dimensions, function () {
  48010. var argLen = arguments.length;
  48011. var dataIndex = arguments[argLen - 1];
  48012. var name = data.getName(dataIndex);
  48013. for (var i = 0; i < argLen - 1; i++) {
  48014. vals[i] = arguments[i];
  48015. }
  48016. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  48017. });
  48018. return lines.join('\n');
  48019. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  48020. }
  48021. function getContentFromModel(ecModel) {
  48022. var result = groupSeries(ecModel);
  48023. return {
  48024. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  48025. return !!str.replace(/[\n\t\s]/g, '');
  48026. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  48027. meta: result.meta
  48028. };
  48029. }
  48030. function trim$1(str) {
  48031. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  48032. }
  48033. /**
  48034. * If a block is tsv format
  48035. */
  48036. function isTSVFormat(block) {
  48037. // Simple method to find out if a block is tsv format
  48038. var firstLine = block.slice(0, block.indexOf('\n'));
  48039. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  48040. return true;
  48041. }
  48042. }
  48043. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  48044. /**
  48045. * @param {string} tsv
  48046. * @return {Object}
  48047. */
  48048. function parseTSVContents(tsv) {
  48049. var tsvLines = tsv.split(/\n+/g);
  48050. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  48051. var categories = [];
  48052. var series = map(headers, function (header) {
  48053. return {
  48054. name: header,
  48055. data: []
  48056. };
  48057. });
  48058. for (var i = 0; i < tsvLines.length; i++) {
  48059. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  48060. categories.push(items.shift());
  48061. for (var j = 0; j < items.length; j++) {
  48062. series[j] && (series[j].data[i] = items[j]);
  48063. }
  48064. }
  48065. return {
  48066. series: series,
  48067. categories: categories
  48068. };
  48069. }
  48070. function parseListContents(str) {
  48071. var lines = str.split(/\n+/g);
  48072. var seriesName = trim$1(lines.shift());
  48073. var data = [];
  48074. for (var i = 0; i < lines.length; i++) {
  48075. // if line is empty, ignore it.
  48076. // there is a case that a user forgot to delete `\n`.
  48077. var line = trim$1(lines[i]);
  48078. if (!line) {
  48079. continue;
  48080. }
  48081. var items = line.split(itemSplitRegex);
  48082. var name_1 = '';
  48083. var value = void 0;
  48084. var hasName = false;
  48085. if (isNaN(items[0])) {
  48086. // First item is name
  48087. hasName = true;
  48088. name_1 = items[0];
  48089. items = items.slice(1);
  48090. data[i] = {
  48091. name: name_1,
  48092. value: []
  48093. };
  48094. value = data[i].value;
  48095. } else {
  48096. value = data[i] = [];
  48097. }
  48098. for (var j = 0; j < items.length; j++) {
  48099. value.push(+items[j]);
  48100. }
  48101. if (value.length === 1) {
  48102. hasName ? data[i].value = value[0] : data[i] = value[0];
  48103. }
  48104. }
  48105. return {
  48106. name: seriesName,
  48107. data: data
  48108. };
  48109. }
  48110. function parseContents(str, blockMetaList) {
  48111. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  48112. var newOption = {
  48113. series: []
  48114. };
  48115. each(blocks, function (block, idx) {
  48116. if (isTSVFormat(block)) {
  48117. var result = parseTSVContents(block);
  48118. var blockMeta = blockMetaList[idx];
  48119. var axisKey = blockMeta.axisDim + 'Axis';
  48120. if (blockMeta) {
  48121. newOption[axisKey] = newOption[axisKey] || [];
  48122. newOption[axisKey][blockMeta.axisIndex] = {
  48123. data: result.categories
  48124. };
  48125. newOption.series = newOption.series.concat(result.series);
  48126. }
  48127. } else {
  48128. var result = parseListContents(block);
  48129. newOption.series.push(result);
  48130. }
  48131. });
  48132. return newOption;
  48133. }
  48134. var DataView = /** @class */function (_super) {
  48135. __extends(DataView, _super);
  48136. function DataView() {
  48137. return _super !== null && _super.apply(this, arguments) || this;
  48138. }
  48139. DataView.prototype.onclick = function (ecModel, api) {
  48140. // FIXME: better way?
  48141. setTimeout(function () {
  48142. api.dispatchAction({
  48143. type: 'hideTip'
  48144. });
  48145. });
  48146. var container = api.getDom();
  48147. var model = this.model;
  48148. if (this._dom) {
  48149. container.removeChild(this._dom);
  48150. }
  48151. var root = document.createElement('div');
  48152. // use padding to avoid 5px whitespace
  48153. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  48154. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  48155. // Create elements
  48156. var header = document.createElement('h4');
  48157. var lang = model.get('lang') || [];
  48158. header.innerHTML = lang[0] || model.get('title');
  48159. header.style.cssText = 'margin:10px 20px';
  48160. header.style.color = model.get('textColor');
  48161. var viewMain = document.createElement('div');
  48162. var textarea = document.createElement('textarea');
  48163. viewMain.style.cssText = 'overflow:auto';
  48164. var optionToContent = model.get('optionToContent');
  48165. var contentToOption = model.get('contentToOption');
  48166. var result = getContentFromModel(ecModel);
  48167. if (isFunction(optionToContent)) {
  48168. var htmlOrDom = optionToContent(api.getOption());
  48169. if (isString(htmlOrDom)) {
  48170. viewMain.innerHTML = htmlOrDom;
  48171. } else if (isDom(htmlOrDom)) {
  48172. viewMain.appendChild(htmlOrDom);
  48173. }
  48174. } else {
  48175. // Use default textarea
  48176. textarea.readOnly = model.get('readOnly');
  48177. var style = textarea.style;
  48178. // eslint-disable-next-line max-len
  48179. 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';
  48180. style.color = model.get('textColor');
  48181. style.borderColor = model.get('textareaBorderColor');
  48182. style.backgroundColor = model.get('textareaColor');
  48183. textarea.value = result.value;
  48184. viewMain.appendChild(textarea);
  48185. }
  48186. var blockMetaList = result.meta;
  48187. var buttonContainer = document.createElement('div');
  48188. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0';
  48189. // eslint-disable-next-line max-len
  48190. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  48191. var closeButton = document.createElement('div');
  48192. var refreshButton = document.createElement('div');
  48193. buttonStyle += ';background-color:' + model.get('buttonColor');
  48194. buttonStyle += ';color:' + model.get('buttonTextColor');
  48195. var self = this;
  48196. function close() {
  48197. container.removeChild(root);
  48198. self._dom = null;
  48199. }
  48200. addEventListener(closeButton, 'click', close);
  48201. addEventListener(refreshButton, 'click', function () {
  48202. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  48203. if ("development" !== 'production') {
  48204. // eslint-disable-next-line
  48205. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  48206. }
  48207. close();
  48208. return;
  48209. }
  48210. var newOption;
  48211. try {
  48212. if (isFunction(contentToOption)) {
  48213. newOption = contentToOption(viewMain, api.getOption());
  48214. } else {
  48215. newOption = parseContents(textarea.value, blockMetaList);
  48216. }
  48217. } catch (e) {
  48218. close();
  48219. throw new Error('Data view format error ' + e);
  48220. }
  48221. if (newOption) {
  48222. api.dispatchAction({
  48223. type: 'changeDataView',
  48224. newOption: newOption
  48225. });
  48226. }
  48227. close();
  48228. });
  48229. closeButton.innerHTML = lang[1];
  48230. refreshButton.innerHTML = lang[2];
  48231. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  48232. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  48233. buttonContainer.appendChild(closeButton);
  48234. root.appendChild(header);
  48235. root.appendChild(viewMain);
  48236. root.appendChild(buttonContainer);
  48237. viewMain.style.height = container.clientHeight - 80 + 'px';
  48238. container.appendChild(root);
  48239. this._dom = root;
  48240. };
  48241. DataView.prototype.remove = function (ecModel, api) {
  48242. this._dom && api.getDom().removeChild(this._dom);
  48243. };
  48244. DataView.prototype.dispose = function (ecModel, api) {
  48245. this.remove(ecModel, api);
  48246. };
  48247. DataView.getDefaultOption = function (ecModel) {
  48248. var defaultOption = {
  48249. show: true,
  48250. readOnly: false,
  48251. optionToContent: null,
  48252. contentToOption: null,
  48253. // eslint-disable-next-line
  48254. 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',
  48255. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  48256. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  48257. backgroundColor: '#fff',
  48258. textColor: '#000',
  48259. textareaColor: '#fff',
  48260. textareaBorderColor: '#333',
  48261. buttonColor: '#c23531',
  48262. buttonTextColor: '#fff'
  48263. };
  48264. return defaultOption;
  48265. };
  48266. return DataView;
  48267. }(ToolboxFeature);
  48268. /**
  48269. * @inner
  48270. */
  48271. function tryMergeDataOption(newData, originalData) {
  48272. return map(newData, function (newVal, idx) {
  48273. var original = originalData && originalData[idx];
  48274. if (isObject(original) && !isArray(original)) {
  48275. var newValIsObject = isObject(newVal) && !isArray(newVal);
  48276. if (!newValIsObject) {
  48277. newVal = {
  48278. value: newVal
  48279. };
  48280. }
  48281. // original data has name but new data has no name
  48282. var shouldDeleteName = original.name != null && newVal.name == null;
  48283. // Original data has option
  48284. newVal = defaults(newVal, original);
  48285. shouldDeleteName && delete newVal.name;
  48286. return newVal;
  48287. } else {
  48288. return newVal;
  48289. }
  48290. });
  48291. }
  48292. // TODO: SELF REGISTERED.
  48293. registerAction({
  48294. type: 'changeDataView',
  48295. event: 'dataViewChanged',
  48296. update: 'prepareAndUpdate'
  48297. }, function (payload, ecModel) {
  48298. var newSeriesOptList = [];
  48299. each(payload.newOption.series, function (seriesOpt) {
  48300. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  48301. if (!seriesModel) {
  48302. // New created series
  48303. // Geuss the series type
  48304. newSeriesOptList.push(extend({
  48305. // Default is scatter
  48306. type: 'scatter'
  48307. }, seriesOpt));
  48308. } else {
  48309. var originalData = seriesModel.get('data');
  48310. newSeriesOptList.push({
  48311. name: seriesOpt.name,
  48312. data: tryMergeDataOption(seriesOpt.data, originalData)
  48313. });
  48314. }
  48315. });
  48316. ecModel.mergeOption(defaults({
  48317. series: newSeriesOptList
  48318. }, payload.newOption));
  48319. });
  48320. var each$5 = each;
  48321. var inner$b = makeInner();
  48322. /**
  48323. * @param ecModel
  48324. * @param newSnapshot key is dataZoomId
  48325. */
  48326. function push(ecModel, newSnapshot) {
  48327. var storedSnapshots = getStoreSnapshots(ecModel);
  48328. // If previous dataZoom can not be found,
  48329. // complete an range with current range.
  48330. each$5(newSnapshot, function (batchItem, dataZoomId) {
  48331. var i = storedSnapshots.length - 1;
  48332. for (; i >= 0; i--) {
  48333. var snapshot = storedSnapshots[i];
  48334. if (snapshot[dataZoomId]) {
  48335. break;
  48336. }
  48337. }
  48338. if (i < 0) {
  48339. // No origin range set, create one by current range.
  48340. var dataZoomModel = ecModel.queryComponents({
  48341. mainType: 'dataZoom',
  48342. subType: 'select',
  48343. id: dataZoomId
  48344. })[0];
  48345. if (dataZoomModel) {
  48346. var percentRange = dataZoomModel.getPercentRange();
  48347. storedSnapshots[0][dataZoomId] = {
  48348. dataZoomId: dataZoomId,
  48349. start: percentRange[0],
  48350. end: percentRange[1]
  48351. };
  48352. }
  48353. }
  48354. });
  48355. storedSnapshots.push(newSnapshot);
  48356. }
  48357. function pop(ecModel) {
  48358. var storedSnapshots = getStoreSnapshots(ecModel);
  48359. var head = storedSnapshots[storedSnapshots.length - 1];
  48360. storedSnapshots.length > 1 && storedSnapshots.pop();
  48361. // Find top for all dataZoom.
  48362. var snapshot = {};
  48363. each$5(head, function (batchItem, dataZoomId) {
  48364. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  48365. batchItem = storedSnapshots[i][dataZoomId];
  48366. if (batchItem) {
  48367. snapshot[dataZoomId] = batchItem;
  48368. break;
  48369. }
  48370. }
  48371. });
  48372. return snapshot;
  48373. }
  48374. function clear$1(ecModel) {
  48375. inner$b(ecModel).snapshots = null;
  48376. }
  48377. function count(ecModel) {
  48378. return getStoreSnapshots(ecModel).length;
  48379. }
  48380. /**
  48381. * History length of each dataZoom may be different.
  48382. * this._history[0] is used to store origin range.
  48383. */
  48384. function getStoreSnapshots(ecModel) {
  48385. var store = inner$b(ecModel);
  48386. if (!store.snapshots) {
  48387. store.snapshots = [{}];
  48388. }
  48389. return store.snapshots;
  48390. }
  48391. var RestoreOption = /** @class */function (_super) {
  48392. __extends(RestoreOption, _super);
  48393. function RestoreOption() {
  48394. return _super !== null && _super.apply(this, arguments) || this;
  48395. }
  48396. RestoreOption.prototype.onclick = function (ecModel, api) {
  48397. clear$1(ecModel);
  48398. api.dispatchAction({
  48399. type: 'restore',
  48400. from: this.uid
  48401. });
  48402. };
  48403. RestoreOption.getDefaultOption = function (ecModel) {
  48404. var defaultOption = {
  48405. show: true,
  48406. // eslint-disable-next-line
  48407. 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',
  48408. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  48409. };
  48410. return defaultOption;
  48411. };
  48412. return RestoreOption;
  48413. }(ToolboxFeature);
  48414. // TODO: SELF REGISTERED.
  48415. registerAction({
  48416. type: 'restore',
  48417. event: 'restore',
  48418. update: 'prepareAndUpdate'
  48419. }, function (payload, ecModel) {
  48420. ecModel.resetOption('recreate');
  48421. });
  48422. var ATTR = '\0_ec_interaction_mutex';
  48423. function take(zr, resourceKey, userKey) {
  48424. var store = getStore(zr);
  48425. store[resourceKey] = userKey;
  48426. }
  48427. function release(zr, resourceKey, userKey) {
  48428. var store = getStore(zr);
  48429. var uKey = store[resourceKey];
  48430. if (uKey === userKey) {
  48431. store[resourceKey] = null;
  48432. }
  48433. }
  48434. function isTaken(zr, resourceKey) {
  48435. return !!getStore(zr)[resourceKey];
  48436. }
  48437. function getStore(zr) {
  48438. return zr[ATTR] || (zr[ATTR] = {});
  48439. }
  48440. /**
  48441. * payload: {
  48442. * type: 'takeGlobalCursor',
  48443. * key: 'dataZoomSelect', or 'brush', or ...,
  48444. * If no userKey, release global cursor.
  48445. * }
  48446. */
  48447. // TODO: SELF REGISTERED.
  48448. registerAction({
  48449. type: 'takeGlobalCursor',
  48450. event: 'globalCursorTaken',
  48451. update: 'update'
  48452. }, noop);
  48453. var BRUSH_PANEL_GLOBAL = true;
  48454. var mathMin$7 = Math.min;
  48455. var mathMax$7 = Math.max;
  48456. var mathPow$2 = Math.pow;
  48457. var COVER_Z = 10000;
  48458. var UNSELECT_THRESHOLD = 6;
  48459. var MIN_RESIZE_LINE_WIDTH = 6;
  48460. var MUTEX_RESOURCE_KEY = 'globalPan';
  48461. var DIRECTION_MAP = {
  48462. w: [0, 0],
  48463. e: [0, 1],
  48464. n: [1, 0],
  48465. s: [1, 1]
  48466. };
  48467. var CURSOR_MAP = {
  48468. w: 'ew',
  48469. e: 'ew',
  48470. n: 'ns',
  48471. s: 'ns',
  48472. ne: 'nesw',
  48473. sw: 'nesw',
  48474. nw: 'nwse',
  48475. se: 'nwse'
  48476. };
  48477. var DEFAULT_BRUSH_OPT = {
  48478. brushStyle: {
  48479. lineWidth: 2,
  48480. stroke: 'rgba(210,219,238,0.3)',
  48481. fill: '#D2DBEE'
  48482. },
  48483. transformable: true,
  48484. brushMode: 'single',
  48485. removeOnClick: false
  48486. };
  48487. var baseUID = 0;
  48488. /**
  48489. * params:
  48490. * areas: Array.<Array>, coord relates to container group,
  48491. * If no container specified, to global.
  48492. * opt {
  48493. * isEnd: boolean,
  48494. * removeOnClick: boolean
  48495. * }
  48496. */
  48497. var BrushController = /** @class */function (_super) {
  48498. __extends(BrushController, _super);
  48499. function BrushController(zr) {
  48500. var _this = _super.call(this) || this;
  48501. /**
  48502. * @internal
  48503. */
  48504. _this._track = [];
  48505. /**
  48506. * @internal
  48507. */
  48508. _this._covers = [];
  48509. _this._handlers = {};
  48510. if ("development" !== 'production') {
  48511. assert(zr);
  48512. }
  48513. _this._zr = zr;
  48514. _this.group = new Group();
  48515. _this._uid = 'brushController_' + baseUID++;
  48516. each(pointerHandlers, function (handler, eventName) {
  48517. this._handlers[eventName] = bind(handler, this);
  48518. }, _this);
  48519. return _this;
  48520. }
  48521. /**
  48522. * If set to `false`, select disabled.
  48523. */
  48524. BrushController.prototype.enableBrush = function (brushOption) {
  48525. if ("development" !== 'production') {
  48526. assert(this._mounted);
  48527. }
  48528. this._brushType && this._doDisableBrush();
  48529. brushOption.brushType && this._doEnableBrush(brushOption);
  48530. return this;
  48531. };
  48532. BrushController.prototype._doEnableBrush = function (brushOption) {
  48533. var zr = this._zr;
  48534. // Consider roam, which takes globalPan too.
  48535. if (!this._enableGlobalPan) {
  48536. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  48537. }
  48538. each(this._handlers, function (handler, eventName) {
  48539. zr.on(eventName, handler);
  48540. });
  48541. this._brushType = brushOption.brushType;
  48542. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48543. };
  48544. BrushController.prototype._doDisableBrush = function () {
  48545. var zr = this._zr;
  48546. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  48547. each(this._handlers, function (handler, eventName) {
  48548. zr.off(eventName, handler);
  48549. });
  48550. this._brushType = this._brushOption = null;
  48551. };
  48552. /**
  48553. * @param panelOpts If not pass, it is global brush.
  48554. */
  48555. BrushController.prototype.setPanels = function (panelOpts) {
  48556. if (panelOpts && panelOpts.length) {
  48557. var panels_1 = this._panels = {};
  48558. each(panelOpts, function (panelOpts) {
  48559. panels_1[panelOpts.panelId] = clone(panelOpts);
  48560. });
  48561. } else {
  48562. this._panels = null;
  48563. }
  48564. return this;
  48565. };
  48566. BrushController.prototype.mount = function (opt) {
  48567. opt = opt || {};
  48568. if ("development" !== 'production') {
  48569. this._mounted = true; // should be at first.
  48570. }
  48571. this._enableGlobalPan = opt.enableGlobalPan;
  48572. var thisGroup = this.group;
  48573. this._zr.add(thisGroup);
  48574. thisGroup.attr({
  48575. x: opt.x || 0,
  48576. y: opt.y || 0,
  48577. rotation: opt.rotation || 0,
  48578. scaleX: opt.scaleX || 1,
  48579. scaleY: opt.scaleY || 1
  48580. });
  48581. this._transform = thisGroup.getLocalTransform();
  48582. return this;
  48583. };
  48584. // eachCover(cb, context): void {
  48585. // each(this._covers, cb, context);
  48586. // }
  48587. /**
  48588. * Update covers.
  48589. * @param coverConfigList
  48590. * If coverConfigList is null/undefined, all covers removed.
  48591. */
  48592. BrushController.prototype.updateCovers = function (coverConfigList) {
  48593. if ("development" !== 'production') {
  48594. assert(this._mounted);
  48595. }
  48596. coverConfigList = map(coverConfigList, function (coverConfig) {
  48597. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  48598. });
  48599. var tmpIdPrefix = '\0-brush-index-';
  48600. var oldCovers = this._covers;
  48601. var newCovers = this._covers = [];
  48602. var controller = this;
  48603. var creatingCover = this._creatingCover;
  48604. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  48605. return this;
  48606. function getKey(brushOption, index) {
  48607. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  48608. }
  48609. function oldGetKey(cover, index) {
  48610. return getKey(cover.__brushOption, index);
  48611. }
  48612. function addOrUpdate(newIndex, oldIndex) {
  48613. var newBrushInternal = coverConfigList[newIndex];
  48614. // Consider setOption in event listener of brushSelect,
  48615. // where updating cover when creating should be forbidden.
  48616. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  48617. newCovers[newIndex] = oldCovers[oldIndex];
  48618. } else {
  48619. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  48620. updateCoverAfterCreation(controller, cover);
  48621. }
  48622. }
  48623. function remove(oldIndex) {
  48624. if (oldCovers[oldIndex] !== creatingCover) {
  48625. controller.group.remove(oldCovers[oldIndex]);
  48626. }
  48627. }
  48628. };
  48629. BrushController.prototype.unmount = function () {
  48630. if ("development" !== 'production') {
  48631. if (!this._mounted) {
  48632. return;
  48633. }
  48634. }
  48635. this.enableBrush(false);
  48636. // container may 'removeAll' outside.
  48637. clearCovers(this);
  48638. this._zr.remove(this.group);
  48639. if ("development" !== 'production') {
  48640. this._mounted = false; // should be at last.
  48641. }
  48642. return this;
  48643. };
  48644. BrushController.prototype.dispose = function () {
  48645. this.unmount();
  48646. this.off();
  48647. };
  48648. return BrushController;
  48649. }(Eventful);
  48650. function createCover(controller, brushOption) {
  48651. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  48652. cover.__brushOption = brushOption;
  48653. updateZ(cover, brushOption);
  48654. controller.group.add(cover);
  48655. return cover;
  48656. }
  48657. function endCreating(controller, creatingCover) {
  48658. var coverRenderer = getCoverRenderer(creatingCover);
  48659. if (coverRenderer.endCreating) {
  48660. coverRenderer.endCreating(controller, creatingCover);
  48661. updateZ(creatingCover, creatingCover.__brushOption);
  48662. }
  48663. return creatingCover;
  48664. }
  48665. function updateCoverShape(controller, cover) {
  48666. var brushOption = cover.__brushOption;
  48667. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  48668. }
  48669. function updateZ(cover, brushOption) {
  48670. var z = brushOption.z;
  48671. z == null && (z = COVER_Z);
  48672. cover.traverse(function (el) {
  48673. el.z = z;
  48674. el.z2 = z; // Consider in given container.
  48675. });
  48676. }
  48677. function updateCoverAfterCreation(controller, cover) {
  48678. getCoverRenderer(cover).updateCommon(controller, cover);
  48679. updateCoverShape(controller, cover);
  48680. }
  48681. function getCoverRenderer(cover) {
  48682. return coverRenderers[cover.__brushOption.brushType];
  48683. }
  48684. // return target panel or `true` (means global panel)
  48685. function getPanelByPoint(controller, e, localCursorPoint) {
  48686. var panels = controller._panels;
  48687. if (!panels) {
  48688. return BRUSH_PANEL_GLOBAL; // Global panel
  48689. }
  48690. var panel;
  48691. var transform = controller._transform;
  48692. each(panels, function (pn) {
  48693. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  48694. });
  48695. return panel;
  48696. }
  48697. // Return a panel or true
  48698. function getPanelByCover(controller, cover) {
  48699. var panels = controller._panels;
  48700. if (!panels) {
  48701. return BRUSH_PANEL_GLOBAL; // Global panel
  48702. }
  48703. var panelId = cover.__brushOption.panelId;
  48704. // User may give cover without coord sys info,
  48705. // which is then treated as global panel.
  48706. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  48707. }
  48708. function clearCovers(controller) {
  48709. var covers = controller._covers;
  48710. var originalLength = covers.length;
  48711. each(covers, function (cover) {
  48712. controller.group.remove(cover);
  48713. }, controller);
  48714. covers.length = 0;
  48715. return !!originalLength;
  48716. }
  48717. function trigger(controller, opt) {
  48718. var areas = map(controller._covers, function (cover) {
  48719. var brushOption = cover.__brushOption;
  48720. var range = clone(brushOption.range);
  48721. return {
  48722. brushType: brushOption.brushType,
  48723. panelId: brushOption.panelId,
  48724. range: range
  48725. };
  48726. });
  48727. controller.trigger('brush', {
  48728. areas: areas,
  48729. isEnd: !!opt.isEnd,
  48730. removeOnClick: !!opt.removeOnClick
  48731. });
  48732. }
  48733. function shouldShowCover(controller) {
  48734. var track = controller._track;
  48735. if (!track.length) {
  48736. return false;
  48737. }
  48738. var p2 = track[track.length - 1];
  48739. var p1 = track[0];
  48740. var dx = p2[0] - p1[0];
  48741. var dy = p2[1] - p1[1];
  48742. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  48743. return dist > UNSELECT_THRESHOLD;
  48744. }
  48745. function getTrackEnds(track) {
  48746. var tail = track.length - 1;
  48747. tail < 0 && (tail = 0);
  48748. return [track[0], track[tail]];
  48749. }
  48750. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  48751. var cover = new Group();
  48752. cover.add(new Rect({
  48753. name: 'main',
  48754. style: makeStyle(brushOption),
  48755. silent: true,
  48756. draggable: true,
  48757. cursor: 'move',
  48758. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  48759. ondragend: curry(trigger, controller, {
  48760. isEnd: true
  48761. })
  48762. }));
  48763. each(edgeNameSequences, function (nameSequence) {
  48764. cover.add(new Rect({
  48765. name: nameSequence.join(''),
  48766. style: {
  48767. opacity: 0
  48768. },
  48769. draggable: true,
  48770. silent: true,
  48771. invisible: true,
  48772. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  48773. ondragend: curry(trigger, controller, {
  48774. isEnd: true
  48775. })
  48776. }));
  48777. });
  48778. return cover;
  48779. }
  48780. function updateBaseRect(controller, cover, localRange, brushOption) {
  48781. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  48782. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  48783. var x = localRange[0][0];
  48784. var y = localRange[1][0];
  48785. var xa = x - lineWidth / 2;
  48786. var ya = y - lineWidth / 2;
  48787. var x2 = localRange[0][1];
  48788. var y2 = localRange[1][1];
  48789. var x2a = x2 - handleSize + lineWidth / 2;
  48790. var y2a = y2 - handleSize + lineWidth / 2;
  48791. var width = x2 - x;
  48792. var height = y2 - y;
  48793. var widtha = width + lineWidth;
  48794. var heighta = height + lineWidth;
  48795. updateRectShape(controller, cover, 'main', x, y, width, height);
  48796. if (brushOption.transformable) {
  48797. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  48798. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  48799. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  48800. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  48801. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  48802. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  48803. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  48804. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  48805. }
  48806. }
  48807. function updateCommon(controller, cover) {
  48808. var brushOption = cover.__brushOption;
  48809. var transformable = brushOption.transformable;
  48810. var mainEl = cover.childAt(0);
  48811. mainEl.useStyle(makeStyle(brushOption));
  48812. mainEl.attr({
  48813. silent: !transformable,
  48814. cursor: transformable ? 'move' : 'default'
  48815. });
  48816. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  48817. var el = cover.childOfName(nameSequence.join(''));
  48818. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  48819. el && el.attr({
  48820. silent: !transformable,
  48821. invisible: !transformable,
  48822. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  48823. });
  48824. });
  48825. }
  48826. function updateRectShape(controller, cover, name, x, y, w, h) {
  48827. var el = cover.childOfName(name);
  48828. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  48829. }
  48830. function makeStyle(brushOption) {
  48831. return defaults({
  48832. strokeNoScale: true
  48833. }, brushOption.brushStyle);
  48834. }
  48835. function formatRectRange(x, y, x2, y2) {
  48836. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  48837. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  48838. return [[min[0], max[0]], [min[1], max[1]] // y range
  48839. ];
  48840. }
  48841. function getTransform$1(controller) {
  48842. return getTransform(controller.group);
  48843. }
  48844. function getGlobalDirection1(controller, localDirName) {
  48845. var map = {
  48846. w: 'left',
  48847. e: 'right',
  48848. n: 'top',
  48849. s: 'bottom'
  48850. };
  48851. var inverseMap = {
  48852. left: 'w',
  48853. right: 'e',
  48854. top: 'n',
  48855. bottom: 's'
  48856. };
  48857. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  48858. return inverseMap[dir];
  48859. }
  48860. function getGlobalDirection2(controller, localDirNameSeq) {
  48861. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  48862. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  48863. return globalDir.join('');
  48864. }
  48865. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  48866. var brushOption = cover.__brushOption;
  48867. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  48868. var localDelta = toLocalDelta(controller, dx, dy);
  48869. each(dirNameSequence, function (dirName) {
  48870. var ind = DIRECTION_MAP[dirName];
  48871. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  48872. });
  48873. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  48874. updateCoverAfterCreation(controller, cover);
  48875. trigger(controller, {
  48876. isEnd: false
  48877. });
  48878. }
  48879. function driftPolygon(controller, cover, dx, dy) {
  48880. var range = cover.__brushOption.range;
  48881. var localDelta = toLocalDelta(controller, dx, dy);
  48882. each(range, function (point) {
  48883. point[0] += localDelta[0];
  48884. point[1] += localDelta[1];
  48885. });
  48886. updateCoverAfterCreation(controller, cover);
  48887. trigger(controller, {
  48888. isEnd: false
  48889. });
  48890. }
  48891. function toLocalDelta(controller, dx, dy) {
  48892. var thisGroup = controller.group;
  48893. var localD = thisGroup.transformCoordToLocal(dx, dy);
  48894. var localZero = thisGroup.transformCoordToLocal(0, 0);
  48895. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  48896. }
  48897. function clipByPanel(controller, cover, data) {
  48898. var panel = getPanelByCover(controller, cover);
  48899. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  48900. }
  48901. function pointsToRect(points) {
  48902. var xmin = mathMin$7(points[0][0], points[1][0]);
  48903. var ymin = mathMin$7(points[0][1], points[1][1]);
  48904. var xmax = mathMax$7(points[0][0], points[1][0]);
  48905. var ymax = mathMax$7(points[0][1], points[1][1]);
  48906. return {
  48907. x: xmin,
  48908. y: ymin,
  48909. width: xmax - xmin,
  48910. height: ymax - ymin
  48911. };
  48912. }
  48913. function resetCursor(controller, e, localCursorPoint) {
  48914. if (
  48915. // Check active
  48916. !controller._brushType
  48917. // resetCursor should be always called when mouse is in zr area,
  48918. // but not called when mouse is out of zr area to avoid bad influence
  48919. // if `mousemove`, `mouseup` are triggered from `document` event.
  48920. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  48921. return;
  48922. }
  48923. var zr = controller._zr;
  48924. var covers = controller._covers;
  48925. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  48926. // Check whether in covers.
  48927. if (!controller._dragging) {
  48928. for (var i = 0; i < covers.length; i++) {
  48929. var brushOption = covers[i].__brushOption;
  48930. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  48931. // Use cursor style set on cover.
  48932. return;
  48933. }
  48934. }
  48935. }
  48936. currPanel && zr.setCursorStyle('crosshair');
  48937. }
  48938. function preventDefault(e) {
  48939. var rawE = e.event;
  48940. rawE.preventDefault && rawE.preventDefault();
  48941. }
  48942. function mainShapeContain(cover, x, y) {
  48943. return cover.childOfName('main').contain(x, y);
  48944. }
  48945. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  48946. var creatingCover = controller._creatingCover;
  48947. var panel = controller._creatingPanel;
  48948. var thisBrushOption = controller._brushOption;
  48949. var eventParams;
  48950. controller._track.push(localCursorPoint.slice());
  48951. if (shouldShowCover(controller) || creatingCover) {
  48952. if (panel && !creatingCover) {
  48953. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  48954. var brushOption = clone(thisBrushOption);
  48955. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  48956. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  48957. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  48958. controller._covers.push(creatingCover);
  48959. }
  48960. if (creatingCover) {
  48961. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  48962. var coverBrushOption = creatingCover.__brushOption;
  48963. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  48964. if (isEnd) {
  48965. endCreating(controller, creatingCover);
  48966. coverRenderer.updateCommon(controller, creatingCover);
  48967. }
  48968. updateCoverShape(controller, creatingCover);
  48969. eventParams = {
  48970. isEnd: isEnd
  48971. };
  48972. }
  48973. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  48974. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  48975. // But a single click do not clear covers, because user may have casual
  48976. // clicks (for example, click on other component and do not expect covers
  48977. // disappear).
  48978. // Only some cover removed, trigger action, but not every click trigger action.
  48979. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  48980. eventParams = {
  48981. isEnd: isEnd,
  48982. removeOnClick: true
  48983. };
  48984. }
  48985. }
  48986. return eventParams;
  48987. }
  48988. function determineBrushType(brushType, panel) {
  48989. if (brushType === 'auto') {
  48990. if ("development" !== 'production') {
  48991. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  48992. }
  48993. return panel.defaultBrushType;
  48994. }
  48995. return brushType;
  48996. }
  48997. var pointerHandlers = {
  48998. mousedown: function (e) {
  48999. if (this._dragging) {
  49000. // In case some browser do not support globalOut,
  49001. // and release mouse out side the browser.
  49002. handleDragEnd(this, e);
  49003. } else if (!e.target || !e.target.draggable) {
  49004. preventDefault(e);
  49005. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  49006. this._creatingCover = null;
  49007. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  49008. if (panel) {
  49009. this._dragging = true;
  49010. this._track = [localCursorPoint.slice()];
  49011. }
  49012. }
  49013. },
  49014. mousemove: function (e) {
  49015. var x = e.offsetX;
  49016. var y = e.offsetY;
  49017. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  49018. resetCursor(this, e, localCursorPoint);
  49019. if (this._dragging) {
  49020. preventDefault(e);
  49021. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  49022. eventParams && trigger(this, eventParams);
  49023. }
  49024. },
  49025. mouseup: function (e) {
  49026. handleDragEnd(this, e);
  49027. }
  49028. };
  49029. function handleDragEnd(controller, e) {
  49030. if (controller._dragging) {
  49031. preventDefault(e);
  49032. var x = e.offsetX;
  49033. var y = e.offsetY;
  49034. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  49035. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  49036. controller._dragging = false;
  49037. controller._track = [];
  49038. controller._creatingCover = null;
  49039. // trigger event should be at final, after procedure will be nested.
  49040. eventParams && trigger(controller, eventParams);
  49041. }
  49042. }
  49043. function isOutsideZrArea(controller, x, y) {
  49044. var zr = controller._zr;
  49045. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  49046. }
  49047. /**
  49048. * key: brushType
  49049. */
  49050. var coverRenderers = {
  49051. lineX: getLineRenderer(0),
  49052. lineY: getLineRenderer(1),
  49053. rect: {
  49054. createCover: function (controller, brushOption) {
  49055. function returnInput(range) {
  49056. return range;
  49057. }
  49058. return createBaseRectCover({
  49059. toRectRange: returnInput,
  49060. fromRectRange: returnInput
  49061. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  49062. },
  49063. getCreatingRange: function (localTrack) {
  49064. var ends = getTrackEnds(localTrack);
  49065. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  49066. },
  49067. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49068. updateBaseRect(controller, cover, localRange, brushOption);
  49069. },
  49070. updateCommon: updateCommon,
  49071. contain: mainShapeContain
  49072. },
  49073. polygon: {
  49074. createCover: function (controller, brushOption) {
  49075. var cover = new Group();
  49076. // Do not use graphic.Polygon because graphic.Polyline do not close the
  49077. // border of the shape when drawing, which is a better experience for user.
  49078. cover.add(new Polyline({
  49079. name: 'main',
  49080. style: makeStyle(brushOption),
  49081. silent: true
  49082. }));
  49083. return cover;
  49084. },
  49085. getCreatingRange: function (localTrack) {
  49086. return localTrack;
  49087. },
  49088. endCreating: function (controller, cover) {
  49089. cover.remove(cover.childAt(0));
  49090. // Use graphic.Polygon close the shape.
  49091. cover.add(new Polygon({
  49092. name: 'main',
  49093. draggable: true,
  49094. drift: curry(driftPolygon, controller, cover),
  49095. ondragend: curry(trigger, controller, {
  49096. isEnd: true
  49097. })
  49098. }));
  49099. },
  49100. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49101. cover.childAt(0).setShape({
  49102. points: clipByPanel(controller, cover, localRange)
  49103. });
  49104. },
  49105. updateCommon: updateCommon,
  49106. contain: mainShapeContain
  49107. }
  49108. };
  49109. function getLineRenderer(xyIndex) {
  49110. return {
  49111. createCover: function (controller, brushOption) {
  49112. return createBaseRectCover({
  49113. toRectRange: function (range) {
  49114. var rectRange = [range, [0, 100]];
  49115. xyIndex && rectRange.reverse();
  49116. return rectRange;
  49117. },
  49118. fromRectRange: function (rectRange) {
  49119. return rectRange[xyIndex];
  49120. }
  49121. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  49122. },
  49123. getCreatingRange: function (localTrack) {
  49124. var ends = getTrackEnds(localTrack);
  49125. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  49126. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  49127. return [min, max];
  49128. },
  49129. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49130. var otherExtent;
  49131. // If brushWidth not specified, fit the panel.
  49132. var panel = getPanelByCover(controller, cover);
  49133. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  49134. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  49135. } else {
  49136. var zr = controller._zr;
  49137. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  49138. }
  49139. var rectRange = [localRange, otherExtent];
  49140. xyIndex && rectRange.reverse();
  49141. updateBaseRect(controller, cover, rectRange, brushOption);
  49142. },
  49143. updateCommon: updateCommon,
  49144. contain: mainShapeContain
  49145. };
  49146. }
  49147. /*
  49148. * Licensed to the Apache Software Foundation (ASF) under one
  49149. * or more contributor license agreements. See the NOTICE file
  49150. * distributed with this work for additional information
  49151. * regarding copyright ownership. The ASF licenses this file
  49152. * to you under the Apache License, Version 2.0 (the
  49153. * "License"); you may not use this file except in compliance
  49154. * with the License. You may obtain a copy of the License at
  49155. *
  49156. * http://www.apache.org/licenses/LICENSE-2.0
  49157. *
  49158. * Unless required by applicable law or agreed to in writing,
  49159. * software distributed under the License is distributed on an
  49160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49161. * KIND, either express or implied. See the License for the
  49162. * specific language governing permissions and limitations
  49163. * under the License.
  49164. */
  49165. /**
  49166. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49167. */
  49168. /*
  49169. * Licensed to the Apache Software Foundation (ASF) under one
  49170. * or more contributor license agreements. See the NOTICE file
  49171. * distributed with this work for additional information
  49172. * regarding copyright ownership. The ASF licenses this file
  49173. * to you under the Apache License, Version 2.0 (the
  49174. * "License"); you may not use this file except in compliance
  49175. * with the License. You may obtain a copy of the License at
  49176. *
  49177. * http://www.apache.org/licenses/LICENSE-2.0
  49178. *
  49179. * Unless required by applicable law or agreed to in writing,
  49180. * software distributed under the License is distributed on an
  49181. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49182. * KIND, either express or implied. See the License for the
  49183. * specific language governing permissions and limitations
  49184. * under the License.
  49185. */
  49186. var IRRELEVANT_EXCLUDES = {
  49187. 'axisPointer': 1,
  49188. 'tooltip': 1,
  49189. 'brush': 1
  49190. };
  49191. /**
  49192. * Avoid that: mouse click on a elements that is over geo or graph,
  49193. * but roam is triggered.
  49194. */
  49195. function onIrrelevantElement(e, api, targetCoordSysModel) {
  49196. var model = api.getComponentByElement(e.topTarget);
  49197. // If model is axisModel, it works only if it is injected with coordinateSystem.
  49198. var coordSys = model && model.coordinateSystem;
  49199. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  49200. }
  49201. function makeRectPanelClipPath(rect) {
  49202. rect = normalizeRect(rect);
  49203. return function (localPoints) {
  49204. return clipPointsByRect(localPoints, rect);
  49205. };
  49206. }
  49207. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  49208. rect = normalizeRect(rect);
  49209. return function (xyIndex) {
  49210. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  49211. var brushWidth = idx ? rect.width : rect.height;
  49212. var base = idx ? rect.x : rect.y;
  49213. return [base, base + (brushWidth || 0)];
  49214. };
  49215. }
  49216. function makeRectIsTargetByCursor(rect, api, targetModel) {
  49217. var boundingRect = normalizeRect(rect);
  49218. return function (e, localCursorPoint) {
  49219. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  49220. };
  49221. }
  49222. // Consider width/height is negative.
  49223. function normalizeRect(rect) {
  49224. return BoundingRect.create(rect);
  49225. }
  49226. // FIXME
  49227. // how to genarialize to more coordinate systems.
  49228. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  49229. var BrushTargetManager = /** @class */function () {
  49230. /**
  49231. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  49232. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  49233. * @param opt.include include coordinate system types.
  49234. */
  49235. function BrushTargetManager(finder, ecModel, opt) {
  49236. var _this = this;
  49237. this._targetInfoList = [];
  49238. var foundCpts = parseFinder$1(ecModel, finder);
  49239. each(targetInfoBuilders, function (builder, type) {
  49240. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  49241. builder(foundCpts, _this._targetInfoList);
  49242. }
  49243. });
  49244. }
  49245. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  49246. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  49247. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  49248. // area.coordRange is the first of area.coordRanges
  49249. if (!area.coordRange) {
  49250. area.coordRange = coordRange;
  49251. // In 'category' axis, coord to pixel is not reversible, so we can not
  49252. // rebuild range by coordRange accrately, which may bring trouble when
  49253. // brushing only one item. So we use __rangeOffset to rebuilding range
  49254. // by coordRange. And this it only used in brush component so it is no
  49255. // need to be adapted to coordRanges.
  49256. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  49257. area.__rangeOffset = {
  49258. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  49259. xyMinMax: result.xyMinMax
  49260. };
  49261. }
  49262. });
  49263. return areas;
  49264. };
  49265. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  49266. each(areas, function (area) {
  49267. var targetInfo = this.findTargetInfo(area, ecModel);
  49268. if (targetInfo && targetInfo !== true) {
  49269. each(targetInfo.coordSyses, function (coordSys) {
  49270. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  49271. cb(area, result.values, coordSys, ecModel);
  49272. });
  49273. }
  49274. }, this);
  49275. };
  49276. /**
  49277. * the `areas` is `BrushModel.areas`.
  49278. * Called in layout stage.
  49279. * convert `area.coordRange` to global range and set panelId to `area.range`.
  49280. */
  49281. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  49282. each(areas, function (area) {
  49283. var targetInfo = this.findTargetInfo(area, ecModel);
  49284. if ("development" !== 'production') {
  49285. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  49286. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  49287. }
  49288. area.range = area.range || [];
  49289. // convert coordRange to global range and set panelId.
  49290. if (targetInfo && targetInfo !== true) {
  49291. area.panelId = targetInfo.panelId;
  49292. // (1) area.range should always be calculate from coordRange but does
  49293. // not keep its original value, for the sake of the dataZoom scenario,
  49294. // where area.coordRange remains unchanged but area.range may be changed.
  49295. // (2) Only support converting one coordRange to pixel range in brush
  49296. // component. So do not consider `coordRanges`.
  49297. // (3) About __rangeOffset, see comment above.
  49298. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  49299. var rangeOffset = area.__rangeOffset;
  49300. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  49301. }
  49302. }, this);
  49303. };
  49304. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  49305. return map(this._targetInfoList, function (targetInfo) {
  49306. var rect = targetInfo.getPanelRect();
  49307. return {
  49308. panelId: targetInfo.panelId,
  49309. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  49310. clipPath: makeRectPanelClipPath(rect),
  49311. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  49312. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  49313. };
  49314. });
  49315. };
  49316. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  49317. // Check whether area is bound in coord, and series do not belong to that coord.
  49318. // If do not do this check, some brush (like lineX) will controll all axes.
  49319. var targetInfo = this.findTargetInfo(area, ecModel);
  49320. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  49321. };
  49322. /**
  49323. * If return Object, a coord found.
  49324. * If return true, global found.
  49325. * Otherwise nothing found.
  49326. */
  49327. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  49328. var targetInfoList = this._targetInfoList;
  49329. var foundCpts = parseFinder$1(ecModel, area);
  49330. for (var i = 0; i < targetInfoList.length; i++) {
  49331. var targetInfo = targetInfoList[i];
  49332. var areaPanelId = area.panelId;
  49333. if (areaPanelId) {
  49334. if (targetInfo.panelId === areaPanelId) {
  49335. return targetInfo;
  49336. }
  49337. } else {
  49338. for (var j = 0; j < targetInfoMatchers.length; j++) {
  49339. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  49340. return targetInfo;
  49341. }
  49342. }
  49343. }
  49344. }
  49345. return true;
  49346. };
  49347. return BrushTargetManager;
  49348. }();
  49349. function formatMinMax(minMax) {
  49350. minMax[0] > minMax[1] && minMax.reverse();
  49351. return minMax;
  49352. }
  49353. function parseFinder$1(ecModel, finder) {
  49354. return parseFinder(ecModel, finder, {
  49355. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  49356. });
  49357. }
  49358. var targetInfoBuilders = {
  49359. grid: function (foundCpts, targetInfoList) {
  49360. var xAxisModels = foundCpts.xAxisModels;
  49361. var yAxisModels = foundCpts.yAxisModels;
  49362. var gridModels = foundCpts.gridModels;
  49363. // Remove duplicated.
  49364. var gridModelMap = createHashMap();
  49365. var xAxesHas = {};
  49366. var yAxesHas = {};
  49367. if (!xAxisModels && !yAxisModels && !gridModels) {
  49368. return;
  49369. }
  49370. each(xAxisModels, function (axisModel) {
  49371. var gridModel = axisModel.axis.grid.model;
  49372. gridModelMap.set(gridModel.id, gridModel);
  49373. xAxesHas[gridModel.id] = true;
  49374. });
  49375. each(yAxisModels, function (axisModel) {
  49376. var gridModel = axisModel.axis.grid.model;
  49377. gridModelMap.set(gridModel.id, gridModel);
  49378. yAxesHas[gridModel.id] = true;
  49379. });
  49380. each(gridModels, function (gridModel) {
  49381. gridModelMap.set(gridModel.id, gridModel);
  49382. xAxesHas[gridModel.id] = true;
  49383. yAxesHas[gridModel.id] = true;
  49384. });
  49385. gridModelMap.each(function (gridModel) {
  49386. var grid = gridModel.coordinateSystem;
  49387. var cartesians = [];
  49388. each(grid.getCartesians(), function (cartesian, index) {
  49389. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  49390. cartesians.push(cartesian);
  49391. }
  49392. });
  49393. targetInfoList.push({
  49394. panelId: 'grid--' + gridModel.id,
  49395. gridModel: gridModel,
  49396. coordSysModel: gridModel,
  49397. // Use the first one as the representitive coordSys.
  49398. coordSys: cartesians[0],
  49399. coordSyses: cartesians,
  49400. getPanelRect: panelRectBuilders.grid,
  49401. xAxisDeclared: xAxesHas[gridModel.id],
  49402. yAxisDeclared: yAxesHas[gridModel.id]
  49403. });
  49404. });
  49405. },
  49406. geo: function (foundCpts, targetInfoList) {
  49407. each(foundCpts.geoModels, function (geoModel) {
  49408. var coordSys = geoModel.coordinateSystem;
  49409. targetInfoList.push({
  49410. panelId: 'geo--' + geoModel.id,
  49411. geoModel: geoModel,
  49412. coordSysModel: geoModel,
  49413. coordSys: coordSys,
  49414. coordSyses: [coordSys],
  49415. getPanelRect: panelRectBuilders.geo
  49416. });
  49417. });
  49418. }
  49419. };
  49420. var targetInfoMatchers = [
  49421. // grid
  49422. function (foundCpts, targetInfo) {
  49423. var xAxisModel = foundCpts.xAxisModel;
  49424. var yAxisModel = foundCpts.yAxisModel;
  49425. var gridModel = foundCpts.gridModel;
  49426. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  49427. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  49428. return gridModel && gridModel === targetInfo.gridModel;
  49429. },
  49430. // geo
  49431. function (foundCpts, targetInfo) {
  49432. var geoModel = foundCpts.geoModel;
  49433. return geoModel && geoModel === targetInfo.geoModel;
  49434. }];
  49435. var panelRectBuilders = {
  49436. grid: function () {
  49437. // grid is not Transformable.
  49438. return this.coordSys.master.getRect().clone();
  49439. },
  49440. geo: function () {
  49441. var coordSys = this.coordSys;
  49442. var rect = coordSys.getBoundingRect().clone();
  49443. // geo roam and zoom transform
  49444. rect.applyTransform(getTransform(coordSys));
  49445. return rect;
  49446. }
  49447. };
  49448. var coordConvert = {
  49449. lineX: curry(axisConvert, 0),
  49450. lineY: curry(axisConvert, 1),
  49451. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  49452. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  49453. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  49454. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  49455. return {
  49456. values: values,
  49457. xyMinMax: values
  49458. };
  49459. },
  49460. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  49461. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  49462. var values = map(rangeOrCoordRange, function (item) {
  49463. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  49464. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  49465. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  49466. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  49467. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  49468. return p;
  49469. });
  49470. return {
  49471. values: values,
  49472. xyMinMax: xyMinMax
  49473. };
  49474. }
  49475. };
  49476. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  49477. if ("development" !== 'production') {
  49478. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  49479. }
  49480. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  49481. var values = formatMinMax(map([0, 1], function (i) {
  49482. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  49483. }));
  49484. var xyMinMax = [];
  49485. xyMinMax[axisNameIndex] = values;
  49486. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  49487. return {
  49488. values: values,
  49489. xyMinMax: xyMinMax
  49490. };
  49491. }
  49492. var diffProcessor = {
  49493. lineX: curry(axisDiffProcessor, 0),
  49494. lineY: curry(axisDiffProcessor, 1),
  49495. rect: function (values, refer, scales) {
  49496. 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]]];
  49497. },
  49498. polygon: function (values, refer, scales) {
  49499. return map(values, function (item, idx) {
  49500. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  49501. });
  49502. }
  49503. };
  49504. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  49505. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  49506. }
  49507. // We have to process scale caused by dataZoom manually,
  49508. // although it might be not accurate.
  49509. // Return [0~1, 0~1]
  49510. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  49511. var sizeCurr = getSize$1(xyMinMaxCurr);
  49512. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  49513. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  49514. isNaN(scales[0]) && (scales[0] = 1);
  49515. isNaN(scales[1]) && (scales[1] = 1);
  49516. return scales;
  49517. }
  49518. function getSize$1(xyMinMax) {
  49519. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  49520. }
  49521. var each$6 = each;
  49522. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  49523. var DataZoomFeature = /** @class */function (_super) {
  49524. __extends(DataZoomFeature, _super);
  49525. function DataZoomFeature() {
  49526. return _super !== null && _super.apply(this, arguments) || this;
  49527. }
  49528. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  49529. if (!this._brushController) {
  49530. this._brushController = new BrushController(api.getZr());
  49531. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  49532. }
  49533. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  49534. updateBackBtnStatus(featureModel, ecModel);
  49535. };
  49536. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  49537. handlers[type].call(this);
  49538. };
  49539. DataZoomFeature.prototype.remove = function (ecModel, api) {
  49540. this._brushController && this._brushController.unmount();
  49541. };
  49542. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  49543. this._brushController && this._brushController.dispose();
  49544. };
  49545. DataZoomFeature.prototype._onBrush = function (eventParam) {
  49546. var areas = eventParam.areas;
  49547. if (!eventParam.isEnd || !areas.length) {
  49548. return;
  49549. }
  49550. var snapshot = {};
  49551. var ecModel = this.ecModel;
  49552. this._brushController.updateCovers([]); // remove cover
  49553. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  49554. include: ['grid']
  49555. });
  49556. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  49557. if (coordSys.type !== 'cartesian2d') {
  49558. return;
  49559. }
  49560. var brushType = area.brushType;
  49561. if (brushType === 'rect') {
  49562. setBatch('x', coordSys, coordRange[0]);
  49563. setBatch('y', coordSys, coordRange[1]);
  49564. } else {
  49565. setBatch({
  49566. lineX: 'x',
  49567. lineY: 'y'
  49568. }[brushType], coordSys, coordRange);
  49569. }
  49570. });
  49571. push(ecModel, snapshot);
  49572. this._dispatchZoomAction(snapshot);
  49573. function setBatch(dimName, coordSys, minMax) {
  49574. var axis = coordSys.getAxis(dimName);
  49575. var axisModel = axis.model;
  49576. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  49577. // Restrict range.
  49578. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  49579. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  49580. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  49581. }
  49582. dataZoomModel && (snapshot[dataZoomModel.id] = {
  49583. dataZoomId: dataZoomModel.id,
  49584. startValue: minMax[0],
  49585. endValue: minMax[1]
  49586. });
  49587. }
  49588. function findDataZoom(dimName, axisModel, ecModel) {
  49589. var found;
  49590. ecModel.eachComponent({
  49591. mainType: 'dataZoom',
  49592. subType: 'select'
  49593. }, function (dzModel) {
  49594. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  49595. has && (found = dzModel);
  49596. });
  49597. return found;
  49598. }
  49599. };
  49600. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  49601. var batch = [];
  49602. // Convert from hash map to array.
  49603. each$6(snapshot, function (batchItem, dataZoomId) {
  49604. batch.push(clone(batchItem));
  49605. });
  49606. batch.length && this.api.dispatchAction({
  49607. type: 'dataZoom',
  49608. from: this.uid,
  49609. batch: batch
  49610. });
  49611. };
  49612. DataZoomFeature.getDefaultOption = function (ecModel) {
  49613. var defaultOption = {
  49614. show: true,
  49615. filterMode: 'filter',
  49616. // Icon group
  49617. icon: {
  49618. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  49619. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  49620. },
  49621. // `zoom`, `back`
  49622. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  49623. brushStyle: {
  49624. borderWidth: 0,
  49625. color: 'rgba(210,219,238,0.2)'
  49626. }
  49627. };
  49628. return defaultOption;
  49629. };
  49630. return DataZoomFeature;
  49631. }(ToolboxFeature);
  49632. var handlers = {
  49633. zoom: function () {
  49634. var nextActive = !this._isZoomActive;
  49635. this.api.dispatchAction({
  49636. type: 'takeGlobalCursor',
  49637. key: 'dataZoomSelect',
  49638. dataZoomSelectActive: nextActive
  49639. });
  49640. },
  49641. back: function () {
  49642. this._dispatchZoomAction(pop(this.ecModel));
  49643. }
  49644. };
  49645. function makeAxisFinder(dzFeatureModel) {
  49646. var setting = {
  49647. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  49648. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  49649. xAxisId: dzFeatureModel.get('xAxisId', true),
  49650. yAxisId: dzFeatureModel.get('yAxisId', true)
  49651. };
  49652. // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  49653. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  49654. // Some old cases set like this below to close yAxis control but leave xAxis control:
  49655. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  49656. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  49657. setting.xAxisIndex = 'all';
  49658. }
  49659. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  49660. setting.yAxisIndex = 'all';
  49661. }
  49662. return setting;
  49663. }
  49664. function updateBackBtnStatus(featureModel, ecModel) {
  49665. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  49666. }
  49667. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  49668. var zoomActive = view._isZoomActive;
  49669. if (payload && payload.type === 'takeGlobalCursor') {
  49670. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  49671. }
  49672. view._isZoomActive = zoomActive;
  49673. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  49674. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  49675. include: ['grid']
  49676. });
  49677. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  49678. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  49679. });
  49680. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  49681. brushType: 'auto',
  49682. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  49683. } : false);
  49684. }
  49685. registerInternalOptionCreator('dataZoom', function (ecModel) {
  49686. var toolboxModel = ecModel.getComponent('toolbox', 0);
  49687. var featureDataZoomPath = ['feature', 'dataZoom'];
  49688. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  49689. return;
  49690. }
  49691. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  49692. var dzOptions = [];
  49693. var finder = makeAxisFinder(dzFeatureModel);
  49694. var finderResult = parseFinder(ecModel, finder);
  49695. each$6(finderResult.xAxisModels, function (axisModel) {
  49696. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  49697. });
  49698. each$6(finderResult.yAxisModels, function (axisModel) {
  49699. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  49700. });
  49701. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  49702. var axisIndex = axisModel.componentIndex;
  49703. var newOpt = {
  49704. type: 'select',
  49705. $fromToolbox: true,
  49706. // Default to be filter
  49707. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  49708. // Id for merge mapping.
  49709. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  49710. };
  49711. newOpt[axisIndexPropName] = axisIndex;
  49712. dzOptions.push(newOpt);
  49713. }
  49714. return dzOptions;
  49715. });
  49716. function install$b(registers) {
  49717. registers.registerComponentModel(ToolboxModel);
  49718. registers.registerComponentView(ToolboxView);
  49719. registerFeature('saveAsImage', SaveAsImage);
  49720. registerFeature('magicType', MagicType);
  49721. registerFeature('dataView', DataView);
  49722. registerFeature('dataZoom', DataZoomFeature);
  49723. registerFeature('restore', RestoreOption);
  49724. use(install$a);
  49725. }
  49726. var TooltipModel = /** @class */function (_super) {
  49727. __extends(TooltipModel, _super);
  49728. function TooltipModel() {
  49729. var _this = _super !== null && _super.apply(this, arguments) || this;
  49730. _this.type = TooltipModel.type;
  49731. return _this;
  49732. }
  49733. TooltipModel.type = 'tooltip';
  49734. TooltipModel.dependencies = ['axisPointer'];
  49735. TooltipModel.defaultOption = {
  49736. // zlevel: 0,
  49737. z: 60,
  49738. show: true,
  49739. // tooltip main content
  49740. showContent: true,
  49741. // 'trigger' only works on coordinate system.
  49742. // 'item' | 'axis' | 'none'
  49743. trigger: 'item',
  49744. // 'click' | 'mousemove' | 'none'
  49745. triggerOn: 'mousemove|click',
  49746. alwaysShowContent: false,
  49747. displayMode: 'single',
  49748. renderMode: 'auto',
  49749. // whether restraint content inside viewRect.
  49750. // If renderMode: 'richText', default true.
  49751. // If renderMode: 'html', defaut false (for backward compat).
  49752. confine: null,
  49753. showDelay: 0,
  49754. hideDelay: 100,
  49755. // Animation transition time, unit is second
  49756. transitionDuration: 0.4,
  49757. enterable: false,
  49758. backgroundColor: '#fff',
  49759. // box shadow
  49760. shadowBlur: 10,
  49761. shadowColor: 'rgba(0, 0, 0, .2)',
  49762. shadowOffsetX: 1,
  49763. shadowOffsetY: 2,
  49764. // tooltip border radius, unit is px, default is 4
  49765. borderRadius: 4,
  49766. // tooltip border width, unit is px, default is 0 (no border)
  49767. borderWidth: 1,
  49768. // Tooltip inside padding, default is 5 for all direction
  49769. // Array is allowed to set up, right, bottom, left, same with css
  49770. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  49771. padding: null,
  49772. // Extra css text
  49773. extraCssText: '',
  49774. // axis indicator, trigger by axis
  49775. axisPointer: {
  49776. // default is line
  49777. // legal values: 'line' | 'shadow' | 'cross'
  49778. type: 'line',
  49779. // Valid when type is line, appoint tooltip line locate on which line. Optional
  49780. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  49781. // default is 'auto', chose the axis which type is category.
  49782. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  49783. axis: 'auto',
  49784. animation: 'auto',
  49785. animationDurationUpdate: 200,
  49786. animationEasingUpdate: 'exponentialOut',
  49787. crossStyle: {
  49788. color: '#999',
  49789. width: 1,
  49790. type: 'dashed',
  49791. // TODO formatter
  49792. textStyle: {}
  49793. }
  49794. // lineStyle and shadowStyle should not be specified here,
  49795. // otherwise it will always override those styles on option.axisPointer.
  49796. },
  49797. textStyle: {
  49798. color: '#666',
  49799. fontSize: 14
  49800. }
  49801. };
  49802. return TooltipModel;
  49803. }(ComponentModel);
  49804. /* global document */
  49805. function shouldTooltipConfine(tooltipModel) {
  49806. var confineOption = tooltipModel.get('confine');
  49807. return confineOption != null ? !!confineOption
  49808. // In richText mode, the outside part can not be visible.
  49809. : tooltipModel.get('renderMode') === 'richText';
  49810. }
  49811. function testStyle(styleProps) {
  49812. if (!env.domSupported) {
  49813. return;
  49814. }
  49815. var style = document.documentElement.style;
  49816. for (var i = 0, len = styleProps.length; i < len; i++) {
  49817. if (styleProps[i] in style) {
  49818. return styleProps[i];
  49819. }
  49820. }
  49821. }
  49822. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  49823. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  49824. function toCSSVendorPrefix(styleVendor, styleProp) {
  49825. if (!styleVendor) {
  49826. return styleProp;
  49827. }
  49828. styleProp = toCamelCase(styleProp, true);
  49829. var idx = styleVendor.indexOf(styleProp);
  49830. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  49831. return styleVendor.toLowerCase();
  49832. }
  49833. function getComputedStyle(el, style) {
  49834. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  49835. return stl ? style ? stl[style] : stl : null;
  49836. }
  49837. /* global document, window */
  49838. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  49839. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform');
  49840. // eslint-disable-next-line
  49841. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  49842. function mirrorPos(pos) {
  49843. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  49844. return pos;
  49845. }
  49846. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  49847. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  49848. return '';
  49849. }
  49850. var backgroundColor = tooltipModel.get('backgroundColor');
  49851. var borderWidth = tooltipModel.get('borderWidth');
  49852. borderColor = convertToColorString(borderColor);
  49853. var arrowPos = mirrorPos(arrowPosition);
  49854. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  49855. var positionStyle = '';
  49856. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  49857. var rotateDeg;
  49858. if (indexOf(['left', 'right'], arrowPos) > -1) {
  49859. positionStyle += 'top:50%';
  49860. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  49861. } else {
  49862. positionStyle += 'left:50%';
  49863. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  49864. }
  49865. var rotateRadian = rotateDeg * Math.PI / 180;
  49866. var arrowWH = arrowSize + borderWidth;
  49867. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  49868. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  49869. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  49870. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  49871. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  49872. return "<div style=\"" + styleCss.join('') + "\"></div>";
  49873. }
  49874. function assembleTransition(duration, onlyFade) {
  49875. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  49876. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  49877. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  49878. if (!onlyFade) {
  49879. transitionOption = " " + duration + "s " + transitionCurve;
  49880. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  49881. }
  49882. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  49883. }
  49884. function assembleTransform(x, y, toString) {
  49885. // If using float on style, the final width of the dom might
  49886. // keep changing slightly while mouse move. So `toFixed(0)` them.
  49887. var x0 = x.toFixed(0) + 'px';
  49888. var y0 = y.toFixed(0) + 'px';
  49889. // not support transform, use `left` and `top` instead.
  49890. if (!env.transformSupported) {
  49891. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  49892. }
  49893. // support transform
  49894. var is3d = env.transform3dSupported;
  49895. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  49896. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  49897. }
  49898. /**
  49899. * @param {Object} textStyle
  49900. * @return {string}
  49901. * @inner
  49902. */
  49903. function assembleFont(textStyleModel) {
  49904. var cssText = [];
  49905. var fontSize = textStyleModel.get('fontSize');
  49906. var color = textStyleModel.getTextColor();
  49907. color && cssText.push('color:' + color);
  49908. cssText.push('font:' + textStyleModel.getFont());
  49909. fontSize
  49910. // @ts-ignore, leave it to the tooltip refactor.
  49911. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  49912. var shadowColor = textStyleModel.get('textShadowColor');
  49913. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  49914. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  49915. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  49916. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  49917. each(['decoration', 'align'], function (name) {
  49918. var val = textStyleModel.get(name);
  49919. val && cssText.push('text-' + name + ':' + val);
  49920. });
  49921. return cssText.join(';');
  49922. }
  49923. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  49924. var cssText = [];
  49925. var transitionDuration = tooltipModel.get('transitionDuration');
  49926. var backgroundColor = tooltipModel.get('backgroundColor');
  49927. var shadowBlur = tooltipModel.get('shadowBlur');
  49928. var shadowColor = tooltipModel.get('shadowColor');
  49929. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  49930. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  49931. var textStyleModel = tooltipModel.getModel('textStyle');
  49932. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  49933. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  49934. cssText.push('box-shadow:' + boxShadow);
  49935. // Animation transition. Do not animate when transitionDuration is 0.
  49936. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  49937. if (backgroundColor) {
  49938. cssText.push('background-color:' + backgroundColor);
  49939. }
  49940. // Border style
  49941. each(['width', 'color', 'radius'], function (name) {
  49942. var borderName = 'border-' + name;
  49943. var camelCase = toCamelCase(borderName);
  49944. var val = tooltipModel.get(camelCase);
  49945. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  49946. });
  49947. // Text style
  49948. cssText.push(assembleFont(textStyleModel));
  49949. // Padding
  49950. if (padding != null) {
  49951. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  49952. }
  49953. return cssText.join(';') + ';';
  49954. }
  49955. // If not able to make, do not modify the input `out`.
  49956. function makeStyleCoord(out, zr, container, zrX, zrY) {
  49957. var zrPainter = zr && zr.painter;
  49958. if (container) {
  49959. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  49960. if (zrViewportRoot) {
  49961. // Some APPs might use scale on body, so we support CSS transform here.
  49962. transformLocalCoord(out, zrViewportRoot, container, zrX, zrY);
  49963. }
  49964. } else {
  49965. out[0] = zrX;
  49966. out[1] = zrY;
  49967. // xy should be based on canvas root. But tooltipContent is
  49968. // the sibling of canvas root. So padding of ec container
  49969. // should be considered here.
  49970. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  49971. if (viewportRootOffset) {
  49972. out[0] += viewportRootOffset.offsetLeft;
  49973. out[1] += viewportRootOffset.offsetTop;
  49974. }
  49975. }
  49976. out[2] = out[0] / zr.getWidth();
  49977. out[3] = out[1] / zr.getHeight();
  49978. }
  49979. var TooltipHTMLContent = /** @class */function () {
  49980. function TooltipHTMLContent(api, opt) {
  49981. this._show = false;
  49982. this._styleCoord = [0, 0, 0, 0];
  49983. this._enterable = true;
  49984. this._alwaysShowContent = false;
  49985. this._firstShow = true;
  49986. this._longHide = true;
  49987. if (env.wxa) {
  49988. return null;
  49989. }
  49990. var el = document.createElement('div');
  49991. // TODO: TYPE
  49992. el.domBelongToZr = true;
  49993. this.el = el;
  49994. var zr = this._zr = api.getZr();
  49995. var appendTo = opt.appendTo;
  49996. var container = appendTo && (isString(appendTo) ? document.querySelector(appendTo) : isDom(appendTo) ? appendTo : isFunction(appendTo) && appendTo(api.getDom()));
  49997. makeStyleCoord(this._styleCoord, zr, container, api.getWidth() / 2, api.getHeight() / 2);
  49998. (container || api.getDom()).appendChild(el);
  49999. this._api = api;
  50000. this._container = container;
  50001. // FIXME
  50002. // Is it needed to trigger zr event manually if
  50003. // the browser do not support `pointer-events: none`.
  50004. var self = this;
  50005. el.onmouseenter = function () {
  50006. // clear the timeout in hideLater and keep showing tooltip
  50007. if (self._enterable) {
  50008. clearTimeout(self._hideTimeout);
  50009. self._show = true;
  50010. }
  50011. self._inContent = true;
  50012. };
  50013. el.onmousemove = function (e) {
  50014. e = e || window.event;
  50015. if (!self._enterable) {
  50016. // `pointer-events: none` is set to tooltip content div
  50017. // if `enterable` is set as `false`, and `el.onmousemove`
  50018. // can not be triggered. But in browser that do not
  50019. // support `pointer-events`, we need to do this:
  50020. // Try trigger zrender event to avoid mouse
  50021. // in and out shape too frequently
  50022. var handler = zr.handler;
  50023. var zrViewportRoot = zr.painter.getViewportRoot();
  50024. normalizeEvent(zrViewportRoot, e, true);
  50025. handler.dispatch('mousemove', e);
  50026. }
  50027. };
  50028. el.onmouseleave = function () {
  50029. // set `_inContent` to `false` before `hideLater`
  50030. self._inContent = false;
  50031. if (self._enterable) {
  50032. if (self._show) {
  50033. self.hideLater(self._hideDelay);
  50034. }
  50035. }
  50036. };
  50037. }
  50038. /**
  50039. * Update when tooltip is rendered
  50040. */
  50041. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  50042. // FIXME
  50043. // Move this logic to ec main?
  50044. if (!this._container) {
  50045. var container = this._api.getDom();
  50046. var position = getComputedStyle(container, 'position');
  50047. var domStyle = container.style;
  50048. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  50049. domStyle.position = 'relative';
  50050. }
  50051. }
  50052. // move tooltip if chart resized
  50053. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  50054. alwaysShowContent && this._moveIfResized();
  50055. // update alwaysShowContent
  50056. this._alwaysShowContent = alwaysShowContent;
  50057. // update className
  50058. this.el.className = tooltipModel.get('className') || '';
  50059. // Hide the tooltip
  50060. // PENDING
  50061. // this.hide();
  50062. };
  50063. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  50064. clearTimeout(this._hideTimeout);
  50065. clearTimeout(this._longHideTimeout);
  50066. var el = this.el;
  50067. var style = el.style;
  50068. var styleCoord = this._styleCoord;
  50069. if (!el.innerHTML) {
  50070. style.display = 'none';
  50071. } else {
  50072. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide)
  50073. // initial transform
  50074. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '')
  50075. // If mouse occasionally move over the tooltip, a mouseout event will be
  50076. // triggered by canvas, and cause some unexpectable result like dragging
  50077. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  50078. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  50079. // scenario.
  50080. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  50081. }
  50082. this._show = true;
  50083. this._firstShow = false;
  50084. this._longHide = false;
  50085. };
  50086. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  50087. var el = this.el;
  50088. if (content == null) {
  50089. el.innerHTML = '';
  50090. return;
  50091. }
  50092. var arrow = '';
  50093. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  50094. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  50095. }
  50096. if (isString(content)) {
  50097. el.innerHTML = content + arrow;
  50098. } else if (content) {
  50099. // Clear previous
  50100. el.innerHTML = '';
  50101. if (!isArray(content)) {
  50102. content = [content];
  50103. }
  50104. for (var i = 0; i < content.length; i++) {
  50105. if (isDom(content[i]) && content[i].parentNode !== el) {
  50106. el.appendChild(content[i]);
  50107. }
  50108. }
  50109. // no arrow if empty
  50110. if (arrow && el.childNodes.length) {
  50111. // no need to create a new parent element, but it's not supported by IE 10 and older.
  50112. // const arrowEl = document.createRange().createContextualFragment(arrow);
  50113. var arrowEl = document.createElement('div');
  50114. arrowEl.innerHTML = arrow;
  50115. el.appendChild(arrowEl);
  50116. }
  50117. }
  50118. };
  50119. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  50120. this._enterable = enterable;
  50121. };
  50122. TooltipHTMLContent.prototype.getSize = function () {
  50123. var el = this.el;
  50124. return [el.offsetWidth, el.offsetHeight];
  50125. };
  50126. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  50127. var styleCoord = this._styleCoord;
  50128. makeStyleCoord(styleCoord, this._zr, this._container, zrX, zrY);
  50129. if (styleCoord[0] != null && styleCoord[1] != null) {
  50130. var style_1 = this.el.style;
  50131. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  50132. each(transforms, function (transform) {
  50133. style_1[transform[0]] = transform[1];
  50134. });
  50135. }
  50136. };
  50137. /**
  50138. * when `alwaysShowContent` is true,
  50139. * move the tooltip after chart resized
  50140. */
  50141. TooltipHTMLContent.prototype._moveIfResized = function () {
  50142. // The ratio of left to width
  50143. var ratioX = this._styleCoord[2];
  50144. // The ratio of top to height
  50145. var ratioY = this._styleCoord[3];
  50146. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  50147. };
  50148. TooltipHTMLContent.prototype.hide = function () {
  50149. var _this = this;
  50150. var style = this.el.style;
  50151. style.visibility = 'hidden';
  50152. style.opacity = '0';
  50153. env.transform3dSupported && (style.willChange = '');
  50154. this._show = false;
  50155. this._longHideTimeout = setTimeout(function () {
  50156. return _this._longHide = true;
  50157. }, 500);
  50158. };
  50159. TooltipHTMLContent.prototype.hideLater = function (time) {
  50160. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  50161. if (time) {
  50162. this._hideDelay = time;
  50163. // Set show false to avoid invoke hideLater multiple times
  50164. this._show = false;
  50165. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  50166. } else {
  50167. this.hide();
  50168. }
  50169. }
  50170. };
  50171. TooltipHTMLContent.prototype.isShow = function () {
  50172. return this._show;
  50173. };
  50174. TooltipHTMLContent.prototype.dispose = function () {
  50175. clearTimeout(this._hideTimeout);
  50176. clearTimeout(this._longHideTimeout);
  50177. var parentNode = this.el.parentNode;
  50178. parentNode && parentNode.removeChild(this.el);
  50179. this.el = this._container = null;
  50180. };
  50181. return TooltipHTMLContent;
  50182. }();
  50183. var TooltipRichContent = /** @class */function () {
  50184. function TooltipRichContent(api) {
  50185. this._show = false;
  50186. this._styleCoord = [0, 0, 0, 0];
  50187. this._alwaysShowContent = false;
  50188. this._enterable = true;
  50189. this._zr = api.getZr();
  50190. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  50191. }
  50192. /**
  50193. * Update when tooltip is rendered
  50194. */
  50195. TooltipRichContent.prototype.update = function (tooltipModel) {
  50196. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  50197. alwaysShowContent && this._moveIfResized();
  50198. // update alwaysShowContent
  50199. this._alwaysShowContent = alwaysShowContent;
  50200. };
  50201. TooltipRichContent.prototype.show = function () {
  50202. if (this._hideTimeout) {
  50203. clearTimeout(this._hideTimeout);
  50204. }
  50205. this.el.show();
  50206. this._show = true;
  50207. };
  50208. /**
  50209. * Set tooltip content
  50210. */
  50211. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  50212. var _this = this;
  50213. if (isObject(content)) {
  50214. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  50215. }
  50216. if (this.el) {
  50217. this._zr.remove(this.el);
  50218. }
  50219. var textStyleModel = tooltipModel.getModel('textStyle');
  50220. this.el = new ZRText({
  50221. style: {
  50222. rich: markupStyleCreator.richTextStyles,
  50223. text: content,
  50224. lineHeight: 22,
  50225. borderWidth: 1,
  50226. borderColor: borderColor,
  50227. textShadowColor: textStyleModel.get('textShadowColor'),
  50228. fill: tooltipModel.get(['textStyle', 'color']),
  50229. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  50230. verticalAlign: 'top',
  50231. align: 'left'
  50232. },
  50233. z: tooltipModel.get('z')
  50234. });
  50235. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  50236. _this.el.style[propName] = tooltipModel.get(propName);
  50237. });
  50238. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  50239. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  50240. });
  50241. this._zr.add(this.el);
  50242. var self = this;
  50243. this.el.on('mouseover', function () {
  50244. // clear the timeout in hideLater and keep showing tooltip
  50245. if (self._enterable) {
  50246. clearTimeout(self._hideTimeout);
  50247. self._show = true;
  50248. }
  50249. self._inContent = true;
  50250. });
  50251. this.el.on('mouseout', function () {
  50252. if (self._enterable) {
  50253. if (self._show) {
  50254. self.hideLater(self._hideDelay);
  50255. }
  50256. }
  50257. self._inContent = false;
  50258. });
  50259. };
  50260. TooltipRichContent.prototype.setEnterable = function (enterable) {
  50261. this._enterable = enterable;
  50262. };
  50263. TooltipRichContent.prototype.getSize = function () {
  50264. var el = this.el;
  50265. var bounding = this.el.getBoundingRect();
  50266. // bounding rect does not include shadow. For renderMode richText,
  50267. // if overflow, it will be cut. So calculate them accurately.
  50268. var shadowOuterSize = calcShadowOuterSize(el.style);
  50269. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  50270. };
  50271. TooltipRichContent.prototype.moveTo = function (x, y) {
  50272. var el = this.el;
  50273. if (el) {
  50274. var styleCoord = this._styleCoord;
  50275. makeStyleCoord$1(styleCoord, this._zr, x, y);
  50276. x = styleCoord[0];
  50277. y = styleCoord[1];
  50278. var style = el.style;
  50279. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  50280. var shadowOuterSize = calcShadowOuterSize(style);
  50281. // rich text x, y do not include border.
  50282. el.x = x + borderWidth + shadowOuterSize.left;
  50283. el.y = y + borderWidth + shadowOuterSize.top;
  50284. el.markRedraw();
  50285. }
  50286. };
  50287. /**
  50288. * when `alwaysShowContent` is true,
  50289. * move the tooltip after chart resized
  50290. */
  50291. TooltipRichContent.prototype._moveIfResized = function () {
  50292. // The ratio of left to width
  50293. var ratioX = this._styleCoord[2];
  50294. // The ratio of top to height
  50295. var ratioY = this._styleCoord[3];
  50296. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  50297. };
  50298. TooltipRichContent.prototype.hide = function () {
  50299. if (this.el) {
  50300. this.el.hide();
  50301. }
  50302. this._show = false;
  50303. };
  50304. TooltipRichContent.prototype.hideLater = function (time) {
  50305. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  50306. if (time) {
  50307. this._hideDelay = time;
  50308. // Set show false to avoid invoke hideLater multiple times
  50309. this._show = false;
  50310. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  50311. } else {
  50312. this.hide();
  50313. }
  50314. }
  50315. };
  50316. TooltipRichContent.prototype.isShow = function () {
  50317. return this._show;
  50318. };
  50319. TooltipRichContent.prototype.dispose = function () {
  50320. this._zr.remove(this.el);
  50321. };
  50322. return TooltipRichContent;
  50323. }();
  50324. function mathMaxWith0(val) {
  50325. return Math.max(0, val);
  50326. }
  50327. function calcShadowOuterSize(style) {
  50328. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  50329. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  50330. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  50331. return {
  50332. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  50333. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  50334. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  50335. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  50336. };
  50337. }
  50338. function makeStyleCoord$1(out, zr, zrX, zrY) {
  50339. out[0] = zrX;
  50340. out[1] = zrY;
  50341. out[2] = out[0] / zr.getWidth();
  50342. out[3] = out[1] / zr.getHeight();
  50343. }
  50344. var proxyRect = new Rect({
  50345. shape: {
  50346. x: -1,
  50347. y: -1,
  50348. width: 2,
  50349. height: 2
  50350. }
  50351. });
  50352. var TooltipView = /** @class */function (_super) {
  50353. __extends(TooltipView, _super);
  50354. function TooltipView() {
  50355. var _this = _super !== null && _super.apply(this, arguments) || this;
  50356. _this.type = TooltipView.type;
  50357. return _this;
  50358. }
  50359. TooltipView.prototype.init = function (ecModel, api) {
  50360. if (env.node || !api.getDom()) {
  50361. return;
  50362. }
  50363. var tooltipModel = ecModel.getComponent('tooltip');
  50364. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  50365. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api, {
  50366. appendTo: tooltipModel.get('appendToBody', true) ? 'body' : tooltipModel.get('appendTo', true)
  50367. });
  50368. };
  50369. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  50370. if (env.node || !api.getDom()) {
  50371. return;
  50372. }
  50373. // Reset
  50374. this.group.removeAll();
  50375. this._tooltipModel = tooltipModel;
  50376. this._ecModel = ecModel;
  50377. this._api = api;
  50378. var tooltipContent = this._tooltipContent;
  50379. tooltipContent.update(tooltipModel);
  50380. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  50381. this._initGlobalListener();
  50382. this._keepShow();
  50383. // PENDING
  50384. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  50385. // which causes that the `updatePosition` function was also called frequently.
  50386. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  50387. // To avoid frequent triggering,
  50388. // consider throttling it in 50ms when transition is enabled
  50389. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  50390. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  50391. } else {
  50392. clear(this, '_updatePosition');
  50393. }
  50394. };
  50395. TooltipView.prototype._initGlobalListener = function () {
  50396. var tooltipModel = this._tooltipModel;
  50397. var triggerOn = tooltipModel.get('triggerOn');
  50398. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  50399. // If 'none', it is not controlled by mouse totally.
  50400. if (triggerOn !== 'none') {
  50401. if (triggerOn.indexOf(currTrigger) >= 0) {
  50402. this._tryShow(e, dispatchAction);
  50403. } else if (currTrigger === 'leave') {
  50404. this._hide(dispatchAction);
  50405. }
  50406. }
  50407. }, this));
  50408. };
  50409. TooltipView.prototype._keepShow = function () {
  50410. var tooltipModel = this._tooltipModel;
  50411. var ecModel = this._ecModel;
  50412. var api = this._api;
  50413. var triggerOn = tooltipModel.get('triggerOn');
  50414. // Try to keep the tooltip show when refreshing
  50415. if (this._lastX != null && this._lastY != null
  50416. // When user is willing to control tooltip totally using API,
  50417. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  50418. // which is not expected.
  50419. && triggerOn !== 'none' && triggerOn !== 'click') {
  50420. var self_1 = this;
  50421. clearTimeout(this._refreshUpdateTimeout);
  50422. this._refreshUpdateTimeout = setTimeout(function () {
  50423. // Show tip next tick after other charts are rendered
  50424. // In case highlight action has wrong result
  50425. // FIXME
  50426. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  50427. x: self_1._lastX,
  50428. y: self_1._lastY,
  50429. dataByCoordSys: self_1._lastDataByCoordSys
  50430. });
  50431. });
  50432. }
  50433. };
  50434. /**
  50435. * Show tip manually by
  50436. * dispatchAction({
  50437. * type: 'showTip',
  50438. * x: 10,
  50439. * y: 10
  50440. * });
  50441. * Or
  50442. * dispatchAction({
  50443. * type: 'showTip',
  50444. * seriesIndex: 0,
  50445. * dataIndex or dataIndexInside or name
  50446. * });
  50447. *
  50448. * TODO Batch
  50449. */
  50450. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  50451. if (payload.from === this.uid || env.node || !api.getDom()) {
  50452. return;
  50453. }
  50454. var dispatchAction = makeDispatchAction$1(payload, api);
  50455. // Reset ticket
  50456. this._ticket = '';
  50457. // When triggered from axisPointer.
  50458. var dataByCoordSys = payload.dataByCoordSys;
  50459. var cmptRef = findComponentReference(payload, ecModel, api);
  50460. if (cmptRef) {
  50461. var rect = cmptRef.el.getBoundingRect().clone();
  50462. rect.applyTransform(cmptRef.el.transform);
  50463. this._tryShow({
  50464. offsetX: rect.x + rect.width / 2,
  50465. offsetY: rect.y + rect.height / 2,
  50466. target: cmptRef.el,
  50467. position: payload.position,
  50468. // When manully trigger, the mouse is not on the el, so we'd better to
  50469. // position tooltip on the bottom of the el and display arrow is possible.
  50470. positionDefault: 'bottom'
  50471. }, dispatchAction);
  50472. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  50473. var el = proxyRect;
  50474. el.x = payload.x;
  50475. el.y = payload.y;
  50476. el.update();
  50477. getECData(el).tooltipConfig = {
  50478. name: null,
  50479. option: payload.tooltip
  50480. };
  50481. // Manually show tooltip while view is not using zrender elements.
  50482. this._tryShow({
  50483. offsetX: payload.x,
  50484. offsetY: payload.y,
  50485. target: el
  50486. }, dispatchAction);
  50487. } else if (dataByCoordSys) {
  50488. this._tryShow({
  50489. offsetX: payload.x,
  50490. offsetY: payload.y,
  50491. position: payload.position,
  50492. dataByCoordSys: dataByCoordSys,
  50493. tooltipOption: payload.tooltipOption
  50494. }, dispatchAction);
  50495. } else if (payload.seriesIndex != null) {
  50496. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  50497. return;
  50498. }
  50499. var pointInfo = findPointFromSeries(payload, ecModel);
  50500. var cx = pointInfo.point[0];
  50501. var cy = pointInfo.point[1];
  50502. if (cx != null && cy != null) {
  50503. this._tryShow({
  50504. offsetX: cx,
  50505. offsetY: cy,
  50506. target: pointInfo.el,
  50507. position: payload.position,
  50508. // When manully trigger, the mouse is not on the el, so we'd better to
  50509. // position tooltip on the bottom of the el and display arrow is possible.
  50510. positionDefault: 'bottom'
  50511. }, dispatchAction);
  50512. }
  50513. } else if (payload.x != null && payload.y != null) {
  50514. // FIXME
  50515. // should wrap dispatchAction like `axisPointer/globalListener` ?
  50516. api.dispatchAction({
  50517. type: 'updateAxisPointer',
  50518. x: payload.x,
  50519. y: payload.y
  50520. });
  50521. this._tryShow({
  50522. offsetX: payload.x,
  50523. offsetY: payload.y,
  50524. position: payload.position,
  50525. target: api.getZr().findHover(payload.x, payload.y).target
  50526. }, dispatchAction);
  50527. }
  50528. };
  50529. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  50530. var tooltipContent = this._tooltipContent;
  50531. if (this._tooltipModel) {
  50532. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  50533. }
  50534. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  50535. if (payload.from !== this.uid) {
  50536. this._hide(makeDispatchAction$1(payload, api));
  50537. }
  50538. };
  50539. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  50540. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  50541. // and tooltip.
  50542. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  50543. var seriesIndex = payload.seriesIndex;
  50544. var dataIndex = payload.dataIndex;
  50545. // @ts-ignore
  50546. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  50547. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  50548. return;
  50549. }
  50550. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  50551. if (!seriesModel) {
  50552. return;
  50553. }
  50554. var data = seriesModel.getData();
  50555. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  50556. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  50557. return;
  50558. }
  50559. api.dispatchAction({
  50560. type: 'updateAxisPointer',
  50561. seriesIndex: seriesIndex,
  50562. dataIndex: dataIndex,
  50563. position: payload.position
  50564. });
  50565. return true;
  50566. };
  50567. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  50568. var el = e.target;
  50569. var tooltipModel = this._tooltipModel;
  50570. if (!tooltipModel) {
  50571. return;
  50572. }
  50573. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  50574. this._lastX = e.offsetX;
  50575. this._lastY = e.offsetY;
  50576. var dataByCoordSys = e.dataByCoordSys;
  50577. if (dataByCoordSys && dataByCoordSys.length) {
  50578. this._showAxisTooltip(dataByCoordSys, e);
  50579. } else if (el) {
  50580. var ecData = getECData(el);
  50581. if (ecData.ssrType === 'legend') {
  50582. // Don't trigger tooltip for legend tooltip item
  50583. return;
  50584. }
  50585. this._lastDataByCoordSys = null;
  50586. var seriesDispatcher_1;
  50587. var cmptDispatcher_1;
  50588. findEventDispatcher(el, function (target) {
  50589. // Always show item tooltip if mouse is on the element with dataIndex
  50590. if (getECData(target).dataIndex != null) {
  50591. seriesDispatcher_1 = target;
  50592. return true;
  50593. }
  50594. // Tooltip provided directly. Like legend.
  50595. if (getECData(target).tooltipConfig != null) {
  50596. cmptDispatcher_1 = target;
  50597. return true;
  50598. }
  50599. }, true);
  50600. if (seriesDispatcher_1) {
  50601. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  50602. } else if (cmptDispatcher_1) {
  50603. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  50604. } else {
  50605. this._hide(dispatchAction);
  50606. }
  50607. } else {
  50608. this._lastDataByCoordSys = null;
  50609. this._hide(dispatchAction);
  50610. }
  50611. };
  50612. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  50613. // showDelay is used in this case: tooltip.enterable is set
  50614. // as true. User intent to move mouse into tooltip and click
  50615. // something. `showDelay` makes it easier to enter the content
  50616. // but tooltip do not move immediately.
  50617. var delay = tooltipModel.get('showDelay');
  50618. cb = bind(cb, this);
  50619. clearTimeout(this._showTimout);
  50620. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  50621. };
  50622. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  50623. var ecModel = this._ecModel;
  50624. var globalTooltipModel = this._tooltipModel;
  50625. var point = [e.offsetX, e.offsetY];
  50626. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  50627. var renderMode = this._renderMode;
  50628. var cbParamsList = [];
  50629. var articleMarkup = createTooltipMarkup('section', {
  50630. blocks: [],
  50631. noHeader: true
  50632. });
  50633. // Only for legacy: `Serise['formatTooltip']` returns a string.
  50634. var markupTextArrLegacy = [];
  50635. var markupStyleCreator = new TooltipMarkupStyleCreator();
  50636. each(dataByCoordSys, function (itemCoordSys) {
  50637. each(itemCoordSys.dataByAxis, function (axisItem) {
  50638. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  50639. var axisValue = axisItem.value;
  50640. if (!axisModel || axisValue == null) {
  50641. return;
  50642. }
  50643. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  50644. var axisSectionMarkup = createTooltipMarkup('section', {
  50645. header: axisValueLabel,
  50646. noHeader: !trim(axisValueLabel),
  50647. sortBlocks: true,
  50648. blocks: []
  50649. });
  50650. articleMarkup.blocks.push(axisSectionMarkup);
  50651. each(axisItem.seriesDataIndices, function (idxItem) {
  50652. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  50653. var dataIndex = idxItem.dataIndexInside;
  50654. var cbParams = series.getDataParams(dataIndex);
  50655. // Can't find data.
  50656. if (cbParams.dataIndex < 0) {
  50657. return;
  50658. }
  50659. cbParams.axisDim = axisItem.axisDim;
  50660. cbParams.axisIndex = axisItem.axisIndex;
  50661. cbParams.axisType = axisItem.axisType;
  50662. cbParams.axisId = axisItem.axisId;
  50663. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  50664. value: axisValue
  50665. });
  50666. cbParams.axisValueLabel = axisValueLabel;
  50667. // Pre-create marker style for makers. Users can assemble richText
  50668. // text in `formatter` callback and use those markers style.
  50669. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  50670. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  50671. var frag = seriesTooltipResult.frag;
  50672. if (frag) {
  50673. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  50674. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  50675. valueFormatter: valueFormatter
  50676. }, frag) : frag);
  50677. }
  50678. if (seriesTooltipResult.text) {
  50679. markupTextArrLegacy.push(seriesTooltipResult.text);
  50680. }
  50681. cbParamsList.push(cbParams);
  50682. });
  50683. });
  50684. });
  50685. // In most cases, the second axis is displays upper on the first one.
  50686. // So we reverse it to look better.
  50687. articleMarkup.blocks.reverse();
  50688. markupTextArrLegacy.reverse();
  50689. var positionExpr = e.position;
  50690. var orderMode = singleTooltipModel.get('order');
  50691. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  50692. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  50693. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  50694. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  50695. this._showOrMove(singleTooltipModel, function () {
  50696. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  50697. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  50698. } else {
  50699. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  50700. }
  50701. });
  50702. // Do not trigger events here, because this branch only be entered
  50703. // from dispatchAction.
  50704. };
  50705. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  50706. var ecModel = this._ecModel;
  50707. var ecData = getECData(dispatcher);
  50708. // Use dataModel in element if possible
  50709. // Used when mouseover on a element like markPoint or edge
  50710. // In which case, the data is not main data in series.
  50711. var seriesIndex = ecData.seriesIndex;
  50712. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  50713. // For example, graph link.
  50714. var dataModel = ecData.dataModel || seriesModel;
  50715. var dataIndex = ecData.dataIndex;
  50716. var dataType = ecData.dataType;
  50717. var data = dataModel.getData(dataType);
  50718. var renderMode = this._renderMode;
  50719. var positionDefault = e.positionDefault;
  50720. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  50721. position: positionDefault
  50722. } : null);
  50723. var tooltipTrigger = tooltipModel.get('trigger');
  50724. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  50725. return;
  50726. }
  50727. var params = dataModel.getDataParams(dataIndex, dataType);
  50728. var markupStyleCreator = new TooltipMarkupStyleCreator();
  50729. // Pre-create marker style for makers. Users can assemble richText
  50730. // text in `formatter` callback and use those markers style.
  50731. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  50732. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  50733. var orderMode = tooltipModel.get('order');
  50734. var valueFormatter = tooltipModel.get('valueFormatter');
  50735. var frag = seriesTooltipResult.frag;
  50736. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  50737. valueFormatter: valueFormatter
  50738. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  50739. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  50740. this._showOrMove(tooltipModel, function () {
  50741. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  50742. });
  50743. // FIXME
  50744. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  50745. dispatchAction({
  50746. type: 'showTip',
  50747. dataIndexInside: dataIndex,
  50748. dataIndex: data.getRawIndex(dataIndex),
  50749. seriesIndex: seriesIndex,
  50750. from: this.uid
  50751. });
  50752. };
  50753. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  50754. var isHTMLRenderMode = this._renderMode === 'html';
  50755. var ecData = getECData(el);
  50756. var tooltipConfig = ecData.tooltipConfig;
  50757. var tooltipOpt = tooltipConfig.option || {};
  50758. var encodeHTMLContent = tooltipOpt.encodeHTMLContent;
  50759. if (isString(tooltipOpt)) {
  50760. var content = tooltipOpt;
  50761. tooltipOpt = {
  50762. content: content,
  50763. // Fixed formatter
  50764. formatter: content
  50765. };
  50766. // when `tooltipConfig.option` is a string rather than an object,
  50767. // we can't know if the content needs to be encoded
  50768. // for the sake of security, encode it by default.
  50769. encodeHTMLContent = true;
  50770. }
  50771. if (encodeHTMLContent && isHTMLRenderMode && tooltipOpt.content) {
  50772. // clone might be unnecessary?
  50773. tooltipOpt = clone(tooltipOpt);
  50774. tooltipOpt.content = encodeHTML(tooltipOpt.content);
  50775. }
  50776. var tooltipModelCascade = [tooltipOpt];
  50777. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  50778. if (cmpt) {
  50779. tooltipModelCascade.push(cmpt);
  50780. }
  50781. // In most cases, component tooltip formatter has different params with series tooltip formatter,
  50782. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  50783. // by convention, we do not use it as the default formatter for component.
  50784. tooltipModelCascade.push({
  50785. formatter: tooltipOpt.content
  50786. });
  50787. var positionDefault = e.positionDefault;
  50788. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  50789. position: positionDefault
  50790. } : null);
  50791. var defaultHtml = subTooltipModel.get('content');
  50792. var asyncTicket = Math.random() + '';
  50793. // PENDING: this case do not support richText style yet.
  50794. var markupStyleCreator = new TooltipMarkupStyleCreator();
  50795. // Do not check whether `trigger` is 'none' here, because `trigger`
  50796. // only works on coordinate system. In fact, we have not found case
  50797. // that requires setting `trigger` nothing on component yet.
  50798. this._showOrMove(subTooltipModel, function () {
  50799. // Use formatterParams from element defined in component
  50800. // Avoid users modify it.
  50801. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  50802. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  50803. });
  50804. // If not dispatch showTip, tip may be hide triggered by axis.
  50805. dispatchAction({
  50806. type: 'showTip',
  50807. from: this.uid
  50808. });
  50809. };
  50810. TooltipView.prototype._showTooltipContent = function (
  50811. // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  50812. // Instead of top level tooltip.
  50813. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  50814. // Reset ticket
  50815. this._ticket = '';
  50816. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  50817. return;
  50818. }
  50819. var tooltipContent = this._tooltipContent;
  50820. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  50821. var formatter = tooltipModel.get('formatter');
  50822. positionExpr = positionExpr || tooltipModel.get('position');
  50823. var html = defaultHtml;
  50824. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  50825. var nearPointColor = nearPoint.color;
  50826. if (formatter) {
  50827. if (isString(formatter)) {
  50828. var useUTC = tooltipModel.ecModel.get('useUTC');
  50829. var params0 = isArray(params) ? params[0] : params;
  50830. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  50831. html = formatter;
  50832. if (isTimeAxis) {
  50833. html = format(params0.axisValue, html, useUTC);
  50834. }
  50835. html = formatTpl(html, params, true);
  50836. } else if (isFunction(formatter)) {
  50837. var callback = bind(function (cbTicket, html) {
  50838. if (cbTicket === this._ticket) {
  50839. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  50840. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  50841. }
  50842. }, this);
  50843. this._ticket = asyncTicket;
  50844. html = formatter(params, asyncTicket, callback);
  50845. } else {
  50846. html = formatter;
  50847. }
  50848. }
  50849. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  50850. tooltipContent.show(tooltipModel, nearPointColor);
  50851. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  50852. };
  50853. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  50854. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  50855. return {
  50856. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  50857. };
  50858. }
  50859. if (!isArray(tooltipDataParams)) {
  50860. return {
  50861. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  50862. };
  50863. }
  50864. };
  50865. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x,
  50866. // Mouse x
  50867. y,
  50868. // Mouse y
  50869. content, params, el) {
  50870. var viewWidth = this._api.getWidth();
  50871. var viewHeight = this._api.getHeight();
  50872. positionExpr = positionExpr || tooltipModel.get('position');
  50873. var contentSize = content.getSize();
  50874. var align = tooltipModel.get('align');
  50875. var vAlign = tooltipModel.get('verticalAlign');
  50876. var rect = el && el.getBoundingRect().clone();
  50877. el && rect.applyTransform(el.transform);
  50878. if (isFunction(positionExpr)) {
  50879. // Callback of position can be an array or a string specify the position
  50880. positionExpr = positionExpr([x, y], params, content.el, rect, {
  50881. viewSize: [viewWidth, viewHeight],
  50882. contentSize: contentSize.slice()
  50883. });
  50884. }
  50885. if (isArray(positionExpr)) {
  50886. x = parsePercent$1(positionExpr[0], viewWidth);
  50887. y = parsePercent$1(positionExpr[1], viewHeight);
  50888. } else if (isObject(positionExpr)) {
  50889. var boxLayoutPosition = positionExpr;
  50890. boxLayoutPosition.width = contentSize[0];
  50891. boxLayoutPosition.height = contentSize[1];
  50892. var layoutRect = getLayoutRect(boxLayoutPosition, {
  50893. width: viewWidth,
  50894. height: viewHeight
  50895. });
  50896. x = layoutRect.x;
  50897. y = layoutRect.y;
  50898. align = null;
  50899. // When positionExpr is left/top/right/bottom,
  50900. // align and verticalAlign will not work.
  50901. vAlign = null;
  50902. }
  50903. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  50904. else if (isString(positionExpr) && el) {
  50905. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  50906. x = pos[0];
  50907. y = pos[1];
  50908. } else {
  50909. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  50910. x = pos[0];
  50911. y = pos[1];
  50912. }
  50913. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  50914. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  50915. if (shouldTooltipConfine(tooltipModel)) {
  50916. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  50917. x = pos[0];
  50918. y = pos[1];
  50919. }
  50920. content.moveTo(x, y);
  50921. };
  50922. // FIXME
  50923. // Should we remove this but leave this to user?
  50924. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  50925. var lastCoordSys = this._lastDataByCoordSys;
  50926. var lastCbParamsList = this._cbParamsList;
  50927. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  50928. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  50929. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  50930. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  50931. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  50932. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  50933. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  50934. var thisItem = thisDataByAxis[indexAxis] || {};
  50935. var lastIndices = lastItem.seriesDataIndices || [];
  50936. var newIndices = thisItem.seriesDataIndices || [];
  50937. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  50938. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  50939. var newIdxItem = newIndices[j];
  50940. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  50941. });
  50942. // check is cbParams data value changed
  50943. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  50944. var seriesIdx = idxItem.seriesIndex;
  50945. var cbParams = cbParamsList[seriesIdx];
  50946. var lastCbParams = lastCbParamsList[seriesIdx];
  50947. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  50948. contentNotChanged = false;
  50949. }
  50950. });
  50951. });
  50952. });
  50953. this._lastDataByCoordSys = dataByCoordSys;
  50954. this._cbParamsList = cbParamsList;
  50955. return !!contentNotChanged;
  50956. };
  50957. TooltipView.prototype._hide = function (dispatchAction) {
  50958. // Do not directly hideLater here, because this behavior may be prevented
  50959. // in dispatchAction when showTip is dispatched.
  50960. // FIXME
  50961. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  50962. this._lastDataByCoordSys = null;
  50963. dispatchAction({
  50964. type: 'hideTip',
  50965. from: this.uid
  50966. });
  50967. };
  50968. TooltipView.prototype.dispose = function (ecModel, api) {
  50969. if (env.node || !api.getDom()) {
  50970. return;
  50971. }
  50972. clear(this, '_updatePosition');
  50973. this._tooltipContent.dispose();
  50974. unregister('itemTooltip', api);
  50975. };
  50976. TooltipView.type = 'tooltip';
  50977. return TooltipView;
  50978. }(ComponentView);
  50979. /**
  50980. * From top to bottom. (the last one should be globalTooltipModel);
  50981. */
  50982. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  50983. // Last is always tooltip model.
  50984. var ecModel = globalTooltipModel.ecModel;
  50985. var resultModel;
  50986. if (defaultTooltipOption) {
  50987. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  50988. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  50989. } else {
  50990. resultModel = globalTooltipModel;
  50991. }
  50992. for (var i = modelCascade.length - 1; i >= 0; i--) {
  50993. var tooltipOpt = modelCascade[i];
  50994. if (tooltipOpt) {
  50995. if (tooltipOpt instanceof Model) {
  50996. tooltipOpt = tooltipOpt.get('tooltip', true);
  50997. }
  50998. // In each data item tooltip can be simply write:
  50999. // {
  51000. // value: 10,
  51001. // tooltip: 'Something you need to know'
  51002. // }
  51003. if (isString(tooltipOpt)) {
  51004. tooltipOpt = {
  51005. formatter: tooltipOpt
  51006. };
  51007. }
  51008. if (tooltipOpt) {
  51009. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  51010. }
  51011. }
  51012. }
  51013. return resultModel;
  51014. }
  51015. function makeDispatchAction$1(payload, api) {
  51016. return payload.dispatchAction || bind(api.dispatchAction, api);
  51017. }
  51018. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  51019. var size = content.getSize();
  51020. var width = size[0];
  51021. var height = size[1];
  51022. if (gapH != null) {
  51023. // Add extra 2 pixels for this case:
  51024. // At present the "values" in default tooltip are using CSS `float: right`.
  51025. // When the right edge of the tooltip box is on the right side of the
  51026. // viewport, the `float` layout might push the "values" to the second line.
  51027. if (x + width + gapH + 2 > viewWidth) {
  51028. x -= width + gapH;
  51029. } else {
  51030. x += gapH;
  51031. }
  51032. }
  51033. if (gapV != null) {
  51034. if (y + height + gapV > viewHeight) {
  51035. y -= height + gapV;
  51036. } else {
  51037. y += gapV;
  51038. }
  51039. }
  51040. return [x, y];
  51041. }
  51042. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  51043. var size = content.getSize();
  51044. var width = size[0];
  51045. var height = size[1];
  51046. x = Math.min(x + width, viewWidth) - width;
  51047. y = Math.min(y + height, viewHeight) - height;
  51048. x = Math.max(x, 0);
  51049. y = Math.max(y, 0);
  51050. return [x, y];
  51051. }
  51052. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  51053. var domWidth = contentSize[0];
  51054. var domHeight = contentSize[1];
  51055. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  51056. var x = 0;
  51057. var y = 0;
  51058. var rectWidth = rect.width;
  51059. var rectHeight = rect.height;
  51060. switch (position) {
  51061. case 'inside':
  51062. x = rect.x + rectWidth / 2 - domWidth / 2;
  51063. y = rect.y + rectHeight / 2 - domHeight / 2;
  51064. break;
  51065. case 'top':
  51066. x = rect.x + rectWidth / 2 - domWidth / 2;
  51067. y = rect.y - domHeight - offset;
  51068. break;
  51069. case 'bottom':
  51070. x = rect.x + rectWidth / 2 - domWidth / 2;
  51071. y = rect.y + rectHeight + offset;
  51072. break;
  51073. case 'left':
  51074. x = rect.x - domWidth - offset;
  51075. y = rect.y + rectHeight / 2 - domHeight / 2;
  51076. break;
  51077. case 'right':
  51078. x = rect.x + rectWidth + offset;
  51079. y = rect.y + rectHeight / 2 - domHeight / 2;
  51080. }
  51081. return [x, y];
  51082. }
  51083. function isCenterAlign(align) {
  51084. return align === 'center' || align === 'middle';
  51085. }
  51086. /**
  51087. * Find target component by payload like:
  51088. * ```js
  51089. * { legendId: 'some_id', name: 'xxx' }
  51090. * { toolboxIndex: 1, name: 'xxx' }
  51091. * { geoName: 'some_name', name: 'xxx' }
  51092. * ```
  51093. * PENDING: at present only
  51094. *
  51095. * If not found, return null/undefined.
  51096. */
  51097. function findComponentReference(payload, ecModel, api) {
  51098. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  51099. var componentMainType = queryOptionMap.keys()[0];
  51100. if (!componentMainType || componentMainType === 'series') {
  51101. return;
  51102. }
  51103. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  51104. useDefault: false,
  51105. enableAll: false,
  51106. enableNone: false
  51107. });
  51108. var model = queryResult.models[0];
  51109. if (!model) {
  51110. return;
  51111. }
  51112. var view = api.getViewOfComponentModel(model);
  51113. var el;
  51114. view.group.traverse(function (subEl) {
  51115. var tooltipConfig = getECData(subEl).tooltipConfig;
  51116. if (tooltipConfig && tooltipConfig.name === payload.name) {
  51117. el = subEl;
  51118. return true; // stop
  51119. }
  51120. });
  51121. if (el) {
  51122. return {
  51123. componentMainType: componentMainType,
  51124. componentIndex: model.componentIndex,
  51125. el: el
  51126. };
  51127. }
  51128. }
  51129. function install$c(registers) {
  51130. use(install$7);
  51131. registers.registerComponentModel(TooltipModel);
  51132. registers.registerComponentView(TooltipView);
  51133. /**
  51134. * @action
  51135. * @property {string} type
  51136. * @property {number} seriesIndex
  51137. * @property {number} dataIndex
  51138. * @property {number} [x]
  51139. * @property {number} [y]
  51140. */
  51141. registers.registerAction({
  51142. type: 'showTip',
  51143. event: 'showTip',
  51144. update: 'tooltip:manuallyShowTip'
  51145. }, noop);
  51146. registers.registerAction({
  51147. type: 'hideTip',
  51148. event: 'hideTip',
  51149. update: 'tooltip:manuallyHideTip'
  51150. }, noop);
  51151. }
  51152. var TitleModel = /** @class */function (_super) {
  51153. __extends(TitleModel, _super);
  51154. function TitleModel() {
  51155. var _this = _super !== null && _super.apply(this, arguments) || this;
  51156. _this.type = TitleModel.type;
  51157. _this.layoutMode = {
  51158. type: 'box',
  51159. ignoreSize: true
  51160. };
  51161. return _this;
  51162. }
  51163. TitleModel.type = 'title';
  51164. TitleModel.defaultOption = {
  51165. // zlevel: 0,
  51166. z: 6,
  51167. show: true,
  51168. text: '',
  51169. target: 'blank',
  51170. subtext: '',
  51171. subtarget: 'blank',
  51172. left: 0,
  51173. top: 0,
  51174. backgroundColor: 'rgba(0,0,0,0)',
  51175. borderColor: '#ccc',
  51176. borderWidth: 0,
  51177. padding: 5,
  51178. itemGap: 10,
  51179. textStyle: {
  51180. fontSize: 18,
  51181. fontWeight: 'bold',
  51182. color: '#464646'
  51183. },
  51184. subtextStyle: {
  51185. fontSize: 12,
  51186. color: '#6E7079'
  51187. }
  51188. };
  51189. return TitleModel;
  51190. }(ComponentModel);
  51191. // View
  51192. var TitleView = /** @class */function (_super) {
  51193. __extends(TitleView, _super);
  51194. function TitleView() {
  51195. var _this = _super !== null && _super.apply(this, arguments) || this;
  51196. _this.type = TitleView.type;
  51197. return _this;
  51198. }
  51199. TitleView.prototype.render = function (titleModel, ecModel, api) {
  51200. this.group.removeAll();
  51201. if (!titleModel.get('show')) {
  51202. return;
  51203. }
  51204. var group = this.group;
  51205. var textStyleModel = titleModel.getModel('textStyle');
  51206. var subtextStyleModel = titleModel.getModel('subtextStyle');
  51207. var textAlign = titleModel.get('textAlign');
  51208. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  51209. var textEl = new ZRText({
  51210. style: createTextStyle(textStyleModel, {
  51211. text: titleModel.get('text'),
  51212. fill: textStyleModel.getTextColor()
  51213. }, {
  51214. disableBox: true
  51215. }),
  51216. z2: 10
  51217. });
  51218. var textRect = textEl.getBoundingRect();
  51219. var subText = titleModel.get('subtext');
  51220. var subTextEl = new ZRText({
  51221. style: createTextStyle(subtextStyleModel, {
  51222. text: subText,
  51223. fill: subtextStyleModel.getTextColor(),
  51224. y: textRect.height + titleModel.get('itemGap'),
  51225. verticalAlign: 'top'
  51226. }, {
  51227. disableBox: true
  51228. }),
  51229. z2: 10
  51230. });
  51231. var link = titleModel.get('link');
  51232. var sublink = titleModel.get('sublink');
  51233. var triggerEvent = titleModel.get('triggerEvent', true);
  51234. textEl.silent = !link && !triggerEvent;
  51235. subTextEl.silent = !sublink && !triggerEvent;
  51236. if (link) {
  51237. textEl.on('click', function () {
  51238. windowOpen(link, '_' + titleModel.get('target'));
  51239. });
  51240. }
  51241. if (sublink) {
  51242. subTextEl.on('click', function () {
  51243. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  51244. });
  51245. }
  51246. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  51247. componentType: 'title',
  51248. componentIndex: titleModel.componentIndex
  51249. } : null;
  51250. group.add(textEl);
  51251. subText && group.add(subTextEl);
  51252. // If no subText, but add subTextEl, there will be an empty line.
  51253. var groupRect = group.getBoundingRect();
  51254. var layoutOption = titleModel.getBoxLayoutParams();
  51255. layoutOption.width = groupRect.width;
  51256. layoutOption.height = groupRect.height;
  51257. var layoutRect = getLayoutRect(layoutOption, {
  51258. width: api.getWidth(),
  51259. height: api.getHeight()
  51260. }, titleModel.get('padding'));
  51261. // Adjust text align based on position
  51262. if (!textAlign) {
  51263. // Align left if title is on the left. center and right is same
  51264. textAlign = titleModel.get('left') || titleModel.get('right');
  51265. // @ts-ignore
  51266. if (textAlign === 'middle') {
  51267. textAlign = 'center';
  51268. }
  51269. // Adjust layout by text align
  51270. if (textAlign === 'right') {
  51271. layoutRect.x += layoutRect.width;
  51272. } else if (textAlign === 'center') {
  51273. layoutRect.x += layoutRect.width / 2;
  51274. }
  51275. }
  51276. if (!textVerticalAlign) {
  51277. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  51278. // @ts-ignore
  51279. if (textVerticalAlign === 'center') {
  51280. textVerticalAlign = 'middle';
  51281. }
  51282. if (textVerticalAlign === 'bottom') {
  51283. layoutRect.y += layoutRect.height;
  51284. } else if (textVerticalAlign === 'middle') {
  51285. layoutRect.y += layoutRect.height / 2;
  51286. }
  51287. textVerticalAlign = textVerticalAlign || 'top';
  51288. }
  51289. group.x = layoutRect.x;
  51290. group.y = layoutRect.y;
  51291. group.markRedraw();
  51292. var alignStyle = {
  51293. align: textAlign,
  51294. verticalAlign: textVerticalAlign
  51295. };
  51296. textEl.setStyle(alignStyle);
  51297. subTextEl.setStyle(alignStyle);
  51298. // Render background
  51299. // Get groupRect again because textAlign has been changed
  51300. groupRect = group.getBoundingRect();
  51301. var padding = layoutRect.margin;
  51302. var style = titleModel.getItemStyle(['color', 'opacity']);
  51303. style.fill = titleModel.get('backgroundColor');
  51304. var rect = new Rect({
  51305. shape: {
  51306. x: groupRect.x - padding[3],
  51307. y: groupRect.y - padding[0],
  51308. width: groupRect.width + padding[1] + padding[3],
  51309. height: groupRect.height + padding[0] + padding[2],
  51310. r: titleModel.get('borderRadius')
  51311. },
  51312. style: style,
  51313. subPixelOptimize: true,
  51314. silent: true
  51315. });
  51316. group.add(rect);
  51317. };
  51318. TitleView.type = 'title';
  51319. return TitleView;
  51320. }(ComponentView);
  51321. function install$d(registers) {
  51322. registers.registerComponentModel(TitleModel);
  51323. registers.registerComponentView(TitleView);
  51324. }
  51325. function checkMarkerInSeries(seriesOpts, markerType) {
  51326. if (!seriesOpts) {
  51327. return false;
  51328. }
  51329. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  51330. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  51331. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  51332. return true;
  51333. }
  51334. }
  51335. return false;
  51336. }
  51337. function fillLabel(opt) {
  51338. defaultEmphasis(opt, 'label', ['show']);
  51339. }
  51340. // { [componentType]: MarkerModel }
  51341. var inner$c = makeInner();
  51342. var MarkerModel = /** @class */function (_super) {
  51343. __extends(MarkerModel, _super);
  51344. function MarkerModel() {
  51345. var _this = _super !== null && _super.apply(this, arguments) || this;
  51346. _this.type = MarkerModel.type;
  51347. /**
  51348. * If marker model is created by self from series
  51349. */
  51350. _this.createdBySelf = false;
  51351. return _this;
  51352. }
  51353. /**
  51354. * @overrite
  51355. */
  51356. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  51357. if ("development" !== 'production') {
  51358. if (this.type === 'marker') {
  51359. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  51360. }
  51361. }
  51362. this.mergeDefaultAndTheme(option, ecModel);
  51363. this._mergeOption(option, ecModel, false, true);
  51364. };
  51365. MarkerModel.prototype.isAnimationEnabled = function () {
  51366. if (env.node) {
  51367. return false;
  51368. }
  51369. var hostSeries = this.__hostSeries;
  51370. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  51371. };
  51372. /**
  51373. * @overrite
  51374. */
  51375. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  51376. this._mergeOption(newOpt, ecModel, false, false);
  51377. };
  51378. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  51379. var componentType = this.mainType;
  51380. if (!createdBySelf) {
  51381. ecModel.eachSeries(function (seriesModel) {
  51382. // mainType can be markPoint, markLine, markArea
  51383. var markerOpt = seriesModel.get(this.mainType, true);
  51384. var markerModel = inner$c(seriesModel)[componentType];
  51385. if (!markerOpt || !markerOpt.data) {
  51386. inner$c(seriesModel)[componentType] = null;
  51387. return;
  51388. }
  51389. if (!markerModel) {
  51390. if (isInit) {
  51391. // Default label emphasis `position` and `show`
  51392. fillLabel(markerOpt);
  51393. }
  51394. each(markerOpt.data, function (item) {
  51395. // FIXME Overwrite fillLabel method ?
  51396. if (item instanceof Array) {
  51397. fillLabel(item[0]);
  51398. fillLabel(item[1]);
  51399. } else {
  51400. fillLabel(item);
  51401. }
  51402. });
  51403. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel);
  51404. // markerModel = new ImplementedMarkerModel(
  51405. // markerOpt, this, ecModel
  51406. // );
  51407. extend(markerModel, {
  51408. mainType: this.mainType,
  51409. // Use the same series index and name
  51410. seriesIndex: seriesModel.seriesIndex,
  51411. name: seriesModel.name,
  51412. createdBySelf: true
  51413. });
  51414. markerModel.__hostSeries = seriesModel;
  51415. } else {
  51416. markerModel._mergeOption(markerOpt, ecModel, true);
  51417. }
  51418. inner$c(seriesModel)[componentType] = markerModel;
  51419. }, this);
  51420. }
  51421. };
  51422. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  51423. var data = this.getData();
  51424. var value = this.getRawValue(dataIndex);
  51425. var itemName = data.getName(dataIndex);
  51426. return createTooltipMarkup('section', {
  51427. header: this.name,
  51428. blocks: [createTooltipMarkup('nameValue', {
  51429. name: itemName,
  51430. value: value,
  51431. noName: !itemName,
  51432. noValue: value == null
  51433. })]
  51434. });
  51435. };
  51436. MarkerModel.prototype.getData = function () {
  51437. return this._data;
  51438. };
  51439. MarkerModel.prototype.setData = function (data) {
  51440. this._data = data;
  51441. };
  51442. MarkerModel.prototype.getDataParams = function (dataIndex, dataType) {
  51443. var params = DataFormatMixin.prototype.getDataParams.call(this, dataIndex, dataType);
  51444. var hostSeries = this.__hostSeries;
  51445. if (hostSeries) {
  51446. params.seriesId = hostSeries.id;
  51447. params.seriesName = hostSeries.name;
  51448. params.seriesType = hostSeries.subType;
  51449. }
  51450. return params;
  51451. };
  51452. MarkerModel.getMarkerModelFromSeries = function (seriesModel,
  51453. // Support three types of markers. Strict check.
  51454. componentType) {
  51455. return inner$c(seriesModel)[componentType];
  51456. };
  51457. MarkerModel.type = 'marker';
  51458. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  51459. return MarkerModel;
  51460. }(ComponentModel);
  51461. mixin(MarkerModel, DataFormatMixin.prototype);
  51462. var MarkPointModel = /** @class */function (_super) {
  51463. __extends(MarkPointModel, _super);
  51464. function MarkPointModel() {
  51465. var _this = _super !== null && _super.apply(this, arguments) || this;
  51466. _this.type = MarkPointModel.type;
  51467. return _this;
  51468. }
  51469. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  51470. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  51471. };
  51472. MarkPointModel.type = 'markPoint';
  51473. MarkPointModel.defaultOption = {
  51474. // zlevel: 0,
  51475. z: 5,
  51476. symbol: 'pin',
  51477. symbolSize: 50,
  51478. // symbolRotate: 0,
  51479. // symbolOffset: [0, 0]
  51480. tooltip: {
  51481. trigger: 'item'
  51482. },
  51483. label: {
  51484. show: true,
  51485. position: 'inside'
  51486. },
  51487. itemStyle: {
  51488. borderWidth: 2
  51489. },
  51490. emphasis: {
  51491. label: {
  51492. show: true
  51493. }
  51494. }
  51495. };
  51496. return MarkPointModel;
  51497. }(MarkerModel);
  51498. function hasXOrY(item) {
  51499. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  51500. }
  51501. function hasXAndY(item) {
  51502. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  51503. }
  51504. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  51505. var coordArr = [];
  51506. var stacked = isDimensionStacked(data, targetDataDim /* , otherDataDim */);
  51507. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  51508. var value = numCalculate(data, calcDataDim, markerType);
  51509. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  51510. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  51511. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  51512. var coordArrValue = data.get(targetDataDim, dataIndex);
  51513. // Make it simple, do not visit all stacked value to count precision.
  51514. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  51515. precision = Math.min(precision, 20);
  51516. if (precision >= 0) {
  51517. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  51518. }
  51519. return [coordArr, coordArrValue];
  51520. }
  51521. // TODO Specified percent
  51522. var markerTypeCalculator = {
  51523. min: curry(markerTypeCalculatorWithExtent, 'min'),
  51524. max: curry(markerTypeCalculatorWithExtent, 'max'),
  51525. average: curry(markerTypeCalculatorWithExtent, 'average'),
  51526. median: curry(markerTypeCalculatorWithExtent, 'median')
  51527. };
  51528. /**
  51529. * Transform markPoint data item to format used in List by do the following
  51530. * 1. Calculate statistic like `max`, `min`, `average`
  51531. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  51532. */
  51533. function dataTransform(seriesModel, item) {
  51534. if (!item) {
  51535. return;
  51536. }
  51537. var data = seriesModel.getData();
  51538. var coordSys = seriesModel.coordinateSystem;
  51539. var dims = coordSys && coordSys.dimensions;
  51540. // 1. If not specify the position with pixel directly
  51541. // 2. If `coord` is not a data array. Which uses `xAxis`,
  51542. // `yAxis` to specify the coord on each dimension
  51543. // parseFloat first because item.x and item.y can be percent string like '20%'
  51544. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  51545. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  51546. // Clone the option
  51547. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  51548. item = clone(item);
  51549. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  51550. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  51551. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  51552. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  51553. item.coord = coordInfo[0];
  51554. // Force to use the value of calculated value.
  51555. // let item use the value without stack.
  51556. item.value = coordInfo[1];
  51557. } else {
  51558. // FIXME Only has one of xAxis and yAxis.
  51559. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  51560. }
  51561. }
  51562. // x y is provided
  51563. if (item.coord == null || !isArray(dims)) {
  51564. item.coord = [];
  51565. } else {
  51566. // Each coord support max, min, average
  51567. var coord = item.coord;
  51568. for (var i = 0; i < 2; i++) {
  51569. if (markerTypeCalculator[coord[i]]) {
  51570. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  51571. }
  51572. }
  51573. }
  51574. return item;
  51575. }
  51576. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  51577. var ret = {};
  51578. if (item.valueIndex != null || item.valueDim != null) {
  51579. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  51580. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  51581. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  51582. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  51583. } else {
  51584. ret.baseAxis = seriesModel.getBaseAxis();
  51585. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  51586. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  51587. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  51588. }
  51589. return ret;
  51590. }
  51591. function dataDimToCoordDim(seriesModel, dataDim) {
  51592. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  51593. return dimItem && dimItem.coordDim;
  51594. }
  51595. /**
  51596. * Filter data which is out of coordinateSystem range
  51597. * [dataFilter description]
  51598. */
  51599. function dataFilter$1(
  51600. // Currently only polar and cartesian has containData.
  51601. coordSys, item) {
  51602. // Always return true if there is no coordSys
  51603. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  51604. }
  51605. function zoneFilter(
  51606. // Currently only polar and cartesian has containData.
  51607. coordSys, item1, item2) {
  51608. // Always return true if there is no coordSys
  51609. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  51610. }
  51611. function createMarkerDimValueGetter(inCoordSys, dims) {
  51612. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  51613. var rawVal = dimIndex < 2
  51614. // x, y, radius, angle
  51615. ? item.coord && item.coord[dimIndex] : item.value;
  51616. return parseDataValue(rawVal, dims[dimIndex]);
  51617. } : function (item, dimName, dataIndex, dimIndex) {
  51618. return parseDataValue(item.value, dims[dimIndex]);
  51619. };
  51620. }
  51621. function numCalculate(data, valueDataDim, type) {
  51622. if (type === 'average') {
  51623. var sum_1 = 0;
  51624. var count_1 = 0;
  51625. data.each(valueDataDim, function (val, idx) {
  51626. if (!isNaN(val)) {
  51627. sum_1 += val;
  51628. count_1++;
  51629. }
  51630. });
  51631. return sum_1 / count_1;
  51632. } else if (type === 'median') {
  51633. return data.getMedian(valueDataDim);
  51634. } else {
  51635. // max & min
  51636. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  51637. }
  51638. }
  51639. var inner$d = makeInner();
  51640. var MarkerView = /** @class */function (_super) {
  51641. __extends(MarkerView, _super);
  51642. function MarkerView() {
  51643. var _this = _super !== null && _super.apply(this, arguments) || this;
  51644. _this.type = MarkerView.type;
  51645. return _this;
  51646. }
  51647. MarkerView.prototype.init = function () {
  51648. this.markerGroupMap = createHashMap();
  51649. };
  51650. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  51651. var _this = this;
  51652. var markerGroupMap = this.markerGroupMap;
  51653. markerGroupMap.each(function (item) {
  51654. inner$d(item).keep = false;
  51655. });
  51656. ecModel.eachSeries(function (seriesModel) {
  51657. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  51658. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  51659. });
  51660. markerGroupMap.each(function (item) {
  51661. !inner$d(item).keep && _this.group.remove(item.group);
  51662. });
  51663. };
  51664. MarkerView.prototype.markKeep = function (drawGroup) {
  51665. inner$d(drawGroup).keep = true;
  51666. };
  51667. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  51668. var _this = this;
  51669. each(seriesModelList, function (seriesModel) {
  51670. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  51671. if (markerModel) {
  51672. var data = markerModel.getData();
  51673. data.eachItemGraphicEl(function (el) {
  51674. if (el) {
  51675. isBlur ? enterBlur(el) : leaveBlur(el);
  51676. }
  51677. });
  51678. }
  51679. });
  51680. };
  51681. MarkerView.type = 'marker';
  51682. return MarkerView;
  51683. }(ComponentView);
  51684. function updateMarkerLayout(mpData, seriesModel, api) {
  51685. var coordSys = seriesModel.coordinateSystem;
  51686. mpData.each(function (idx) {
  51687. var itemModel = mpData.getItemModel(idx);
  51688. var point;
  51689. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  51690. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  51691. if (!isNaN(xPx) && !isNaN(yPx)) {
  51692. point = [xPx, yPx];
  51693. }
  51694. // Chart like bar may have there own marker positioning logic
  51695. else if (seriesModel.getMarkerPosition) {
  51696. // Use the getMarkerPosition
  51697. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  51698. } else if (coordSys) {
  51699. var x = mpData.get(coordSys.dimensions[0], idx);
  51700. var y = mpData.get(coordSys.dimensions[1], idx);
  51701. point = coordSys.dataToPoint([x, y]);
  51702. }
  51703. // Use x, y if has any
  51704. if (!isNaN(xPx)) {
  51705. point[0] = xPx;
  51706. }
  51707. if (!isNaN(yPx)) {
  51708. point[1] = yPx;
  51709. }
  51710. mpData.setItemLayout(idx, point);
  51711. });
  51712. }
  51713. var MarkPointView = /** @class */function (_super) {
  51714. __extends(MarkPointView, _super);
  51715. function MarkPointView() {
  51716. var _this = _super !== null && _super.apply(this, arguments) || this;
  51717. _this.type = MarkPointView.type;
  51718. return _this;
  51719. }
  51720. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  51721. ecModel.eachSeries(function (seriesModel) {
  51722. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  51723. if (mpModel) {
  51724. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  51725. this.markerGroupMap.get(seriesModel.id).updateLayout();
  51726. }
  51727. }, this);
  51728. };
  51729. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  51730. var coordSys = seriesModel.coordinateSystem;
  51731. var seriesId = seriesModel.id;
  51732. var seriesData = seriesModel.getData();
  51733. var symbolDrawMap = this.markerGroupMap;
  51734. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  51735. var mpData = createData(coordSys, seriesModel, mpModel);
  51736. // FIXME
  51737. mpModel.setData(mpData);
  51738. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  51739. mpData.each(function (idx) {
  51740. var itemModel = mpData.getItemModel(idx);
  51741. var symbol = itemModel.getShallow('symbol');
  51742. var symbolSize = itemModel.getShallow('symbolSize');
  51743. var symbolRotate = itemModel.getShallow('symbolRotate');
  51744. var symbolOffset = itemModel.getShallow('symbolOffset');
  51745. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect');
  51746. // TODO: refactor needed: single data item should not support callback function
  51747. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  51748. var rawIdx = mpModel.getRawValue(idx);
  51749. var dataParams = mpModel.getDataParams(idx);
  51750. if (isFunction(symbol)) {
  51751. symbol = symbol(rawIdx, dataParams);
  51752. }
  51753. if (isFunction(symbolSize)) {
  51754. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  51755. symbolSize = symbolSize(rawIdx, dataParams);
  51756. }
  51757. if (isFunction(symbolRotate)) {
  51758. symbolRotate = symbolRotate(rawIdx, dataParams);
  51759. }
  51760. if (isFunction(symbolOffset)) {
  51761. symbolOffset = symbolOffset(rawIdx, dataParams);
  51762. }
  51763. }
  51764. var style = itemModel.getModel('itemStyle').getItemStyle();
  51765. var color = getVisualFromData(seriesData, 'color');
  51766. if (!style.fill) {
  51767. style.fill = color;
  51768. }
  51769. mpData.setItemVisual(idx, {
  51770. symbol: symbol,
  51771. symbolSize: symbolSize,
  51772. symbolRotate: symbolRotate,
  51773. symbolOffset: symbolOffset,
  51774. symbolKeepAspect: symbolKeepAspect,
  51775. style: style
  51776. });
  51777. });
  51778. // TODO Text are wrong
  51779. symbolDraw.updateData(mpData);
  51780. this.group.add(symbolDraw.group);
  51781. // Set host model for tooltip
  51782. // FIXME
  51783. mpData.eachItemGraphicEl(function (el) {
  51784. el.traverse(function (child) {
  51785. getECData(child).dataModel = mpModel;
  51786. });
  51787. });
  51788. this.markKeep(symbolDraw);
  51789. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  51790. };
  51791. MarkPointView.type = 'markPoint';
  51792. return MarkPointView;
  51793. }(MarkerView);
  51794. function createData(coordSys, seriesModel, mpModel) {
  51795. var coordDimsInfos;
  51796. if (coordSys) {
  51797. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  51798. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {};
  51799. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  51800. return extend(extend({}, info), {
  51801. name: coordDim,
  51802. // DON'T use ordinalMeta to parse and collect ordinal.
  51803. ordinalMeta: null
  51804. });
  51805. });
  51806. } else {
  51807. coordDimsInfos = [{
  51808. name: 'value',
  51809. type: 'float'
  51810. }];
  51811. }
  51812. var mpData = new SeriesData(coordDimsInfos, mpModel);
  51813. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  51814. if (coordSys) {
  51815. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  51816. }
  51817. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  51818. mpData.initData(dataOpt, null, dimValueGetter);
  51819. return mpData;
  51820. }
  51821. function install$e(registers) {
  51822. registers.registerComponentModel(MarkPointModel);
  51823. registers.registerComponentView(MarkPointView);
  51824. registers.registerPreprocessor(function (opt) {
  51825. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  51826. // Make sure markPoint component is enabled
  51827. opt.markPoint = opt.markPoint || {};
  51828. }
  51829. });
  51830. }
  51831. var MarkLineModel = /** @class */function (_super) {
  51832. __extends(MarkLineModel, _super);
  51833. function MarkLineModel() {
  51834. var _this = _super !== null && _super.apply(this, arguments) || this;
  51835. _this.type = MarkLineModel.type;
  51836. return _this;
  51837. }
  51838. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  51839. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  51840. };
  51841. MarkLineModel.type = 'markLine';
  51842. MarkLineModel.defaultOption = {
  51843. // zlevel: 0,
  51844. z: 5,
  51845. symbol: ['circle', 'arrow'],
  51846. symbolSize: [8, 16],
  51847. // symbolRotate: 0,
  51848. symbolOffset: 0,
  51849. precision: 2,
  51850. tooltip: {
  51851. trigger: 'item'
  51852. },
  51853. label: {
  51854. show: true,
  51855. position: 'end',
  51856. distance: 5
  51857. },
  51858. lineStyle: {
  51859. type: 'dashed'
  51860. },
  51861. emphasis: {
  51862. label: {
  51863. show: true
  51864. },
  51865. lineStyle: {
  51866. width: 3
  51867. }
  51868. },
  51869. animationEasing: 'linear'
  51870. };
  51871. return MarkLineModel;
  51872. }(MarkerModel);
  51873. var straightLineProto = Line.prototype;
  51874. var bezierCurveProto = BezierCurve.prototype;
  51875. var StraightLineShape = /** @class */function () {
  51876. function StraightLineShape() {
  51877. // Start point
  51878. this.x1 = 0;
  51879. this.y1 = 0;
  51880. // End point
  51881. this.x2 = 0;
  51882. this.y2 = 0;
  51883. this.percent = 1;
  51884. }
  51885. return StraightLineShape;
  51886. }();
  51887. var CurveShape = /** @class */function (_super) {
  51888. __extends(CurveShape, _super);
  51889. function CurveShape() {
  51890. return _super !== null && _super.apply(this, arguments) || this;
  51891. }
  51892. return CurveShape;
  51893. }(StraightLineShape);
  51894. function isStraightLine(shape) {
  51895. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  51896. }
  51897. var ECLinePath = /** @class */function (_super) {
  51898. __extends(ECLinePath, _super);
  51899. function ECLinePath(opts) {
  51900. var _this = _super.call(this, opts) || this;
  51901. _this.type = 'ec-line';
  51902. return _this;
  51903. }
  51904. ECLinePath.prototype.getDefaultStyle = function () {
  51905. return {
  51906. stroke: '#000',
  51907. fill: null
  51908. };
  51909. };
  51910. ECLinePath.prototype.getDefaultShape = function () {
  51911. return new StraightLineShape();
  51912. };
  51913. ECLinePath.prototype.buildPath = function (ctx, shape) {
  51914. if (isStraightLine(shape)) {
  51915. straightLineProto.buildPath.call(this, ctx, shape);
  51916. } else {
  51917. bezierCurveProto.buildPath.call(this, ctx, shape);
  51918. }
  51919. };
  51920. ECLinePath.prototype.pointAt = function (t) {
  51921. if (isStraightLine(this.shape)) {
  51922. return straightLineProto.pointAt.call(this, t);
  51923. } else {
  51924. return bezierCurveProto.pointAt.call(this, t);
  51925. }
  51926. };
  51927. ECLinePath.prototype.tangentAt = function (t) {
  51928. var shape = this.shape;
  51929. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  51930. return normalize(p, p);
  51931. };
  51932. return ECLinePath;
  51933. }(Path);
  51934. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  51935. function makeSymbolTypeKey(symbolCategory) {
  51936. return '_' + symbolCategory + 'Type';
  51937. }
  51938. function makeSymbolTypeValue(name, lineData, idx) {
  51939. var symbolType = lineData.getItemVisual(idx, name);
  51940. if (!symbolType || symbolType === 'none') {
  51941. return symbolType;
  51942. }
  51943. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  51944. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  51945. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  51946. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  51947. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  51948. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  51949. return symbolType + symbolSizeArr + symbolOffsetArr + (symbolRotate || '') + (symbolKeepAspect || '');
  51950. }
  51951. /**
  51952. * @inner
  51953. */
  51954. function createSymbol$1(name, lineData, idx) {
  51955. var symbolType = lineData.getItemVisual(idx, name);
  51956. if (!symbolType || symbolType === 'none') {
  51957. return;
  51958. }
  51959. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  51960. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  51961. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  51962. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  51963. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  51964. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  51965. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  51966. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  51967. symbolPath.name = name;
  51968. return symbolPath;
  51969. }
  51970. function createLine(points) {
  51971. var line = new ECLinePath({
  51972. name: 'line',
  51973. subPixelOptimize: true
  51974. });
  51975. setLinePoints(line.shape, points);
  51976. return line;
  51977. }
  51978. function setLinePoints(targetShape, points) {
  51979. targetShape.x1 = points[0][0];
  51980. targetShape.y1 = points[0][1];
  51981. targetShape.x2 = points[1][0];
  51982. targetShape.y2 = points[1][1];
  51983. targetShape.percent = 1;
  51984. var cp1 = points[2];
  51985. if (cp1) {
  51986. targetShape.cpx1 = cp1[0];
  51987. targetShape.cpy1 = cp1[1];
  51988. } else {
  51989. targetShape.cpx1 = NaN;
  51990. targetShape.cpy1 = NaN;
  51991. }
  51992. }
  51993. var Line$1 = /** @class */function (_super) {
  51994. __extends(Line, _super);
  51995. function Line(lineData, idx, seriesScope) {
  51996. var _this = _super.call(this) || this;
  51997. _this._createLine(lineData, idx, seriesScope);
  51998. return _this;
  51999. }
  52000. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  52001. var seriesModel = lineData.hostModel;
  52002. var linePoints = lineData.getItemLayout(idx);
  52003. var line = createLine(linePoints);
  52004. line.shape.percent = 0;
  52005. initProps(line, {
  52006. shape: {
  52007. percent: 1
  52008. }
  52009. }, seriesModel, idx);
  52010. this.add(line);
  52011. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52012. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52013. // symbols must added after line to make sure
  52014. // it will be updated after line#update.
  52015. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  52016. this.add(symbol);
  52017. this[makeSymbolTypeKey(symbolCategory)] = makeSymbolTypeValue(symbolCategory, lineData, idx);
  52018. }, this);
  52019. this._updateCommonStl(lineData, idx, seriesScope);
  52020. };
  52021. // TODO More strict on the List type in parameters?
  52022. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  52023. var seriesModel = lineData.hostModel;
  52024. var line = this.childOfName('line');
  52025. var linePoints = lineData.getItemLayout(idx);
  52026. var target = {
  52027. shape: {}
  52028. };
  52029. setLinePoints(target.shape, linePoints);
  52030. updateProps(line, target, seriesModel, idx);
  52031. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52032. var symbolType = makeSymbolTypeValue(symbolCategory, lineData, idx);
  52033. var key = makeSymbolTypeKey(symbolCategory);
  52034. // Symbol changed
  52035. if (this[key] !== symbolType) {
  52036. this.remove(this.childOfName(symbolCategory));
  52037. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52038. this.add(symbol);
  52039. }
  52040. this[key] = symbolType;
  52041. }, this);
  52042. this._updateCommonStl(lineData, idx, seriesScope);
  52043. };
  52044. Line.prototype.getLinePath = function () {
  52045. return this.childAt(0);
  52046. };
  52047. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  52048. var seriesModel = lineData.hostModel;
  52049. var line = this.childOfName('line');
  52050. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  52051. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  52052. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  52053. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  52054. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  52055. var focus = seriesScope && seriesScope.focus;
  52056. var blurScope = seriesScope && seriesScope.blurScope;
  52057. // Optimization for large dataset
  52058. if (!seriesScope || lineData.hasItemOption) {
  52059. var itemModel = lineData.getItemModel(idx);
  52060. var emphasisModel = itemModel.getModel('emphasis');
  52061. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  52062. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  52063. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  52064. emphasisDisabled = emphasisModel.get('disabled');
  52065. focus = emphasisModel.get('focus');
  52066. blurScope = emphasisModel.get('blurScope');
  52067. labelStatesModels = getLabelStatesModels(itemModel);
  52068. }
  52069. var lineStyle = lineData.getItemVisual(idx, 'style');
  52070. var visualColor = lineStyle.stroke;
  52071. line.useStyle(lineStyle);
  52072. line.style.fill = null;
  52073. line.style.strokeNoScale = true;
  52074. line.ensureState('emphasis').style = emphasisLineStyle;
  52075. line.ensureState('blur').style = blurLineStyle;
  52076. line.ensureState('select').style = selectLineStyle;
  52077. // Update symbol
  52078. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52079. var symbol = this.childOfName(symbolCategory);
  52080. if (symbol) {
  52081. // Share opacity and color with line.
  52082. symbol.setColor(visualColor);
  52083. symbol.style.opacity = lineStyle.opacity;
  52084. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  52085. var stateName = SPECIAL_STATES[i];
  52086. var lineState = line.getState(stateName);
  52087. if (lineState) {
  52088. var lineStateStyle = lineState.style || {};
  52089. var state = symbol.ensureState(stateName);
  52090. var stateStyle = state.style || (state.style = {});
  52091. if (lineStateStyle.stroke != null) {
  52092. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  52093. }
  52094. if (lineStateStyle.opacity != null) {
  52095. stateStyle.opacity = lineStateStyle.opacity;
  52096. }
  52097. }
  52098. }
  52099. symbol.markRedraw();
  52100. }
  52101. }, this);
  52102. var rawVal = seriesModel.getRawValue(idx);
  52103. setLabelStyle(this, labelStatesModels, {
  52104. labelDataIndex: idx,
  52105. labelFetcher: {
  52106. getFormattedLabel: function (dataIndex, stateName) {
  52107. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  52108. }
  52109. },
  52110. inheritColor: visualColor || '#000',
  52111. defaultOpacity: lineStyle.opacity,
  52112. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  52113. });
  52114. var label = this.getTextContent();
  52115. // Always set `textStyle` even if `normalStyle.text` is null, because default
  52116. // values have to be set on `normalStyle`.
  52117. if (label) {
  52118. var labelNormalModel = labelStatesModels.normal;
  52119. label.__align = label.style.align;
  52120. label.__verticalAlign = label.style.verticalAlign;
  52121. // 'start', 'middle', 'end'
  52122. label.__position = labelNormalModel.get('position') || 'middle';
  52123. var distance = labelNormalModel.get('distance');
  52124. if (!isArray(distance)) {
  52125. distance = [distance, distance];
  52126. }
  52127. label.__labelDistance = distance;
  52128. }
  52129. this.setTextConfig({
  52130. position: null,
  52131. local: true,
  52132. inside: false // Can't be inside for stroke element.
  52133. });
  52134. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  52135. };
  52136. Line.prototype.highlight = function () {
  52137. enterEmphasis(this);
  52138. };
  52139. Line.prototype.downplay = function () {
  52140. leaveEmphasis(this);
  52141. };
  52142. Line.prototype.updateLayout = function (lineData, idx) {
  52143. this.setLinePoints(lineData.getItemLayout(idx));
  52144. };
  52145. Line.prototype.setLinePoints = function (points) {
  52146. var linePath = this.childOfName('line');
  52147. setLinePoints(linePath.shape, points);
  52148. linePath.dirty();
  52149. };
  52150. Line.prototype.beforeUpdate = function () {
  52151. var lineGroup = this;
  52152. var symbolFrom = lineGroup.childOfName('fromSymbol');
  52153. var symbolTo = lineGroup.childOfName('toSymbol');
  52154. var label = lineGroup.getTextContent();
  52155. // Quick reject
  52156. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  52157. return;
  52158. }
  52159. var invScale = 1;
  52160. var parentNode = this.parent;
  52161. while (parentNode) {
  52162. if (parentNode.scaleX) {
  52163. invScale /= parentNode.scaleX;
  52164. }
  52165. parentNode = parentNode.parent;
  52166. }
  52167. var line = lineGroup.childOfName('line');
  52168. // If line not changed
  52169. // FIXME Parent scale changed
  52170. if (!this.__dirty && !line.__dirty) {
  52171. return;
  52172. }
  52173. var percent = line.shape.percent;
  52174. var fromPos = line.pointAt(0);
  52175. var toPos = line.pointAt(percent);
  52176. var d = sub([], toPos, fromPos);
  52177. normalize(d, d);
  52178. function setSymbolRotation(symbol, percent) {
  52179. // Fix #12388
  52180. // when symbol is set to be 'arrow' in markLine,
  52181. // symbolRotate value will be ignored, and compulsively use tangent angle.
  52182. // rotate by default if symbol rotation is not specified
  52183. var specifiedRotation = symbol.__specifiedRotation;
  52184. if (specifiedRotation == null) {
  52185. var tangent = line.tangentAt(percent);
  52186. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  52187. } else {
  52188. symbol.attr('rotation', specifiedRotation);
  52189. }
  52190. }
  52191. if (symbolFrom) {
  52192. symbolFrom.setPosition(fromPos);
  52193. setSymbolRotation(symbolFrom, 0);
  52194. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  52195. symbolFrom.markRedraw();
  52196. }
  52197. if (symbolTo) {
  52198. symbolTo.setPosition(toPos);
  52199. setSymbolRotation(symbolTo, 1);
  52200. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  52201. symbolTo.markRedraw();
  52202. }
  52203. if (label && !label.ignore) {
  52204. label.x = label.y = 0;
  52205. label.originX = label.originY = 0;
  52206. var textAlign = void 0;
  52207. var textVerticalAlign = void 0;
  52208. var distance = label.__labelDistance;
  52209. var distanceX = distance[0] * invScale;
  52210. var distanceY = distance[1] * invScale;
  52211. var halfPercent = percent / 2;
  52212. var tangent = line.tangentAt(halfPercent);
  52213. var n = [tangent[1], -tangent[0]];
  52214. var cp = line.pointAt(halfPercent);
  52215. if (n[1] > 0) {
  52216. n[0] = -n[0];
  52217. n[1] = -n[1];
  52218. }
  52219. var dir = tangent[0] < 0 ? -1 : 1;
  52220. if (label.__position !== 'start' && label.__position !== 'end') {
  52221. var rotation = -Math.atan2(tangent[1], tangent[0]);
  52222. if (toPos[0] < fromPos[0]) {
  52223. rotation = Math.PI + rotation;
  52224. }
  52225. label.rotation = rotation;
  52226. }
  52227. var dy = void 0;
  52228. switch (label.__position) {
  52229. case 'insideStartTop':
  52230. case 'insideMiddleTop':
  52231. case 'insideEndTop':
  52232. case 'middle':
  52233. dy = -distanceY;
  52234. textVerticalAlign = 'bottom';
  52235. break;
  52236. case 'insideStartBottom':
  52237. case 'insideMiddleBottom':
  52238. case 'insideEndBottom':
  52239. dy = distanceY;
  52240. textVerticalAlign = 'top';
  52241. break;
  52242. default:
  52243. dy = 0;
  52244. textVerticalAlign = 'middle';
  52245. }
  52246. switch (label.__position) {
  52247. case 'end':
  52248. label.x = d[0] * distanceX + toPos[0];
  52249. label.y = d[1] * distanceY + toPos[1];
  52250. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  52251. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  52252. break;
  52253. case 'start':
  52254. label.x = -d[0] * distanceX + fromPos[0];
  52255. label.y = -d[1] * distanceY + fromPos[1];
  52256. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  52257. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  52258. break;
  52259. case 'insideStartTop':
  52260. case 'insideStart':
  52261. case 'insideStartBottom':
  52262. label.x = distanceX * dir + fromPos[0];
  52263. label.y = fromPos[1] + dy;
  52264. textAlign = tangent[0] < 0 ? 'right' : 'left';
  52265. label.originX = -distanceX * dir;
  52266. label.originY = -dy;
  52267. break;
  52268. case 'insideMiddleTop':
  52269. case 'insideMiddle':
  52270. case 'insideMiddleBottom':
  52271. case 'middle':
  52272. label.x = cp[0];
  52273. label.y = cp[1] + dy;
  52274. textAlign = 'center';
  52275. label.originY = -dy;
  52276. break;
  52277. case 'insideEndTop':
  52278. case 'insideEnd':
  52279. case 'insideEndBottom':
  52280. label.x = -distanceX * dir + toPos[0];
  52281. label.y = toPos[1] + dy;
  52282. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  52283. label.originX = distanceX * dir;
  52284. label.originY = -dy;
  52285. break;
  52286. }
  52287. label.scaleX = label.scaleY = invScale;
  52288. label.setStyle({
  52289. // Use the user specified text align and baseline first
  52290. verticalAlign: label.__verticalAlign || textVerticalAlign,
  52291. align: label.__align || textAlign
  52292. });
  52293. }
  52294. };
  52295. return Line;
  52296. }(Group);
  52297. var LineDraw = /** @class */function () {
  52298. function LineDraw(LineCtor) {
  52299. this.group = new Group();
  52300. this._LineCtor = LineCtor || Line$1;
  52301. }
  52302. LineDraw.prototype.updateData = function (lineData) {
  52303. var _this = this;
  52304. // Remove progressive els.
  52305. this._progressiveEls = null;
  52306. var lineDraw = this;
  52307. var group = lineDraw.group;
  52308. var oldLineData = lineDraw._lineData;
  52309. lineDraw._lineData = lineData;
  52310. // There is no oldLineData only when first rendering or switching from
  52311. // stream mode to normal mode, where previous elements should be removed.
  52312. if (!oldLineData) {
  52313. group.removeAll();
  52314. }
  52315. var seriesScope = makeSeriesScope$1(lineData);
  52316. lineData.diff(oldLineData).add(function (idx) {
  52317. _this._doAdd(lineData, idx, seriesScope);
  52318. }).update(function (newIdx, oldIdx) {
  52319. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  52320. }).remove(function (idx) {
  52321. group.remove(oldLineData.getItemGraphicEl(idx));
  52322. }).execute();
  52323. };
  52324. LineDraw.prototype.updateLayout = function () {
  52325. var lineData = this._lineData;
  52326. // Do not support update layout in incremental mode.
  52327. if (!lineData) {
  52328. return;
  52329. }
  52330. lineData.eachItemGraphicEl(function (el, idx) {
  52331. el.updateLayout(lineData, idx);
  52332. }, this);
  52333. };
  52334. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  52335. this._seriesScope = makeSeriesScope$1(lineData);
  52336. this._lineData = null;
  52337. this.group.removeAll();
  52338. };
  52339. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  52340. this._progressiveEls = [];
  52341. function updateIncrementalAndHover(el) {
  52342. if (!el.isGroup && !isEffectObject(el)) {
  52343. el.incremental = true;
  52344. el.ensureState('emphasis').hoverLayer = true;
  52345. }
  52346. }
  52347. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  52348. var itemLayout = lineData.getItemLayout(idx);
  52349. if (lineNeedsDraw(itemLayout)) {
  52350. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  52351. el.traverse(updateIncrementalAndHover);
  52352. this.group.add(el);
  52353. lineData.setItemGraphicEl(idx, el);
  52354. this._progressiveEls.push(el);
  52355. }
  52356. }
  52357. };
  52358. LineDraw.prototype.remove = function () {
  52359. this.group.removeAll();
  52360. };
  52361. LineDraw.prototype.eachRendered = function (cb) {
  52362. traverseElements(this._progressiveEls || this.group, cb);
  52363. };
  52364. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  52365. var itemLayout = lineData.getItemLayout(idx);
  52366. if (!lineNeedsDraw(itemLayout)) {
  52367. return;
  52368. }
  52369. var el = new this._LineCtor(lineData, idx, seriesScope);
  52370. lineData.setItemGraphicEl(idx, el);
  52371. this.group.add(el);
  52372. };
  52373. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  52374. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  52375. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  52376. this.group.remove(itemEl);
  52377. return;
  52378. }
  52379. if (!itemEl) {
  52380. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  52381. } else {
  52382. itemEl.updateData(newLineData, newIdx, seriesScope);
  52383. }
  52384. newLineData.setItemGraphicEl(newIdx, itemEl);
  52385. this.group.add(itemEl);
  52386. };
  52387. return LineDraw;
  52388. }();
  52389. function isEffectObject(el) {
  52390. return el.animators && el.animators.length > 0;
  52391. }
  52392. function makeSeriesScope$1(lineData) {
  52393. var hostModel = lineData.hostModel;
  52394. var emphasisModel = hostModel.getModel('emphasis');
  52395. return {
  52396. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  52397. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  52398. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  52399. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  52400. emphasisDisabled: emphasisModel.get('disabled'),
  52401. blurScope: emphasisModel.get('blurScope'),
  52402. focus: emphasisModel.get('focus'),
  52403. labelStatesModels: getLabelStatesModels(hostModel)
  52404. };
  52405. }
  52406. function isPointNaN(pt) {
  52407. return isNaN(pt[0]) || isNaN(pt[1]);
  52408. }
  52409. function lineNeedsDraw(pts) {
  52410. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  52411. }
  52412. var inner$e = makeInner();
  52413. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  52414. var data = seriesModel.getData();
  52415. var itemArray;
  52416. if (!isArray(item)) {
  52417. // Special type markLine like 'min', 'max', 'average', 'median'
  52418. var mlType = item.type;
  52419. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  52420. // In case
  52421. // data: [{
  52422. // yAxis: 10
  52423. // }]
  52424. || item.xAxis != null || item.yAxis != null) {
  52425. var valueAxis = void 0;
  52426. var value = void 0;
  52427. if (item.yAxis != null || item.xAxis != null) {
  52428. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  52429. value = retrieve(item.yAxis, item.xAxis);
  52430. } else {
  52431. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  52432. valueAxis = axisInfo.valueAxis;
  52433. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  52434. value = numCalculate(data, valueDataDim, mlType);
  52435. }
  52436. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  52437. var baseIndex = 1 - valueIndex;
  52438. // Normized to 2d data with start and end point
  52439. var mlFrom = clone(item);
  52440. var mlTo = {
  52441. coord: []
  52442. };
  52443. mlFrom.type = null;
  52444. mlFrom.coord = [];
  52445. mlFrom.coord[baseIndex] = -Infinity;
  52446. mlTo.coord[baseIndex] = Infinity;
  52447. var precision = mlModel.get('precision');
  52448. if (precision >= 0 && isNumber(value)) {
  52449. value = +value.toFixed(Math.min(precision, 20));
  52450. }
  52451. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  52452. itemArray = [mlFrom, mlTo, {
  52453. type: mlType,
  52454. valueIndex: item.valueIndex,
  52455. // Force to use the value of calculated value.
  52456. value: value
  52457. }];
  52458. } else {
  52459. // Invalid data
  52460. if ("development" !== 'production') {
  52461. logError('Invalid markLine data.');
  52462. }
  52463. itemArray = [];
  52464. }
  52465. } else {
  52466. itemArray = item;
  52467. }
  52468. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])];
  52469. // Avoid line data type is extended by from(to) data type
  52470. normalizedItem[2].type = normalizedItem[2].type || null;
  52471. // Merge from option and to option into line option
  52472. merge(normalizedItem[2], normalizedItem[0]);
  52473. merge(normalizedItem[2], normalizedItem[1]);
  52474. return normalizedItem;
  52475. };
  52476. function isInfinity(val) {
  52477. return !isNaN(val) && !isFinite(val);
  52478. }
  52479. // If a markLine has one dim
  52480. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  52481. var otherDimIndex = 1 - dimIndex;
  52482. var dimName = coordSys.dimensions[dimIndex];
  52483. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  52484. }
  52485. function markLineFilter(coordSys, item) {
  52486. if (coordSys.type === 'cartesian2d') {
  52487. var fromCoord = item[0].coord;
  52488. var toCoord = item[1].coord;
  52489. // In case
  52490. // {
  52491. // markLine: {
  52492. // data: [{ yAxis: 2 }]
  52493. // }
  52494. // }
  52495. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  52496. return true;
  52497. }
  52498. }
  52499. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  52500. }
  52501. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  52502. var coordSys = seriesModel.coordinateSystem;
  52503. var itemModel = data.getItemModel(idx);
  52504. var point;
  52505. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  52506. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  52507. if (!isNaN(xPx) && !isNaN(yPx)) {
  52508. point = [xPx, yPx];
  52509. } else {
  52510. // Chart like bar may have there own marker positioning logic
  52511. if (seriesModel.getMarkerPosition) {
  52512. // Use the getMarkerPosition
  52513. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  52514. } else {
  52515. var dims = coordSys.dimensions;
  52516. var x = data.get(dims[0], idx);
  52517. var y = data.get(dims[1], idx);
  52518. point = coordSys.dataToPoint([x, y]);
  52519. }
  52520. // Expand line to the edge of grid if value on one axis is Inifnity
  52521. // In case
  52522. // markLine: {
  52523. // data: [{
  52524. // yAxis: 2
  52525. // // or
  52526. // type: 'average'
  52527. // }]
  52528. // }
  52529. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  52530. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  52531. var xAxis = coordSys.getAxis('x');
  52532. var yAxis = coordSys.getAxis('y');
  52533. var dims = coordSys.dimensions;
  52534. if (isInfinity(data.get(dims[0], idx))) {
  52535. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  52536. } else if (isInfinity(data.get(dims[1], idx))) {
  52537. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  52538. }
  52539. }
  52540. // Use x, y if has any
  52541. if (!isNaN(xPx)) {
  52542. point[0] = xPx;
  52543. }
  52544. if (!isNaN(yPx)) {
  52545. point[1] = yPx;
  52546. }
  52547. }
  52548. data.setItemLayout(idx, point);
  52549. }
  52550. var MarkLineView = /** @class */function (_super) {
  52551. __extends(MarkLineView, _super);
  52552. function MarkLineView() {
  52553. var _this = _super !== null && _super.apply(this, arguments) || this;
  52554. _this.type = MarkLineView.type;
  52555. return _this;
  52556. }
  52557. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  52558. ecModel.eachSeries(function (seriesModel) {
  52559. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  52560. if (mlModel) {
  52561. var mlData_1 = mlModel.getData();
  52562. var fromData_1 = inner$e(mlModel).from;
  52563. var toData_1 = inner$e(mlModel).to;
  52564. // Update visual and layout of from symbol and to symbol
  52565. fromData_1.each(function (idx) {
  52566. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  52567. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  52568. });
  52569. // Update layout of line
  52570. mlData_1.each(function (idx) {
  52571. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  52572. });
  52573. this.markerGroupMap.get(seriesModel.id).updateLayout();
  52574. }
  52575. }, this);
  52576. };
  52577. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  52578. var coordSys = seriesModel.coordinateSystem;
  52579. var seriesId = seriesModel.id;
  52580. var seriesData = seriesModel.getData();
  52581. var lineDrawMap = this.markerGroupMap;
  52582. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  52583. this.group.add(lineDraw.group);
  52584. var mlData = createList$1(coordSys, seriesModel, mlModel);
  52585. var fromData = mlData.from;
  52586. var toData = mlData.to;
  52587. var lineData = mlData.line;
  52588. inner$e(mlModel).from = fromData;
  52589. inner$e(mlModel).to = toData;
  52590. // Line data for tooltip and formatter
  52591. mlModel.setData(lineData);
  52592. // TODO
  52593. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  52594. // But the related logic and type definition are not finished yet.
  52595. // Finish it if required
  52596. var symbolType = mlModel.get('symbol');
  52597. var symbolSize = mlModel.get('symbolSize');
  52598. var symbolRotate = mlModel.get('symbolRotate');
  52599. var symbolOffset = mlModel.get('symbolOffset');
  52600. // TODO: support callback function like markPoint
  52601. if (!isArray(symbolType)) {
  52602. symbolType = [symbolType, symbolType];
  52603. }
  52604. if (!isArray(symbolSize)) {
  52605. symbolSize = [symbolSize, symbolSize];
  52606. }
  52607. if (!isArray(symbolRotate)) {
  52608. symbolRotate = [symbolRotate, symbolRotate];
  52609. }
  52610. if (!isArray(symbolOffset)) {
  52611. symbolOffset = [symbolOffset, symbolOffset];
  52612. }
  52613. // Update visual and layout of from symbol and to symbol
  52614. mlData.from.each(function (idx) {
  52615. updateDataVisualAndLayout(fromData, idx, true);
  52616. updateDataVisualAndLayout(toData, idx, false);
  52617. });
  52618. // Update visual and layout of line
  52619. lineData.each(function (idx) {
  52620. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle();
  52621. // lineData.setItemVisual(idx, {
  52622. // color: lineColor || fromData.getItemVisual(idx, 'color')
  52623. // });
  52624. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  52625. if (lineStyle.stroke == null) {
  52626. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  52627. }
  52628. lineData.setItemVisual(idx, {
  52629. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  52630. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  52631. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  52632. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  52633. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  52634. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  52635. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  52636. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  52637. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  52638. toSymbol: toData.getItemVisual(idx, 'symbol'),
  52639. style: lineStyle
  52640. });
  52641. });
  52642. lineDraw.updateData(lineData);
  52643. // Set host model for tooltip
  52644. // FIXME
  52645. mlData.line.eachItemGraphicEl(function (el) {
  52646. getECData(el).dataModel = mlModel;
  52647. el.traverse(function (child) {
  52648. getECData(child).dataModel = mlModel;
  52649. });
  52650. });
  52651. function updateDataVisualAndLayout(data, idx, isFrom) {
  52652. var itemModel = data.getItemModel(idx);
  52653. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  52654. var style = itemModel.getModel('itemStyle').getItemStyle();
  52655. if (style.fill == null) {
  52656. style.fill = getVisualFromData(seriesData, 'color');
  52657. }
  52658. data.setItemVisual(idx, {
  52659. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  52660. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  52661. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  52662. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  52663. // TODO: when 2d array is supported, it should ignore parent
  52664. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  52665. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  52666. style: style
  52667. });
  52668. }
  52669. this.markKeep(lineDraw);
  52670. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  52671. };
  52672. MarkLineView.type = 'markLine';
  52673. return MarkLineView;
  52674. }(MarkerView);
  52675. function createList$1(coordSys, seriesModel, mlModel) {
  52676. var coordDimsInfos;
  52677. if (coordSys) {
  52678. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  52679. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {};
  52680. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  52681. return extend(extend({}, info), {
  52682. name: coordDim,
  52683. // DON'T use ordinalMeta to parse and collect ordinal.
  52684. ordinalMeta: null
  52685. });
  52686. });
  52687. } else {
  52688. coordDimsInfos = [{
  52689. name: 'value',
  52690. type: 'float'
  52691. }];
  52692. }
  52693. var fromData = new SeriesData(coordDimsInfos, mlModel);
  52694. var toData = new SeriesData(coordDimsInfos, mlModel);
  52695. // No dimensions
  52696. var lineData = new SeriesData([], mlModel);
  52697. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  52698. if (coordSys) {
  52699. optData = filter(optData, curry(markLineFilter, coordSys));
  52700. }
  52701. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  52702. fromData.initData(map(optData, function (item) {
  52703. return item[0];
  52704. }), null, dimValueGetter);
  52705. toData.initData(map(optData, function (item) {
  52706. return item[1];
  52707. }), null, dimValueGetter);
  52708. lineData.initData(map(optData, function (item) {
  52709. return item[2];
  52710. }));
  52711. lineData.hasItemOption = true;
  52712. return {
  52713. from: fromData,
  52714. to: toData,
  52715. line: lineData
  52716. };
  52717. }
  52718. function install$f(registers) {
  52719. registers.registerComponentModel(MarkLineModel);
  52720. registers.registerComponentView(MarkLineView);
  52721. registers.registerPreprocessor(function (opt) {
  52722. if (checkMarkerInSeries(opt.series, 'markLine')) {
  52723. // Make sure markLine component is enabled
  52724. opt.markLine = opt.markLine || {};
  52725. }
  52726. });
  52727. }
  52728. var MarkAreaModel = /** @class */function (_super) {
  52729. __extends(MarkAreaModel, _super);
  52730. function MarkAreaModel() {
  52731. var _this = _super !== null && _super.apply(this, arguments) || this;
  52732. _this.type = MarkAreaModel.type;
  52733. return _this;
  52734. }
  52735. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  52736. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  52737. };
  52738. MarkAreaModel.type = 'markArea';
  52739. MarkAreaModel.defaultOption = {
  52740. // zlevel: 0,
  52741. // PENDING
  52742. z: 1,
  52743. tooltip: {
  52744. trigger: 'item'
  52745. },
  52746. // markArea should fixed on the coordinate system
  52747. animation: false,
  52748. label: {
  52749. show: true,
  52750. position: 'top'
  52751. },
  52752. itemStyle: {
  52753. // color and borderColor default to use color from series
  52754. // color: 'auto'
  52755. // borderColor: 'auto'
  52756. borderWidth: 0
  52757. },
  52758. emphasis: {
  52759. label: {
  52760. show: true,
  52761. position: 'top'
  52762. }
  52763. }
  52764. };
  52765. return MarkAreaModel;
  52766. }(MarkerModel);
  52767. var inner$f = makeInner();
  52768. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  52769. // item may be null
  52770. var item0 = item[0];
  52771. var item1 = item[1];
  52772. if (!item0 || !item1) {
  52773. return;
  52774. }
  52775. var lt = dataTransform(seriesModel, item0);
  52776. var rb = dataTransform(seriesModel, item1);
  52777. // FIXME make sure lt is less than rb
  52778. var ltCoord = lt.coord;
  52779. var rbCoord = rb.coord;
  52780. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  52781. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  52782. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  52783. rbCoord[1] = retrieve(rbCoord[1], Infinity);
  52784. // Merge option into one
  52785. var result = mergeAll([{}, lt, rb]);
  52786. result.coord = [lt.coord, rb.coord];
  52787. result.x0 = lt.x;
  52788. result.y0 = lt.y;
  52789. result.x1 = rb.x;
  52790. result.y1 = rb.y;
  52791. return result;
  52792. };
  52793. function isInfinity$1(val) {
  52794. return !isNaN(val) && !isFinite(val);
  52795. }
  52796. // If a markArea has one dim
  52797. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  52798. var otherDimIndex = 1 - dimIndex;
  52799. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  52800. }
  52801. function markAreaFilter(coordSys, item) {
  52802. var fromCoord = item.coord[0];
  52803. var toCoord = item.coord[1];
  52804. var item0 = {
  52805. coord: fromCoord,
  52806. x: item.x0,
  52807. y: item.y0
  52808. };
  52809. var item1 = {
  52810. coord: toCoord,
  52811. x: item.x1,
  52812. y: item.y1
  52813. };
  52814. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  52815. // In case
  52816. // {
  52817. // markArea: {
  52818. // data: [{ yAxis: 2 }]
  52819. // }
  52820. // }
  52821. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  52822. return true;
  52823. }
  52824. // Directly returning true may also do the work,
  52825. // because markArea will not be shown automatically
  52826. // when it's not included in coordinate system.
  52827. // But filtering ahead can avoid keeping rendering markArea
  52828. // when there are too many of them.
  52829. return zoneFilter(coordSys, item0, item1);
  52830. }
  52831. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  52832. }
  52833. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  52834. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  52835. var coordSys = seriesModel.coordinateSystem;
  52836. var itemModel = data.getItemModel(idx);
  52837. var point;
  52838. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  52839. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  52840. if (!isNaN(xPx) && !isNaN(yPx)) {
  52841. point = [xPx, yPx];
  52842. } else {
  52843. // Chart like bar may have there own marker positioning logic
  52844. if (seriesModel.getMarkerPosition) {
  52845. // Consider the case that user input the right-bottom point first
  52846. // Pick the larger x and y as 'x1' and 'y1'
  52847. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  52848. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  52849. var clampPointValue0 = coordSys.clampData(pointValue0);
  52850. var clampPointValue1 = coordSys.clampData(pointValue1);
  52851. var pointValue = [];
  52852. if (dims[0] === 'x0') {
  52853. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  52854. } else {
  52855. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  52856. }
  52857. if (dims[1] === 'y0') {
  52858. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  52859. } else {
  52860. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  52861. }
  52862. // Use the getMarkerPosition
  52863. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  52864. } else {
  52865. var x = data.get(dims[0], idx);
  52866. var y = data.get(dims[1], idx);
  52867. var pt = [x, y];
  52868. coordSys.clampData && coordSys.clampData(pt, pt);
  52869. point = coordSys.dataToPoint(pt, true);
  52870. }
  52871. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  52872. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  52873. var xAxis = coordSys.getAxis('x');
  52874. var yAxis = coordSys.getAxis('y');
  52875. var x = data.get(dims[0], idx);
  52876. var y = data.get(dims[1], idx);
  52877. if (isInfinity$1(x)) {
  52878. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  52879. } else if (isInfinity$1(y)) {
  52880. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  52881. }
  52882. }
  52883. // Use x, y if has any
  52884. if (!isNaN(xPx)) {
  52885. point[0] = xPx;
  52886. }
  52887. if (!isNaN(yPx)) {
  52888. point[1] = yPx;
  52889. }
  52890. }
  52891. return point;
  52892. }
  52893. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  52894. var MarkAreaView = /** @class */function (_super) {
  52895. __extends(MarkAreaView, _super);
  52896. function MarkAreaView() {
  52897. var _this = _super !== null && _super.apply(this, arguments) || this;
  52898. _this.type = MarkAreaView.type;
  52899. return _this;
  52900. }
  52901. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  52902. ecModel.eachSeries(function (seriesModel) {
  52903. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  52904. if (maModel) {
  52905. var areaData_1 = maModel.getData();
  52906. areaData_1.each(function (idx) {
  52907. var points = map(dimPermutations, function (dim) {
  52908. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  52909. });
  52910. // Layout
  52911. areaData_1.setItemLayout(idx, points);
  52912. var el = areaData_1.getItemGraphicEl(idx);
  52913. el.setShape('points', points);
  52914. });
  52915. }
  52916. }, this);
  52917. };
  52918. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  52919. var coordSys = seriesModel.coordinateSystem;
  52920. var seriesId = seriesModel.id;
  52921. var seriesData = seriesModel.getData();
  52922. var areaGroupMap = this.markerGroupMap;
  52923. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  52924. group: new Group()
  52925. });
  52926. this.group.add(polygonGroup.group);
  52927. this.markKeep(polygonGroup);
  52928. var areaData = createList$2(coordSys, seriesModel, maModel);
  52929. // Line data for tooltip and formatter
  52930. maModel.setData(areaData);
  52931. // Update visual and layout of line
  52932. areaData.each(function (idx) {
  52933. // Layout
  52934. var points = map(dimPermutations, function (dim) {
  52935. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  52936. });
  52937. var xAxisScale = coordSys.getAxis('x').scale;
  52938. var yAxisScale = coordSys.getAxis('y').scale;
  52939. var xAxisExtent = xAxisScale.getExtent();
  52940. var yAxisExtent = yAxisScale.getExtent();
  52941. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  52942. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  52943. asc(xPointExtent);
  52944. asc(yPointExtent);
  52945. var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]);
  52946. // If none of the area is inside coordSys, allClipped is set to be true
  52947. // in layout so that label will not be displayed. See #12591
  52948. var allClipped = !overlapped;
  52949. areaData.setItemLayout(idx, {
  52950. points: points,
  52951. allClipped: allClipped
  52952. });
  52953. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  52954. var color$1 = getVisualFromData(seriesData, 'color');
  52955. if (!style.fill) {
  52956. style.fill = color$1;
  52957. if (isString(style.fill)) {
  52958. style.fill = modifyAlpha(style.fill, 0.4);
  52959. }
  52960. }
  52961. if (!style.stroke) {
  52962. style.stroke = color$1;
  52963. }
  52964. // Visual
  52965. areaData.setItemVisual(idx, 'style', style);
  52966. });
  52967. areaData.diff(inner$f(polygonGroup).data).add(function (idx) {
  52968. var layout = areaData.getItemLayout(idx);
  52969. if (!layout.allClipped) {
  52970. var polygon = new Polygon({
  52971. shape: {
  52972. points: layout.points
  52973. }
  52974. });
  52975. areaData.setItemGraphicEl(idx, polygon);
  52976. polygonGroup.group.add(polygon);
  52977. }
  52978. }).update(function (newIdx, oldIdx) {
  52979. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(oldIdx);
  52980. var layout = areaData.getItemLayout(newIdx);
  52981. if (!layout.allClipped) {
  52982. if (polygon) {
  52983. updateProps(polygon, {
  52984. shape: {
  52985. points: layout.points
  52986. }
  52987. }, maModel, newIdx);
  52988. } else {
  52989. polygon = new Polygon({
  52990. shape: {
  52991. points: layout.points
  52992. }
  52993. });
  52994. }
  52995. areaData.setItemGraphicEl(newIdx, polygon);
  52996. polygonGroup.group.add(polygon);
  52997. } else if (polygon) {
  52998. polygonGroup.group.remove(polygon);
  52999. }
  53000. }).remove(function (idx) {
  53001. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(idx);
  53002. polygonGroup.group.remove(polygon);
  53003. }).execute();
  53004. areaData.eachItemGraphicEl(function (polygon, idx) {
  53005. var itemModel = areaData.getItemModel(idx);
  53006. var style = areaData.getItemVisual(idx, 'style');
  53007. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  53008. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  53009. labelFetcher: maModel,
  53010. labelDataIndex: idx,
  53011. defaultText: areaData.getName(idx) || '',
  53012. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  53013. });
  53014. setStatesStylesFromModel(polygon, itemModel);
  53015. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  53016. getECData(polygon).dataModel = maModel;
  53017. });
  53018. inner$f(polygonGroup).data = areaData;
  53019. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  53020. };
  53021. MarkAreaView.type = 'markArea';
  53022. return MarkAreaView;
  53023. }(MarkerView);
  53024. function createList$2(coordSys, seriesModel, maModel) {
  53025. var areaData;
  53026. var dataDims;
  53027. var dims = ['x0', 'y0', 'x1', 'y1'];
  53028. if (coordSys) {
  53029. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  53030. var data = seriesModel.getData();
  53031. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {};
  53032. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  53033. return extend(extend({}, info), {
  53034. name: coordDim,
  53035. // DON'T use ordinalMeta to parse and collect ordinal.
  53036. ordinalMeta: null
  53037. });
  53038. });
  53039. dataDims = map(dims, function (dim, idx) {
  53040. return {
  53041. name: dim,
  53042. type: coordDimsInfos_1[idx % 2].type
  53043. };
  53044. });
  53045. areaData = new SeriesData(dataDims, maModel);
  53046. } else {
  53047. dataDims = [{
  53048. name: 'value',
  53049. type: 'float'
  53050. }];
  53051. areaData = new SeriesData(dataDims, maModel);
  53052. }
  53053. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  53054. if (coordSys) {
  53055. optData = filter(optData, curry(markAreaFilter, coordSys));
  53056. }
  53057. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  53058. // TODO should convert to ParsedValue?
  53059. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  53060. return parseDataValue(rawVal, dataDims[dimIndex]);
  53061. } : function (item, dimName, dataIndex, dimIndex) {
  53062. return parseDataValue(item.value, dataDims[dimIndex]);
  53063. };
  53064. areaData.initData(optData, null, dimValueGetter);
  53065. areaData.hasItemOption = true;
  53066. return areaData;
  53067. }
  53068. function install$g(registers) {
  53069. registers.registerComponentModel(MarkAreaModel);
  53070. registers.registerComponentView(MarkAreaView);
  53071. registers.registerPreprocessor(function (opt) {
  53072. if (checkMarkerInSeries(opt.series, 'markArea')) {
  53073. // Make sure markArea component is enabled
  53074. opt.markArea = opt.markArea || {};
  53075. }
  53076. });
  53077. }
  53078. var getDefaultSelectorOptions = function (ecModel, type) {
  53079. if (type === 'all') {
  53080. return {
  53081. type: 'all',
  53082. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  53083. };
  53084. } else if (type === 'inverse') {
  53085. return {
  53086. type: 'inverse',
  53087. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  53088. };
  53089. }
  53090. };
  53091. var LegendModel = /** @class */function (_super) {
  53092. __extends(LegendModel, _super);
  53093. function LegendModel() {
  53094. var _this = _super !== null && _super.apply(this, arguments) || this;
  53095. _this.type = LegendModel.type;
  53096. _this.layoutMode = {
  53097. type: 'box',
  53098. // legend.width/height are maxWidth/maxHeight actually,
  53099. // whereas real width/height is calculated by its content.
  53100. // (Setting {left: 10, right: 10} does not make sense).
  53101. // So consider the case:
  53102. // `setOption({legend: {left: 10});`
  53103. // then `setOption({legend: {right: 10});`
  53104. // The previous `left` should be cleared by setting `ignoreSize`.
  53105. ignoreSize: true
  53106. };
  53107. return _this;
  53108. }
  53109. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  53110. this.mergeDefaultAndTheme(option, ecModel);
  53111. option.selected = option.selected || {};
  53112. this._updateSelector(option);
  53113. };
  53114. LegendModel.prototype.mergeOption = function (option, ecModel) {
  53115. _super.prototype.mergeOption.call(this, option, ecModel);
  53116. this._updateSelector(option);
  53117. };
  53118. LegendModel.prototype._updateSelector = function (option) {
  53119. var selector = option.selector;
  53120. var ecModel = this.ecModel;
  53121. if (selector === true) {
  53122. selector = option.selector = ['all', 'inverse'];
  53123. }
  53124. if (isArray(selector)) {
  53125. each(selector, function (item, index) {
  53126. isString(item) && (item = {
  53127. type: item
  53128. });
  53129. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  53130. });
  53131. }
  53132. };
  53133. LegendModel.prototype.optionUpdated = function () {
  53134. this._updateData(this.ecModel);
  53135. var legendData = this._data;
  53136. // If selectedMode is single, try to select one
  53137. if (legendData[0] && this.get('selectedMode') === 'single') {
  53138. var hasSelected = false;
  53139. // If has any selected in option.selected
  53140. for (var i = 0; i < legendData.length; i++) {
  53141. var name_1 = legendData[i].get('name');
  53142. if (this.isSelected(name_1)) {
  53143. // Force to unselect others
  53144. this.select(name_1);
  53145. hasSelected = true;
  53146. break;
  53147. }
  53148. }
  53149. // Try select the first if selectedMode is single
  53150. !hasSelected && this.select(legendData[0].get('name'));
  53151. }
  53152. };
  53153. LegendModel.prototype._updateData = function (ecModel) {
  53154. var potentialData = [];
  53155. var availableNames = [];
  53156. ecModel.eachRawSeries(function (seriesModel) {
  53157. var seriesName = seriesModel.name;
  53158. availableNames.push(seriesName);
  53159. var isPotential;
  53160. if (seriesModel.legendVisualProvider) {
  53161. var provider = seriesModel.legendVisualProvider;
  53162. var names = provider.getAllNames();
  53163. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53164. availableNames = availableNames.concat(names);
  53165. }
  53166. if (names.length) {
  53167. potentialData = potentialData.concat(names);
  53168. } else {
  53169. isPotential = true;
  53170. }
  53171. } else {
  53172. isPotential = true;
  53173. }
  53174. if (isPotential && isNameSpecified(seriesModel)) {
  53175. potentialData.push(seriesModel.name);
  53176. }
  53177. });
  53178. /**
  53179. * @type {Array.<string>}
  53180. * @private
  53181. */
  53182. this._availableNames = availableNames;
  53183. // If legend.data is not specified in option, use availableNames as data,
  53184. // which is convenient for user preparing option.
  53185. var rawData = this.get('data') || potentialData;
  53186. var legendNameMap = createHashMap();
  53187. var legendData = map(rawData, function (dataItem) {
  53188. // Can be string or number
  53189. if (isString(dataItem) || isNumber(dataItem)) {
  53190. dataItem = {
  53191. name: dataItem
  53192. };
  53193. }
  53194. if (legendNameMap.get(dataItem.name)) {
  53195. // remove legend name duplicate
  53196. return null;
  53197. }
  53198. legendNameMap.set(dataItem.name, true);
  53199. return new Model(dataItem, this, this.ecModel);
  53200. }, this);
  53201. /**
  53202. * @type {Array.<module:echarts/model/Model>}
  53203. * @private
  53204. */
  53205. this._data = filter(legendData, function (item) {
  53206. return !!item;
  53207. });
  53208. };
  53209. LegendModel.prototype.getData = function () {
  53210. return this._data;
  53211. };
  53212. LegendModel.prototype.select = function (name) {
  53213. var selected = this.option.selected;
  53214. var selectedMode = this.get('selectedMode');
  53215. if (selectedMode === 'single') {
  53216. var data = this._data;
  53217. each(data, function (dataItem) {
  53218. selected[dataItem.get('name')] = false;
  53219. });
  53220. }
  53221. selected[name] = true;
  53222. };
  53223. LegendModel.prototype.unSelect = function (name) {
  53224. if (this.get('selectedMode') !== 'single') {
  53225. this.option.selected[name] = false;
  53226. }
  53227. };
  53228. LegendModel.prototype.toggleSelected = function (name) {
  53229. var selected = this.option.selected;
  53230. // Default is true
  53231. if (!selected.hasOwnProperty(name)) {
  53232. selected[name] = true;
  53233. }
  53234. this[selected[name] ? 'unSelect' : 'select'](name);
  53235. };
  53236. LegendModel.prototype.allSelect = function () {
  53237. var data = this._data;
  53238. var selected = this.option.selected;
  53239. each(data, function (dataItem) {
  53240. selected[dataItem.get('name', true)] = true;
  53241. });
  53242. };
  53243. LegendModel.prototype.inverseSelect = function () {
  53244. var data = this._data;
  53245. var selected = this.option.selected;
  53246. each(data, function (dataItem) {
  53247. var name = dataItem.get('name', true);
  53248. // Initially, default value is true
  53249. if (!selected.hasOwnProperty(name)) {
  53250. selected[name] = true;
  53251. }
  53252. selected[name] = !selected[name];
  53253. });
  53254. };
  53255. LegendModel.prototype.isSelected = function (name) {
  53256. var selected = this.option.selected;
  53257. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  53258. };
  53259. LegendModel.prototype.getOrient = function () {
  53260. return this.get('orient') === 'vertical' ? {
  53261. index: 1,
  53262. name: 'vertical'
  53263. } : {
  53264. index: 0,
  53265. name: 'horizontal'
  53266. };
  53267. };
  53268. LegendModel.type = 'legend.plain';
  53269. LegendModel.dependencies = ['series'];
  53270. LegendModel.defaultOption = {
  53271. // zlevel: 0,
  53272. z: 4,
  53273. show: true,
  53274. orient: 'horizontal',
  53275. left: 'center',
  53276. // right: 'center',
  53277. top: 0,
  53278. // bottom: null,
  53279. align: 'auto',
  53280. backgroundColor: 'rgba(0,0,0,0)',
  53281. borderColor: '#ccc',
  53282. borderRadius: 0,
  53283. borderWidth: 0,
  53284. padding: 5,
  53285. itemGap: 10,
  53286. itemWidth: 25,
  53287. itemHeight: 14,
  53288. symbolRotate: 'inherit',
  53289. symbolKeepAspect: true,
  53290. inactiveColor: '#ccc',
  53291. inactiveBorderColor: '#ccc',
  53292. inactiveBorderWidth: 'auto',
  53293. itemStyle: {
  53294. color: 'inherit',
  53295. opacity: 'inherit',
  53296. borderColor: 'inherit',
  53297. borderWidth: 'auto',
  53298. borderCap: 'inherit',
  53299. borderJoin: 'inherit',
  53300. borderDashOffset: 'inherit',
  53301. borderMiterLimit: 'inherit'
  53302. },
  53303. lineStyle: {
  53304. width: 'auto',
  53305. color: 'inherit',
  53306. inactiveColor: '#ccc',
  53307. inactiveWidth: 2,
  53308. opacity: 'inherit',
  53309. type: 'inherit',
  53310. cap: 'inherit',
  53311. join: 'inherit',
  53312. dashOffset: 'inherit',
  53313. miterLimit: 'inherit'
  53314. },
  53315. textStyle: {
  53316. color: '#333'
  53317. },
  53318. selectedMode: true,
  53319. selector: false,
  53320. selectorLabel: {
  53321. show: true,
  53322. borderRadius: 10,
  53323. padding: [3, 5, 3, 5],
  53324. fontSize: 12,
  53325. fontFamily: 'sans-serif',
  53326. color: '#666',
  53327. borderWidth: 1,
  53328. borderColor: '#666'
  53329. },
  53330. emphasis: {
  53331. selectorLabel: {
  53332. show: true,
  53333. color: '#eee',
  53334. backgroundColor: '#666'
  53335. }
  53336. },
  53337. selectorPosition: 'auto',
  53338. selectorItemGap: 7,
  53339. selectorButtonGap: 10,
  53340. tooltip: {
  53341. show: false
  53342. }
  53343. };
  53344. return LegendModel;
  53345. }(ComponentModel);
  53346. var curry$1 = curry;
  53347. var each$7 = each;
  53348. var Group$1 = Group;
  53349. var LegendView = /** @class */function (_super) {
  53350. __extends(LegendView, _super);
  53351. function LegendView() {
  53352. var _this = _super !== null && _super.apply(this, arguments) || this;
  53353. _this.type = LegendView.type;
  53354. _this.newlineDisabled = false;
  53355. return _this;
  53356. }
  53357. LegendView.prototype.init = function () {
  53358. this.group.add(this._contentGroup = new Group$1());
  53359. this.group.add(this._selectorGroup = new Group$1());
  53360. this._isFirstRender = true;
  53361. };
  53362. /**
  53363. * @protected
  53364. */
  53365. LegendView.prototype.getContentGroup = function () {
  53366. return this._contentGroup;
  53367. };
  53368. /**
  53369. * @protected
  53370. */
  53371. LegendView.prototype.getSelectorGroup = function () {
  53372. return this._selectorGroup;
  53373. };
  53374. /**
  53375. * @override
  53376. */
  53377. LegendView.prototype.render = function (legendModel, ecModel, api) {
  53378. var isFirstRender = this._isFirstRender;
  53379. this._isFirstRender = false;
  53380. this.resetInner();
  53381. if (!legendModel.get('show', true)) {
  53382. return;
  53383. }
  53384. var itemAlign = legendModel.get('align');
  53385. var orient = legendModel.get('orient');
  53386. if (!itemAlign || itemAlign === 'auto') {
  53387. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  53388. }
  53389. // selector has been normalized to an array in model
  53390. var selector = legendModel.get('selector', true);
  53391. var selectorPosition = legendModel.get('selectorPosition', true);
  53392. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  53393. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  53394. }
  53395. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  53396. // Perform layout.
  53397. var positionInfo = legendModel.getBoxLayoutParams();
  53398. var viewportSize = {
  53399. width: api.getWidth(),
  53400. height: api.getHeight()
  53401. };
  53402. var padding = legendModel.get('padding');
  53403. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  53404. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  53405. // Place mainGroup, based on the calculated `mainRect`.
  53406. var layoutRect = getLayoutRect(defaults({
  53407. width: mainRect.width,
  53408. height: mainRect.height
  53409. }, positionInfo), viewportSize, padding);
  53410. this.group.x = layoutRect.x - mainRect.x;
  53411. this.group.y = layoutRect.y - mainRect.y;
  53412. this.group.markRedraw();
  53413. // Render background after group is layout.
  53414. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  53415. };
  53416. LegendView.prototype.resetInner = function () {
  53417. this.getContentGroup().removeAll();
  53418. this._backgroundEl && this.group.remove(this._backgroundEl);
  53419. this.getSelectorGroup().removeAll();
  53420. };
  53421. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  53422. var contentGroup = this.getContentGroup();
  53423. var legendDrawnMap = createHashMap();
  53424. var selectMode = legendModel.get('selectedMode');
  53425. var excludeSeriesId = [];
  53426. ecModel.eachRawSeries(function (seriesModel) {
  53427. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  53428. });
  53429. each$7(legendModel.getData(), function (legendItemModel, dataIndex) {
  53430. var name = legendItemModel.get('name');
  53431. // Use empty string or \n as a newline string
  53432. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  53433. var g = new Group$1();
  53434. // @ts-ignore
  53435. g.newline = true;
  53436. contentGroup.add(g);
  53437. return;
  53438. }
  53439. // Representitive series.
  53440. var seriesModel = ecModel.getSeriesByName(name)[0];
  53441. if (legendDrawnMap.get(name)) {
  53442. // Have been drawn
  53443. return;
  53444. }
  53445. // Legend to control series.
  53446. if (seriesModel) {
  53447. var data = seriesModel.getData();
  53448. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  53449. var legendIcon = data.getVisual('legendIcon');
  53450. /**
  53451. * `data.getVisual('style')` may be the color from the register
  53452. * in series. For example, for line series,
  53453. */
  53454. var style = data.getVisual('style');
  53455. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  53456. 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));
  53457. if (ecModel.ssr) {
  53458. itemGroup.eachChild(function (child) {
  53459. var ecData = getECData(child);
  53460. ecData.seriesIndex = seriesModel.seriesIndex;
  53461. ecData.dataIndex = dataIndex;
  53462. ecData.ssrType = 'legend';
  53463. });
  53464. }
  53465. legendDrawnMap.set(name, true);
  53466. } else {
  53467. // Legend to control data. In pie and funnel.
  53468. ecModel.eachRawSeries(function (seriesModel) {
  53469. // In case multiple series has same data name
  53470. if (legendDrawnMap.get(name)) {
  53471. return;
  53472. }
  53473. if (seriesModel.legendVisualProvider) {
  53474. var provider = seriesModel.legendVisualProvider;
  53475. if (!provider.containName(name)) {
  53476. return;
  53477. }
  53478. var idx = provider.indexOfName(name);
  53479. var style = provider.getItemVisual(idx, 'style');
  53480. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  53481. var colorArr = parse(style.fill);
  53482. // Color may be set to transparent in visualMap when data is out of range.
  53483. // Do not show nothing.
  53484. if (colorArr && colorArr[3] === 0) {
  53485. colorArr[3] = 0.2;
  53486. // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  53487. style = extend(extend({}, style), {
  53488. fill: stringify(colorArr, 'rgba')
  53489. });
  53490. }
  53491. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api);
  53492. // FIXME: consider different series has items with the same name.
  53493. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId))
  53494. // Should not specify the series name, consider legend controls
  53495. // more than one pie series.
  53496. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  53497. if (ecModel.ssr) {
  53498. itemGroup.eachChild(function (child) {
  53499. var ecData = getECData(child);
  53500. ecData.seriesIndex = seriesModel.seriesIndex;
  53501. ecData.dataIndex = dataIndex;
  53502. ecData.ssrType = 'legend';
  53503. });
  53504. }
  53505. legendDrawnMap.set(name, true);
  53506. }
  53507. }, this);
  53508. }
  53509. if ("development" !== 'production') {
  53510. if (!legendDrawnMap.get(name)) {
  53511. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  53512. }
  53513. }
  53514. }, this);
  53515. if (selector) {
  53516. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  53517. }
  53518. };
  53519. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  53520. var selectorGroup = this.getSelectorGroup();
  53521. each$7(selector, function createSelectorButton(selectorItem) {
  53522. var type = selectorItem.type;
  53523. var labelText = new ZRText({
  53524. style: {
  53525. x: 0,
  53526. y: 0,
  53527. align: 'center',
  53528. verticalAlign: 'middle'
  53529. },
  53530. onclick: function () {
  53531. api.dispatchAction({
  53532. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  53533. });
  53534. }
  53535. });
  53536. selectorGroup.add(labelText);
  53537. var labelModel = legendModel.getModel('selectorLabel');
  53538. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  53539. setLabelStyle(labelText, {
  53540. normal: labelModel,
  53541. emphasis: emphasisLabelModel
  53542. }, {
  53543. defaultText: selectorItem.title
  53544. });
  53545. enableHoverEmphasis(labelText);
  53546. });
  53547. };
  53548. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  53549. var drawType = seriesModel.visualDrawType;
  53550. var itemWidth = legendModel.get('itemWidth');
  53551. var itemHeight = legendModel.get('itemHeight');
  53552. var isSelected = legendModel.isSelected(name);
  53553. var iconRotate = legendItemModel.get('symbolRotate');
  53554. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  53555. var legendIconType = legendItemModel.get('icon');
  53556. legendIcon = legendIconType || legendIcon || 'roundRect';
  53557. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  53558. var itemGroup = new Group$1();
  53559. var textStyleModel = legendItemModel.getModel('textStyle');
  53560. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  53561. // Series has specific way to define legend icon
  53562. itemGroup.add(seriesModel.getLegendIcon({
  53563. itemWidth: itemWidth,
  53564. itemHeight: itemHeight,
  53565. icon: legendIcon,
  53566. iconRotate: iconRotate,
  53567. itemStyle: style.itemStyle,
  53568. lineStyle: style.lineStyle,
  53569. symbolKeepAspect: symbolKeepAspect
  53570. }));
  53571. } else {
  53572. // Use default legend icon policy for most series
  53573. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  53574. itemGroup.add(getDefaultLegendIcon({
  53575. itemWidth: itemWidth,
  53576. itemHeight: itemHeight,
  53577. icon: legendIcon,
  53578. iconRotate: rotate,
  53579. itemStyle: style.itemStyle,
  53580. lineStyle: style.lineStyle,
  53581. symbolKeepAspect: symbolKeepAspect
  53582. }));
  53583. }
  53584. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  53585. var textAlign = itemAlign;
  53586. var formatter = legendModel.get('formatter');
  53587. var content = name;
  53588. if (isString(formatter) && formatter) {
  53589. content = formatter.replace('{name}', name != null ? name : '');
  53590. } else if (isFunction(formatter)) {
  53591. content = formatter(name);
  53592. }
  53593. var textColor = isSelected ? textStyleModel.getTextColor() : legendItemModel.get('inactiveColor');
  53594. itemGroup.add(new ZRText({
  53595. style: createTextStyle(textStyleModel, {
  53596. text: content,
  53597. x: textX,
  53598. y: itemHeight / 2,
  53599. fill: textColor,
  53600. align: textAlign,
  53601. verticalAlign: 'middle'
  53602. }, {
  53603. inheritColor: textColor
  53604. })
  53605. }));
  53606. // Add a invisible rect to increase the area of mouse hover
  53607. var hitRect = new Rect({
  53608. shape: itemGroup.getBoundingRect(),
  53609. style: {
  53610. // Cannot use 'invisible' because SVG SSR will miss the node
  53611. fill: 'transparent'
  53612. }
  53613. });
  53614. var tooltipModel = legendItemModel.getModel('tooltip');
  53615. if (tooltipModel.get('show')) {
  53616. setTooltipConfig({
  53617. el: hitRect,
  53618. componentModel: legendModel,
  53619. itemName: name,
  53620. itemTooltipOption: tooltipModel.option
  53621. });
  53622. }
  53623. itemGroup.add(hitRect);
  53624. itemGroup.eachChild(function (child) {
  53625. child.silent = true;
  53626. });
  53627. hitRect.silent = !selectMode;
  53628. this.getContentGroup().add(itemGroup);
  53629. enableHoverEmphasis(itemGroup);
  53630. // @ts-ignore
  53631. itemGroup.__legendDataIndex = dataIndex;
  53632. return itemGroup;
  53633. };
  53634. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  53635. var contentGroup = this.getContentGroup();
  53636. var selectorGroup = this.getSelectorGroup();
  53637. // Place items in contentGroup.
  53638. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  53639. var contentRect = contentGroup.getBoundingRect();
  53640. var contentPos = [-contentRect.x, -contentRect.y];
  53641. selectorGroup.markRedraw();
  53642. contentGroup.markRedraw();
  53643. if (selector) {
  53644. // Place buttons in selectorGroup
  53645. box(
  53646. // Buttons in selectorGroup always layout horizontally
  53647. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  53648. var selectorRect = selectorGroup.getBoundingRect();
  53649. var selectorPos = [-selectorRect.x, -selectorRect.y];
  53650. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  53651. var orientIdx = legendModel.getOrient().index;
  53652. var wh = orientIdx === 0 ? 'width' : 'height';
  53653. var hw = orientIdx === 0 ? 'height' : 'width';
  53654. var yx = orientIdx === 0 ? 'y' : 'x';
  53655. if (selectorPosition === 'end') {
  53656. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  53657. } else {
  53658. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  53659. }
  53660. // Always align selector to content as 'middle'
  53661. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  53662. selectorGroup.x = selectorPos[0];
  53663. selectorGroup.y = selectorPos[1];
  53664. contentGroup.x = contentPos[0];
  53665. contentGroup.y = contentPos[1];
  53666. var mainRect = {
  53667. x: 0,
  53668. y: 0
  53669. };
  53670. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  53671. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  53672. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  53673. return mainRect;
  53674. } else {
  53675. contentGroup.x = contentPos[0];
  53676. contentGroup.y = contentPos[1];
  53677. return this.group.getBoundingRect();
  53678. }
  53679. };
  53680. /**
  53681. * @protected
  53682. */
  53683. LegendView.prototype.remove = function () {
  53684. this.getContentGroup().removeAll();
  53685. this._isFirstRender = true;
  53686. };
  53687. LegendView.type = 'legend.plain';
  53688. return LegendView;
  53689. }(ComponentView);
  53690. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  53691. /**
  53692. * Use series style if is inherit;
  53693. * elsewise, use legend style
  53694. */
  53695. function handleCommonProps(style, visualStyle) {
  53696. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  53697. if (style.lineWidth === 'auto') {
  53698. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  53699. }
  53700. each$7(style, function (propVal, propName) {
  53701. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  53702. });
  53703. }
  53704. // itemStyle
  53705. var itemStyleModel = legendItemModel.getModel('itemStyle');
  53706. var itemStyle = itemStyleModel.getItemStyle();
  53707. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  53708. var decalStyle = itemStyleModel.getShallow('decal');
  53709. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  53710. if (itemStyle.fill === 'inherit') {
  53711. /**
  53712. * Series with visualDrawType as 'stroke' should have
  53713. * series stroke as legend fill
  53714. */
  53715. itemStyle.fill = itemVisualStyle[drawType];
  53716. }
  53717. if (itemStyle.stroke === 'inherit') {
  53718. /**
  53719. * icon type with "emptyXXX" should use fill color
  53720. * in visual style
  53721. */
  53722. itemStyle.stroke = itemVisualStyle[iconBrushType];
  53723. }
  53724. if (itemStyle.opacity === 'inherit') {
  53725. /**
  53726. * Use lineStyle.opacity if drawType is stroke
  53727. */
  53728. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  53729. }
  53730. handleCommonProps(itemStyle, itemVisualStyle);
  53731. // lineStyle
  53732. var legendLineModel = legendItemModel.getModel('lineStyle');
  53733. var lineStyle = legendLineModel.getLineStyle();
  53734. handleCommonProps(lineStyle, lineVisualStyle);
  53735. // Fix auto color to real color
  53736. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  53737. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  53738. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  53739. if (!isSelected) {
  53740. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  53741. /**
  53742. * Since stroke is set to be inactiveBorderColor, it may occur that
  53743. * there is no border in series but border in legend, so we need to
  53744. * use border only when series has border if is set to be auto
  53745. */
  53746. var visualHasBorder = itemStyle[iconBrushType];
  53747. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  53748. itemStyle.fill = legendItemModel.get('inactiveColor');
  53749. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  53750. lineStyle.stroke = legendLineModel.get('inactiveColor');
  53751. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  53752. }
  53753. return {
  53754. itemStyle: itemStyle,
  53755. lineStyle: lineStyle
  53756. };
  53757. }
  53758. function getDefaultLegendIcon(opt) {
  53759. var symboType = opt.icon || 'roundRect';
  53760. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  53761. icon.setStyle(opt.itemStyle);
  53762. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  53763. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  53764. if (symboType.indexOf('empty') > -1) {
  53765. icon.style.stroke = icon.style.fill;
  53766. icon.style.fill = '#fff';
  53767. icon.style.lineWidth = 2;
  53768. }
  53769. return icon;
  53770. }
  53771. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  53772. // downplay before unselect
  53773. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  53774. api.dispatchAction({
  53775. type: 'legendToggleSelect',
  53776. name: seriesName != null ? seriesName : dataName
  53777. });
  53778. // highlight after select
  53779. // TODO highlight immediately may cause animation loss.
  53780. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  53781. }
  53782. function isUseHoverLayer(api) {
  53783. var list = api.getZr().storage.getDisplayList();
  53784. var emphasisState;
  53785. var i = 0;
  53786. var len = list.length;
  53787. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  53788. i++;
  53789. }
  53790. return emphasisState && emphasisState.hoverLayer;
  53791. }
  53792. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  53793. // If element hover will move to a hoverLayer.
  53794. if (!isUseHoverLayer(api)) {
  53795. api.dispatchAction({
  53796. type: 'highlight',
  53797. seriesName: seriesName,
  53798. name: dataName,
  53799. excludeSeriesId: excludeSeriesId
  53800. });
  53801. }
  53802. }
  53803. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  53804. // If element hover will move to a hoverLayer.
  53805. if (!isUseHoverLayer(api)) {
  53806. api.dispatchAction({
  53807. type: 'downplay',
  53808. seriesName: seriesName,
  53809. name: dataName,
  53810. excludeSeriesId: excludeSeriesId
  53811. });
  53812. }
  53813. }
  53814. /*
  53815. * Licensed to the Apache Software Foundation (ASF) under one
  53816. * or more contributor license agreements. See the NOTICE file
  53817. * distributed with this work for additional information
  53818. * regarding copyright ownership. The ASF licenses this file
  53819. * to you under the Apache License, Version 2.0 (the
  53820. * "License"); you may not use this file except in compliance
  53821. * with the License. You may obtain a copy of the License at
  53822. *
  53823. * http://www.apache.org/licenses/LICENSE-2.0
  53824. *
  53825. * Unless required by applicable law or agreed to in writing,
  53826. * software distributed under the License is distributed on an
  53827. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53828. * KIND, either express or implied. See the License for the
  53829. * specific language governing permissions and limitations
  53830. * under the License.
  53831. */
  53832. /**
  53833. * AUTO-GENERATED FILE. DO NOT MODIFY.
  53834. */
  53835. /*
  53836. * Licensed to the Apache Software Foundation (ASF) under one
  53837. * or more contributor license agreements. See the NOTICE file
  53838. * distributed with this work for additional information
  53839. * regarding copyright ownership. The ASF licenses this file
  53840. * to you under the Apache License, Version 2.0 (the
  53841. * "License"); you may not use this file except in compliance
  53842. * with the License. You may obtain a copy of the License at
  53843. *
  53844. * http://www.apache.org/licenses/LICENSE-2.0
  53845. *
  53846. * Unless required by applicable law or agreed to in writing,
  53847. * software distributed under the License is distributed on an
  53848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53849. * KIND, either express or implied. See the License for the
  53850. * specific language governing permissions and limitations
  53851. * under the License.
  53852. */
  53853. function legendFilter(ecModel) {
  53854. var legendModels = ecModel.findComponents({
  53855. mainType: 'legend'
  53856. });
  53857. if (legendModels && legendModels.length) {
  53858. ecModel.filterSeries(function (series) {
  53859. // If in any legend component the status is not selected.
  53860. // Because in legend series is assumed selected when it is not in the legend data.
  53861. for (var i = 0; i < legendModels.length; i++) {
  53862. if (!legendModels[i].isSelected(series.name)) {
  53863. return false;
  53864. }
  53865. }
  53866. return true;
  53867. });
  53868. }
  53869. }
  53870. function legendSelectActionHandler(methodName, payload, ecModel) {
  53871. var selectedMap = {};
  53872. var isToggleSelect = methodName === 'toggleSelected';
  53873. var isSelected;
  53874. // Update all legend components
  53875. ecModel.eachComponent('legend', function (legendModel) {
  53876. if (isToggleSelect && isSelected != null) {
  53877. // Force other legend has same selected status
  53878. // Or the first is toggled to true and other are toggled to false
  53879. // In the case one legend has some item unSelected in option. And if other legend
  53880. // doesn't has the item, they will assume it is selected.
  53881. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  53882. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  53883. legendModel[methodName]();
  53884. } else {
  53885. legendModel[methodName](payload.name);
  53886. isSelected = legendModel.isSelected(payload.name);
  53887. }
  53888. var legendData = legendModel.getData();
  53889. each(legendData, function (model) {
  53890. var name = model.get('name');
  53891. // Wrap element
  53892. if (name === '\n' || name === '') {
  53893. return;
  53894. }
  53895. var isItemSelected = legendModel.isSelected(name);
  53896. if (selectedMap.hasOwnProperty(name)) {
  53897. // Unselected if any legend is unselected
  53898. selectedMap[name] = selectedMap[name] && isItemSelected;
  53899. } else {
  53900. selectedMap[name] = isItemSelected;
  53901. }
  53902. });
  53903. });
  53904. // Return the event explicitly
  53905. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  53906. selected: selectedMap
  53907. } : {
  53908. name: payload.name,
  53909. selected: selectedMap
  53910. };
  53911. }
  53912. function installLegendAction(registers) {
  53913. /**
  53914. * @event legendToggleSelect
  53915. * @type {Object}
  53916. * @property {string} type 'legendToggleSelect'
  53917. * @property {string} [from]
  53918. * @property {string} name Series name or data item name
  53919. */
  53920. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  53921. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  53922. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  53923. /**
  53924. * @event legendSelect
  53925. * @type {Object}
  53926. * @property {string} type 'legendSelect'
  53927. * @property {string} name Series name or data item name
  53928. */
  53929. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  53930. /**
  53931. * @event legendUnSelect
  53932. * @type {Object}
  53933. * @property {string} type 'legendUnSelect'
  53934. * @property {string} name Series name or data item name
  53935. */
  53936. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  53937. }
  53938. function install$h(registers) {
  53939. registers.registerComponentModel(LegendModel);
  53940. registers.registerComponentView(LegendView);
  53941. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  53942. registers.registerSubTypeDefaulter('legend', function () {
  53943. return 'plain';
  53944. });
  53945. installLegendAction(registers);
  53946. }
  53947. var ScrollableLegendModel = /** @class */function (_super) {
  53948. __extends(ScrollableLegendModel, _super);
  53949. function ScrollableLegendModel() {
  53950. var _this = _super !== null && _super.apply(this, arguments) || this;
  53951. _this.type = ScrollableLegendModel.type;
  53952. return _this;
  53953. }
  53954. /**
  53955. * @param {number} scrollDataIndex
  53956. */
  53957. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  53958. this.option.scrollDataIndex = scrollDataIndex;
  53959. };
  53960. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  53961. var inputPositionParams = getLayoutParams(option);
  53962. _super.prototype.init.call(this, option, parentModel, ecModel);
  53963. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  53964. };
  53965. /**
  53966. * @override
  53967. */
  53968. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  53969. _super.prototype.mergeOption.call(this, option, ecModel);
  53970. mergeAndNormalizeLayoutParams(this, this.option, option);
  53971. };
  53972. ScrollableLegendModel.type = 'legend.scroll';
  53973. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  53974. scrollDataIndex: 0,
  53975. pageButtonItemGap: 5,
  53976. pageButtonGap: null,
  53977. pageButtonPosition: 'end',
  53978. pageFormatter: '{current}/{total}',
  53979. pageIcons: {
  53980. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  53981. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  53982. },
  53983. pageIconColor: '#2f4554',
  53984. pageIconInactiveColor: '#aaa',
  53985. pageIconSize: 15,
  53986. pageTextStyle: {
  53987. color: '#333'
  53988. },
  53989. animationDurationUpdate: 800
  53990. });
  53991. return ScrollableLegendModel;
  53992. }(LegendModel);
  53993. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  53994. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  53995. var orient = legendModel.getOrient();
  53996. var ignoreSize = [1, 1];
  53997. ignoreSize[orient.index] = 0;
  53998. mergeLayoutParam(target, raw, {
  53999. type: 'box',
  54000. ignoreSize: !!ignoreSize
  54001. });
  54002. }
  54003. var Group$2 = Group;
  54004. var WH = ['width', 'height'];
  54005. var XY = ['x', 'y'];
  54006. var ScrollableLegendView = /** @class */function (_super) {
  54007. __extends(ScrollableLegendView, _super);
  54008. function ScrollableLegendView() {
  54009. var _this = _super !== null && _super.apply(this, arguments) || this;
  54010. _this.type = ScrollableLegendView.type;
  54011. _this.newlineDisabled = true;
  54012. _this._currentIndex = 0;
  54013. return _this;
  54014. }
  54015. ScrollableLegendView.prototype.init = function () {
  54016. _super.prototype.init.call(this);
  54017. this.group.add(this._containerGroup = new Group$2());
  54018. this._containerGroup.add(this.getContentGroup());
  54019. this.group.add(this._controllerGroup = new Group$2());
  54020. };
  54021. /**
  54022. * @override
  54023. */
  54024. ScrollableLegendView.prototype.resetInner = function () {
  54025. _super.prototype.resetInner.call(this);
  54026. this._controllerGroup.removeAll();
  54027. this._containerGroup.removeClipPath();
  54028. this._containerGroup.__rectSize = null;
  54029. };
  54030. /**
  54031. * @override
  54032. */
  54033. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  54034. var self = this;
  54035. // Render content items.
  54036. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  54037. var controllerGroup = this._controllerGroup;
  54038. // FIXME: support be 'auto' adapt to size number text length,
  54039. // e.g., '3/12345' should not overlap with the control arrow button.
  54040. var pageIconSize = legendModel.get('pageIconSize', true);
  54041. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  54042. createPageButton('pagePrev', 0);
  54043. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  54044. controllerGroup.add(new ZRText({
  54045. name: 'pageText',
  54046. style: {
  54047. // Placeholder to calculate a proper layout.
  54048. text: 'xx/xx',
  54049. fill: pageTextStyleModel.getTextColor(),
  54050. font: pageTextStyleModel.getFont(),
  54051. verticalAlign: 'middle',
  54052. align: 'center'
  54053. },
  54054. silent: true
  54055. }));
  54056. createPageButton('pageNext', 1);
  54057. function createPageButton(name, iconIdx) {
  54058. var pageDataIndexName = name + 'DataIndex';
  54059. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  54060. // Buttons will be created in each render, so we do not need
  54061. // to worry about avoiding using legendModel kept in scope.
  54062. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  54063. }, {
  54064. x: -pageIconSizeArr[0] / 2,
  54065. y: -pageIconSizeArr[1] / 2,
  54066. width: pageIconSizeArr[0],
  54067. height: pageIconSizeArr[1]
  54068. });
  54069. icon.name = name;
  54070. controllerGroup.add(icon);
  54071. }
  54072. };
  54073. /**
  54074. * @override
  54075. */
  54076. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  54077. var selectorGroup = this.getSelectorGroup();
  54078. var orientIdx = legendModel.getOrient().index;
  54079. var wh = WH[orientIdx];
  54080. var xy = XY[orientIdx];
  54081. var hw = WH[1 - orientIdx];
  54082. var yx = XY[1 - orientIdx];
  54083. selector && box(
  54084. // Buttons in selectorGroup always layout horizontally
  54085. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  54086. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  54087. var selectorRect = selectorGroup.getBoundingRect();
  54088. var selectorPos = [-selectorRect.x, -selectorRect.y];
  54089. var processMaxSize = clone(maxSize);
  54090. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  54091. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  54092. if (selector) {
  54093. if (selectorPosition === 'end') {
  54094. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  54095. } else {
  54096. var offset = selectorRect[wh] + selectorButtonGap;
  54097. selectorPos[orientIdx] -= offset;
  54098. mainRect[xy] -= offset;
  54099. }
  54100. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  54101. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  54102. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  54103. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  54104. selectorGroup.x = selectorPos[0];
  54105. selectorGroup.y = selectorPos[1];
  54106. selectorGroup.markRedraw();
  54107. }
  54108. return mainRect;
  54109. };
  54110. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  54111. var contentGroup = this.getContentGroup();
  54112. var containerGroup = this._containerGroup;
  54113. var controllerGroup = this._controllerGroup;
  54114. // Place items in contentGroup.
  54115. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  54116. box(
  54117. // Buttons in controller are layout always horizontally.
  54118. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  54119. var contentRect = contentGroup.getBoundingRect();
  54120. var controllerRect = controllerGroup.getBoundingRect();
  54121. var showController = this._showController = contentRect[wh] > maxSize[wh];
  54122. // In case that the inner elements of contentGroup layout do not based on [0, 0]
  54123. var contentPos = [-contentRect.x, -contentRect.y];
  54124. // Remain contentPos when scroll animation perfroming.
  54125. // If first rendering, `contentGroup.position` is [0, 0], which
  54126. // does not make sense and may cause unexepcted animation if adopted.
  54127. if (!isFirstRender) {
  54128. contentPos[orientIdx] = contentGroup[xy];
  54129. }
  54130. // Layout container group based on 0.
  54131. var containerPos = [0, 0];
  54132. var controllerPos = [-controllerRect.x, -controllerRect.y];
  54133. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true));
  54134. // Place containerGroup and controllerGroup and contentGroup.
  54135. if (showController) {
  54136. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  54137. // controller is on the right / bottom.
  54138. if (pageButtonPosition === 'end') {
  54139. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  54140. }
  54141. // controller is on the left / top.
  54142. else {
  54143. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  54144. }
  54145. }
  54146. // Always align controller to content as 'middle'.
  54147. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  54148. contentGroup.setPosition(contentPos);
  54149. containerGroup.setPosition(containerPos);
  54150. controllerGroup.setPosition(controllerPos);
  54151. // Calculate `mainRect` and set `clipPath`.
  54152. // mainRect should not be calculated by `this.group.getBoundingRect()`
  54153. // for sake of the overflow.
  54154. var mainRect = {
  54155. x: 0,
  54156. y: 0
  54157. };
  54158. // Consider content may be overflow (should be clipped).
  54159. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  54160. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  54161. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  54162. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  54163. containerGroup.__rectSize = maxSize[wh];
  54164. if (showController) {
  54165. var clipShape = {
  54166. x: 0,
  54167. y: 0
  54168. };
  54169. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  54170. clipShape[hw] = mainRect[hw];
  54171. containerGroup.setClipPath(new Rect({
  54172. shape: clipShape
  54173. }));
  54174. // Consider content may be larger than container, container rect
  54175. // can not be obtained from `containerGroup.getBoundingRect()`.
  54176. containerGroup.__rectSize = clipShape[wh];
  54177. } else {
  54178. // Do not remove or ignore controller. Keep them set as placeholders.
  54179. controllerGroup.eachChild(function (child) {
  54180. child.attr({
  54181. invisible: true,
  54182. silent: true
  54183. });
  54184. });
  54185. }
  54186. // Content translate animation.
  54187. var pageInfo = this._getPageInfo(legendModel);
  54188. pageInfo.pageIndex != null && updateProps(contentGroup, {
  54189. x: pageInfo.contentPosition[0],
  54190. y: pageInfo.contentPosition[1]
  54191. },
  54192. // When switch from "show controller" to "not show controller", view should be
  54193. // updated immediately without animation, otherwise causes weird effect.
  54194. showController ? legendModel : null);
  54195. this._updatePageInfoView(legendModel, pageInfo);
  54196. return mainRect;
  54197. };
  54198. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  54199. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  54200. scrollDataIndex != null && api.dispatchAction({
  54201. type: 'legendScroll',
  54202. scrollDataIndex: scrollDataIndex,
  54203. legendId: legendModel.id
  54204. });
  54205. };
  54206. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  54207. var controllerGroup = this._controllerGroup;
  54208. each(['pagePrev', 'pageNext'], function (name) {
  54209. var key = name + 'DataIndex';
  54210. var canJump = pageInfo[key] != null;
  54211. var icon = controllerGroup.childOfName(name);
  54212. if (icon) {
  54213. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  54214. icon.cursor = canJump ? 'pointer' : 'default';
  54215. }
  54216. });
  54217. var pageText = controllerGroup.childOfName('pageText');
  54218. var pageFormatter = legendModel.get('pageFormatter');
  54219. var pageIndex = pageInfo.pageIndex;
  54220. var current = pageIndex != null ? pageIndex + 1 : 0;
  54221. var total = pageInfo.pageCount;
  54222. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  54223. current: current,
  54224. total: total
  54225. }));
  54226. };
  54227. /**
  54228. * contentPosition: Array.<number>, null when data item not found.
  54229. * pageIndex: number, null when data item not found.
  54230. * pageCount: number, always be a number, can be 0.
  54231. * pagePrevDataIndex: number, null when no previous page.
  54232. * pageNextDataIndex: number, null when no next page.
  54233. * }
  54234. */
  54235. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  54236. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  54237. var contentGroup = this.getContentGroup();
  54238. var containerRectSize = this._containerGroup.__rectSize;
  54239. var orientIdx = legendModel.getOrient().index;
  54240. var wh = WH[orientIdx];
  54241. var xy = XY[orientIdx];
  54242. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  54243. var children = contentGroup.children();
  54244. var targetItem = children[targetItemIndex];
  54245. var itemCount = children.length;
  54246. var pCount = !itemCount ? 0 : 1;
  54247. var result = {
  54248. contentPosition: [contentGroup.x, contentGroup.y],
  54249. pageCount: pCount,
  54250. pageIndex: pCount - 1,
  54251. pagePrevDataIndex: null,
  54252. pageNextDataIndex: null
  54253. };
  54254. if (!targetItem) {
  54255. return result;
  54256. }
  54257. var targetItemInfo = getItemInfo(targetItem);
  54258. result.contentPosition[orientIdx] = -targetItemInfo.s;
  54259. // Strategy:
  54260. // (1) Always align based on the left/top most item.
  54261. // (2) It is user-friendly that the last item shown in the
  54262. // current window is shown at the begining of next window.
  54263. // Otherwise if half of the last item is cut by the window,
  54264. // it will have no chance to display entirely.
  54265. // (3) Consider that item size probably be different, we
  54266. // have calculate pageIndex by size rather than item index,
  54267. // and we can not get page index directly by division.
  54268. // (4) The window is to narrow to contain more than
  54269. // one item, we should make sure that the page can be fliped.
  54270. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  54271. currItemInfo = getItemInfo(children[i]);
  54272. if (
  54273. // Half of the last item is out of the window.
  54274. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize
  54275. // If the current item does not intersect with the window, the new page
  54276. // can be started at the current item or the last item.
  54277. || currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  54278. if (winEndItemInfo.i > winStartItemInfo.i) {
  54279. winStartItemInfo = winEndItemInfo;
  54280. } else {
  54281. // e.g., when page size is smaller than item size.
  54282. winStartItemInfo = currItemInfo;
  54283. }
  54284. if (winStartItemInfo) {
  54285. if (result.pageNextDataIndex == null) {
  54286. result.pageNextDataIndex = winStartItemInfo.i;
  54287. }
  54288. ++result.pageCount;
  54289. }
  54290. }
  54291. winEndItemInfo = currItemInfo;
  54292. }
  54293. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  54294. currItemInfo = getItemInfo(children[i]);
  54295. if (
  54296. // If the the end item does not intersect with the window started
  54297. // from the current item, a page can be settled.
  54298. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)
  54299. // e.g., when page size is smaller than item size.
  54300. ) && winStartItemInfo.i < winEndItemInfo.i) {
  54301. winEndItemInfo = winStartItemInfo;
  54302. if (result.pagePrevDataIndex == null) {
  54303. result.pagePrevDataIndex = winStartItemInfo.i;
  54304. }
  54305. ++result.pageCount;
  54306. ++result.pageIndex;
  54307. }
  54308. winStartItemInfo = currItemInfo;
  54309. }
  54310. return result;
  54311. function getItemInfo(el) {
  54312. if (el) {
  54313. var itemRect = el.getBoundingRect();
  54314. var start = itemRect[xy] + el[xy];
  54315. return {
  54316. s: start,
  54317. e: start + itemRect[wh],
  54318. i: el.__legendDataIndex
  54319. };
  54320. }
  54321. }
  54322. function intersect(itemInfo, winStart) {
  54323. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  54324. }
  54325. };
  54326. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  54327. if (!this._showController) {
  54328. return 0;
  54329. }
  54330. var index;
  54331. var contentGroup = this.getContentGroup();
  54332. var defaultIndex;
  54333. contentGroup.eachChild(function (child, idx) {
  54334. var legendDataIdx = child.__legendDataIndex;
  54335. // FIXME
  54336. // If the given targetDataIndex (from model) is illegal,
  54337. // we use defaultIndex. But the index on the legend model and
  54338. // action payload is still illegal. That case will not be
  54339. // changed until some scenario requires.
  54340. if (defaultIndex == null && legendDataIdx != null) {
  54341. defaultIndex = idx;
  54342. }
  54343. if (legendDataIdx === targetDataIndex) {
  54344. index = idx;
  54345. }
  54346. });
  54347. return index != null ? index : defaultIndex;
  54348. };
  54349. ScrollableLegendView.type = 'legend.scroll';
  54350. return ScrollableLegendView;
  54351. }(LegendView);
  54352. /*
  54353. * Licensed to the Apache Software Foundation (ASF) under one
  54354. * or more contributor license agreements. See the NOTICE file
  54355. * distributed with this work for additional information
  54356. * regarding copyright ownership. The ASF licenses this file
  54357. * to you under the Apache License, Version 2.0 (the
  54358. * "License"); you may not use this file except in compliance
  54359. * with the License. You may obtain a copy of the License at
  54360. *
  54361. * http://www.apache.org/licenses/LICENSE-2.0
  54362. *
  54363. * Unless required by applicable law or agreed to in writing,
  54364. * software distributed under the License is distributed on an
  54365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54366. * KIND, either express or implied. See the License for the
  54367. * specific language governing permissions and limitations
  54368. * under the License.
  54369. */
  54370. /**
  54371. * AUTO-GENERATED FILE. DO NOT MODIFY.
  54372. */
  54373. /*
  54374. * Licensed to the Apache Software Foundation (ASF) under one
  54375. * or more contributor license agreements. See the NOTICE file
  54376. * distributed with this work for additional information
  54377. * regarding copyright ownership. The ASF licenses this file
  54378. * to you under the Apache License, Version 2.0 (the
  54379. * "License"); you may not use this file except in compliance
  54380. * with the License. You may obtain a copy of the License at
  54381. *
  54382. * http://www.apache.org/licenses/LICENSE-2.0
  54383. *
  54384. * Unless required by applicable law or agreed to in writing,
  54385. * software distributed under the License is distributed on an
  54386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54387. * KIND, either express or implied. See the License for the
  54388. * specific language governing permissions and limitations
  54389. * under the License.
  54390. */
  54391. function installScrollableLegendAction(registers) {
  54392. /**
  54393. * @event legendScroll
  54394. * @type {Object}
  54395. * @property {string} type 'legendScroll'
  54396. * @property {string} scrollDataIndex
  54397. */
  54398. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  54399. var scrollDataIndex = payload.scrollDataIndex;
  54400. scrollDataIndex != null && ecModel.eachComponent({
  54401. mainType: 'legend',
  54402. subType: 'scroll',
  54403. query: payload
  54404. }, function (legendModel) {
  54405. legendModel.setScrollDataIndex(scrollDataIndex);
  54406. });
  54407. });
  54408. }
  54409. function install$i(registers) {
  54410. use(install$h);
  54411. registers.registerComponentModel(ScrollableLegendModel);
  54412. registers.registerComponentView(ScrollableLegendView);
  54413. installScrollableLegendAction(registers);
  54414. }
  54415. function install$j(registers) {
  54416. use(install$h);
  54417. use(install$i);
  54418. }
  54419. var InsideZoomModel = /** @class */function (_super) {
  54420. __extends(InsideZoomModel, _super);
  54421. function InsideZoomModel() {
  54422. var _this = _super !== null && _super.apply(this, arguments) || this;
  54423. _this.type = InsideZoomModel.type;
  54424. return _this;
  54425. }
  54426. InsideZoomModel.type = 'dataZoom.inside';
  54427. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  54428. disabled: false,
  54429. zoomLock: false,
  54430. zoomOnMouseWheel: true,
  54431. moveOnMouseMove: true,
  54432. moveOnMouseWheel: false,
  54433. preventDefaultMouseMove: true
  54434. });
  54435. return InsideZoomModel;
  54436. }(DataZoomModel);
  54437. var RoamController = /** @class */function (_super) {
  54438. __extends(RoamController, _super);
  54439. function RoamController(zr) {
  54440. var _this = _super.call(this) || this;
  54441. _this._zr = zr;
  54442. // Avoid two roamController bind the same handler
  54443. var mousedownHandler = bind(_this._mousedownHandler, _this);
  54444. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  54445. var mouseupHandler = bind(_this._mouseupHandler, _this);
  54446. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  54447. var pinchHandler = bind(_this._pinchHandler, _this);
  54448. /**
  54449. * Notice: only enable needed types. For example, if 'zoom'
  54450. * is not needed, 'zoom' should not be enabled, otherwise
  54451. * default mousewheel behaviour (scroll page) will be disabled.
  54452. */
  54453. _this.enable = function (controlType, opt) {
  54454. // Disable previous first
  54455. this.disable();
  54456. this._opt = defaults(clone(opt) || {}, {
  54457. zoomOnMouseWheel: true,
  54458. moveOnMouseMove: true,
  54459. // By default, wheel do not trigger move.
  54460. moveOnMouseWheel: false,
  54461. preventDefaultMouseMove: true
  54462. });
  54463. if (controlType == null) {
  54464. controlType = true;
  54465. }
  54466. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  54467. zr.on('mousedown', mousedownHandler);
  54468. zr.on('mousemove', mousemoveHandler);
  54469. zr.on('mouseup', mouseupHandler);
  54470. }
  54471. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  54472. zr.on('mousewheel', mousewheelHandler);
  54473. zr.on('pinch', pinchHandler);
  54474. }
  54475. };
  54476. _this.disable = function () {
  54477. zr.off('mousedown', mousedownHandler);
  54478. zr.off('mousemove', mousemoveHandler);
  54479. zr.off('mouseup', mouseupHandler);
  54480. zr.off('mousewheel', mousewheelHandler);
  54481. zr.off('pinch', pinchHandler);
  54482. };
  54483. return _this;
  54484. }
  54485. RoamController.prototype.isDragging = function () {
  54486. return this._dragging;
  54487. };
  54488. RoamController.prototype.isPinching = function () {
  54489. return this._pinching;
  54490. };
  54491. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  54492. this.pointerChecker = pointerChecker;
  54493. };
  54494. RoamController.prototype.dispose = function () {
  54495. this.disable();
  54496. };
  54497. RoamController.prototype._mousedownHandler = function (e) {
  54498. if (isMiddleOrRightButtonOnMouseUpDown(e)) {
  54499. return;
  54500. }
  54501. var el = e.target;
  54502. while (el) {
  54503. if (el.draggable) {
  54504. return;
  54505. }
  54506. // check if host is draggable
  54507. el = el.__hostTarget || el.parent;
  54508. }
  54509. var x = e.offsetX;
  54510. var y = e.offsetY;
  54511. // Only check on mosedown, but not mousemove.
  54512. // Mouse can be out of target when mouse moving.
  54513. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  54514. this._x = x;
  54515. this._y = y;
  54516. this._dragging = true;
  54517. }
  54518. };
  54519. RoamController.prototype._mousemoveHandler = function (e) {
  54520. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  54521. return;
  54522. }
  54523. var x = e.offsetX;
  54524. var y = e.offsetY;
  54525. var oldX = this._x;
  54526. var oldY = this._y;
  54527. var dx = x - oldX;
  54528. var dy = y - oldY;
  54529. this._x = x;
  54530. this._y = y;
  54531. this._opt.preventDefaultMouseMove && stop(e.event);
  54532. trigger$1(this, 'pan', 'moveOnMouseMove', e, {
  54533. dx: dx,
  54534. dy: dy,
  54535. oldX: oldX,
  54536. oldY: oldY,
  54537. newX: x,
  54538. newY: y,
  54539. isAvailableBehavior: null
  54540. });
  54541. };
  54542. RoamController.prototype._mouseupHandler = function (e) {
  54543. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  54544. this._dragging = false;
  54545. }
  54546. };
  54547. RoamController.prototype._mousewheelHandler = function (e) {
  54548. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  54549. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  54550. var wheelDelta = e.wheelDelta;
  54551. var absWheelDeltaDelta = Math.abs(wheelDelta);
  54552. var originX = e.offsetX;
  54553. var originY = e.offsetY;
  54554. // wheelDelta maybe -0 in chrome mac.
  54555. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  54556. return;
  54557. }
  54558. // If both `shouldZoom` and `shouldMove` is true, trigger
  54559. // their event both, and the final behavior is determined
  54560. // by event listener themselves.
  54561. if (shouldZoom) {
  54562. // Convenience:
  54563. // Mac and VM Windows on Mac: scroll up: zoom out.
  54564. // Windows: scroll up: zoom in.
  54565. // FIXME: Should do more test in different environment.
  54566. // wheelDelta is too complicated in difference nvironment
  54567. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  54568. // although it has been normallized by zrender.
  54569. // wheelDelta of mouse wheel is bigger than touch pad.
  54570. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  54571. var scale = wheelDelta > 0 ? factor : 1 / factor;
  54572. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  54573. scale: scale,
  54574. originX: originX,
  54575. originY: originY,
  54576. isAvailableBehavior: null
  54577. });
  54578. }
  54579. if (shouldMove) {
  54580. // FIXME: Should do more test in different environment.
  54581. var absDelta = Math.abs(wheelDelta);
  54582. // wheelDelta of mouse wheel is bigger than touch pad.
  54583. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  54584. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  54585. scrollDelta: scrollDelta,
  54586. originX: originX,
  54587. originY: originY,
  54588. isAvailableBehavior: null
  54589. });
  54590. }
  54591. };
  54592. RoamController.prototype._pinchHandler = function (e) {
  54593. if (isTaken(this._zr, 'globalPan')) {
  54594. return;
  54595. }
  54596. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  54597. checkPointerAndTrigger(this, 'zoom', null, e, {
  54598. scale: scale,
  54599. originX: e.pinchX,
  54600. originY: e.pinchY,
  54601. isAvailableBehavior: null
  54602. });
  54603. };
  54604. return RoamController;
  54605. }(Eventful);
  54606. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  54607. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  54608. // When mouse is out of roamController rect,
  54609. // default befavoius should not be be disabled, otherwise
  54610. // page sliding is disabled, contrary to expectation.
  54611. stop(e.event);
  54612. trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent);
  54613. }
  54614. }
  54615. function trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent) {
  54616. // Also provide behavior checker for event listener, for some case that
  54617. // multiple components share one listener.
  54618. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  54619. // TODO should not have type issue.
  54620. controller.trigger(eventName, contollerEvent);
  54621. }
  54622. // settings: {
  54623. // zoomOnMouseWheel
  54624. // moveOnMouseMove
  54625. // moveOnMouseWheel
  54626. // }
  54627. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  54628. function isAvailableBehavior(behaviorToCheck, e, settings) {
  54629. var setting = settings[behaviorToCheck];
  54630. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  54631. }
  54632. var inner$g = makeInner();
  54633. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  54634. inner$g(api).coordSysRecordMap.each(function (coordSysRecord) {
  54635. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  54636. if (dzInfo) {
  54637. dzInfo.getRange = getRange;
  54638. }
  54639. });
  54640. }
  54641. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  54642. var coordSysRecordMap = inner$g(api).coordSysRecordMap;
  54643. var coordSysKeyArr = coordSysRecordMap.keys();
  54644. for (var i = 0; i < coordSysKeyArr.length; i++) {
  54645. var coordSysKey = coordSysKeyArr[i];
  54646. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  54647. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  54648. if (dataZoomInfoMap) {
  54649. var dzUid = dataZoomModel.uid;
  54650. var dzInfo = dataZoomInfoMap.get(dzUid);
  54651. if (dzInfo) {
  54652. dataZoomInfoMap.removeKey(dzUid);
  54653. if (!dataZoomInfoMap.keys().length) {
  54654. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  54655. }
  54656. }
  54657. }
  54658. }
  54659. }
  54660. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  54661. if (coordSysRecord) {
  54662. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  54663. var controller = coordSysRecord.controller;
  54664. controller && controller.dispose();
  54665. }
  54666. }
  54667. function createCoordSysRecord(api, coordSysModel) {
  54668. // These init props will never change after record created.
  54669. var coordSysRecord = {
  54670. model: coordSysModel,
  54671. containsPoint: curry(containsPoint, coordSysModel),
  54672. dispatchAction: curry(dispatchAction, api),
  54673. dataZoomInfoMap: null,
  54674. controller: null
  54675. };
  54676. // Must not do anything depends on coordSysRecord outside the event handler here,
  54677. // because coordSysRecord not completed yet.
  54678. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  54679. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  54680. controller.on(eventName, function (event) {
  54681. var batch = [];
  54682. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  54683. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  54684. // moveOnMouseWheel, ...) enabled.
  54685. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  54686. return;
  54687. }
  54688. var method = (dzInfo.getRange || {})[eventName];
  54689. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  54690. !dzInfo.model.get('disabled', true) && range && batch.push({
  54691. dataZoomId: dzInfo.model.id,
  54692. start: range[0],
  54693. end: range[1]
  54694. });
  54695. });
  54696. batch.length && coordSysRecord.dispatchAction(batch);
  54697. });
  54698. });
  54699. return coordSysRecord;
  54700. }
  54701. /**
  54702. * This action will be throttled.
  54703. */
  54704. function dispatchAction(api, batch) {
  54705. if (!api.isDisposed()) {
  54706. api.dispatchAction({
  54707. type: 'dataZoom',
  54708. animation: {
  54709. easing: 'cubicOut',
  54710. duration: 100
  54711. },
  54712. batch: batch
  54713. });
  54714. }
  54715. }
  54716. function containsPoint(coordSysModel, e, x, y) {
  54717. return coordSysModel.coordinateSystem.containPoint([x, y]);
  54718. }
  54719. /**
  54720. * Merge roamController settings when multiple dataZooms share one roamController.
  54721. */
  54722. function mergeControllerParams(dataZoomInfoMap) {
  54723. var controlType;
  54724. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  54725. // as string, it is probably revert to reserved word by compress tool. See #7411.
  54726. var prefix = 'type_';
  54727. var typePriority = {
  54728. 'type_true': 2,
  54729. 'type_move': 1,
  54730. 'type_false': 0,
  54731. 'type_undefined': -1
  54732. };
  54733. var preventDefaultMouseMove = true;
  54734. dataZoomInfoMap.each(function (dataZoomInfo) {
  54735. var dataZoomModel = dataZoomInfo.model;
  54736. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  54737. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  54738. controlType = oneType;
  54739. }
  54740. // Prevent default move event by default. If one false, do not prevent. Otherwise
  54741. // users may be confused why it does not work when multiple insideZooms exist.
  54742. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  54743. });
  54744. return {
  54745. controlType: controlType,
  54746. opt: {
  54747. // RoamController will enable all of these functionalities,
  54748. // and the final behavior is determined by its event listener
  54749. // provided by each inside zoom.
  54750. zoomOnMouseWheel: true,
  54751. moveOnMouseMove: true,
  54752. moveOnMouseWheel: true,
  54753. preventDefaultMouseMove: !!preventDefaultMouseMove
  54754. }
  54755. };
  54756. }
  54757. function installDataZoomRoamProcessor(registers) {
  54758. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  54759. var apiInner = inner$g(api);
  54760. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  54761. coordSysRecordMap.each(function (coordSysRecord) {
  54762. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  54763. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  54764. coordSysRecord.dataZoomInfoMap = null;
  54765. });
  54766. ecModel.eachComponent({
  54767. mainType: 'dataZoom',
  54768. subType: 'inside'
  54769. }, function (dataZoomModel) {
  54770. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  54771. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  54772. var coordSysUid = dzCoordSysInfo.model.uid;
  54773. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  54774. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap());
  54775. // Notice these props might be changed each time for a single dataZoomModel.
  54776. dataZoomInfoMap.set(dataZoomModel.uid, {
  54777. dzReferCoordSysInfo: dzCoordSysInfo,
  54778. model: dataZoomModel,
  54779. getRange: null
  54780. });
  54781. });
  54782. });
  54783. // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  54784. // (2) Clear coord sys if not refered by any dataZoom.
  54785. coordSysRecordMap.each(function (coordSysRecord) {
  54786. var controller = coordSysRecord.controller;
  54787. var firstDzInfo;
  54788. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  54789. if (dataZoomInfoMap) {
  54790. var firstDzKey = dataZoomInfoMap.keys()[0];
  54791. if (firstDzKey != null) {
  54792. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  54793. }
  54794. }
  54795. if (!firstDzInfo) {
  54796. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  54797. return;
  54798. }
  54799. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  54800. controller.enable(controllerParams.controlType, controllerParams.opt);
  54801. controller.setPointerChecker(coordSysRecord.containsPoint);
  54802. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  54803. });
  54804. });
  54805. }
  54806. var InsideZoomView = /** @class */function (_super) {
  54807. __extends(InsideZoomView, _super);
  54808. function InsideZoomView() {
  54809. var _this = _super !== null && _super.apply(this, arguments) || this;
  54810. _this.type = 'dataZoom.inside';
  54811. return _this;
  54812. }
  54813. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  54814. _super.prototype.render.apply(this, arguments);
  54815. if (dataZoomModel.noTarget()) {
  54816. this._clear();
  54817. return;
  54818. }
  54819. // Hence the `throttle` util ensures to preserve command order,
  54820. // here simply updating range all the time will not cause missing
  54821. // any of the the roam change.
  54822. this.range = dataZoomModel.getPercentRange();
  54823. // Reset controllers.
  54824. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  54825. pan: bind(getRangeHandlers.pan, this),
  54826. zoom: bind(getRangeHandlers.zoom, this),
  54827. scrollMove: bind(getRangeHandlers.scrollMove, this)
  54828. });
  54829. };
  54830. InsideZoomView.prototype.dispose = function () {
  54831. this._clear();
  54832. _super.prototype.dispose.apply(this, arguments);
  54833. };
  54834. InsideZoomView.prototype._clear = function () {
  54835. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  54836. this.range = null;
  54837. };
  54838. InsideZoomView.type = 'dataZoom.inside';
  54839. return InsideZoomView;
  54840. }(DataZoomView);
  54841. var getRangeHandlers = {
  54842. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  54843. var lastRange = this.range;
  54844. var range = lastRange.slice();
  54845. // Calculate transform by the first axis.
  54846. var axisModel = coordSysInfo.axisModels[0];
  54847. if (!axisModel) {
  54848. return;
  54849. }
  54850. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  54851. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  54852. var scale = Math.max(1 / e.scale, 0);
  54853. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  54854. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  54855. // Restrict range.
  54856. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  54857. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  54858. this.range = range;
  54859. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  54860. return range;
  54861. }
  54862. },
  54863. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  54864. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  54865. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  54866. }),
  54867. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  54868. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  54869. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  54870. })
  54871. };
  54872. function makeMover(getPercentDelta) {
  54873. return function (coordSysInfo, coordSysMainType, controller, e) {
  54874. var lastRange = this.range;
  54875. var range = lastRange.slice();
  54876. // Calculate transform by the first axis.
  54877. var axisModel = coordSysInfo.axisModels[0];
  54878. if (!axisModel) {
  54879. return;
  54880. }
  54881. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  54882. sliderMove(percentDelta, range, [0, 100], 'all');
  54883. this.range = range;
  54884. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  54885. return range;
  54886. }
  54887. };
  54888. }
  54889. var getDirectionInfo = {
  54890. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  54891. var axis = axisModel.axis;
  54892. var ret = {};
  54893. var rect = coordSysInfo.model.coordinateSystem.getRect();
  54894. oldPoint = oldPoint || [0, 0];
  54895. if (axis.dim === 'x') {
  54896. ret.pixel = newPoint[0] - oldPoint[0];
  54897. ret.pixelLength = rect.width;
  54898. ret.pixelStart = rect.x;
  54899. ret.signal = axis.inverse ? 1 : -1;
  54900. } else {
  54901. // axis.dim === 'y'
  54902. ret.pixel = newPoint[1] - oldPoint[1];
  54903. ret.pixelLength = rect.height;
  54904. ret.pixelStart = rect.y;
  54905. ret.signal = axis.inverse ? -1 : 1;
  54906. }
  54907. return ret;
  54908. },
  54909. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  54910. var axis = axisModel.axis;
  54911. var ret = {};
  54912. var polar = coordSysInfo.model.coordinateSystem;
  54913. var radiusExtent = polar.getRadiusAxis().getExtent();
  54914. var angleExtent = polar.getAngleAxis().getExtent();
  54915. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  54916. newPoint = polar.pointToCoord(newPoint);
  54917. if (axisModel.mainType === 'radiusAxis') {
  54918. ret.pixel = newPoint[0] - oldPoint[0];
  54919. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  54920. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  54921. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  54922. ret.pixelStart = radiusExtent[0];
  54923. ret.signal = axis.inverse ? 1 : -1;
  54924. } else {
  54925. // 'angleAxis'
  54926. ret.pixel = newPoint[1] - oldPoint[1];
  54927. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  54928. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  54929. ret.pixelLength = angleExtent[1] - angleExtent[0];
  54930. ret.pixelStart = angleExtent[0];
  54931. ret.signal = axis.inverse ? -1 : 1;
  54932. }
  54933. return ret;
  54934. },
  54935. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  54936. var axis = axisModel.axis;
  54937. var rect = coordSysInfo.model.coordinateSystem.getRect();
  54938. var ret = {};
  54939. oldPoint = oldPoint || [0, 0];
  54940. if (axis.orient === 'horizontal') {
  54941. ret.pixel = newPoint[0] - oldPoint[0];
  54942. ret.pixelLength = rect.width;
  54943. ret.pixelStart = rect.x;
  54944. ret.signal = axis.inverse ? 1 : -1;
  54945. } else {
  54946. // 'vertical'
  54947. ret.pixel = newPoint[1] - oldPoint[1];
  54948. ret.pixelLength = rect.height;
  54949. ret.pixelStart = rect.y;
  54950. ret.signal = axis.inverse ? -1 : 1;
  54951. }
  54952. return ret;
  54953. }
  54954. };
  54955. function install$k(registers) {
  54956. installCommon(registers);
  54957. registers.registerComponentModel(InsideZoomModel);
  54958. registers.registerComponentView(InsideZoomView);
  54959. installDataZoomRoamProcessor(registers);
  54960. }
  54961. var SliderZoomModel = /** @class */function (_super) {
  54962. __extends(SliderZoomModel, _super);
  54963. function SliderZoomModel() {
  54964. var _this = _super !== null && _super.apply(this, arguments) || this;
  54965. _this.type = SliderZoomModel.type;
  54966. return _this;
  54967. }
  54968. SliderZoomModel.type = 'dataZoom.slider';
  54969. SliderZoomModel.layoutMode = 'box';
  54970. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  54971. show: true,
  54972. // deault value can only be drived in view stage.
  54973. right: 'ph',
  54974. top: 'ph',
  54975. width: 'ph',
  54976. height: 'ph',
  54977. left: null,
  54978. bottom: null,
  54979. borderColor: '#d2dbee',
  54980. borderRadius: 3,
  54981. backgroundColor: 'rgba(47,69,84,0)',
  54982. // dataBackgroundColor: '#ddd',
  54983. dataBackground: {
  54984. lineStyle: {
  54985. color: '#d2dbee',
  54986. width: 0.5
  54987. },
  54988. areaStyle: {
  54989. color: '#d2dbee',
  54990. opacity: 0.2
  54991. }
  54992. },
  54993. selectedDataBackground: {
  54994. lineStyle: {
  54995. color: '#8fb0f7',
  54996. width: 0.5
  54997. },
  54998. areaStyle: {
  54999. color: '#8fb0f7',
  55000. opacity: 0.2
  55001. }
  55002. },
  55003. // Color of selected window.
  55004. fillerColor: 'rgba(135,175,274,0.2)',
  55005. 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',
  55006. // Percent of the slider height
  55007. handleSize: '100%',
  55008. handleStyle: {
  55009. color: '#fff',
  55010. borderColor: '#ACB8D1'
  55011. },
  55012. moveHandleSize: 7,
  55013. 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',
  55014. moveHandleStyle: {
  55015. color: '#D2DBEE',
  55016. opacity: 0.7
  55017. },
  55018. showDetail: true,
  55019. showDataShadow: 'auto',
  55020. realtime: true,
  55021. zoomLock: false,
  55022. textStyle: {
  55023. color: '#6E7079'
  55024. },
  55025. brushSelect: true,
  55026. brushStyle: {
  55027. color: 'rgba(135,175,274,0.15)'
  55028. },
  55029. emphasis: {
  55030. handleStyle: {
  55031. borderColor: '#8FB0F7'
  55032. },
  55033. moveHandleStyle: {
  55034. color: '#8FB0F7'
  55035. }
  55036. }
  55037. });
  55038. return SliderZoomModel;
  55039. }(DataZoomModel);
  55040. var Rect$1 = Rect;
  55041. // Constants
  55042. var DEFAULT_LOCATION_EDGE_GAP = 7;
  55043. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  55044. var DEFAULT_FILLER_SIZE = 30;
  55045. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  55046. var HORIZONTAL = 'horizontal';
  55047. var VERTICAL = 'vertical';
  55048. var LABEL_GAP = 5;
  55049. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  55050. var REALTIME_ANIMATION_CONFIG = {
  55051. easing: 'cubicOut',
  55052. duration: 100,
  55053. delay: 0
  55054. };
  55055. var SliderZoomView = /** @class */function (_super) {
  55056. __extends(SliderZoomView, _super);
  55057. function SliderZoomView() {
  55058. var _this = _super !== null && _super.apply(this, arguments) || this;
  55059. _this.type = SliderZoomView.type;
  55060. _this._displayables = {};
  55061. return _this;
  55062. }
  55063. SliderZoomView.prototype.init = function (ecModel, api) {
  55064. this.api = api;
  55065. // A unique handler for each dataZoom component
  55066. this._onBrush = bind(this._onBrush, this);
  55067. this._onBrushEnd = bind(this._onBrushEnd, this);
  55068. };
  55069. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  55070. _super.prototype.render.apply(this, arguments);
  55071. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  55072. this._orient = dataZoomModel.getOrient();
  55073. if (dataZoomModel.get('show') === false) {
  55074. this.group.removeAll();
  55075. return;
  55076. }
  55077. if (dataZoomModel.noTarget()) {
  55078. this._clear();
  55079. this.group.removeAll();
  55080. return;
  55081. }
  55082. // Notice: this._resetInterval() should not be executed when payload.type
  55083. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  55084. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  55085. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  55086. this._buildView();
  55087. }
  55088. this._updateView();
  55089. };
  55090. SliderZoomView.prototype.dispose = function () {
  55091. this._clear();
  55092. _super.prototype.dispose.apply(this, arguments);
  55093. };
  55094. SliderZoomView.prototype._clear = function () {
  55095. clear(this, '_dispatchZoomAction');
  55096. var zr = this.api.getZr();
  55097. zr.off('mousemove', this._onBrush);
  55098. zr.off('mouseup', this._onBrushEnd);
  55099. };
  55100. SliderZoomView.prototype._buildView = function () {
  55101. var thisGroup = this.group;
  55102. thisGroup.removeAll();
  55103. this._brushing = false;
  55104. this._displayables.brushRect = null;
  55105. this._resetLocation();
  55106. this._resetInterval();
  55107. var barGroup = this._displayables.sliderGroup = new Group();
  55108. this._renderBackground();
  55109. this._renderHandle();
  55110. this._renderDataShadow();
  55111. thisGroup.add(barGroup);
  55112. this._positionGroup();
  55113. };
  55114. SliderZoomView.prototype._resetLocation = function () {
  55115. var dataZoomModel = this.dataZoomModel;
  55116. var api = this.api;
  55117. var showMoveHandle = dataZoomModel.get('brushSelect');
  55118. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0;
  55119. // If some of x/y/width/height are not specified,
  55120. // auto-adapt according to target grid.
  55121. var coordRect = this._findCoordRect();
  55122. var ecSize = {
  55123. width: api.getWidth(),
  55124. height: api.getHeight()
  55125. };
  55126. // Default align by coordinate system rect.
  55127. var positionInfo = this._orient === HORIZONTAL ? {
  55128. // Why using 'right', because right should be used in vertical,
  55129. // and it is better to be consistent for dealing with position param merge.
  55130. right: ecSize.width - coordRect.x - coordRect.width,
  55131. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  55132. width: coordRect.width,
  55133. height: DEFAULT_FILLER_SIZE
  55134. } : {
  55135. right: DEFAULT_LOCATION_EDGE_GAP,
  55136. top: coordRect.y,
  55137. width: DEFAULT_FILLER_SIZE,
  55138. height: coordRect.height
  55139. };
  55140. // Do not write back to option and replace value 'ph', because
  55141. // the 'ph' value should be recalculated when resize.
  55142. var layoutParams = getLayoutParams(dataZoomModel.option);
  55143. // Replace the placeholder value.
  55144. each(['right', 'top', 'width', 'height'], function (name) {
  55145. if (layoutParams[name] === 'ph') {
  55146. layoutParams[name] = positionInfo[name];
  55147. }
  55148. });
  55149. var layoutRect = getLayoutRect(layoutParams, ecSize);
  55150. this._location = {
  55151. x: layoutRect.x,
  55152. y: layoutRect.y
  55153. };
  55154. this._size = [layoutRect.width, layoutRect.height];
  55155. this._orient === VERTICAL && this._size.reverse();
  55156. };
  55157. SliderZoomView.prototype._positionGroup = function () {
  55158. var thisGroup = this.group;
  55159. var location = this._location;
  55160. var orient = this._orient;
  55161. // Just use the first axis to determine mapping.
  55162. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  55163. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  55164. var sliderGroup = this._displayables.sliderGroup;
  55165. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  55166. // Transform barGroup.
  55167. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  55168. scaleY: otherAxisInverse ? 1 : -1,
  55169. scaleX: 1
  55170. } : orient === HORIZONTAL && inverse ? {
  55171. scaleY: otherAxisInverse ? 1 : -1,
  55172. scaleX: -1
  55173. } : orient === VERTICAL && !inverse ? {
  55174. scaleY: otherAxisInverse ? -1 : 1,
  55175. scaleX: 1,
  55176. rotation: Math.PI / 2
  55177. }
  55178. // Don't use Math.PI, considering shadow direction.
  55179. : {
  55180. scaleY: otherAxisInverse ? -1 : 1,
  55181. scaleX: -1,
  55182. rotation: Math.PI / 2
  55183. });
  55184. // Position barGroup
  55185. var rect = thisGroup.getBoundingRect([sliderGroup]);
  55186. thisGroup.x = location.x - rect.x;
  55187. thisGroup.y = location.y - rect.y;
  55188. thisGroup.markRedraw();
  55189. };
  55190. SliderZoomView.prototype._getViewExtent = function () {
  55191. return [0, this._size[0]];
  55192. };
  55193. SliderZoomView.prototype._renderBackground = function () {
  55194. var dataZoomModel = this.dataZoomModel;
  55195. var size = this._size;
  55196. var barGroup = this._displayables.sliderGroup;
  55197. var brushSelect = dataZoomModel.get('brushSelect');
  55198. barGroup.add(new Rect$1({
  55199. silent: true,
  55200. shape: {
  55201. x: 0,
  55202. y: 0,
  55203. width: size[0],
  55204. height: size[1]
  55205. },
  55206. style: {
  55207. fill: dataZoomModel.get('backgroundColor')
  55208. },
  55209. z2: -40
  55210. }));
  55211. // Click panel, over shadow, below handles.
  55212. var clickPanel = new Rect$1({
  55213. shape: {
  55214. x: 0,
  55215. y: 0,
  55216. width: size[0],
  55217. height: size[1]
  55218. },
  55219. style: {
  55220. fill: 'transparent'
  55221. },
  55222. z2: 0,
  55223. onclick: bind(this._onClickPanel, this)
  55224. });
  55225. var zr = this.api.getZr();
  55226. if (brushSelect) {
  55227. clickPanel.on('mousedown', this._onBrushStart, this);
  55228. clickPanel.cursor = 'crosshair';
  55229. zr.on('mousemove', this._onBrush);
  55230. zr.on('mouseup', this._onBrushEnd);
  55231. } else {
  55232. zr.off('mousemove', this._onBrush);
  55233. zr.off('mouseup', this._onBrushEnd);
  55234. }
  55235. barGroup.add(clickPanel);
  55236. };
  55237. SliderZoomView.prototype._renderDataShadow = function () {
  55238. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  55239. this._displayables.dataShadowSegs = [];
  55240. if (!info) {
  55241. return;
  55242. }
  55243. var size = this._size;
  55244. var oldSize = this._shadowSize || [];
  55245. var seriesModel = info.series;
  55246. var data = seriesModel.getRawData();
  55247. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  55248. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  55249. : info.otherDim;
  55250. if (otherDim == null) {
  55251. return;
  55252. }
  55253. var polygonPts = this._shadowPolygonPts;
  55254. var polylinePts = this._shadowPolylinePts;
  55255. // Not re-render if data doesn't change.
  55256. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  55257. var otherDataExtent_1 = data.getDataExtent(otherDim);
  55258. // Nice extent.
  55259. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  55260. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  55261. var otherShadowExtent_1 = [0, size[1]];
  55262. var thisShadowExtent = [0, size[0]];
  55263. var areaPoints_1 = [[size[0], 0], [0, 0]];
  55264. var linePoints_1 = [];
  55265. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  55266. var thisCoord_1 = 0;
  55267. // Optimize for large data shadow
  55268. var stride_1 = Math.round(data.count() / size[0]);
  55269. var lastIsEmpty_1;
  55270. data.each([otherDim], function (value, index) {
  55271. if (stride_1 > 0 && index % stride_1) {
  55272. thisCoord_1 += step_1;
  55273. return;
  55274. }
  55275. // FIXME
  55276. // Should consider axis.min/axis.max when drawing dataShadow.
  55277. // FIXME
  55278. // 应该使用统一的空判断?还是在list里进行空判断?
  55279. var isEmpty = value == null || isNaN(value) || value === '';
  55280. // See #4235.
  55281. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true);
  55282. // Attempt to draw data shadow precisely when there are empty value.
  55283. if (isEmpty && !lastIsEmpty_1 && index) {
  55284. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  55285. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  55286. } else if (!isEmpty && lastIsEmpty_1) {
  55287. areaPoints_1.push([thisCoord_1, 0]);
  55288. linePoints_1.push([thisCoord_1, 0]);
  55289. }
  55290. areaPoints_1.push([thisCoord_1, otherCoord]);
  55291. linePoints_1.push([thisCoord_1, otherCoord]);
  55292. thisCoord_1 += step_1;
  55293. lastIsEmpty_1 = isEmpty;
  55294. });
  55295. polygonPts = this._shadowPolygonPts = areaPoints_1;
  55296. polylinePts = this._shadowPolylinePts = linePoints_1;
  55297. }
  55298. this._shadowData = data;
  55299. this._shadowDim = otherDim;
  55300. this._shadowSize = [size[0], size[1]];
  55301. var dataZoomModel = this.dataZoomModel;
  55302. function createDataShadowGroup(isSelectedArea) {
  55303. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  55304. var group = new Group();
  55305. var polygon = new Polygon({
  55306. shape: {
  55307. points: polygonPts
  55308. },
  55309. segmentIgnoreThreshold: 1,
  55310. style: model.getModel('areaStyle').getAreaStyle(),
  55311. silent: true,
  55312. z2: -20
  55313. });
  55314. var polyline = new Polyline({
  55315. shape: {
  55316. points: polylinePts
  55317. },
  55318. segmentIgnoreThreshold: 1,
  55319. style: model.getModel('lineStyle').getLineStyle(),
  55320. silent: true,
  55321. z2: -19
  55322. });
  55323. group.add(polygon);
  55324. group.add(polyline);
  55325. return group;
  55326. }
  55327. // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  55328. for (var i = 0; i < 3; i++) {
  55329. var group = createDataShadowGroup(i === 1);
  55330. this._displayables.sliderGroup.add(group);
  55331. this._displayables.dataShadowSegs.push(group);
  55332. }
  55333. };
  55334. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  55335. var dataZoomModel = this.dataZoomModel;
  55336. var showDataShadow = dataZoomModel.get('showDataShadow');
  55337. if (showDataShadow === false) {
  55338. return;
  55339. }
  55340. // Find a representative series.
  55341. var result;
  55342. var ecModel = this.ecModel;
  55343. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  55344. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  55345. each(seriesModels, function (seriesModel) {
  55346. if (result) {
  55347. return;
  55348. }
  55349. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  55350. return;
  55351. }
  55352. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  55353. var otherDim = getOtherDim(axisDim);
  55354. var otherAxisInverse;
  55355. var coordSys = seriesModel.coordinateSystem;
  55356. if (otherDim != null && coordSys.getOtherAxis) {
  55357. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  55358. }
  55359. otherDim = seriesModel.getData().mapDimension(otherDim);
  55360. result = {
  55361. thisAxis: thisAxis,
  55362. series: seriesModel,
  55363. thisDim: axisDim,
  55364. otherDim: otherDim,
  55365. otherAxisInverse: otherAxisInverse
  55366. };
  55367. }, this);
  55368. }, this);
  55369. return result;
  55370. };
  55371. SliderZoomView.prototype._renderHandle = function () {
  55372. var thisGroup = this.group;
  55373. var displayables = this._displayables;
  55374. var handles = displayables.handles = [null, null];
  55375. var handleLabels = displayables.handleLabels = [null, null];
  55376. var sliderGroup = this._displayables.sliderGroup;
  55377. var size = this._size;
  55378. var dataZoomModel = this.dataZoomModel;
  55379. var api = this.api;
  55380. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  55381. var brushSelect = dataZoomModel.get('brushSelect');
  55382. var filler = displayables.filler = new Rect$1({
  55383. silent: brushSelect,
  55384. style: {
  55385. fill: dataZoomModel.get('fillerColor')
  55386. },
  55387. textConfig: {
  55388. position: 'inside'
  55389. }
  55390. });
  55391. sliderGroup.add(filler);
  55392. // Frame border.
  55393. sliderGroup.add(new Rect$1({
  55394. silent: true,
  55395. subPixelOptimize: true,
  55396. shape: {
  55397. x: 0,
  55398. y: 0,
  55399. width: size[0],
  55400. height: size[1],
  55401. r: borderRadius
  55402. },
  55403. style: {
  55404. // deprecated option
  55405. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  55406. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  55407. fill: 'rgba(0,0,0,0)'
  55408. }
  55409. }));
  55410. // Left and right handle to resize
  55411. each([0, 1], function (handleIndex) {
  55412. var iconStr = dataZoomModel.get('handleIcon');
  55413. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  55414. // Compatitable with the old icon parsers. Which can use a path string without path://
  55415. iconStr = 'path://' + iconStr;
  55416. if ("development" !== 'production') {
  55417. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  55418. }
  55419. }
  55420. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  55421. path.attr({
  55422. cursor: getCursor(this._orient),
  55423. draggable: true,
  55424. drift: bind(this._onDragMove, this, handleIndex),
  55425. ondragend: bind(this._onDragEnd, this),
  55426. onmouseover: bind(this._showDataInfo, this, true),
  55427. onmouseout: bind(this._showDataInfo, this, false),
  55428. z2: 5
  55429. });
  55430. var bRect = path.getBoundingRect();
  55431. var handleSize = dataZoomModel.get('handleSize');
  55432. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  55433. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  55434. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  55435. path.style.strokeNoScale = true;
  55436. path.rectHover = true;
  55437. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  55438. enableHoverEmphasis(path);
  55439. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  55440. // Compatitable with previous version
  55441. if (handleColor != null) {
  55442. path.style.fill = handleColor;
  55443. }
  55444. sliderGroup.add(handles[handleIndex] = path);
  55445. var textStyleModel = dataZoomModel.getModel('textStyle');
  55446. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  55447. silent: true,
  55448. invisible: true,
  55449. style: createTextStyle(textStyleModel, {
  55450. x: 0,
  55451. y: 0,
  55452. text: '',
  55453. verticalAlign: 'middle',
  55454. align: 'center',
  55455. fill: textStyleModel.getTextColor(),
  55456. font: textStyleModel.getFont()
  55457. }),
  55458. z2: 10
  55459. }));
  55460. }, this);
  55461. // Handle to move. Only visible when brushSelect is set true.
  55462. var actualMoveZone = filler;
  55463. if (brushSelect) {
  55464. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  55465. var moveHandle_1 = displayables.moveHandle = new Rect({
  55466. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  55467. silent: true,
  55468. shape: {
  55469. r: [0, 0, 2, 2],
  55470. y: size[1] - 0.5,
  55471. height: moveHandleHeight
  55472. }
  55473. });
  55474. var iconSize = moveHandleHeight * 0.8;
  55475. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  55476. moveHandleIcon.silent = true;
  55477. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  55478. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  55479. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  55480. actualMoveZone = displayables.moveZone = new Rect({
  55481. invisible: true,
  55482. shape: {
  55483. y: size[1] - moveZoneExpandSize,
  55484. height: moveHandleHeight + moveZoneExpandSize
  55485. }
  55486. });
  55487. actualMoveZone.on('mouseover', function () {
  55488. api.enterEmphasis(moveHandle_1);
  55489. }).on('mouseout', function () {
  55490. api.leaveEmphasis(moveHandle_1);
  55491. });
  55492. sliderGroup.add(moveHandle_1);
  55493. sliderGroup.add(moveHandleIcon);
  55494. sliderGroup.add(actualMoveZone);
  55495. }
  55496. actualMoveZone.attr({
  55497. draggable: true,
  55498. cursor: getCursor(this._orient),
  55499. drift: bind(this._onDragMove, this, 'all'),
  55500. ondragstart: bind(this._showDataInfo, this, true),
  55501. ondragend: bind(this._onDragEnd, this),
  55502. onmouseover: bind(this._showDataInfo, this, true),
  55503. onmouseout: bind(this._showDataInfo, this, false)
  55504. });
  55505. };
  55506. SliderZoomView.prototype._resetInterval = function () {
  55507. var range = this._range = this.dataZoomModel.getPercentRange();
  55508. var viewExtent = this._getViewExtent();
  55509. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  55510. };
  55511. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  55512. var dataZoomModel = this.dataZoomModel;
  55513. var handleEnds = this._handleEnds;
  55514. var viewExtend = this._getViewExtent();
  55515. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55516. var percentExtent = [0, 100];
  55517. 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);
  55518. var lastRange = this._range;
  55519. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  55520. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  55521. };
  55522. SliderZoomView.prototype._updateView = function (nonRealtime) {
  55523. var displaybles = this._displayables;
  55524. var handleEnds = this._handleEnds;
  55525. var handleInterval = asc(handleEnds.slice());
  55526. var size = this._size;
  55527. each([0, 1], function (handleIndex) {
  55528. // Handles
  55529. var handle = displaybles.handles[handleIndex];
  55530. var handleHeight = this._handleHeight;
  55531. handle.attr({
  55532. scaleX: handleHeight / 2,
  55533. scaleY: handleHeight / 2,
  55534. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  55535. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  55536. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  55537. y: size[1] / 2 - handleHeight / 2
  55538. });
  55539. }, this);
  55540. // Filler
  55541. displaybles.filler.setShape({
  55542. x: handleInterval[0],
  55543. y: 0,
  55544. width: handleInterval[1] - handleInterval[0],
  55545. height: size[1]
  55546. });
  55547. var viewExtent = {
  55548. x: handleInterval[0],
  55549. width: handleInterval[1] - handleInterval[0]
  55550. };
  55551. // Move handle
  55552. if (displaybles.moveHandle) {
  55553. displaybles.moveHandle.setShape(viewExtent);
  55554. displaybles.moveZone.setShape(viewExtent);
  55555. // Force update path on the invisible object
  55556. displaybles.moveZone.getBoundingRect();
  55557. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  55558. }
  55559. // update clip path of shadow.
  55560. var dataShadowSegs = displaybles.dataShadowSegs;
  55561. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  55562. for (var i = 0; i < dataShadowSegs.length; i++) {
  55563. var segGroup = dataShadowSegs[i];
  55564. var clipPath = segGroup.getClipPath();
  55565. if (!clipPath) {
  55566. clipPath = new Rect();
  55567. segGroup.setClipPath(clipPath);
  55568. }
  55569. clipPath.setShape({
  55570. x: segIntervals[i],
  55571. y: 0,
  55572. width: segIntervals[i + 1] - segIntervals[i],
  55573. height: size[1]
  55574. });
  55575. }
  55576. this._updateDataInfo(nonRealtime);
  55577. };
  55578. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  55579. var dataZoomModel = this.dataZoomModel;
  55580. var displaybles = this._displayables;
  55581. var handleLabels = displaybles.handleLabels;
  55582. var orient = this._orient;
  55583. var labelTexts = ['', ''];
  55584. // FIXME
  55585. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  55586. if (dataZoomModel.get('showDetail')) {
  55587. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  55588. if (axisProxy) {
  55589. var axis = axisProxy.getAxisModel().axis;
  55590. var range = this._range;
  55591. var dataInterval = nonRealtime
  55592. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  55593. ? axisProxy.calculateDataWindow({
  55594. start: range[0],
  55595. end: range[1]
  55596. }).valueWindow : axisProxy.getDataValueWindow();
  55597. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  55598. }
  55599. }
  55600. var orderedHandleEnds = asc(this._handleEnds.slice());
  55601. setLabel.call(this, 0);
  55602. setLabel.call(this, 1);
  55603. function setLabel(handleIndex) {
  55604. // Label
  55605. // Text should not transform by barGroup.
  55606. // Ignore handlers transform
  55607. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  55608. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  55609. var offset = this._handleWidth / 2 + LABEL_GAP;
  55610. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  55611. handleLabels[handleIndex].setStyle({
  55612. x: textPoint[0],
  55613. y: textPoint[1],
  55614. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  55615. align: orient === HORIZONTAL ? direction : 'center',
  55616. text: labelTexts[handleIndex]
  55617. });
  55618. }
  55619. };
  55620. SliderZoomView.prototype._formatLabel = function (value, axis) {
  55621. var dataZoomModel = this.dataZoomModel;
  55622. var labelFormatter = dataZoomModel.get('labelFormatter');
  55623. var labelPrecision = dataZoomModel.get('labelPrecision');
  55624. if (labelPrecision == null || labelPrecision === 'auto') {
  55625. labelPrecision = axis.getPixelPrecision();
  55626. }
  55627. var valueStr = value == null || isNaN(value) ? ''
  55628. // FIXME Glue code
  55629. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  55630. value: Math.round(value)
  55631. })
  55632. // param of toFixed should less then 20.
  55633. : value.toFixed(Math.min(labelPrecision, 20));
  55634. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  55635. };
  55636. /**
  55637. * @param showOrHide true: show, false: hide
  55638. */
  55639. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  55640. // Always show when drgging.
  55641. showOrHide = this._dragging || showOrHide;
  55642. var displayables = this._displayables;
  55643. var handleLabels = displayables.handleLabels;
  55644. handleLabels[0].attr('invisible', !showOrHide);
  55645. handleLabels[1].attr('invisible', !showOrHide);
  55646. // Highlight move handle
  55647. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  55648. };
  55649. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  55650. this._dragging = true;
  55651. // For mobile device, prevent screen slider on the button.
  55652. stop(event.event);
  55653. // Transform dx, dy to bar coordination.
  55654. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  55655. var vertex = applyTransform$1([dx, dy], barTransform, true);
  55656. var changed = this._updateInterval(handleIndex, vertex[0]);
  55657. var realtime = this.dataZoomModel.get('realtime');
  55658. this._updateView(!realtime);
  55659. // Avoid dispatch dataZoom repeatly but range not changed,
  55660. // which cause bad visual effect when progressive enabled.
  55661. changed && realtime && this._dispatchZoomAction(true);
  55662. };
  55663. SliderZoomView.prototype._onDragEnd = function () {
  55664. this._dragging = false;
  55665. this._showDataInfo(false);
  55666. // While in realtime mode and stream mode, dispatch action when
  55667. // drag end will cause the whole view rerender, which is unnecessary.
  55668. var realtime = this.dataZoomModel.get('realtime');
  55669. !realtime && this._dispatchZoomAction(false);
  55670. };
  55671. SliderZoomView.prototype._onClickPanel = function (e) {
  55672. var size = this._size;
  55673. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  55674. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  55675. return;
  55676. }
  55677. var handleEnds = this._handleEnds;
  55678. var center = (handleEnds[0] + handleEnds[1]) / 2;
  55679. var changed = this._updateInterval('all', localPoint[0] - center);
  55680. this._updateView();
  55681. changed && this._dispatchZoomAction(false);
  55682. };
  55683. SliderZoomView.prototype._onBrushStart = function (e) {
  55684. var x = e.offsetX;
  55685. var y = e.offsetY;
  55686. this._brushStart = new Point(x, y);
  55687. this._brushing = true;
  55688. this._brushStartTime = +new Date();
  55689. // this._updateBrushRect(x, y);
  55690. };
  55691. SliderZoomView.prototype._onBrushEnd = function (e) {
  55692. if (!this._brushing) {
  55693. return;
  55694. }
  55695. var brushRect = this._displayables.brushRect;
  55696. this._brushing = false;
  55697. if (!brushRect) {
  55698. return;
  55699. }
  55700. brushRect.attr('ignore', true);
  55701. var brushShape = brushRect.shape;
  55702. var brushEndTime = +new Date();
  55703. // console.log(brushEndTime - this._brushStartTime);
  55704. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  55705. // Will treat it as a click
  55706. return;
  55707. }
  55708. var viewExtend = this._getViewExtent();
  55709. var percentExtent = [0, 100];
  55710. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  55711. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  55712. this._updateView();
  55713. this._dispatchZoomAction(false);
  55714. };
  55715. SliderZoomView.prototype._onBrush = function (e) {
  55716. if (this._brushing) {
  55717. // For mobile device, prevent screen slider on the button.
  55718. stop(e.event);
  55719. this._updateBrushRect(e.offsetX, e.offsetY);
  55720. }
  55721. };
  55722. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  55723. var displayables = this._displayables;
  55724. var dataZoomModel = this.dataZoomModel;
  55725. var brushRect = displayables.brushRect;
  55726. if (!brushRect) {
  55727. brushRect = displayables.brushRect = new Rect$1({
  55728. silent: true,
  55729. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  55730. });
  55731. displayables.sliderGroup.add(brushRect);
  55732. }
  55733. brushRect.attr('ignore', false);
  55734. var brushStart = this._brushStart;
  55735. var sliderGroup = this._displayables.sliderGroup;
  55736. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  55737. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  55738. var size = this._size;
  55739. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  55740. brushRect.setShape({
  55741. x: startPoint[0],
  55742. y: 0,
  55743. width: endPoint[0] - startPoint[0],
  55744. height: size[1]
  55745. });
  55746. };
  55747. /**
  55748. * This action will be throttled.
  55749. */
  55750. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  55751. var range = this._range;
  55752. this.api.dispatchAction({
  55753. type: 'dataZoom',
  55754. from: this.uid,
  55755. dataZoomId: this.dataZoomModel.id,
  55756. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  55757. start: range[0],
  55758. end: range[1]
  55759. });
  55760. };
  55761. SliderZoomView.prototype._findCoordRect = function () {
  55762. // Find the grid corresponding to the first axis referred by dataZoom.
  55763. var rect;
  55764. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  55765. if (!rect && coordSysInfoList.length) {
  55766. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  55767. rect = coordSys.getRect && coordSys.getRect();
  55768. }
  55769. if (!rect) {
  55770. var width = this.api.getWidth();
  55771. var height = this.api.getHeight();
  55772. rect = {
  55773. x: width * 0.2,
  55774. y: height * 0.2,
  55775. width: width * 0.6,
  55776. height: height * 0.6
  55777. };
  55778. }
  55779. return rect;
  55780. };
  55781. SliderZoomView.type = 'dataZoom.slider';
  55782. return SliderZoomView;
  55783. }(DataZoomView);
  55784. function getOtherDim(thisDim) {
  55785. // FIXME
  55786. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  55787. var map = {
  55788. x: 'y',
  55789. y: 'x',
  55790. radius: 'angle',
  55791. angle: 'radius'
  55792. };
  55793. return map[thisDim];
  55794. }
  55795. function getCursor(orient) {
  55796. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  55797. }
  55798. function install$l(registers) {
  55799. registers.registerComponentModel(SliderZoomModel);
  55800. registers.registerComponentView(SliderZoomView);
  55801. installCommon(registers);
  55802. }
  55803. function install$m(registers) {
  55804. use(install$k);
  55805. use(install$l);
  55806. // Do not install './dataZoomSelect',
  55807. // since it only work for toolbox dataZoom.
  55808. }
  55809. var DEFAULT_OPTION = {
  55810. label: {
  55811. enabled: true
  55812. },
  55813. decal: {
  55814. show: false
  55815. }
  55816. };
  55817. var inner$h = makeInner();
  55818. var decalPaletteScope = {};
  55819. function ariaVisual(ecModel, api) {
  55820. var ariaModel = ecModel.getModel('aria');
  55821. // See "area enabled" detection code in `GlobalModel.ts`.
  55822. if (!ariaModel.get('enabled')) {
  55823. return;
  55824. }
  55825. var defaultOption = clone(DEFAULT_OPTION);
  55826. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  55827. merge(ariaModel.option, defaultOption, false);
  55828. setDecal();
  55829. setLabel();
  55830. function setDecal() {
  55831. var decalModel = ariaModel.getModel('decal');
  55832. var useDecal = decalModel.get('show');
  55833. if (useDecal) {
  55834. // Each type of series use one scope.
  55835. // Pie and funnel are using different scopes.
  55836. var paletteScopeGroupByType_1 = createHashMap();
  55837. ecModel.eachSeries(function (seriesModel) {
  55838. if (seriesModel.isColorBySeries()) {
  55839. return;
  55840. }
  55841. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  55842. if (!decalScope) {
  55843. decalScope = {};
  55844. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  55845. }
  55846. inner$h(seriesModel).scope = decalScope;
  55847. });
  55848. ecModel.eachRawSeries(function (seriesModel) {
  55849. if (ecModel.isSeriesFiltered(seriesModel)) {
  55850. return;
  55851. }
  55852. if (isFunction(seriesModel.enableAriaDecal)) {
  55853. // Let series define how to use decal palette on data
  55854. seriesModel.enableAriaDecal();
  55855. return;
  55856. }
  55857. var data = seriesModel.getData();
  55858. if (!seriesModel.isColorBySeries()) {
  55859. var dataAll_1 = seriesModel.getRawData();
  55860. var idxMap_1 = {};
  55861. var decalScope_1 = inner$h(seriesModel).scope;
  55862. data.each(function (idx) {
  55863. var rawIdx = data.getRawIndex(idx);
  55864. idxMap_1[rawIdx] = idx;
  55865. });
  55866. var dataCount_1 = dataAll_1.count();
  55867. dataAll_1.each(function (rawIdx) {
  55868. var idx = idxMap_1[rawIdx];
  55869. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  55870. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  55871. var specifiedDecal = data.getItemVisual(idx, 'decal');
  55872. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  55873. });
  55874. } else {
  55875. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  55876. var specifiedDecal = data.getVisual('decal');
  55877. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  55878. }
  55879. function mergeDecal(specifiedDecal, paletteDecal) {
  55880. // Merge decal from palette to decal from itemStyle.
  55881. // User do not need to specify all of the decal props.
  55882. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  55883. resultDecal.dirty = true;
  55884. return resultDecal;
  55885. }
  55886. });
  55887. }
  55888. }
  55889. function setLabel() {
  55890. var dom = api.getZr().dom;
  55891. // TODO: support for SSR
  55892. if (!dom) {
  55893. return;
  55894. }
  55895. var labelLocale = ecModel.getLocaleModel().get('aria');
  55896. var labelModel = ariaModel.getModel('label');
  55897. labelModel.option = defaults(labelModel.option, labelLocale);
  55898. if (!labelModel.get('enabled')) {
  55899. return;
  55900. }
  55901. if (labelModel.get('description')) {
  55902. dom.setAttribute('aria-label', labelModel.get('description'));
  55903. return;
  55904. }
  55905. var seriesCnt = ecModel.getSeriesCount();
  55906. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  55907. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  55908. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  55909. var ariaLabel;
  55910. if (seriesCnt < 1) {
  55911. // No series, no aria label
  55912. return;
  55913. } else {
  55914. var title = getTitle();
  55915. if (title) {
  55916. var withTitle = labelModel.get(['general', 'withTitle']);
  55917. ariaLabel = replace(withTitle, {
  55918. title: title
  55919. });
  55920. } else {
  55921. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  55922. }
  55923. var seriesLabels_1 = [];
  55924. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  55925. ariaLabel += replace(prefix, {
  55926. seriesCount: seriesCnt
  55927. });
  55928. ecModel.eachSeries(function (seriesModel, idx) {
  55929. if (idx < displaySeriesCnt) {
  55930. var seriesLabel = void 0;
  55931. var seriesName = seriesModel.get('name');
  55932. var withName = seriesName ? 'withName' : 'withoutName';
  55933. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  55934. seriesLabel = replace(seriesLabel, {
  55935. seriesId: seriesModel.seriesIndex,
  55936. seriesName: seriesModel.get('name'),
  55937. seriesType: getSeriesTypeName(seriesModel.subType)
  55938. });
  55939. var data = seriesModel.getData();
  55940. if (data.count() > maxDataCnt) {
  55941. // Show part of data
  55942. var partialLabel = labelModel.get(['data', 'partialData']);
  55943. seriesLabel += replace(partialLabel, {
  55944. displayCnt: maxDataCnt
  55945. });
  55946. } else {
  55947. seriesLabel += labelModel.get(['data', 'allData']);
  55948. }
  55949. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  55950. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  55951. var dataLabels = [];
  55952. for (var i = 0; i < data.count(); i++) {
  55953. if (i < maxDataCnt) {
  55954. var name_1 = data.getName(i);
  55955. var value = data.getValues(i);
  55956. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  55957. dataLabels.push(replace(dataLabel, {
  55958. name: name_1,
  55959. value: value.join(middleSeparator_1)
  55960. }));
  55961. }
  55962. }
  55963. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  55964. seriesLabels_1.push(seriesLabel);
  55965. }
  55966. });
  55967. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  55968. var middleSeparator = separatorModel.get('middle');
  55969. var endSeparator = separatorModel.get('end');
  55970. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  55971. dom.setAttribute('aria-label', ariaLabel);
  55972. }
  55973. }
  55974. function replace(str, keyValues) {
  55975. if (!isString(str)) {
  55976. return str;
  55977. }
  55978. var result = str;
  55979. each(keyValues, function (value, key) {
  55980. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  55981. });
  55982. return result;
  55983. }
  55984. function getTitle() {
  55985. var title = ecModel.get('title');
  55986. if (title && title.length) {
  55987. title = title[0];
  55988. }
  55989. return title && title.text;
  55990. }
  55991. function getSeriesTypeName(type) {
  55992. var typeNames = ecModel.getLocaleModel().get(['series', 'typeNames']);
  55993. return typeNames[type] || typeNames.chart;
  55994. }
  55995. }
  55996. function ariaPreprocessor(option) {
  55997. if (!option || !option.aria) {
  55998. return;
  55999. }
  56000. var aria = option.aria;
  56001. // aria.show is deprecated and should use aria.enabled instead
  56002. if (aria.show != null) {
  56003. aria.enabled = aria.show;
  56004. }
  56005. aria.label = aria.label || {};
  56006. // move description, general, series, data to be under aria.label
  56007. each(['description', 'general', 'series', 'data'], function (name) {
  56008. if (aria[name] != null) {
  56009. aria.label[name] = aria[name];
  56010. }
  56011. });
  56012. }
  56013. function install$n(registers) {
  56014. registers.registerPreprocessor(ariaPreprocessor);
  56015. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  56016. }
  56017. var DatasetModel = /** @class */function (_super) {
  56018. __extends(DatasetModel, _super);
  56019. function DatasetModel() {
  56020. var _this = _super !== null && _super.apply(this, arguments) || this;
  56021. _this.type = 'dataset';
  56022. return _this;
  56023. }
  56024. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  56025. _super.prototype.init.call(this, option, parentModel, ecModel);
  56026. this._sourceManager = new SourceManager(this);
  56027. disableTransformOptionMerge(this);
  56028. };
  56029. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  56030. _super.prototype.mergeOption.call(this, newOption, ecModel);
  56031. disableTransformOptionMerge(this);
  56032. };
  56033. DatasetModel.prototype.optionUpdated = function () {
  56034. this._sourceManager.dirty();
  56035. };
  56036. DatasetModel.prototype.getSourceManager = function () {
  56037. return this._sourceManager;
  56038. };
  56039. DatasetModel.type = 'dataset';
  56040. DatasetModel.defaultOption = {
  56041. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  56042. };
  56043. return DatasetModel;
  56044. }(ComponentModel);
  56045. var DatasetView = /** @class */function (_super) {
  56046. __extends(DatasetView, _super);
  56047. function DatasetView() {
  56048. var _this = _super !== null && _super.apply(this, arguments) || this;
  56049. _this.type = 'dataset';
  56050. return _this;
  56051. }
  56052. DatasetView.type = 'dataset';
  56053. return DatasetView;
  56054. }(ComponentView);
  56055. function install$o(registers) {
  56056. registers.registerComponentModel(DatasetModel);
  56057. registers.registerComponentView(DatasetView);
  56058. }
  56059. use([install$1]);
  56060. use([install]);
  56061. use([install$2, install$3, install$4, install$6]);
  56062. 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]);
  56063. exports.Axis = Axis;
  56064. exports.ChartView = ChartView;
  56065. exports.ComponentModel = ComponentModel;
  56066. exports.ComponentView = ComponentView;
  56067. exports.List = SeriesData;
  56068. exports.Model = Model;
  56069. exports.PRIORITY = PRIORITY;
  56070. exports.SeriesModel = SeriesModel;
  56071. exports.color = color;
  56072. exports.connect = connect;
  56073. exports.dataTool = dataTool;
  56074. exports.dependencies = dependencies;
  56075. exports.disConnect = disConnect;
  56076. exports.disconnect = disconnect;
  56077. exports.dispose = dispose$1;
  56078. exports.env = env;
  56079. exports.extendChartView = extendChartView;
  56080. exports.extendComponentModel = extendComponentModel;
  56081. exports.extendComponentView = extendComponentView;
  56082. exports.extendSeriesModel = extendSeriesModel;
  56083. exports.format = format$1;
  56084. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  56085. exports.getInstanceByDom = getInstanceByDom;
  56086. exports.getInstanceById = getInstanceById;
  56087. exports.getMap = getMap;
  56088. exports.graphic = graphic$1;
  56089. exports.helper = helper;
  56090. exports.init = init$1;
  56091. exports.innerDrawElementOnCanvas = brushSingle;
  56092. exports.matrix = matrix;
  56093. exports.number = number;
  56094. exports.parseGeoJSON = parseGeoJSON;
  56095. exports.parseGeoJson = parseGeoJSON;
  56096. exports.registerAction = registerAction;
  56097. exports.registerCoordinateSystem = registerCoordinateSystem;
  56098. exports.registerLayout = registerLayout;
  56099. exports.registerLoading = registerLoading;
  56100. exports.registerLocale = registerLocale;
  56101. exports.registerMap = registerMap;
  56102. exports.registerPostInit = registerPostInit;
  56103. exports.registerPostUpdate = registerPostUpdate;
  56104. exports.registerPreprocessor = registerPreprocessor;
  56105. exports.registerProcessor = registerProcessor;
  56106. exports.registerTheme = registerTheme;
  56107. exports.registerTransform = registerTransform;
  56108. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  56109. exports.registerVisual = registerVisual;
  56110. exports.setCanvasCreator = setCanvasCreator;
  56111. exports.setPlatformAPI = setPlatformAPI;
  56112. exports.throttle = throttle;
  56113. exports.time = time;
  56114. exports.use = use;
  56115. exports.util = util$1;
  56116. exports.vector = vector;
  56117. exports.version = version$1;
  56118. exports.zrUtil = util;
  56119. exports.zrender = zrender;
  56120. Object.defineProperty(exports, '__esModule', { value: true });
  56121. })));
  56122. //# sourceMappingURL=echarts.common.js.map