echarts.common.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. (function (global, factory) {
  20. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  21. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  23. }(this, (function (exports) { 'use strict';
  24. /*! *****************************************************************************
  25. Copyright (c) Microsoft Corporation.
  26. Permission to use, copy, modify, and/or distribute this software for any
  27. purpose with or without fee is hereby granted.
  28. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  30. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. PERFORMANCE OF THIS SOFTWARE.
  35. ***************************************************************************** */
  36. /* global Reflect, Promise */
  37. var extendStatics = function(d, b) {
  38. extendStatics = Object.setPrototypeOf ||
  39. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  40. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  41. return extendStatics(d, b);
  42. };
  43. function __extends(d, b) {
  44. if (typeof b !== "function" && b !== null)
  45. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  46. extendStatics(d, b);
  47. function __() { this.constructor = d; }
  48. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  49. }
  50. var Browser = (function () {
  51. function Browser() {
  52. this.firefox = false;
  53. this.ie = false;
  54. this.edge = false;
  55. this.newEdge = false;
  56. this.weChat = false;
  57. }
  58. return Browser;
  59. }());
  60. var Env = (function () {
  61. function Env() {
  62. this.browser = new Browser();
  63. this.node = false;
  64. this.wxa = false;
  65. this.worker = false;
  66. this.svgSupported = false;
  67. this.touchEventsSupported = false;
  68. this.pointerEventsSupported = false;
  69. this.domSupported = false;
  70. this.transformSupported = false;
  71. this.transform3dSupported = false;
  72. this.hasGlobalWindow = typeof window !== 'undefined';
  73. }
  74. return Env;
  75. }());
  76. var env = new Env();
  77. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  78. env.wxa = true;
  79. env.touchEventsSupported = true;
  80. }
  81. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  82. env.worker = true;
  83. }
  84. else if (!env.hasGlobalWindow
  85. || 'Deno' in window
  86. || (typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string'
  87. && navigator.userAgent.indexOf('Node.js') > -1)) {
  88. env.node = true;
  89. env.svgSupported = true;
  90. }
  91. else {
  92. detect(navigator.userAgent, env);
  93. }
  94. function detect(ua, env) {
  95. var browser = env.browser;
  96. var firefox = ua.match(/Firefox\/([\d.]+)/);
  97. var ie = ua.match(/MSIE\s([\d.]+)/)
  98. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  99. var edge = ua.match(/Edge?\/([\d.]+)/);
  100. var weChat = (/micromessenger/i).test(ua);
  101. if (firefox) {
  102. browser.firefox = true;
  103. browser.version = firefox[1];
  104. }
  105. if (ie) {
  106. browser.ie = true;
  107. browser.version = ie[1];
  108. }
  109. if (edge) {
  110. browser.edge = true;
  111. browser.version = edge[1];
  112. browser.newEdge = +edge[1].split('.')[0] > 18;
  113. }
  114. if (weChat) {
  115. browser.weChat = true;
  116. }
  117. env.svgSupported = typeof SVGRect !== 'undefined';
  118. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  119. env.pointerEventsSupported = 'onpointerdown' in window
  120. && (browser.edge || (browser.ie && +browser.version >= 11));
  121. var domSupported = env.domSupported = typeof document !== 'undefined';
  122. if (domSupported) {
  123. var style = document.documentElement.style;
  124. env.transform3dSupported = ((browser.ie && 'transition' in style)
  125. || browser.edge
  126. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  127. || 'MozPerspective' in style)
  128. && !('OTransition' in style);
  129. env.transformSupported = env.transform3dSupported
  130. || (browser.ie && +browser.version >= 9);
  131. }
  132. }
  133. var DEFAULT_FONT_SIZE = 12;
  134. var DEFAULT_FONT_FAMILY = 'sans-serif';
  135. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  136. var OFFSET = 20;
  137. var SCALE = 100;
  138. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  139. function getTextWidthMap(mapStr) {
  140. var map = {};
  141. if (typeof JSON === 'undefined') {
  142. return map;
  143. }
  144. for (var i = 0; i < mapStr.length; i++) {
  145. var char = String.fromCharCode(i + 32);
  146. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  147. map[char] = size;
  148. }
  149. return map;
  150. }
  151. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  152. var platformApi = {
  153. createCanvas: function () {
  154. return typeof document !== 'undefined'
  155. && document.createElement('canvas');
  156. },
  157. measureText: (function () {
  158. var _ctx;
  159. var _cachedFont;
  160. return function (text, font) {
  161. if (!_ctx) {
  162. var canvas = platformApi.createCanvas();
  163. _ctx = canvas && canvas.getContext('2d');
  164. }
  165. if (_ctx) {
  166. if (_cachedFont !== font) {
  167. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  168. }
  169. return _ctx.measureText(text);
  170. }
  171. else {
  172. text = text || '';
  173. font = font || DEFAULT_FONT;
  174. var res = /((?:\d+)?\.?\d*)px/.exec(font);
  175. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  176. var width = 0;
  177. if (font.indexOf('mono') >= 0) {
  178. width = fontSize * text.length;
  179. }
  180. else {
  181. for (var i = 0; i < text.length; i++) {
  182. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  183. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  184. }
  185. }
  186. return { width: width };
  187. }
  188. };
  189. })(),
  190. loadImage: function (src, onload, onerror) {
  191. var image = new Image();
  192. image.onload = onload;
  193. image.onerror = onerror;
  194. image.src = src;
  195. return image;
  196. }
  197. };
  198. function setPlatformAPI(newPlatformApis) {
  199. for (var key in platformApi) {
  200. if (newPlatformApis[key]) {
  201. platformApi[key] = newPlatformApis[key];
  202. }
  203. }
  204. }
  205. var BUILTIN_OBJECT = reduce([
  206. 'Function',
  207. 'RegExp',
  208. 'Date',
  209. 'Error',
  210. 'CanvasGradient',
  211. 'CanvasPattern',
  212. 'Image',
  213. 'Canvas'
  214. ], function (obj, val) {
  215. obj['[object ' + val + ']'] = true;
  216. return obj;
  217. }, {});
  218. var TYPED_ARRAY = reduce([
  219. 'Int8',
  220. 'Uint8',
  221. 'Uint8Clamped',
  222. 'Int16',
  223. 'Uint16',
  224. 'Int32',
  225. 'Uint32',
  226. 'Float32',
  227. 'Float64'
  228. ], function (obj, val) {
  229. obj['[object ' + val + 'Array]'] = true;
  230. return obj;
  231. }, {});
  232. var objToString = Object.prototype.toString;
  233. var arrayProto = Array.prototype;
  234. var nativeForEach = arrayProto.forEach;
  235. var nativeFilter = arrayProto.filter;
  236. var nativeSlice = arrayProto.slice;
  237. var nativeMap = arrayProto.map;
  238. var ctorFunction = function () { }.constructor;
  239. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  240. var protoKey = '__proto__';
  241. var idStart = 0x0907;
  242. function guid() {
  243. return idStart++;
  244. }
  245. function logError() {
  246. var args = [];
  247. for (var _i = 0; _i < arguments.length; _i++) {
  248. args[_i] = arguments[_i];
  249. }
  250. if (typeof console !== 'undefined') {
  251. console.error.apply(console, args);
  252. }
  253. }
  254. function clone(source) {
  255. if (source == null || typeof source !== 'object') {
  256. return source;
  257. }
  258. var result = source;
  259. var typeStr = objToString.call(source);
  260. if (typeStr === '[object Array]') {
  261. if (!isPrimitive(source)) {
  262. result = [];
  263. for (var i = 0, len = source.length; i < len; i++) {
  264. result[i] = clone(source[i]);
  265. }
  266. }
  267. }
  268. else if (TYPED_ARRAY[typeStr]) {
  269. if (!isPrimitive(source)) {
  270. var Ctor = source.constructor;
  271. if (Ctor.from) {
  272. result = Ctor.from(source);
  273. }
  274. else {
  275. result = new Ctor(source.length);
  276. for (var i = 0, len = source.length; i < len; i++) {
  277. result[i] = source[i];
  278. }
  279. }
  280. }
  281. }
  282. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  283. result = {};
  284. for (var key in source) {
  285. if (source.hasOwnProperty(key) && key !== protoKey) {
  286. result[key] = clone(source[key]);
  287. }
  288. }
  289. }
  290. return result;
  291. }
  292. function merge(target, source, overwrite) {
  293. if (!isObject(source) || !isObject(target)) {
  294. return overwrite ? clone(source) : target;
  295. }
  296. for (var key in source) {
  297. if (source.hasOwnProperty(key) && key !== protoKey) {
  298. var targetProp = target[key];
  299. var sourceProp = source[key];
  300. if (isObject(sourceProp)
  301. && isObject(targetProp)
  302. && !isArray(sourceProp)
  303. && !isArray(targetProp)
  304. && !isDom(sourceProp)
  305. && !isDom(targetProp)
  306. && !isBuiltInObject(sourceProp)
  307. && !isBuiltInObject(targetProp)
  308. && !isPrimitive(sourceProp)
  309. && !isPrimitive(targetProp)) {
  310. merge(targetProp, sourceProp, overwrite);
  311. }
  312. else if (overwrite || !(key in target)) {
  313. target[key] = clone(source[key]);
  314. }
  315. }
  316. }
  317. return target;
  318. }
  319. function mergeAll(targetAndSources, overwrite) {
  320. var result = targetAndSources[0];
  321. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  322. result = merge(result, targetAndSources[i], overwrite);
  323. }
  324. return result;
  325. }
  326. function extend(target, source) {
  327. if (Object.assign) {
  328. Object.assign(target, source);
  329. }
  330. else {
  331. for (var key in source) {
  332. if (source.hasOwnProperty(key) && key !== protoKey) {
  333. target[key] = source[key];
  334. }
  335. }
  336. }
  337. return target;
  338. }
  339. function defaults(target, source, overlay) {
  340. var keysArr = keys(source);
  341. for (var i = 0, len = keysArr.length; i < len; i++) {
  342. var key = keysArr[i];
  343. if ((overlay ? source[key] != null : target[key] == null)) {
  344. target[key] = source[key];
  345. }
  346. }
  347. return target;
  348. }
  349. var createCanvas = platformApi.createCanvas;
  350. function indexOf(array, value) {
  351. if (array) {
  352. if (array.indexOf) {
  353. return array.indexOf(value);
  354. }
  355. for (var i = 0, len = array.length; i < len; i++) {
  356. if (array[i] === value) {
  357. return i;
  358. }
  359. }
  360. }
  361. return -1;
  362. }
  363. function inherits(clazz, baseClazz) {
  364. var clazzPrototype = clazz.prototype;
  365. function F() { }
  366. F.prototype = baseClazz.prototype;
  367. clazz.prototype = new F();
  368. for (var prop in clazzPrototype) {
  369. if (clazzPrototype.hasOwnProperty(prop)) {
  370. clazz.prototype[prop] = clazzPrototype[prop];
  371. }
  372. }
  373. clazz.prototype.constructor = clazz;
  374. clazz.superClass = baseClazz;
  375. }
  376. function mixin(target, source, override) {
  377. target = 'prototype' in target ? target.prototype : target;
  378. source = 'prototype' in source ? source.prototype : source;
  379. if (Object.getOwnPropertyNames) {
  380. var keyList = Object.getOwnPropertyNames(source);
  381. for (var i = 0; i < keyList.length; i++) {
  382. var key = keyList[i];
  383. if (key !== 'constructor') {
  384. if ((override ? source[key] != null : target[key] == null)) {
  385. target[key] = source[key];
  386. }
  387. }
  388. }
  389. }
  390. else {
  391. defaults(target, source, override);
  392. }
  393. }
  394. function isArrayLike(data) {
  395. if (!data) {
  396. return false;
  397. }
  398. if (typeof data === 'string') {
  399. return false;
  400. }
  401. return typeof data.length === 'number';
  402. }
  403. function each(arr, cb, context) {
  404. if (!(arr && cb)) {
  405. return;
  406. }
  407. if (arr.forEach && arr.forEach === nativeForEach) {
  408. arr.forEach(cb, context);
  409. }
  410. else if (arr.length === +arr.length) {
  411. for (var i = 0, len = arr.length; i < len; i++) {
  412. cb.call(context, arr[i], i, arr);
  413. }
  414. }
  415. else {
  416. for (var key in arr) {
  417. if (arr.hasOwnProperty(key)) {
  418. cb.call(context, arr[key], key, arr);
  419. }
  420. }
  421. }
  422. }
  423. function map(arr, cb, context) {
  424. if (!arr) {
  425. return [];
  426. }
  427. if (!cb) {
  428. return slice(arr);
  429. }
  430. if (arr.map && arr.map === nativeMap) {
  431. return arr.map(cb, context);
  432. }
  433. else {
  434. var result = [];
  435. for (var i = 0, len = arr.length; i < len; i++) {
  436. result.push(cb.call(context, arr[i], i, arr));
  437. }
  438. return result;
  439. }
  440. }
  441. function reduce(arr, cb, memo, context) {
  442. if (!(arr && cb)) {
  443. return;
  444. }
  445. for (var i = 0, len = arr.length; i < len; i++) {
  446. memo = cb.call(context, memo, arr[i], i, arr);
  447. }
  448. return memo;
  449. }
  450. function filter(arr, cb, context) {
  451. if (!arr) {
  452. return [];
  453. }
  454. if (!cb) {
  455. return slice(arr);
  456. }
  457. if (arr.filter && arr.filter === nativeFilter) {
  458. return arr.filter(cb, context);
  459. }
  460. else {
  461. var result = [];
  462. for (var i = 0, len = arr.length; i < len; i++) {
  463. if (cb.call(context, arr[i], i, arr)) {
  464. result.push(arr[i]);
  465. }
  466. }
  467. return result;
  468. }
  469. }
  470. function find(arr, cb, context) {
  471. if (!(arr && cb)) {
  472. return;
  473. }
  474. for (var i = 0, len = arr.length; i < len; i++) {
  475. if (cb.call(context, arr[i], i, arr)) {
  476. return arr[i];
  477. }
  478. }
  479. }
  480. function keys(obj) {
  481. if (!obj) {
  482. return [];
  483. }
  484. if (Object.keys) {
  485. return Object.keys(obj);
  486. }
  487. var keyList = [];
  488. for (var key in obj) {
  489. if (obj.hasOwnProperty(key)) {
  490. keyList.push(key);
  491. }
  492. }
  493. return keyList;
  494. }
  495. function bindPolyfill(func, context) {
  496. var args = [];
  497. for (var _i = 2; _i < arguments.length; _i++) {
  498. args[_i - 2] = arguments[_i];
  499. }
  500. return function () {
  501. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  502. };
  503. }
  504. var bind = (protoFunction && isFunction(protoFunction.bind))
  505. ? protoFunction.call.bind(protoFunction.bind)
  506. : bindPolyfill;
  507. function curry(func) {
  508. var args = [];
  509. for (var _i = 1; _i < arguments.length; _i++) {
  510. args[_i - 1] = arguments[_i];
  511. }
  512. return function () {
  513. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  514. };
  515. }
  516. function isArray(value) {
  517. if (Array.isArray) {
  518. return Array.isArray(value);
  519. }
  520. return objToString.call(value) === '[object Array]';
  521. }
  522. function isFunction(value) {
  523. return typeof value === 'function';
  524. }
  525. function isString(value) {
  526. return typeof value === 'string';
  527. }
  528. function isStringSafe(value) {
  529. return objToString.call(value) === '[object String]';
  530. }
  531. function isNumber(value) {
  532. return typeof value === 'number';
  533. }
  534. function isObject(value) {
  535. var type = typeof value;
  536. return type === 'function' || (!!value && type === 'object');
  537. }
  538. function isBuiltInObject(value) {
  539. return !!BUILTIN_OBJECT[objToString.call(value)];
  540. }
  541. function isTypedArray(value) {
  542. return !!TYPED_ARRAY[objToString.call(value)];
  543. }
  544. function isDom(value) {
  545. return typeof value === 'object'
  546. && typeof value.nodeType === 'number'
  547. && typeof value.ownerDocument === 'object';
  548. }
  549. function isGradientObject(value) {
  550. return value.colorStops != null;
  551. }
  552. function isImagePatternObject(value) {
  553. return value.image != null;
  554. }
  555. function isRegExp(value) {
  556. return objToString.call(value) === '[object RegExp]';
  557. }
  558. function eqNaN(value) {
  559. return value !== value;
  560. }
  561. function retrieve() {
  562. var args = [];
  563. for (var _i = 0; _i < arguments.length; _i++) {
  564. args[_i] = arguments[_i];
  565. }
  566. for (var i = 0, len = args.length; i < len; i++) {
  567. if (args[i] != null) {
  568. return args[i];
  569. }
  570. }
  571. }
  572. function retrieve2(value0, value1) {
  573. return value0 != null
  574. ? value0
  575. : value1;
  576. }
  577. function retrieve3(value0, value1, value2) {
  578. return value0 != null
  579. ? value0
  580. : value1 != null
  581. ? value1
  582. : value2;
  583. }
  584. function slice(arr) {
  585. var args = [];
  586. for (var _i = 1; _i < arguments.length; _i++) {
  587. args[_i - 1] = arguments[_i];
  588. }
  589. return nativeSlice.apply(arr, args);
  590. }
  591. function normalizeCssArray(val) {
  592. if (typeof (val) === 'number') {
  593. return [val, val, val, val];
  594. }
  595. var len = val.length;
  596. if (len === 2) {
  597. return [val[0], val[1], val[0], val[1]];
  598. }
  599. else if (len === 3) {
  600. return [val[0], val[1], val[2], val[1]];
  601. }
  602. return val;
  603. }
  604. function assert(condition, message) {
  605. if (!condition) {
  606. throw new Error(message);
  607. }
  608. }
  609. function trim(str) {
  610. if (str == null) {
  611. return null;
  612. }
  613. else if (typeof str.trim === 'function') {
  614. return str.trim();
  615. }
  616. else {
  617. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  618. }
  619. }
  620. var primitiveKey = '__ec_primitive__';
  621. function setAsPrimitive(obj) {
  622. obj[primitiveKey] = true;
  623. }
  624. function isPrimitive(obj) {
  625. return obj[primitiveKey];
  626. }
  627. var MapPolyfill = (function () {
  628. function MapPolyfill() {
  629. this.data = {};
  630. }
  631. MapPolyfill.prototype["delete"] = function (key) {
  632. var existed = this.has(key);
  633. if (existed) {
  634. delete this.data[key];
  635. }
  636. return existed;
  637. };
  638. MapPolyfill.prototype.has = function (key) {
  639. return this.data.hasOwnProperty(key);
  640. };
  641. MapPolyfill.prototype.get = function (key) {
  642. return this.data[key];
  643. };
  644. MapPolyfill.prototype.set = function (key, value) {
  645. this.data[key] = value;
  646. return this;
  647. };
  648. MapPolyfill.prototype.keys = function () {
  649. return keys(this.data);
  650. };
  651. MapPolyfill.prototype.forEach = function (callback) {
  652. var data = this.data;
  653. for (var key in data) {
  654. if (data.hasOwnProperty(key)) {
  655. callback(data[key], key);
  656. }
  657. }
  658. };
  659. return MapPolyfill;
  660. }());
  661. var isNativeMapSupported = typeof Map === 'function';
  662. function maybeNativeMap() {
  663. return (isNativeMapSupported ? new Map() : new MapPolyfill());
  664. }
  665. var HashMap = (function () {
  666. function HashMap(obj) {
  667. var isArr = isArray(obj);
  668. this.data = maybeNativeMap();
  669. var thisMap = this;
  670. (obj instanceof HashMap)
  671. ? obj.each(visit)
  672. : (obj && each(obj, visit));
  673. function visit(value, key) {
  674. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  675. }
  676. }
  677. HashMap.prototype.hasKey = function (key) {
  678. return this.data.has(key);
  679. };
  680. HashMap.prototype.get = function (key) {
  681. return this.data.get(key);
  682. };
  683. HashMap.prototype.set = function (key, value) {
  684. this.data.set(key, value);
  685. return value;
  686. };
  687. HashMap.prototype.each = function (cb, context) {
  688. this.data.forEach(function (value, key) {
  689. cb.call(context, value, key);
  690. });
  691. };
  692. HashMap.prototype.keys = function () {
  693. var keys = this.data.keys();
  694. return isNativeMapSupported
  695. ? Array.from(keys)
  696. : keys;
  697. };
  698. HashMap.prototype.removeKey = function (key) {
  699. this.data["delete"](key);
  700. };
  701. return HashMap;
  702. }());
  703. function createHashMap(obj) {
  704. return new HashMap(obj);
  705. }
  706. function concatArray(a, b) {
  707. var newArray = new a.constructor(a.length + b.length);
  708. for (var i = 0; i < a.length; i++) {
  709. newArray[i] = a[i];
  710. }
  711. var offset = a.length;
  712. for (var i = 0; i < b.length; i++) {
  713. newArray[i + offset] = b[i];
  714. }
  715. return newArray;
  716. }
  717. function createObject(proto, properties) {
  718. var obj;
  719. if (Object.create) {
  720. obj = Object.create(proto);
  721. }
  722. else {
  723. var StyleCtor = function () { };
  724. StyleCtor.prototype = proto;
  725. obj = new StyleCtor();
  726. }
  727. if (properties) {
  728. extend(obj, properties);
  729. }
  730. return obj;
  731. }
  732. function disableUserSelect(dom) {
  733. var domStyle = dom.style;
  734. domStyle.webkitUserSelect = 'none';
  735. domStyle.userSelect = 'none';
  736. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  737. domStyle['-webkit-touch-callout'] = 'none';
  738. }
  739. function hasOwn(own, prop) {
  740. return own.hasOwnProperty(prop);
  741. }
  742. function noop() { }
  743. var RADIAN_TO_DEGREE = 180 / Math.PI;
  744. var EPSILON = Number.EPSILON || Math.pow(2, -52);
  745. var util = /*#__PURE__*/Object.freeze({
  746. __proto__: null,
  747. guid: guid,
  748. logError: logError,
  749. clone: clone,
  750. merge: merge,
  751. mergeAll: mergeAll,
  752. extend: extend,
  753. defaults: defaults,
  754. createCanvas: createCanvas,
  755. indexOf: indexOf,
  756. inherits: inherits,
  757. mixin: mixin,
  758. isArrayLike: isArrayLike,
  759. each: each,
  760. map: map,
  761. reduce: reduce,
  762. filter: filter,
  763. find: find,
  764. keys: keys,
  765. bind: bind,
  766. curry: curry,
  767. isArray: isArray,
  768. isFunction: isFunction,
  769. isString: isString,
  770. isStringSafe: isStringSafe,
  771. isNumber: isNumber,
  772. isObject: isObject,
  773. isBuiltInObject: isBuiltInObject,
  774. isTypedArray: isTypedArray,
  775. isDom: isDom,
  776. isGradientObject: isGradientObject,
  777. isImagePatternObject: isImagePatternObject,
  778. isRegExp: isRegExp,
  779. eqNaN: eqNaN,
  780. retrieve: retrieve,
  781. retrieve2: retrieve2,
  782. retrieve3: retrieve3,
  783. slice: slice,
  784. normalizeCssArray: normalizeCssArray,
  785. assert: assert,
  786. trim: trim,
  787. setAsPrimitive: setAsPrimitive,
  788. isPrimitive: isPrimitive,
  789. HashMap: HashMap,
  790. createHashMap: createHashMap,
  791. concatArray: concatArray,
  792. createObject: createObject,
  793. disableUserSelect: disableUserSelect,
  794. hasOwn: hasOwn,
  795. noop: noop,
  796. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE,
  797. EPSILON: EPSILON
  798. });
  799. function create(x, y) {
  800. if (x == null) {
  801. x = 0;
  802. }
  803. if (y == null) {
  804. y = 0;
  805. }
  806. return [x, y];
  807. }
  808. function copy(out, v) {
  809. out[0] = v[0];
  810. out[1] = v[1];
  811. return out;
  812. }
  813. function clone$1(v) {
  814. return [v[0], v[1]];
  815. }
  816. function set(out, a, b) {
  817. out[0] = a;
  818. out[1] = b;
  819. return out;
  820. }
  821. function add(out, v1, v2) {
  822. out[0] = v1[0] + v2[0];
  823. out[1] = v1[1] + v2[1];
  824. return out;
  825. }
  826. function scaleAndAdd(out, v1, v2, a) {
  827. out[0] = v1[0] + v2[0] * a;
  828. out[1] = v1[1] + v2[1] * a;
  829. return out;
  830. }
  831. function sub(out, v1, v2) {
  832. out[0] = v1[0] - v2[0];
  833. out[1] = v1[1] - v2[1];
  834. return out;
  835. }
  836. function len(v) {
  837. return Math.sqrt(lenSquare(v));
  838. }
  839. var length = len;
  840. function lenSquare(v) {
  841. return v[0] * v[0] + v[1] * v[1];
  842. }
  843. var lengthSquare = lenSquare;
  844. function mul(out, v1, v2) {
  845. out[0] = v1[0] * v2[0];
  846. out[1] = v1[1] * v2[1];
  847. return out;
  848. }
  849. function div(out, v1, v2) {
  850. out[0] = v1[0] / v2[0];
  851. out[1] = v1[1] / v2[1];
  852. return out;
  853. }
  854. function dot(v1, v2) {
  855. return v1[0] * v2[0] + v1[1] * v2[1];
  856. }
  857. function scale(out, v, s) {
  858. out[0] = v[0] * s;
  859. out[1] = v[1] * s;
  860. return out;
  861. }
  862. function normalize(out, v) {
  863. var d = len(v);
  864. if (d === 0) {
  865. out[0] = 0;
  866. out[1] = 0;
  867. }
  868. else {
  869. out[0] = v[0] / d;
  870. out[1] = v[1] / d;
  871. }
  872. return out;
  873. }
  874. function distance(v1, v2) {
  875. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  876. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  877. }
  878. var dist = distance;
  879. function distanceSquare(v1, v2) {
  880. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  881. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  882. }
  883. var distSquare = distanceSquare;
  884. function negate(out, v) {
  885. out[0] = -v[0];
  886. out[1] = -v[1];
  887. return out;
  888. }
  889. function lerp(out, v1, v2, t) {
  890. out[0] = v1[0] + t * (v2[0] - v1[0]);
  891. out[1] = v1[1] + t * (v2[1] - v1[1]);
  892. return out;
  893. }
  894. function applyTransform(out, v, m) {
  895. var x = v[0];
  896. var y = v[1];
  897. out[0] = m[0] * x + m[2] * y + m[4];
  898. out[1] = m[1] * x + m[3] * y + m[5];
  899. return out;
  900. }
  901. function min(out, v1, v2) {
  902. out[0] = Math.min(v1[0], v2[0]);
  903. out[1] = Math.min(v1[1], v2[1]);
  904. return out;
  905. }
  906. function max(out, v1, v2) {
  907. out[0] = Math.max(v1[0], v2[0]);
  908. out[1] = Math.max(v1[1], v2[1]);
  909. return out;
  910. }
  911. var vector = /*#__PURE__*/Object.freeze({
  912. __proto__: null,
  913. create: create,
  914. copy: copy,
  915. clone: clone$1,
  916. set: set,
  917. add: add,
  918. scaleAndAdd: scaleAndAdd,
  919. sub: sub,
  920. len: len,
  921. length: length,
  922. lenSquare: lenSquare,
  923. lengthSquare: lengthSquare,
  924. mul: mul,
  925. div: div,
  926. dot: dot,
  927. scale: scale,
  928. normalize: normalize,
  929. distance: distance,
  930. dist: dist,
  931. distanceSquare: distanceSquare,
  932. distSquare: distSquare,
  933. negate: negate,
  934. lerp: lerp,
  935. applyTransform: applyTransform,
  936. min: min,
  937. max: max
  938. });
  939. var Param = (function () {
  940. function Param(target, e) {
  941. this.target = target;
  942. this.topTarget = e && e.topTarget;
  943. }
  944. return Param;
  945. }());
  946. var Draggable = (function () {
  947. function Draggable(handler) {
  948. this.handler = handler;
  949. handler.on('mousedown', this._dragStart, this);
  950. handler.on('mousemove', this._drag, this);
  951. handler.on('mouseup', this._dragEnd, this);
  952. }
  953. Draggable.prototype._dragStart = function (e) {
  954. var draggingTarget = e.target;
  955. while (draggingTarget && !draggingTarget.draggable) {
  956. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  957. }
  958. if (draggingTarget) {
  959. this._draggingTarget = draggingTarget;
  960. draggingTarget.dragging = true;
  961. this._x = e.offsetX;
  962. this._y = e.offsetY;
  963. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  964. }
  965. };
  966. Draggable.prototype._drag = function (e) {
  967. var draggingTarget = this._draggingTarget;
  968. if (draggingTarget) {
  969. var x = e.offsetX;
  970. var y = e.offsetY;
  971. var dx = x - this._x;
  972. var dy = y - this._y;
  973. this._x = x;
  974. this._y = y;
  975. draggingTarget.drift(dx, dy, e);
  976. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  977. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  978. var lastDropTarget = this._dropTarget;
  979. this._dropTarget = dropTarget;
  980. if (draggingTarget !== dropTarget) {
  981. if (lastDropTarget && dropTarget !== lastDropTarget) {
  982. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  983. }
  984. if (dropTarget && dropTarget !== lastDropTarget) {
  985. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  986. }
  987. }
  988. }
  989. };
  990. Draggable.prototype._dragEnd = function (e) {
  991. var draggingTarget = this._draggingTarget;
  992. if (draggingTarget) {
  993. draggingTarget.dragging = false;
  994. }
  995. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  996. if (this._dropTarget) {
  997. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  998. }
  999. this._draggingTarget = null;
  1000. this._dropTarget = null;
  1001. };
  1002. return Draggable;
  1003. }());
  1004. var Eventful = (function () {
  1005. function Eventful(eventProcessors) {
  1006. if (eventProcessors) {
  1007. this._$eventProcessor = eventProcessors;
  1008. }
  1009. }
  1010. Eventful.prototype.on = function (event, query, handler, context) {
  1011. if (!this._$handlers) {
  1012. this._$handlers = {};
  1013. }
  1014. var _h = this._$handlers;
  1015. if (typeof query === 'function') {
  1016. context = handler;
  1017. handler = query;
  1018. query = null;
  1019. }
  1020. if (!handler || !event) {
  1021. return this;
  1022. }
  1023. var eventProcessor = this._$eventProcessor;
  1024. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1025. query = eventProcessor.normalizeQuery(query);
  1026. }
  1027. if (!_h[event]) {
  1028. _h[event] = [];
  1029. }
  1030. for (var i = 0; i < _h[event].length; i++) {
  1031. if (_h[event][i].h === handler) {
  1032. return this;
  1033. }
  1034. }
  1035. var wrap = {
  1036. h: handler,
  1037. query: query,
  1038. ctx: (context || this),
  1039. callAtLast: handler.zrEventfulCallAtLast
  1040. };
  1041. var lastIndex = _h[event].length - 1;
  1042. var lastWrap = _h[event][lastIndex];
  1043. (lastWrap && lastWrap.callAtLast)
  1044. ? _h[event].splice(lastIndex, 0, wrap)
  1045. : _h[event].push(wrap);
  1046. return this;
  1047. };
  1048. Eventful.prototype.isSilent = function (eventName) {
  1049. var _h = this._$handlers;
  1050. return !_h || !_h[eventName] || !_h[eventName].length;
  1051. };
  1052. Eventful.prototype.off = function (eventType, handler) {
  1053. var _h = this._$handlers;
  1054. if (!_h) {
  1055. return this;
  1056. }
  1057. if (!eventType) {
  1058. this._$handlers = {};
  1059. return this;
  1060. }
  1061. if (handler) {
  1062. if (_h[eventType]) {
  1063. var newList = [];
  1064. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1065. if (_h[eventType][i].h !== handler) {
  1066. newList.push(_h[eventType][i]);
  1067. }
  1068. }
  1069. _h[eventType] = newList;
  1070. }
  1071. if (_h[eventType] && _h[eventType].length === 0) {
  1072. delete _h[eventType];
  1073. }
  1074. }
  1075. else {
  1076. delete _h[eventType];
  1077. }
  1078. return this;
  1079. };
  1080. Eventful.prototype.trigger = function (eventType) {
  1081. var args = [];
  1082. for (var _i = 1; _i < arguments.length; _i++) {
  1083. args[_i - 1] = arguments[_i];
  1084. }
  1085. if (!this._$handlers) {
  1086. return this;
  1087. }
  1088. var _h = this._$handlers[eventType];
  1089. var eventProcessor = this._$eventProcessor;
  1090. if (_h) {
  1091. var argLen = args.length;
  1092. var len = _h.length;
  1093. for (var i = 0; i < len; i++) {
  1094. var hItem = _h[i];
  1095. if (eventProcessor
  1096. && eventProcessor.filter
  1097. && hItem.query != null
  1098. && !eventProcessor.filter(eventType, hItem.query)) {
  1099. continue;
  1100. }
  1101. switch (argLen) {
  1102. case 0:
  1103. hItem.h.call(hItem.ctx);
  1104. break;
  1105. case 1:
  1106. hItem.h.call(hItem.ctx, args[0]);
  1107. break;
  1108. case 2:
  1109. hItem.h.call(hItem.ctx, args[0], args[1]);
  1110. break;
  1111. default:
  1112. hItem.h.apply(hItem.ctx, args);
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. eventProcessor && eventProcessor.afterTrigger
  1118. && eventProcessor.afterTrigger(eventType);
  1119. return this;
  1120. };
  1121. Eventful.prototype.triggerWithContext = function (type) {
  1122. var args = [];
  1123. for (var _i = 1; _i < arguments.length; _i++) {
  1124. args[_i - 1] = arguments[_i];
  1125. }
  1126. if (!this._$handlers) {
  1127. return this;
  1128. }
  1129. var _h = this._$handlers[type];
  1130. var eventProcessor = this._$eventProcessor;
  1131. if (_h) {
  1132. var argLen = args.length;
  1133. var ctx = args[argLen - 1];
  1134. var len = _h.length;
  1135. for (var i = 0; i < len; i++) {
  1136. var hItem = _h[i];
  1137. if (eventProcessor
  1138. && eventProcessor.filter
  1139. && hItem.query != null
  1140. && !eventProcessor.filter(type, hItem.query)) {
  1141. continue;
  1142. }
  1143. switch (argLen) {
  1144. case 0:
  1145. hItem.h.call(ctx);
  1146. break;
  1147. case 1:
  1148. hItem.h.call(ctx, args[0]);
  1149. break;
  1150. case 2:
  1151. hItem.h.call(ctx, args[0], args[1]);
  1152. break;
  1153. default:
  1154. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1155. break;
  1156. }
  1157. }
  1158. }
  1159. eventProcessor && eventProcessor.afterTrigger
  1160. && eventProcessor.afterTrigger(type);
  1161. return this;
  1162. };
  1163. return Eventful;
  1164. }());
  1165. var LN2 = Math.log(2);
  1166. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1167. var cacheKey = rowMask + '-' + colMask;
  1168. var fullRank = rows.length;
  1169. if (detCache.hasOwnProperty(cacheKey)) {
  1170. return detCache[cacheKey];
  1171. }
  1172. if (rank === 1) {
  1173. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1174. return rows[rowStart][colStart];
  1175. }
  1176. var subRowMask = rowMask | (1 << rowStart);
  1177. var subRowStart = rowStart + 1;
  1178. while (rowMask & (1 << subRowStart)) {
  1179. subRowStart++;
  1180. }
  1181. var sum = 0;
  1182. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1183. var colTag = 1 << j;
  1184. if (!(colTag & colMask)) {
  1185. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1186. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1187. colLocalIdx++;
  1188. }
  1189. }
  1190. detCache[cacheKey] = sum;
  1191. return sum;
  1192. }
  1193. function buildTransformer(src, dest) {
  1194. var mA = [
  1195. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1196. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1197. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1198. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1199. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1200. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1201. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1202. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1203. ];
  1204. var detCache = {};
  1205. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1206. if (det === 0) {
  1207. return;
  1208. }
  1209. var vh = [];
  1210. for (var i = 0; i < 8; i++) {
  1211. for (var j = 0; j < 8; j++) {
  1212. vh[j] == null && (vh[j] = 0);
  1213. vh[j] += ((i + j) % 2 ? -1 : 1)
  1214. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1215. / det * dest[i];
  1216. }
  1217. }
  1218. return function (out, srcPointX, srcPointY) {
  1219. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1220. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1221. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1222. };
  1223. }
  1224. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1225. var _calcOut = [];
  1226. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1227. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1228. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1229. }
  1230. function transformLocalCoordClear(elFrom, elTarget) {
  1231. elFrom && dealClear(elFrom);
  1232. elTarget && dealClear(elTarget);
  1233. function dealClear(el) {
  1234. var saved = el[EVENT_SAVED_PROP];
  1235. if (saved) {
  1236. saved.clearMarkers && saved.clearMarkers();
  1237. delete el[EVENT_SAVED_PROP];
  1238. }
  1239. }
  1240. }
  1241. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1242. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1243. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1244. var markers = prepareCoordMarkers(el, saved);
  1245. var transformer = preparePointerTransformer(markers, saved, inverse);
  1246. if (transformer) {
  1247. transformer(out, inX, inY);
  1248. return true;
  1249. }
  1250. }
  1251. return false;
  1252. }
  1253. function prepareCoordMarkers(el, saved) {
  1254. var markers = saved.markers;
  1255. if (markers) {
  1256. return markers;
  1257. }
  1258. markers = saved.markers = [];
  1259. var propLR = ['left', 'right'];
  1260. var propTB = ['top', 'bottom'];
  1261. for (var i = 0; i < 4; i++) {
  1262. var marker = document.createElement('div');
  1263. var stl = marker.style;
  1264. var idxLR = i % 2;
  1265. var idxTB = (i >> 1) % 2;
  1266. stl.cssText = [
  1267. 'position: absolute',
  1268. 'visibility: hidden',
  1269. 'padding: 0',
  1270. 'margin: 0',
  1271. 'border-width: 0',
  1272. 'user-select: none',
  1273. 'width:0',
  1274. 'height:0',
  1275. propLR[idxLR] + ':0',
  1276. propTB[idxTB] + ':0',
  1277. propLR[1 - idxLR] + ':auto',
  1278. propTB[1 - idxTB] + ':auto',
  1279. ''
  1280. ].join('!important;');
  1281. el.appendChild(marker);
  1282. markers.push(marker);
  1283. }
  1284. saved.clearMarkers = function () {
  1285. each(markers, function (marker) {
  1286. marker.parentNode && marker.parentNode.removeChild(marker);
  1287. });
  1288. };
  1289. return markers;
  1290. }
  1291. function preparePointerTransformer(markers, saved, inverse) {
  1292. var transformerName = inverse ? 'invTrans' : 'trans';
  1293. var transformer = saved[transformerName];
  1294. var oldSrcCoords = saved.srcCoords;
  1295. var srcCoords = [];
  1296. var destCoords = [];
  1297. var oldCoordTheSame = true;
  1298. for (var i = 0; i < 4; i++) {
  1299. var rect = markers[i].getBoundingClientRect();
  1300. var ii = 2 * i;
  1301. var x = rect.left;
  1302. var y = rect.top;
  1303. srcCoords.push(x, y);
  1304. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1305. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1306. }
  1307. return (oldCoordTheSame && transformer)
  1308. ? transformer
  1309. : (saved.srcCoords = srcCoords,
  1310. saved[transformerName] = inverse
  1311. ? buildTransformer(destCoords, srcCoords)
  1312. : buildTransformer(srcCoords, destCoords));
  1313. }
  1314. function isCanvasEl(el) {
  1315. return el.nodeName.toUpperCase() === 'CANVAS';
  1316. }
  1317. var replaceReg = /([&<>"'])/g;
  1318. var replaceMap = {
  1319. '&': '&amp;',
  1320. '<': '&lt;',
  1321. '>': '&gt;',
  1322. '"': '&quot;',
  1323. '\'': '&#39;'
  1324. };
  1325. function encodeHTML(source) {
  1326. return source == null
  1327. ? ''
  1328. : (source + '').replace(replaceReg, function (str, c) {
  1329. return replaceMap[c];
  1330. });
  1331. }
  1332. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1333. var _calcOut$1 = [];
  1334. var firefoxNotSupportOffsetXY = env.browser.firefox
  1335. && +env.browser.version.split('.')[0] < 39;
  1336. function clientToLocal(el, e, out, calculate) {
  1337. out = out || {};
  1338. if (calculate) {
  1339. calculateZrXY(el, e, out);
  1340. }
  1341. else if (firefoxNotSupportOffsetXY
  1342. && e.layerX != null
  1343. && e.layerX !== e.offsetX) {
  1344. out.zrX = e.layerX;
  1345. out.zrY = e.layerY;
  1346. }
  1347. else if (e.offsetX != null) {
  1348. out.zrX = e.offsetX;
  1349. out.zrY = e.offsetY;
  1350. }
  1351. else {
  1352. calculateZrXY(el, e, out);
  1353. }
  1354. return out;
  1355. }
  1356. function calculateZrXY(el, e, out) {
  1357. if (env.domSupported && el.getBoundingClientRect) {
  1358. var ex = e.clientX;
  1359. var ey = e.clientY;
  1360. if (isCanvasEl(el)) {
  1361. var box = el.getBoundingClientRect();
  1362. out.zrX = ex - box.left;
  1363. out.zrY = ey - box.top;
  1364. return;
  1365. }
  1366. else {
  1367. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1368. out.zrX = _calcOut$1[0];
  1369. out.zrY = _calcOut$1[1];
  1370. return;
  1371. }
  1372. }
  1373. }
  1374. out.zrX = out.zrY = 0;
  1375. }
  1376. function getNativeEvent(e) {
  1377. return e
  1378. || window.event;
  1379. }
  1380. function normalizeEvent(el, e, calculate) {
  1381. e = getNativeEvent(e);
  1382. if (e.zrX != null) {
  1383. return e;
  1384. }
  1385. var eventType = e.type;
  1386. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1387. if (!isTouch) {
  1388. clientToLocal(el, e, e, calculate);
  1389. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1390. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1391. }
  1392. else {
  1393. var touch = eventType !== 'touchend'
  1394. ? e.targetTouches[0]
  1395. : e.changedTouches[0];
  1396. touch && clientToLocal(el, touch, e, calculate);
  1397. }
  1398. var button = e.button;
  1399. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1400. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1401. }
  1402. return e;
  1403. }
  1404. function getWheelDeltaMayPolyfill(e) {
  1405. var rawWheelDelta = e.wheelDelta;
  1406. if (rawWheelDelta) {
  1407. return rawWheelDelta;
  1408. }
  1409. var deltaX = e.deltaX;
  1410. var deltaY = e.deltaY;
  1411. if (deltaX == null || deltaY == null) {
  1412. return rawWheelDelta;
  1413. }
  1414. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1415. var sign = deltaY > 0 ? -1
  1416. : deltaY < 0 ? 1
  1417. : deltaX > 0 ? -1
  1418. : 1;
  1419. return 3 * delta * sign;
  1420. }
  1421. function addEventListener(el, name, handler, opt) {
  1422. el.addEventListener(name, handler, opt);
  1423. }
  1424. function removeEventListener(el, name, handler, opt) {
  1425. el.removeEventListener(name, handler, opt);
  1426. }
  1427. var stop = function (e) {
  1428. e.preventDefault();
  1429. e.stopPropagation();
  1430. e.cancelBubble = true;
  1431. };
  1432. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1433. return e.which === 2 || e.which === 3;
  1434. }
  1435. var GestureMgr = (function () {
  1436. function GestureMgr() {
  1437. this._track = [];
  1438. }
  1439. GestureMgr.prototype.recognize = function (event, target, root) {
  1440. this._doTrack(event, target, root);
  1441. return this._recognize(event);
  1442. };
  1443. GestureMgr.prototype.clear = function () {
  1444. this._track.length = 0;
  1445. return this;
  1446. };
  1447. GestureMgr.prototype._doTrack = function (event, target, root) {
  1448. var touches = event.touches;
  1449. if (!touches) {
  1450. return;
  1451. }
  1452. var trackItem = {
  1453. points: [],
  1454. touches: [],
  1455. target: target,
  1456. event: event
  1457. };
  1458. for (var i = 0, len = touches.length; i < len; i++) {
  1459. var touch = touches[i];
  1460. var pos = clientToLocal(root, touch, {});
  1461. trackItem.points.push([pos.zrX, pos.zrY]);
  1462. trackItem.touches.push(touch);
  1463. }
  1464. this._track.push(trackItem);
  1465. };
  1466. GestureMgr.prototype._recognize = function (event) {
  1467. for (var eventName in recognizers) {
  1468. if (recognizers.hasOwnProperty(eventName)) {
  1469. var gestureInfo = recognizers[eventName](this._track, event);
  1470. if (gestureInfo) {
  1471. return gestureInfo;
  1472. }
  1473. }
  1474. }
  1475. };
  1476. return GestureMgr;
  1477. }());
  1478. function dist$1(pointPair) {
  1479. var dx = pointPair[1][0] - pointPair[0][0];
  1480. var dy = pointPair[1][1] - pointPair[0][1];
  1481. return Math.sqrt(dx * dx + dy * dy);
  1482. }
  1483. function center(pointPair) {
  1484. return [
  1485. (pointPair[0][0] + pointPair[1][0]) / 2,
  1486. (pointPair[0][1] + pointPair[1][1]) / 2
  1487. ];
  1488. }
  1489. var recognizers = {
  1490. pinch: function (tracks, event) {
  1491. var trackLen = tracks.length;
  1492. if (!trackLen) {
  1493. return;
  1494. }
  1495. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1496. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1497. if (pinchPre
  1498. && pinchPre.length > 1
  1499. && pinchEnd
  1500. && pinchEnd.length > 1) {
  1501. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1502. !isFinite(pinchScale) && (pinchScale = 1);
  1503. event.pinchScale = pinchScale;
  1504. var pinchCenter = center(pinchEnd);
  1505. event.pinchX = pinchCenter[0];
  1506. event.pinchY = pinchCenter[1];
  1507. return {
  1508. type: 'pinch',
  1509. target: tracks[0].target,
  1510. event: event
  1511. };
  1512. }
  1513. }
  1514. };
  1515. function create$1() {
  1516. return [1, 0, 0, 1, 0, 0];
  1517. }
  1518. function identity(out) {
  1519. out[0] = 1;
  1520. out[1] = 0;
  1521. out[2] = 0;
  1522. out[3] = 1;
  1523. out[4] = 0;
  1524. out[5] = 0;
  1525. return out;
  1526. }
  1527. function copy$1(out, m) {
  1528. out[0] = m[0];
  1529. out[1] = m[1];
  1530. out[2] = m[2];
  1531. out[3] = m[3];
  1532. out[4] = m[4];
  1533. out[5] = m[5];
  1534. return out;
  1535. }
  1536. function mul$1(out, m1, m2) {
  1537. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1538. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1539. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1540. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1541. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1542. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1543. out[0] = out0;
  1544. out[1] = out1;
  1545. out[2] = out2;
  1546. out[3] = out3;
  1547. out[4] = out4;
  1548. out[5] = out5;
  1549. return out;
  1550. }
  1551. function translate(out, a, v) {
  1552. out[0] = a[0];
  1553. out[1] = a[1];
  1554. out[2] = a[2];
  1555. out[3] = a[3];
  1556. out[4] = a[4] + v[0];
  1557. out[5] = a[5] + v[1];
  1558. return out;
  1559. }
  1560. function rotate(out, a, rad, pivot) {
  1561. if (pivot === void 0) { pivot = [0, 0]; }
  1562. var aa = a[0];
  1563. var ac = a[2];
  1564. var atx = a[4];
  1565. var ab = a[1];
  1566. var ad = a[3];
  1567. var aty = a[5];
  1568. var st = Math.sin(rad);
  1569. var ct = Math.cos(rad);
  1570. out[0] = aa * ct + ab * st;
  1571. out[1] = -aa * st + ab * ct;
  1572. out[2] = ac * ct + ad * st;
  1573. out[3] = -ac * st + ct * ad;
  1574. out[4] = ct * (atx - pivot[0]) + st * (aty - pivot[1]) + pivot[0];
  1575. out[5] = ct * (aty - pivot[1]) - st * (atx - pivot[0]) + pivot[1];
  1576. return out;
  1577. }
  1578. function scale$1(out, a, v) {
  1579. var vx = v[0];
  1580. var vy = v[1];
  1581. out[0] = a[0] * vx;
  1582. out[1] = a[1] * vy;
  1583. out[2] = a[2] * vx;
  1584. out[3] = a[3] * vy;
  1585. out[4] = a[4] * vx;
  1586. out[5] = a[5] * vy;
  1587. return out;
  1588. }
  1589. function invert(out, a) {
  1590. var aa = a[0];
  1591. var ac = a[2];
  1592. var atx = a[4];
  1593. var ab = a[1];
  1594. var ad = a[3];
  1595. var aty = a[5];
  1596. var det = aa * ad - ab * ac;
  1597. if (!det) {
  1598. return null;
  1599. }
  1600. det = 1.0 / det;
  1601. out[0] = ad * det;
  1602. out[1] = -ab * det;
  1603. out[2] = -ac * det;
  1604. out[3] = aa * det;
  1605. out[4] = (ac * aty - ad * atx) * det;
  1606. out[5] = (ab * atx - aa * aty) * det;
  1607. return out;
  1608. }
  1609. function clone$2(a) {
  1610. var b = create$1();
  1611. copy$1(b, a);
  1612. return b;
  1613. }
  1614. var matrix = /*#__PURE__*/Object.freeze({
  1615. __proto__: null,
  1616. create: create$1,
  1617. identity: identity,
  1618. copy: copy$1,
  1619. mul: mul$1,
  1620. translate: translate,
  1621. rotate: rotate,
  1622. scale: scale$1,
  1623. invert: invert,
  1624. clone: clone$2
  1625. });
  1626. var Point = (function () {
  1627. function Point(x, y) {
  1628. this.x = x || 0;
  1629. this.y = y || 0;
  1630. }
  1631. Point.prototype.copy = function (other) {
  1632. this.x = other.x;
  1633. this.y = other.y;
  1634. return this;
  1635. };
  1636. Point.prototype.clone = function () {
  1637. return new Point(this.x, this.y);
  1638. };
  1639. Point.prototype.set = function (x, y) {
  1640. this.x = x;
  1641. this.y = y;
  1642. return this;
  1643. };
  1644. Point.prototype.equal = function (other) {
  1645. return other.x === this.x && other.y === this.y;
  1646. };
  1647. Point.prototype.add = function (other) {
  1648. this.x += other.x;
  1649. this.y += other.y;
  1650. return this;
  1651. };
  1652. Point.prototype.scale = function (scalar) {
  1653. this.x *= scalar;
  1654. this.y *= scalar;
  1655. };
  1656. Point.prototype.scaleAndAdd = function (other, scalar) {
  1657. this.x += other.x * scalar;
  1658. this.y += other.y * scalar;
  1659. };
  1660. Point.prototype.sub = function (other) {
  1661. this.x -= other.x;
  1662. this.y -= other.y;
  1663. return this;
  1664. };
  1665. Point.prototype.dot = function (other) {
  1666. return this.x * other.x + this.y * other.y;
  1667. };
  1668. Point.prototype.len = function () {
  1669. return Math.sqrt(this.x * this.x + this.y * this.y);
  1670. };
  1671. Point.prototype.lenSquare = function () {
  1672. return this.x * this.x + this.y * this.y;
  1673. };
  1674. Point.prototype.normalize = function () {
  1675. var len = this.len();
  1676. this.x /= len;
  1677. this.y /= len;
  1678. return this;
  1679. };
  1680. Point.prototype.distance = function (other) {
  1681. var dx = this.x - other.x;
  1682. var dy = this.y - other.y;
  1683. return Math.sqrt(dx * dx + dy * dy);
  1684. };
  1685. Point.prototype.distanceSquare = function (other) {
  1686. var dx = this.x - other.x;
  1687. var dy = this.y - other.y;
  1688. return dx * dx + dy * dy;
  1689. };
  1690. Point.prototype.negate = function () {
  1691. this.x = -this.x;
  1692. this.y = -this.y;
  1693. return this;
  1694. };
  1695. Point.prototype.transform = function (m) {
  1696. if (!m) {
  1697. return;
  1698. }
  1699. var x = this.x;
  1700. var y = this.y;
  1701. this.x = m[0] * x + m[2] * y + m[4];
  1702. this.y = m[1] * x + m[3] * y + m[5];
  1703. return this;
  1704. };
  1705. Point.prototype.toArray = function (out) {
  1706. out[0] = this.x;
  1707. out[1] = this.y;
  1708. return out;
  1709. };
  1710. Point.prototype.fromArray = function (input) {
  1711. this.x = input[0];
  1712. this.y = input[1];
  1713. };
  1714. Point.set = function (p, x, y) {
  1715. p.x = x;
  1716. p.y = y;
  1717. };
  1718. Point.copy = function (p, p2) {
  1719. p.x = p2.x;
  1720. p.y = p2.y;
  1721. };
  1722. Point.len = function (p) {
  1723. return Math.sqrt(p.x * p.x + p.y * p.y);
  1724. };
  1725. Point.lenSquare = function (p) {
  1726. return p.x * p.x + p.y * p.y;
  1727. };
  1728. Point.dot = function (p0, p1) {
  1729. return p0.x * p1.x + p0.y * p1.y;
  1730. };
  1731. Point.add = function (out, p0, p1) {
  1732. out.x = p0.x + p1.x;
  1733. out.y = p0.y + p1.y;
  1734. };
  1735. Point.sub = function (out, p0, p1) {
  1736. out.x = p0.x - p1.x;
  1737. out.y = p0.y - p1.y;
  1738. };
  1739. Point.scale = function (out, p0, scalar) {
  1740. out.x = p0.x * scalar;
  1741. out.y = p0.y * scalar;
  1742. };
  1743. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1744. out.x = p0.x + p1.x * scalar;
  1745. out.y = p0.y + p1.y * scalar;
  1746. };
  1747. Point.lerp = function (out, p0, p1, t) {
  1748. var onet = 1 - t;
  1749. out.x = onet * p0.x + t * p1.x;
  1750. out.y = onet * p0.y + t * p1.y;
  1751. };
  1752. return Point;
  1753. }());
  1754. var mathMin = Math.min;
  1755. var mathMax = Math.max;
  1756. var mathAbs = Math.abs;
  1757. var XY = ['x', 'y'];
  1758. var WH = ['width', 'height'];
  1759. var lt = new Point();
  1760. var rb = new Point();
  1761. var lb = new Point();
  1762. var rt = new Point();
  1763. var _intersectCtx = createIntersectContext();
  1764. var _minTv = _intersectCtx.minTv;
  1765. var _maxTv = _intersectCtx.maxTv;
  1766. var _lenMinMax = [0, 0];
  1767. var BoundingRect = (function () {
  1768. function BoundingRect(x, y, width, height) {
  1769. BoundingRect.set(this, x, y, width, height);
  1770. }
  1771. BoundingRect.set = function (target, x, y, width, height) {
  1772. if (width < 0) {
  1773. x = x + width;
  1774. width = -width;
  1775. }
  1776. if (height < 0) {
  1777. y = y + height;
  1778. height = -height;
  1779. }
  1780. target.x = x;
  1781. target.y = y;
  1782. target.width = width;
  1783. target.height = height;
  1784. return target;
  1785. };
  1786. BoundingRect.prototype.union = function (other) {
  1787. var x = mathMin(other.x, this.x);
  1788. var y = mathMin(other.y, this.y);
  1789. if (isFinite(this.x) && isFinite(this.width)) {
  1790. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1791. }
  1792. else {
  1793. this.width = other.width;
  1794. }
  1795. if (isFinite(this.y) && isFinite(this.height)) {
  1796. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1797. }
  1798. else {
  1799. this.height = other.height;
  1800. }
  1801. this.x = x;
  1802. this.y = y;
  1803. };
  1804. BoundingRect.prototype.applyTransform = function (m) {
  1805. BoundingRect.applyTransform(this, this, m);
  1806. };
  1807. BoundingRect.prototype.calculateTransform = function (b) {
  1808. var a = this;
  1809. var sx = b.width / a.width;
  1810. var sy = b.height / a.height;
  1811. var m = create$1();
  1812. translate(m, m, [-a.x, -a.y]);
  1813. scale$1(m, m, [sx, sy]);
  1814. translate(m, m, [b.x, b.y]);
  1815. return m;
  1816. };
  1817. BoundingRect.prototype.intersect = function (b, mtv, opt) {
  1818. return BoundingRect.intersect(this, b, mtv, opt);
  1819. };
  1820. BoundingRect.intersect = function (a, b, mtv, opt) {
  1821. if (mtv) {
  1822. Point.set(mtv, 0, 0);
  1823. }
  1824. var outIntersectRect = opt && opt.outIntersectRect || null;
  1825. var clamp = opt && opt.clamp;
  1826. if (outIntersectRect) {
  1827. outIntersectRect.x = outIntersectRect.y = outIntersectRect.width = outIntersectRect.height = NaN;
  1828. }
  1829. if (!a || !b) {
  1830. return false;
  1831. }
  1832. if (!(a instanceof BoundingRect)) {
  1833. a = BoundingRect.set(_tmpIntersectA, a.x, a.y, a.width, a.height);
  1834. }
  1835. if (!(b instanceof BoundingRect)) {
  1836. b = BoundingRect.set(_tmpIntersectB, b.x, b.y, b.width, b.height);
  1837. }
  1838. var useMTV = !!mtv;
  1839. _intersectCtx.reset(opt, useMTV);
  1840. var touchThreshold = _intersectCtx.touchThreshold;
  1841. var ax0 = a.x + touchThreshold;
  1842. var ax1 = a.x + a.width - touchThreshold;
  1843. var ay0 = a.y + touchThreshold;
  1844. var ay1 = a.y + a.height - touchThreshold;
  1845. var bx0 = b.x + touchThreshold;
  1846. var bx1 = b.x + b.width - touchThreshold;
  1847. var by0 = b.y + touchThreshold;
  1848. var by1 = b.y + b.height - touchThreshold;
  1849. if (ax0 > ax1 || ay0 > ay1 || bx0 > bx1 || by0 > by1) {
  1850. return false;
  1851. }
  1852. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1853. if (useMTV || outIntersectRect) {
  1854. _lenMinMax[0] = Infinity;
  1855. _lenMinMax[1] = 0;
  1856. intersectOneDim(ax0, ax1, bx0, bx1, 0, useMTV, outIntersectRect, clamp);
  1857. intersectOneDim(ay0, ay1, by0, by1, 1, useMTV, outIntersectRect, clamp);
  1858. if (useMTV) {
  1859. Point.copy(mtv, overlap
  1860. ? (_intersectCtx.useDir ? _intersectCtx.dirMinTv : _minTv)
  1861. : _maxTv);
  1862. }
  1863. }
  1864. return overlap;
  1865. };
  1866. BoundingRect.contain = function (rect, x, y) {
  1867. return x >= rect.x
  1868. && x <= (rect.x + rect.width)
  1869. && y >= rect.y
  1870. && y <= (rect.y + rect.height);
  1871. };
  1872. BoundingRect.prototype.contain = function (x, y) {
  1873. return BoundingRect.contain(this, x, y);
  1874. };
  1875. BoundingRect.prototype.clone = function () {
  1876. return new BoundingRect(this.x, this.y, this.width, this.height);
  1877. };
  1878. BoundingRect.prototype.copy = function (other) {
  1879. BoundingRect.copy(this, other);
  1880. };
  1881. BoundingRect.prototype.plain = function () {
  1882. return {
  1883. x: this.x,
  1884. y: this.y,
  1885. width: this.width,
  1886. height: this.height
  1887. };
  1888. };
  1889. BoundingRect.prototype.isFinite = function () {
  1890. return isFinite(this.x)
  1891. && isFinite(this.y)
  1892. && isFinite(this.width)
  1893. && isFinite(this.height);
  1894. };
  1895. BoundingRect.prototype.isZero = function () {
  1896. return this.width === 0 || this.height === 0;
  1897. };
  1898. BoundingRect.create = function (rect) {
  1899. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1900. };
  1901. BoundingRect.copy = function (target, source) {
  1902. target.x = source.x;
  1903. target.y = source.y;
  1904. target.width = source.width;
  1905. target.height = source.height;
  1906. return target;
  1907. };
  1908. BoundingRect.applyTransform = function (target, source, m) {
  1909. if (!m) {
  1910. if (target !== source) {
  1911. BoundingRect.copy(target, source);
  1912. }
  1913. return;
  1914. }
  1915. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1916. var sx = m[0];
  1917. var sy = m[3];
  1918. var tx = m[4];
  1919. var ty = m[5];
  1920. target.x = source.x * sx + tx;
  1921. target.y = source.y * sy + ty;
  1922. target.width = source.width * sx;
  1923. target.height = source.height * sy;
  1924. if (target.width < 0) {
  1925. target.x += target.width;
  1926. target.width = -target.width;
  1927. }
  1928. if (target.height < 0) {
  1929. target.y += target.height;
  1930. target.height = -target.height;
  1931. }
  1932. return;
  1933. }
  1934. lt.x = lb.x = source.x;
  1935. lt.y = rt.y = source.y;
  1936. rb.x = rt.x = source.x + source.width;
  1937. rb.y = lb.y = source.y + source.height;
  1938. lt.transform(m);
  1939. rt.transform(m);
  1940. rb.transform(m);
  1941. lb.transform(m);
  1942. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1943. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1944. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1945. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1946. target.width = maxX - target.x;
  1947. target.height = maxY - target.y;
  1948. };
  1949. return BoundingRect;
  1950. }());
  1951. var _tmpIntersectA = new BoundingRect(0, 0, 0, 0);
  1952. var _tmpIntersectB = new BoundingRect(0, 0, 0, 0);
  1953. function intersectOneDim(a0, a1, b0, b1, updateDimIdx, useMTV, outIntersectRect, clamp) {
  1954. var d0 = mathAbs(a1 - b0);
  1955. var d1 = mathAbs(b1 - a0);
  1956. var d01min = mathMin(d0, d1);
  1957. var updateDim = XY[updateDimIdx];
  1958. var zeroDim = XY[1 - updateDimIdx];
  1959. var wh = WH[updateDimIdx];
  1960. if (a1 < b0 || b1 < a0) {
  1961. if (d0 < d1) {
  1962. if (useMTV) {
  1963. _maxTv[updateDim] = -d0;
  1964. }
  1965. if (clamp) {
  1966. outIntersectRect[updateDim] = a1;
  1967. outIntersectRect[wh] = 0;
  1968. }
  1969. }
  1970. else {
  1971. if (useMTV) {
  1972. _maxTv[updateDim] = d1;
  1973. }
  1974. if (clamp) {
  1975. outIntersectRect[updateDim] = a0;
  1976. outIntersectRect[wh] = 0;
  1977. }
  1978. }
  1979. }
  1980. else {
  1981. if (outIntersectRect) {
  1982. outIntersectRect[updateDim] = mathMax(a0, b0);
  1983. outIntersectRect[wh] = mathMin(a1, b1) - outIntersectRect[updateDim];
  1984. }
  1985. if (useMTV) {
  1986. if (d01min < _lenMinMax[0] || _intersectCtx.useDir) {
  1987. _lenMinMax[0] = mathMin(d01min, _lenMinMax[0]);
  1988. if (d0 < d1 || !_intersectCtx.bidirectional) {
  1989. _minTv[updateDim] = d0;
  1990. _minTv[zeroDim] = 0;
  1991. if (_intersectCtx.useDir) {
  1992. _intersectCtx.calcDirMTV();
  1993. }
  1994. }
  1995. if (d0 >= d1 || !_intersectCtx.bidirectional) {
  1996. _minTv[updateDim] = -d1;
  1997. _minTv[zeroDim] = 0;
  1998. if (_intersectCtx.useDir) {
  1999. _intersectCtx.calcDirMTV();
  2000. }
  2001. }
  2002. }
  2003. }
  2004. }
  2005. }
  2006. function createIntersectContext() {
  2007. var _direction = 0;
  2008. var _dirCheckVec = new Point();
  2009. var _dirTmp = new Point();
  2010. var _ctx = {
  2011. minTv: new Point(),
  2012. maxTv: new Point(),
  2013. useDir: false,
  2014. dirMinTv: new Point(),
  2015. touchThreshold: 0,
  2016. bidirectional: true,
  2017. negativeSize: false,
  2018. reset: function (opt, useMTV) {
  2019. _ctx.touchThreshold = 0;
  2020. if (opt && opt.touchThreshold != null) {
  2021. _ctx.touchThreshold = mathMax(0, opt.touchThreshold);
  2022. }
  2023. _ctx.negativeSize = false;
  2024. if (!useMTV) {
  2025. return;
  2026. }
  2027. _ctx.minTv.set(Infinity, Infinity);
  2028. _ctx.maxTv.set(0, 0);
  2029. _ctx.useDir = false;
  2030. if (opt && opt.direction != null) {
  2031. _ctx.useDir = true;
  2032. _ctx.dirMinTv.copy(_ctx.minTv);
  2033. _dirTmp.copy(_ctx.minTv);
  2034. _direction = opt.direction;
  2035. _ctx.bidirectional = opt.bidirectional == null || !!opt.bidirectional;
  2036. if (!_ctx.bidirectional) {
  2037. _dirCheckVec.set(Math.cos(_direction), Math.sin(_direction));
  2038. }
  2039. }
  2040. },
  2041. calcDirMTV: function () {
  2042. var minTv = _ctx.minTv;
  2043. var dirMinTv = _ctx.dirMinTv;
  2044. var squareMag = minTv.y * minTv.y + minTv.x * minTv.x;
  2045. var dirSin = Math.sin(_direction);
  2046. var dirCos = Math.cos(_direction);
  2047. var dotProd = dirSin * minTv.y + dirCos * minTv.x;
  2048. if (nearZero(dotProd)) {
  2049. if (nearZero(minTv.x) && nearZero(minTv.y)) {
  2050. dirMinTv.set(0, 0);
  2051. }
  2052. return;
  2053. }
  2054. _dirTmp.x = squareMag * dirCos / dotProd;
  2055. _dirTmp.y = squareMag * dirSin / dotProd;
  2056. if (nearZero(_dirTmp.x) && nearZero(_dirTmp.y)) {
  2057. dirMinTv.set(0, 0);
  2058. return;
  2059. }
  2060. if ((_ctx.bidirectional
  2061. || _dirCheckVec.dot(_dirTmp) > 0)
  2062. && _dirTmp.len() < dirMinTv.len()) {
  2063. dirMinTv.copy(_dirTmp);
  2064. }
  2065. }
  2066. };
  2067. function nearZero(val) {
  2068. return mathAbs(val) < 1e-10;
  2069. }
  2070. return _ctx;
  2071. }
  2072. var SILENT = 'silent';
  2073. function makeEventPacket(eveType, targetInfo, event) {
  2074. return {
  2075. type: eveType,
  2076. event: event,
  2077. target: targetInfo.target,
  2078. topTarget: targetInfo.topTarget,
  2079. cancelBubble: false,
  2080. offsetX: event.zrX,
  2081. offsetY: event.zrY,
  2082. gestureEvent: event.gestureEvent,
  2083. pinchX: event.pinchX,
  2084. pinchY: event.pinchY,
  2085. pinchScale: event.pinchScale,
  2086. wheelDelta: event.zrDelta,
  2087. zrByTouch: event.zrByTouch,
  2088. which: event.which,
  2089. stop: stopEvent
  2090. };
  2091. }
  2092. function stopEvent() {
  2093. stop(this.event);
  2094. }
  2095. var EmptyProxy = (function (_super) {
  2096. __extends(EmptyProxy, _super);
  2097. function EmptyProxy() {
  2098. var _this = _super !== null && _super.apply(this, arguments) || this;
  2099. _this.handler = null;
  2100. return _this;
  2101. }
  2102. EmptyProxy.prototype.dispose = function () { };
  2103. EmptyProxy.prototype.setCursor = function () { };
  2104. return EmptyProxy;
  2105. }(Eventful));
  2106. var HoveredResult = (function () {
  2107. function HoveredResult(x, y) {
  2108. this.x = x;
  2109. this.y = y;
  2110. }
  2111. return HoveredResult;
  2112. }());
  2113. var handlerNames = [
  2114. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2115. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2116. ];
  2117. var tmpRect = new BoundingRect(0, 0, 0, 0);
  2118. var Handler = (function (_super) {
  2119. __extends(Handler, _super);
  2120. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  2121. var _this = _super.call(this) || this;
  2122. _this._hovered = new HoveredResult(0, 0);
  2123. _this.storage = storage;
  2124. _this.painter = painter;
  2125. _this.painterRoot = painterRoot;
  2126. _this._pointerSize = pointerSize;
  2127. proxy = proxy || new EmptyProxy();
  2128. _this.proxy = null;
  2129. _this.setHandlerProxy(proxy);
  2130. _this._draggingMgr = new Draggable(_this);
  2131. return _this;
  2132. }
  2133. Handler.prototype.setHandlerProxy = function (proxy) {
  2134. if (this.proxy) {
  2135. this.proxy.dispose();
  2136. }
  2137. if (proxy) {
  2138. each(handlerNames, function (name) {
  2139. proxy.on && proxy.on(name, this[name], this);
  2140. }, this);
  2141. proxy.handler = this;
  2142. }
  2143. this.proxy = proxy;
  2144. };
  2145. Handler.prototype.mousemove = function (event) {
  2146. var x = event.zrX;
  2147. var y = event.zrY;
  2148. var isOutside = isOutsideBoundary(this, x, y);
  2149. var lastHovered = this._hovered;
  2150. var lastHoveredTarget = lastHovered.target;
  2151. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2152. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2153. lastHoveredTarget = lastHovered.target;
  2154. }
  2155. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2156. var hoveredTarget = hovered.target;
  2157. var proxy = this.proxy;
  2158. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2159. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2160. this.dispatchToElement(lastHovered, 'mouseout', event);
  2161. }
  2162. this.dispatchToElement(hovered, 'mousemove', event);
  2163. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2164. this.dispatchToElement(hovered, 'mouseover', event);
  2165. }
  2166. };
  2167. Handler.prototype.mouseout = function (event) {
  2168. var eventControl = event.zrEventControl;
  2169. if (eventControl !== 'only_globalout') {
  2170. this.dispatchToElement(this._hovered, 'mouseout', event);
  2171. }
  2172. if (eventControl !== 'no_globalout') {
  2173. this.trigger('globalout', { type: 'globalout', event: event });
  2174. }
  2175. };
  2176. Handler.prototype.resize = function () {
  2177. this._hovered = new HoveredResult(0, 0);
  2178. };
  2179. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2180. var handler = this[eventName];
  2181. handler && handler.call(this, eventArgs);
  2182. };
  2183. Handler.prototype.dispose = function () {
  2184. this.proxy.dispose();
  2185. this.storage = null;
  2186. this.proxy = null;
  2187. this.painter = null;
  2188. };
  2189. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2190. var proxy = this.proxy;
  2191. proxy.setCursor && proxy.setCursor(cursorStyle);
  2192. };
  2193. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2194. targetInfo = targetInfo || {};
  2195. var el = targetInfo.target;
  2196. if (el && el.silent) {
  2197. return;
  2198. }
  2199. var eventKey = ('on' + eventName);
  2200. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2201. while (el) {
  2202. el[eventKey]
  2203. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2204. el.trigger(eventName, eventPacket);
  2205. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2206. if (eventPacket.cancelBubble) {
  2207. break;
  2208. }
  2209. }
  2210. if (!eventPacket.cancelBubble) {
  2211. this.trigger(eventName, eventPacket);
  2212. if (this.painter && this.painter.eachOtherLayer) {
  2213. this.painter.eachOtherLayer(function (layer) {
  2214. if (typeof (layer[eventKey]) === 'function') {
  2215. layer[eventKey].call(layer, eventPacket);
  2216. }
  2217. if (layer.trigger) {
  2218. layer.trigger(eventName, eventPacket);
  2219. }
  2220. });
  2221. }
  2222. }
  2223. };
  2224. Handler.prototype.findHover = function (x, y, exclude) {
  2225. var list = this.storage.getDisplayList();
  2226. var out = new HoveredResult(x, y);
  2227. setHoverTarget(list, out, x, y, exclude);
  2228. if (this._pointerSize && !out.target) {
  2229. var candidates = [];
  2230. var pointerSize = this._pointerSize;
  2231. var targetSizeHalf = pointerSize / 2;
  2232. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2233. for (var i = list.length - 1; i >= 0; i--) {
  2234. var el = list[i];
  2235. if (el !== exclude
  2236. && !el.ignore
  2237. && !el.ignoreCoarsePointer
  2238. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2239. tmpRect.copy(el.getBoundingRect());
  2240. if (el.transform) {
  2241. tmpRect.applyTransform(el.transform);
  2242. }
  2243. if (tmpRect.intersect(pointerRect)) {
  2244. candidates.push(el);
  2245. }
  2246. }
  2247. }
  2248. if (candidates.length) {
  2249. var rStep = 4;
  2250. var thetaStep = Math.PI / 12;
  2251. var PI2 = Math.PI * 2;
  2252. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2253. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2254. var x1 = x + r * Math.cos(theta);
  2255. var y1 = y + r * Math.sin(theta);
  2256. setHoverTarget(candidates, out, x1, y1, exclude);
  2257. if (out.target) {
  2258. return out;
  2259. }
  2260. }
  2261. }
  2262. }
  2263. }
  2264. return out;
  2265. };
  2266. Handler.prototype.processGesture = function (event, stage) {
  2267. if (!this._gestureMgr) {
  2268. this._gestureMgr = new GestureMgr();
  2269. }
  2270. var gestureMgr = this._gestureMgr;
  2271. stage === 'start' && gestureMgr.clear();
  2272. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2273. stage === 'end' && gestureMgr.clear();
  2274. if (gestureInfo) {
  2275. var type = gestureInfo.type;
  2276. event.gestureEvent = type;
  2277. var res = new HoveredResult();
  2278. res.target = gestureInfo.target;
  2279. this.dispatchToElement(res, type, gestureInfo.event);
  2280. }
  2281. };
  2282. return Handler;
  2283. }(Eventful));
  2284. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2285. Handler.prototype[name] = function (event) {
  2286. var x = event.zrX;
  2287. var y = event.zrY;
  2288. var isOutside = isOutsideBoundary(this, x, y);
  2289. var hovered;
  2290. var hoveredTarget;
  2291. if (name !== 'mouseup' || !isOutside) {
  2292. hovered = this.findHover(x, y);
  2293. hoveredTarget = hovered.target;
  2294. }
  2295. if (name === 'mousedown') {
  2296. this._downEl = hoveredTarget;
  2297. this._downPoint = [event.zrX, event.zrY];
  2298. this._upEl = hoveredTarget;
  2299. }
  2300. else if (name === 'mouseup') {
  2301. this._upEl = hoveredTarget;
  2302. }
  2303. else if (name === 'click') {
  2304. if (this._downEl !== this._upEl
  2305. || !this._downPoint
  2306. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2307. return;
  2308. }
  2309. this._downPoint = null;
  2310. }
  2311. this.dispatchToElement(hovered, name, event);
  2312. };
  2313. });
  2314. function isHover(displayable, x, y) {
  2315. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2316. var el = displayable;
  2317. var isSilent = void 0;
  2318. var ignoreClip = false;
  2319. while (el) {
  2320. if (el.ignoreClip) {
  2321. ignoreClip = true;
  2322. }
  2323. if (!ignoreClip) {
  2324. var clipPath = el.getClipPath();
  2325. if (clipPath && !clipPath.contain(x, y)) {
  2326. return false;
  2327. }
  2328. }
  2329. if (el.silent) {
  2330. isSilent = true;
  2331. }
  2332. var hostEl = el.__hostTarget;
  2333. el = hostEl ? (el.ignoreHostSilent ? null : hostEl) : el.parent;
  2334. }
  2335. return isSilent ? SILENT : true;
  2336. }
  2337. return false;
  2338. }
  2339. function setHoverTarget(list, out, x, y, exclude) {
  2340. for (var i = list.length - 1; i >= 0; i--) {
  2341. var el = list[i];
  2342. var hoverCheckResult = void 0;
  2343. if (el !== exclude
  2344. && !el.ignore
  2345. && (hoverCheckResult = isHover(el, x, y))) {
  2346. !out.topTarget && (out.topTarget = el);
  2347. if (hoverCheckResult !== SILENT) {
  2348. out.target = el;
  2349. break;
  2350. }
  2351. }
  2352. }
  2353. }
  2354. function isOutsideBoundary(handlerInstance, x, y) {
  2355. var painter = handlerInstance.painter;
  2356. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2357. }
  2358. var DEFAULT_MIN_MERGE = 32;
  2359. var DEFAULT_MIN_GALLOPING = 7;
  2360. function minRunLength(n) {
  2361. var r = 0;
  2362. while (n >= DEFAULT_MIN_MERGE) {
  2363. r |= n & 1;
  2364. n >>= 1;
  2365. }
  2366. return n + r;
  2367. }
  2368. function makeAscendingRun(array, lo, hi, compare) {
  2369. var runHi = lo + 1;
  2370. if (runHi === hi) {
  2371. return 1;
  2372. }
  2373. if (compare(array[runHi++], array[lo]) < 0) {
  2374. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2375. runHi++;
  2376. }
  2377. reverseRun(array, lo, runHi);
  2378. }
  2379. else {
  2380. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2381. runHi++;
  2382. }
  2383. }
  2384. return runHi - lo;
  2385. }
  2386. function reverseRun(array, lo, hi) {
  2387. hi--;
  2388. while (lo < hi) {
  2389. var t = array[lo];
  2390. array[lo++] = array[hi];
  2391. array[hi--] = t;
  2392. }
  2393. }
  2394. function binaryInsertionSort(array, lo, hi, start, compare) {
  2395. if (start === lo) {
  2396. start++;
  2397. }
  2398. for (; start < hi; start++) {
  2399. var pivot = array[start];
  2400. var left = lo;
  2401. var right = start;
  2402. var mid;
  2403. while (left < right) {
  2404. mid = left + right >>> 1;
  2405. if (compare(pivot, array[mid]) < 0) {
  2406. right = mid;
  2407. }
  2408. else {
  2409. left = mid + 1;
  2410. }
  2411. }
  2412. var n = start - left;
  2413. switch (n) {
  2414. case 3:
  2415. array[left + 3] = array[left + 2];
  2416. case 2:
  2417. array[left + 2] = array[left + 1];
  2418. case 1:
  2419. array[left + 1] = array[left];
  2420. break;
  2421. default:
  2422. while (n > 0) {
  2423. array[left + n] = array[left + n - 1];
  2424. n--;
  2425. }
  2426. }
  2427. array[left] = pivot;
  2428. }
  2429. }
  2430. function gallopLeft(value, array, start, length, hint, compare) {
  2431. var lastOffset = 0;
  2432. var maxOffset = 0;
  2433. var offset = 1;
  2434. if (compare(value, array[start + hint]) > 0) {
  2435. maxOffset = length - hint;
  2436. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2437. lastOffset = offset;
  2438. offset = (offset << 1) + 1;
  2439. if (offset <= 0) {
  2440. offset = maxOffset;
  2441. }
  2442. }
  2443. if (offset > maxOffset) {
  2444. offset = maxOffset;
  2445. }
  2446. lastOffset += hint;
  2447. offset += hint;
  2448. }
  2449. else {
  2450. maxOffset = hint + 1;
  2451. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2452. lastOffset = offset;
  2453. offset = (offset << 1) + 1;
  2454. if (offset <= 0) {
  2455. offset = maxOffset;
  2456. }
  2457. }
  2458. if (offset > maxOffset) {
  2459. offset = maxOffset;
  2460. }
  2461. var tmp = lastOffset;
  2462. lastOffset = hint - offset;
  2463. offset = hint - tmp;
  2464. }
  2465. lastOffset++;
  2466. while (lastOffset < offset) {
  2467. var m = lastOffset + (offset - lastOffset >>> 1);
  2468. if (compare(value, array[start + m]) > 0) {
  2469. lastOffset = m + 1;
  2470. }
  2471. else {
  2472. offset = m;
  2473. }
  2474. }
  2475. return offset;
  2476. }
  2477. function gallopRight(value, array, start, length, hint, compare) {
  2478. var lastOffset = 0;
  2479. var maxOffset = 0;
  2480. var offset = 1;
  2481. if (compare(value, array[start + hint]) < 0) {
  2482. maxOffset = hint + 1;
  2483. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2484. lastOffset = offset;
  2485. offset = (offset << 1) + 1;
  2486. if (offset <= 0) {
  2487. offset = maxOffset;
  2488. }
  2489. }
  2490. if (offset > maxOffset) {
  2491. offset = maxOffset;
  2492. }
  2493. var tmp = lastOffset;
  2494. lastOffset = hint - offset;
  2495. offset = hint - tmp;
  2496. }
  2497. else {
  2498. maxOffset = length - hint;
  2499. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2500. lastOffset = offset;
  2501. offset = (offset << 1) + 1;
  2502. if (offset <= 0) {
  2503. offset = maxOffset;
  2504. }
  2505. }
  2506. if (offset > maxOffset) {
  2507. offset = maxOffset;
  2508. }
  2509. lastOffset += hint;
  2510. offset += hint;
  2511. }
  2512. lastOffset++;
  2513. while (lastOffset < offset) {
  2514. var m = lastOffset + (offset - lastOffset >>> 1);
  2515. if (compare(value, array[start + m]) < 0) {
  2516. offset = m;
  2517. }
  2518. else {
  2519. lastOffset = m + 1;
  2520. }
  2521. }
  2522. return offset;
  2523. }
  2524. function TimSort(array, compare) {
  2525. var minGallop = DEFAULT_MIN_GALLOPING;
  2526. var runStart;
  2527. var runLength;
  2528. var stackSize = 0;
  2529. var tmp = [];
  2530. runStart = [];
  2531. runLength = [];
  2532. function pushRun(_runStart, _runLength) {
  2533. runStart[stackSize] = _runStart;
  2534. runLength[stackSize] = _runLength;
  2535. stackSize += 1;
  2536. }
  2537. function mergeRuns() {
  2538. while (stackSize > 1) {
  2539. var n = stackSize - 2;
  2540. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2541. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2542. if (runLength[n - 1] < runLength[n + 1]) {
  2543. n--;
  2544. }
  2545. }
  2546. else if (runLength[n] > runLength[n + 1]) {
  2547. break;
  2548. }
  2549. mergeAt(n);
  2550. }
  2551. }
  2552. function forceMergeRuns() {
  2553. while (stackSize > 1) {
  2554. var n = stackSize - 2;
  2555. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2556. n--;
  2557. }
  2558. mergeAt(n);
  2559. }
  2560. }
  2561. function mergeAt(i) {
  2562. var start1 = runStart[i];
  2563. var length1 = runLength[i];
  2564. var start2 = runStart[i + 1];
  2565. var length2 = runLength[i + 1];
  2566. runLength[i] = length1 + length2;
  2567. if (i === stackSize - 3) {
  2568. runStart[i + 1] = runStart[i + 2];
  2569. runLength[i + 1] = runLength[i + 2];
  2570. }
  2571. stackSize--;
  2572. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2573. start1 += k;
  2574. length1 -= k;
  2575. if (length1 === 0) {
  2576. return;
  2577. }
  2578. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2579. if (length2 === 0) {
  2580. return;
  2581. }
  2582. if (length1 <= length2) {
  2583. mergeLow(start1, length1, start2, length2);
  2584. }
  2585. else {
  2586. mergeHigh(start1, length1, start2, length2);
  2587. }
  2588. }
  2589. function mergeLow(start1, length1, start2, length2) {
  2590. var i = 0;
  2591. for (i = 0; i < length1; i++) {
  2592. tmp[i] = array[start1 + i];
  2593. }
  2594. var cursor1 = 0;
  2595. var cursor2 = start2;
  2596. var dest = start1;
  2597. array[dest++] = array[cursor2++];
  2598. if (--length2 === 0) {
  2599. for (i = 0; i < length1; i++) {
  2600. array[dest + i] = tmp[cursor1 + i];
  2601. }
  2602. return;
  2603. }
  2604. if (length1 === 1) {
  2605. for (i = 0; i < length2; i++) {
  2606. array[dest + i] = array[cursor2 + i];
  2607. }
  2608. array[dest + length2] = tmp[cursor1];
  2609. return;
  2610. }
  2611. var _minGallop = minGallop;
  2612. var count1;
  2613. var count2;
  2614. var exit;
  2615. while (1) {
  2616. count1 = 0;
  2617. count2 = 0;
  2618. exit = false;
  2619. do {
  2620. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2621. array[dest++] = array[cursor2++];
  2622. count2++;
  2623. count1 = 0;
  2624. if (--length2 === 0) {
  2625. exit = true;
  2626. break;
  2627. }
  2628. }
  2629. else {
  2630. array[dest++] = tmp[cursor1++];
  2631. count1++;
  2632. count2 = 0;
  2633. if (--length1 === 1) {
  2634. exit = true;
  2635. break;
  2636. }
  2637. }
  2638. } while ((count1 | count2) < _minGallop);
  2639. if (exit) {
  2640. break;
  2641. }
  2642. do {
  2643. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2644. if (count1 !== 0) {
  2645. for (i = 0; i < count1; i++) {
  2646. array[dest + i] = tmp[cursor1 + i];
  2647. }
  2648. dest += count1;
  2649. cursor1 += count1;
  2650. length1 -= count1;
  2651. if (length1 <= 1) {
  2652. exit = true;
  2653. break;
  2654. }
  2655. }
  2656. array[dest++] = array[cursor2++];
  2657. if (--length2 === 0) {
  2658. exit = true;
  2659. break;
  2660. }
  2661. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2662. if (count2 !== 0) {
  2663. for (i = 0; i < count2; i++) {
  2664. array[dest + i] = array[cursor2 + i];
  2665. }
  2666. dest += count2;
  2667. cursor2 += count2;
  2668. length2 -= count2;
  2669. if (length2 === 0) {
  2670. exit = true;
  2671. break;
  2672. }
  2673. }
  2674. array[dest++] = tmp[cursor1++];
  2675. if (--length1 === 1) {
  2676. exit = true;
  2677. break;
  2678. }
  2679. _minGallop--;
  2680. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2681. if (exit) {
  2682. break;
  2683. }
  2684. if (_minGallop < 0) {
  2685. _minGallop = 0;
  2686. }
  2687. _minGallop += 2;
  2688. }
  2689. minGallop = _minGallop;
  2690. minGallop < 1 && (minGallop = 1);
  2691. if (length1 === 1) {
  2692. for (i = 0; i < length2; i++) {
  2693. array[dest + i] = array[cursor2 + i];
  2694. }
  2695. array[dest + length2] = tmp[cursor1];
  2696. }
  2697. else if (length1 === 0) {
  2698. throw new Error();
  2699. }
  2700. else {
  2701. for (i = 0; i < length1; i++) {
  2702. array[dest + i] = tmp[cursor1 + i];
  2703. }
  2704. }
  2705. }
  2706. function mergeHigh(start1, length1, start2, length2) {
  2707. var i = 0;
  2708. for (i = 0; i < length2; i++) {
  2709. tmp[i] = array[start2 + i];
  2710. }
  2711. var cursor1 = start1 + length1 - 1;
  2712. var cursor2 = length2 - 1;
  2713. var dest = start2 + length2 - 1;
  2714. var customCursor = 0;
  2715. var customDest = 0;
  2716. array[dest--] = array[cursor1--];
  2717. if (--length1 === 0) {
  2718. customCursor = dest - (length2 - 1);
  2719. for (i = 0; i < length2; i++) {
  2720. array[customCursor + i] = tmp[i];
  2721. }
  2722. return;
  2723. }
  2724. if (length2 === 1) {
  2725. dest -= length1;
  2726. cursor1 -= length1;
  2727. customDest = dest + 1;
  2728. customCursor = cursor1 + 1;
  2729. for (i = length1 - 1; i >= 0; i--) {
  2730. array[customDest + i] = array[customCursor + i];
  2731. }
  2732. array[dest] = tmp[cursor2];
  2733. return;
  2734. }
  2735. var _minGallop = minGallop;
  2736. while (true) {
  2737. var count1 = 0;
  2738. var count2 = 0;
  2739. var exit = false;
  2740. do {
  2741. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2742. array[dest--] = array[cursor1--];
  2743. count1++;
  2744. count2 = 0;
  2745. if (--length1 === 0) {
  2746. exit = true;
  2747. break;
  2748. }
  2749. }
  2750. else {
  2751. array[dest--] = tmp[cursor2--];
  2752. count2++;
  2753. count1 = 0;
  2754. if (--length2 === 1) {
  2755. exit = true;
  2756. break;
  2757. }
  2758. }
  2759. } while ((count1 | count2) < _minGallop);
  2760. if (exit) {
  2761. break;
  2762. }
  2763. do {
  2764. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2765. if (count1 !== 0) {
  2766. dest -= count1;
  2767. cursor1 -= count1;
  2768. length1 -= count1;
  2769. customDest = dest + 1;
  2770. customCursor = cursor1 + 1;
  2771. for (i = count1 - 1; i >= 0; i--) {
  2772. array[customDest + i] = array[customCursor + i];
  2773. }
  2774. if (length1 === 0) {
  2775. exit = true;
  2776. break;
  2777. }
  2778. }
  2779. array[dest--] = tmp[cursor2--];
  2780. if (--length2 === 1) {
  2781. exit = true;
  2782. break;
  2783. }
  2784. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2785. if (count2 !== 0) {
  2786. dest -= count2;
  2787. cursor2 -= count2;
  2788. length2 -= count2;
  2789. customDest = dest + 1;
  2790. customCursor = cursor2 + 1;
  2791. for (i = 0; i < count2; i++) {
  2792. array[customDest + i] = tmp[customCursor + i];
  2793. }
  2794. if (length2 <= 1) {
  2795. exit = true;
  2796. break;
  2797. }
  2798. }
  2799. array[dest--] = array[cursor1--];
  2800. if (--length1 === 0) {
  2801. exit = true;
  2802. break;
  2803. }
  2804. _minGallop--;
  2805. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2806. if (exit) {
  2807. break;
  2808. }
  2809. if (_minGallop < 0) {
  2810. _minGallop = 0;
  2811. }
  2812. _minGallop += 2;
  2813. }
  2814. minGallop = _minGallop;
  2815. if (minGallop < 1) {
  2816. minGallop = 1;
  2817. }
  2818. if (length2 === 1) {
  2819. dest -= length1;
  2820. cursor1 -= length1;
  2821. customDest = dest + 1;
  2822. customCursor = cursor1 + 1;
  2823. for (i = length1 - 1; i >= 0; i--) {
  2824. array[customDest + i] = array[customCursor + i];
  2825. }
  2826. array[dest] = tmp[cursor2];
  2827. }
  2828. else if (length2 === 0) {
  2829. throw new Error();
  2830. }
  2831. else {
  2832. customCursor = dest - (length2 - 1);
  2833. for (i = 0; i < length2; i++) {
  2834. array[customCursor + i] = tmp[i];
  2835. }
  2836. }
  2837. }
  2838. return {
  2839. mergeRuns: mergeRuns,
  2840. forceMergeRuns: forceMergeRuns,
  2841. pushRun: pushRun
  2842. };
  2843. }
  2844. function sort(array, compare, lo, hi) {
  2845. if (!lo) {
  2846. lo = 0;
  2847. }
  2848. if (!hi) {
  2849. hi = array.length;
  2850. }
  2851. var remaining = hi - lo;
  2852. if (remaining < 2) {
  2853. return;
  2854. }
  2855. var runLength = 0;
  2856. if (remaining < DEFAULT_MIN_MERGE) {
  2857. runLength = makeAscendingRun(array, lo, hi, compare);
  2858. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2859. return;
  2860. }
  2861. var ts = TimSort(array, compare);
  2862. var minRun = minRunLength(remaining);
  2863. do {
  2864. runLength = makeAscendingRun(array, lo, hi, compare);
  2865. if (runLength < minRun) {
  2866. var force = remaining;
  2867. if (force > minRun) {
  2868. force = minRun;
  2869. }
  2870. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2871. runLength = force;
  2872. }
  2873. ts.pushRun(lo, runLength);
  2874. ts.mergeRuns();
  2875. remaining -= runLength;
  2876. lo += runLength;
  2877. } while (remaining !== 0);
  2878. ts.forceMergeRuns();
  2879. }
  2880. var REDRAW_BIT = 1;
  2881. var STYLE_CHANGED_BIT = 2;
  2882. var SHAPE_CHANGED_BIT = 4;
  2883. var invalidZErrorLogged = false;
  2884. function logInvalidZError() {
  2885. if (invalidZErrorLogged) {
  2886. return;
  2887. }
  2888. invalidZErrorLogged = true;
  2889. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2890. }
  2891. function shapeCompareFunc(a, b) {
  2892. if (a.zlevel === b.zlevel) {
  2893. if (a.z === b.z) {
  2894. return a.z2 - b.z2;
  2895. }
  2896. return a.z - b.z;
  2897. }
  2898. return a.zlevel - b.zlevel;
  2899. }
  2900. var Storage = (function () {
  2901. function Storage() {
  2902. this._roots = [];
  2903. this._displayList = [];
  2904. this._displayListLen = 0;
  2905. this.displayableSortFunc = shapeCompareFunc;
  2906. }
  2907. Storage.prototype.traverse = function (cb, context) {
  2908. for (var i = 0; i < this._roots.length; i++) {
  2909. this._roots[i].traverse(cb, context);
  2910. }
  2911. };
  2912. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2913. includeIgnore = includeIgnore || false;
  2914. var displayList = this._displayList;
  2915. if (update || !displayList.length) {
  2916. this.updateDisplayList(includeIgnore);
  2917. }
  2918. return displayList;
  2919. };
  2920. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2921. this._displayListLen = 0;
  2922. var roots = this._roots;
  2923. var displayList = this._displayList;
  2924. for (var i = 0, len = roots.length; i < len; i++) {
  2925. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2926. }
  2927. displayList.length = this._displayListLen;
  2928. sort(displayList, shapeCompareFunc);
  2929. };
  2930. Storage.prototype._updateAndAddDisplayable = function (el, parentClipPaths, includeIgnore) {
  2931. if (el.ignore && !includeIgnore) {
  2932. return;
  2933. }
  2934. el.beforeUpdate();
  2935. el.update();
  2936. el.afterUpdate();
  2937. var userSetClipPath = el.getClipPath();
  2938. var parentHasClipPaths = parentClipPaths && parentClipPaths.length;
  2939. var clipPathIdx = 0;
  2940. var thisClipPaths = el.__clipPaths;
  2941. if (!el.ignoreClip
  2942. && (parentHasClipPaths || userSetClipPath)) {
  2943. if (!thisClipPaths) {
  2944. thisClipPaths = el.__clipPaths = [];
  2945. }
  2946. if (parentHasClipPaths) {
  2947. for (var idx = 0; idx < parentClipPaths.length; idx++) {
  2948. thisClipPaths[clipPathIdx++] = parentClipPaths[idx];
  2949. }
  2950. }
  2951. var currentClipPath = userSetClipPath;
  2952. var parentClipPath = el;
  2953. while (currentClipPath) {
  2954. currentClipPath.parent = parentClipPath;
  2955. currentClipPath.updateTransform();
  2956. thisClipPaths[clipPathIdx++] = currentClipPath;
  2957. parentClipPath = currentClipPath;
  2958. currentClipPath = currentClipPath.getClipPath();
  2959. }
  2960. }
  2961. if (thisClipPaths) {
  2962. thisClipPaths.length = clipPathIdx;
  2963. }
  2964. if (el.childrenRef) {
  2965. var children = el.childrenRef();
  2966. for (var i = 0; i < children.length; i++) {
  2967. var child = children[i];
  2968. if (el.__dirty) {
  2969. child.__dirty |= REDRAW_BIT;
  2970. }
  2971. this._updateAndAddDisplayable(child, thisClipPaths, includeIgnore);
  2972. }
  2973. el.__dirty = 0;
  2974. }
  2975. else {
  2976. var disp = el;
  2977. if (isNaN(disp.z)) {
  2978. logInvalidZError();
  2979. disp.z = 0;
  2980. }
  2981. if (isNaN(disp.z2)) {
  2982. logInvalidZError();
  2983. disp.z2 = 0;
  2984. }
  2985. if (isNaN(disp.zlevel)) {
  2986. logInvalidZError();
  2987. disp.zlevel = 0;
  2988. }
  2989. this._displayList[this._displayListLen++] = disp;
  2990. }
  2991. var decalEl = el.getDecalElement && el.getDecalElement();
  2992. if (decalEl) {
  2993. this._updateAndAddDisplayable(decalEl, thisClipPaths, includeIgnore);
  2994. }
  2995. var textGuide = el.getTextGuideLine();
  2996. if (textGuide) {
  2997. this._updateAndAddDisplayable(textGuide, thisClipPaths, includeIgnore);
  2998. }
  2999. var textEl = el.getTextContent();
  3000. if (textEl) {
  3001. this._updateAndAddDisplayable(textEl, thisClipPaths, includeIgnore);
  3002. }
  3003. };
  3004. Storage.prototype.addRoot = function (el) {
  3005. if (el.__zr && el.__zr.storage === this) {
  3006. return;
  3007. }
  3008. this._roots.push(el);
  3009. };
  3010. Storage.prototype.delRoot = function (el) {
  3011. if (el instanceof Array) {
  3012. for (var i = 0, l = el.length; i < l; i++) {
  3013. this.delRoot(el[i]);
  3014. }
  3015. return;
  3016. }
  3017. var idx = indexOf(this._roots, el);
  3018. if (idx >= 0) {
  3019. this._roots.splice(idx, 1);
  3020. }
  3021. };
  3022. Storage.prototype.delAllRoots = function () {
  3023. this._roots = [];
  3024. this._displayList = [];
  3025. this._displayListLen = 0;
  3026. return;
  3027. };
  3028. Storage.prototype.getRoots = function () {
  3029. return this._roots;
  3030. };
  3031. Storage.prototype.dispose = function () {
  3032. this._displayList = null;
  3033. this._roots = null;
  3034. };
  3035. return Storage;
  3036. }());
  3037. var requestAnimationFrame;
  3038. requestAnimationFrame = (env.hasGlobalWindow
  3039. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  3040. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  3041. || window.mozRequestAnimationFrame
  3042. || window.webkitRequestAnimationFrame)) || function (func) {
  3043. return setTimeout(func, 16);
  3044. };
  3045. var requestAnimationFrame$1 = requestAnimationFrame;
  3046. var easingFuncs = {
  3047. linear: function (k) {
  3048. return k;
  3049. },
  3050. quadraticIn: function (k) {
  3051. return k * k;
  3052. },
  3053. quadraticOut: function (k) {
  3054. return k * (2 - k);
  3055. },
  3056. quadraticInOut: function (k) {
  3057. if ((k *= 2) < 1) {
  3058. return 0.5 * k * k;
  3059. }
  3060. return -0.5 * (--k * (k - 2) - 1);
  3061. },
  3062. cubicIn: function (k) {
  3063. return k * k * k;
  3064. },
  3065. cubicOut: function (k) {
  3066. return --k * k * k + 1;
  3067. },
  3068. cubicInOut: function (k) {
  3069. if ((k *= 2) < 1) {
  3070. return 0.5 * k * k * k;
  3071. }
  3072. return 0.5 * ((k -= 2) * k * k + 2);
  3073. },
  3074. quarticIn: function (k) {
  3075. return k * k * k * k;
  3076. },
  3077. quarticOut: function (k) {
  3078. return 1 - (--k * k * k * k);
  3079. },
  3080. quarticInOut: function (k) {
  3081. if ((k *= 2) < 1) {
  3082. return 0.5 * k * k * k * k;
  3083. }
  3084. return -0.5 * ((k -= 2) * k * k * k - 2);
  3085. },
  3086. quinticIn: function (k) {
  3087. return k * k * k * k * k;
  3088. },
  3089. quinticOut: function (k) {
  3090. return --k * k * k * k * k + 1;
  3091. },
  3092. quinticInOut: function (k) {
  3093. if ((k *= 2) < 1) {
  3094. return 0.5 * k * k * k * k * k;
  3095. }
  3096. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  3097. },
  3098. sinusoidalIn: function (k) {
  3099. return 1 - Math.cos(k * Math.PI / 2);
  3100. },
  3101. sinusoidalOut: function (k) {
  3102. return Math.sin(k * Math.PI / 2);
  3103. },
  3104. sinusoidalInOut: function (k) {
  3105. return 0.5 * (1 - Math.cos(Math.PI * k));
  3106. },
  3107. exponentialIn: function (k) {
  3108. return k === 0 ? 0 : Math.pow(1024, k - 1);
  3109. },
  3110. exponentialOut: function (k) {
  3111. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  3112. },
  3113. exponentialInOut: function (k) {
  3114. if (k === 0) {
  3115. return 0;
  3116. }
  3117. if (k === 1) {
  3118. return 1;
  3119. }
  3120. if ((k *= 2) < 1) {
  3121. return 0.5 * Math.pow(1024, k - 1);
  3122. }
  3123. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  3124. },
  3125. circularIn: function (k) {
  3126. return 1 - Math.sqrt(1 - k * k);
  3127. },
  3128. circularOut: function (k) {
  3129. return Math.sqrt(1 - (--k * k));
  3130. },
  3131. circularInOut: function (k) {
  3132. if ((k *= 2) < 1) {
  3133. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3134. }
  3135. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3136. },
  3137. elasticIn: function (k) {
  3138. var s;
  3139. var a = 0.1;
  3140. var p = 0.4;
  3141. if (k === 0) {
  3142. return 0;
  3143. }
  3144. if (k === 1) {
  3145. return 1;
  3146. }
  3147. if (!a || a < 1) {
  3148. a = 1;
  3149. s = p / 4;
  3150. }
  3151. else {
  3152. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3153. }
  3154. return -(a * Math.pow(2, 10 * (k -= 1))
  3155. * Math.sin((k - s) * (2 * Math.PI) / p));
  3156. },
  3157. elasticOut: function (k) {
  3158. var s;
  3159. var a = 0.1;
  3160. var p = 0.4;
  3161. if (k === 0) {
  3162. return 0;
  3163. }
  3164. if (k === 1) {
  3165. return 1;
  3166. }
  3167. if (!a || a < 1) {
  3168. a = 1;
  3169. s = p / 4;
  3170. }
  3171. else {
  3172. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3173. }
  3174. return (a * Math.pow(2, -10 * k)
  3175. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3176. },
  3177. elasticInOut: function (k) {
  3178. var s;
  3179. var a = 0.1;
  3180. var p = 0.4;
  3181. if (k === 0) {
  3182. return 0;
  3183. }
  3184. if (k === 1) {
  3185. return 1;
  3186. }
  3187. if (!a || a < 1) {
  3188. a = 1;
  3189. s = p / 4;
  3190. }
  3191. else {
  3192. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3193. }
  3194. if ((k *= 2) < 1) {
  3195. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3196. * Math.sin((k - s) * (2 * Math.PI) / p));
  3197. }
  3198. return a * Math.pow(2, -10 * (k -= 1))
  3199. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3200. },
  3201. backIn: function (k) {
  3202. var s = 1.70158;
  3203. return k * k * ((s + 1) * k - s);
  3204. },
  3205. backOut: function (k) {
  3206. var s = 1.70158;
  3207. return --k * k * ((s + 1) * k + s) + 1;
  3208. },
  3209. backInOut: function (k) {
  3210. var s = 1.70158 * 1.525;
  3211. if ((k *= 2) < 1) {
  3212. return 0.5 * (k * k * ((s + 1) * k - s));
  3213. }
  3214. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3215. },
  3216. bounceIn: function (k) {
  3217. return 1 - easingFuncs.bounceOut(1 - k);
  3218. },
  3219. bounceOut: function (k) {
  3220. if (k < (1 / 2.75)) {
  3221. return 7.5625 * k * k;
  3222. }
  3223. else if (k < (2 / 2.75)) {
  3224. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3225. }
  3226. else if (k < (2.5 / 2.75)) {
  3227. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3228. }
  3229. else {
  3230. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3231. }
  3232. },
  3233. bounceInOut: function (k) {
  3234. if (k < 0.5) {
  3235. return easingFuncs.bounceIn(k * 2) * 0.5;
  3236. }
  3237. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3238. }
  3239. };
  3240. var mathPow = Math.pow;
  3241. var mathSqrt = Math.sqrt;
  3242. var EPSILON$1 = 1e-8;
  3243. var EPSILON_NUMERIC = 1e-4;
  3244. var THREE_SQRT = mathSqrt(3);
  3245. var ONE_THIRD = 1 / 3;
  3246. var _v0 = create();
  3247. var _v1 = create();
  3248. var _v2 = create();
  3249. function isAroundZero(val) {
  3250. return val > -EPSILON$1 && val < EPSILON$1;
  3251. }
  3252. function isNotAroundZero(val) {
  3253. return val > EPSILON$1 || val < -EPSILON$1;
  3254. }
  3255. function cubicAt(p0, p1, p2, p3, t) {
  3256. var onet = 1 - t;
  3257. return onet * onet * (onet * p0 + 3 * t * p1)
  3258. + t * t * (t * p3 + 3 * onet * p2);
  3259. }
  3260. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3261. var onet = 1 - t;
  3262. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3263. + (p3 - p2) * t * t);
  3264. }
  3265. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3266. var a = p3 + 3 * (p1 - p2) - p0;
  3267. var b = 3 * (p2 - p1 * 2 + p0);
  3268. var c = 3 * (p1 - p0);
  3269. var d = p0 - val;
  3270. var A = b * b - 3 * a * c;
  3271. var B = b * c - 9 * a * d;
  3272. var C = c * c - 3 * b * d;
  3273. var n = 0;
  3274. if (isAroundZero(A) && isAroundZero(B)) {
  3275. if (isAroundZero(b)) {
  3276. roots[0] = 0;
  3277. }
  3278. else {
  3279. var t1 = -c / b;
  3280. if (t1 >= 0 && t1 <= 1) {
  3281. roots[n++] = t1;
  3282. }
  3283. }
  3284. }
  3285. else {
  3286. var disc = B * B - 4 * A * C;
  3287. if (isAroundZero(disc)) {
  3288. var K = B / A;
  3289. var t1 = -b / a + K;
  3290. var t2 = -K / 2;
  3291. if (t1 >= 0 && t1 <= 1) {
  3292. roots[n++] = t1;
  3293. }
  3294. if (t2 >= 0 && t2 <= 1) {
  3295. roots[n++] = t2;
  3296. }
  3297. }
  3298. else if (disc > 0) {
  3299. var discSqrt = mathSqrt(disc);
  3300. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3301. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3302. if (Y1 < 0) {
  3303. Y1 = -mathPow(-Y1, ONE_THIRD);
  3304. }
  3305. else {
  3306. Y1 = mathPow(Y1, ONE_THIRD);
  3307. }
  3308. if (Y2 < 0) {
  3309. Y2 = -mathPow(-Y2, ONE_THIRD);
  3310. }
  3311. else {
  3312. Y2 = mathPow(Y2, ONE_THIRD);
  3313. }
  3314. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3315. if (t1 >= 0 && t1 <= 1) {
  3316. roots[n++] = t1;
  3317. }
  3318. }
  3319. else {
  3320. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3321. var theta = Math.acos(T) / 3;
  3322. var ASqrt = mathSqrt(A);
  3323. var tmp = Math.cos(theta);
  3324. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3325. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3326. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3327. if (t1 >= 0 && t1 <= 1) {
  3328. roots[n++] = t1;
  3329. }
  3330. if (t2 >= 0 && t2 <= 1) {
  3331. roots[n++] = t2;
  3332. }
  3333. if (t3 >= 0 && t3 <= 1) {
  3334. roots[n++] = t3;
  3335. }
  3336. }
  3337. }
  3338. return n;
  3339. }
  3340. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3341. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3342. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3343. var c = 3 * p1 - 3 * p0;
  3344. var n = 0;
  3345. if (isAroundZero(a)) {
  3346. if (isNotAroundZero(b)) {
  3347. var t1 = -c / b;
  3348. if (t1 >= 0 && t1 <= 1) {
  3349. extrema[n++] = t1;
  3350. }
  3351. }
  3352. }
  3353. else {
  3354. var disc = b * b - 4 * a * c;
  3355. if (isAroundZero(disc)) {
  3356. extrema[0] = -b / (2 * a);
  3357. }
  3358. else if (disc > 0) {
  3359. var discSqrt = mathSqrt(disc);
  3360. var t1 = (-b + discSqrt) / (2 * a);
  3361. var t2 = (-b - discSqrt) / (2 * a);
  3362. if (t1 >= 0 && t1 <= 1) {
  3363. extrema[n++] = t1;
  3364. }
  3365. if (t2 >= 0 && t2 <= 1) {
  3366. extrema[n++] = t2;
  3367. }
  3368. }
  3369. }
  3370. return n;
  3371. }
  3372. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3373. var p01 = (p1 - p0) * t + p0;
  3374. var p12 = (p2 - p1) * t + p1;
  3375. var p23 = (p3 - p2) * t + p2;
  3376. var p012 = (p12 - p01) * t + p01;
  3377. var p123 = (p23 - p12) * t + p12;
  3378. var p0123 = (p123 - p012) * t + p012;
  3379. out[0] = p0;
  3380. out[1] = p01;
  3381. out[2] = p012;
  3382. out[3] = p0123;
  3383. out[4] = p0123;
  3384. out[5] = p123;
  3385. out[6] = p23;
  3386. out[7] = p3;
  3387. }
  3388. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3389. var t;
  3390. var interval = 0.005;
  3391. var d = Infinity;
  3392. var prev;
  3393. var next;
  3394. var d1;
  3395. var d2;
  3396. _v0[0] = x;
  3397. _v0[1] = y;
  3398. for (var _t = 0; _t < 1; _t += 0.05) {
  3399. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3400. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3401. d1 = distSquare(_v0, _v1);
  3402. if (d1 < d) {
  3403. t = _t;
  3404. d = d1;
  3405. }
  3406. }
  3407. d = Infinity;
  3408. for (var i = 0; i < 32; i++) {
  3409. if (interval < EPSILON_NUMERIC) {
  3410. break;
  3411. }
  3412. prev = t - interval;
  3413. next = t + interval;
  3414. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3415. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3416. d1 = distSquare(_v1, _v0);
  3417. if (prev >= 0 && d1 < d) {
  3418. t = prev;
  3419. d = d1;
  3420. }
  3421. else {
  3422. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3423. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3424. d2 = distSquare(_v2, _v0);
  3425. if (next <= 1 && d2 < d) {
  3426. t = next;
  3427. d = d2;
  3428. }
  3429. else {
  3430. interval *= 0.5;
  3431. }
  3432. }
  3433. }
  3434. if (out) {
  3435. out[0] = cubicAt(x0, x1, x2, x3, t);
  3436. out[1] = cubicAt(y0, y1, y2, y3, t);
  3437. }
  3438. return mathSqrt(d);
  3439. }
  3440. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3441. var px = x0;
  3442. var py = y0;
  3443. var d = 0;
  3444. var step = 1 / iteration;
  3445. for (var i = 1; i <= iteration; i++) {
  3446. var t = i * step;
  3447. var x = cubicAt(x0, x1, x2, x3, t);
  3448. var y = cubicAt(y0, y1, y2, y3, t);
  3449. var dx = x - px;
  3450. var dy = y - py;
  3451. d += Math.sqrt(dx * dx + dy * dy);
  3452. px = x;
  3453. py = y;
  3454. }
  3455. return d;
  3456. }
  3457. function quadraticAt(p0, p1, p2, t) {
  3458. var onet = 1 - t;
  3459. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3460. }
  3461. function quadraticDerivativeAt(p0, p1, p2, t) {
  3462. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3463. }
  3464. function quadraticRootAt(p0, p1, p2, val, roots) {
  3465. var a = p0 - 2 * p1 + p2;
  3466. var b = 2 * (p1 - p0);
  3467. var c = p0 - val;
  3468. var n = 0;
  3469. if (isAroundZero(a)) {
  3470. if (isNotAroundZero(b)) {
  3471. var t1 = -c / b;
  3472. if (t1 >= 0 && t1 <= 1) {
  3473. roots[n++] = t1;
  3474. }
  3475. }
  3476. }
  3477. else {
  3478. var disc = b * b - 4 * a * c;
  3479. if (isAroundZero(disc)) {
  3480. var t1 = -b / (2 * a);
  3481. if (t1 >= 0 && t1 <= 1) {
  3482. roots[n++] = t1;
  3483. }
  3484. }
  3485. else if (disc > 0) {
  3486. var discSqrt = mathSqrt(disc);
  3487. var t1 = (-b + discSqrt) / (2 * a);
  3488. var t2 = (-b - discSqrt) / (2 * a);
  3489. if (t1 >= 0 && t1 <= 1) {
  3490. roots[n++] = t1;
  3491. }
  3492. if (t2 >= 0 && t2 <= 1) {
  3493. roots[n++] = t2;
  3494. }
  3495. }
  3496. }
  3497. return n;
  3498. }
  3499. function quadraticExtremum(p0, p1, p2) {
  3500. var divider = p0 + p2 - 2 * p1;
  3501. if (divider === 0) {
  3502. return 0.5;
  3503. }
  3504. else {
  3505. return (p0 - p1) / divider;
  3506. }
  3507. }
  3508. function quadraticSubdivide(p0, p1, p2, t, out) {
  3509. var p01 = (p1 - p0) * t + p0;
  3510. var p12 = (p2 - p1) * t + p1;
  3511. var p012 = (p12 - p01) * t + p01;
  3512. out[0] = p0;
  3513. out[1] = p01;
  3514. out[2] = p012;
  3515. out[3] = p012;
  3516. out[4] = p12;
  3517. out[5] = p2;
  3518. }
  3519. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3520. var t;
  3521. var interval = 0.005;
  3522. var d = Infinity;
  3523. _v0[0] = x;
  3524. _v0[1] = y;
  3525. for (var _t = 0; _t < 1; _t += 0.05) {
  3526. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3527. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3528. var d1 = distSquare(_v0, _v1);
  3529. if (d1 < d) {
  3530. t = _t;
  3531. d = d1;
  3532. }
  3533. }
  3534. d = Infinity;
  3535. for (var i = 0; i < 32; i++) {
  3536. if (interval < EPSILON_NUMERIC) {
  3537. break;
  3538. }
  3539. var prev = t - interval;
  3540. var next = t + interval;
  3541. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3542. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3543. var d1 = distSquare(_v1, _v0);
  3544. if (prev >= 0 && d1 < d) {
  3545. t = prev;
  3546. d = d1;
  3547. }
  3548. else {
  3549. _v2[0] = quadraticAt(x0, x1, x2, next);
  3550. _v2[1] = quadraticAt(y0, y1, y2, next);
  3551. var d2 = distSquare(_v2, _v0);
  3552. if (next <= 1 && d2 < d) {
  3553. t = next;
  3554. d = d2;
  3555. }
  3556. else {
  3557. interval *= 0.5;
  3558. }
  3559. }
  3560. }
  3561. if (out) {
  3562. out[0] = quadraticAt(x0, x1, x2, t);
  3563. out[1] = quadraticAt(y0, y1, y2, t);
  3564. }
  3565. return mathSqrt(d);
  3566. }
  3567. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3568. var px = x0;
  3569. var py = y0;
  3570. var d = 0;
  3571. var step = 1 / iteration;
  3572. for (var i = 1; i <= iteration; i++) {
  3573. var t = i * step;
  3574. var x = quadraticAt(x0, x1, x2, t);
  3575. var y = quadraticAt(y0, y1, y2, t);
  3576. var dx = x - px;
  3577. var dy = y - py;
  3578. d += Math.sqrt(dx * dx + dy * dy);
  3579. px = x;
  3580. py = y;
  3581. }
  3582. return d;
  3583. }
  3584. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3585. function createCubicEasingFunc(cubicEasingStr) {
  3586. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3587. if (cubic) {
  3588. var points = cubic[1].split(',');
  3589. var a_1 = +trim(points[0]);
  3590. var b_1 = +trim(points[1]);
  3591. var c_1 = +trim(points[2]);
  3592. var d_1 = +trim(points[3]);
  3593. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3594. return;
  3595. }
  3596. var roots_1 = [];
  3597. return function (p) {
  3598. return p <= 0
  3599. ? 0 : p >= 1
  3600. ? 1
  3601. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3602. };
  3603. }
  3604. }
  3605. var Clip = (function () {
  3606. function Clip(opts) {
  3607. this._inited = false;
  3608. this._startTime = 0;
  3609. this._pausedTime = 0;
  3610. this._paused = false;
  3611. this._life = opts.life || 1000;
  3612. this._delay = opts.delay || 0;
  3613. this.loop = opts.loop || false;
  3614. this.onframe = opts.onframe || noop;
  3615. this.ondestroy = opts.ondestroy || noop;
  3616. this.onrestart = opts.onrestart || noop;
  3617. opts.easing && this.setEasing(opts.easing);
  3618. }
  3619. Clip.prototype.step = function (globalTime, deltaTime) {
  3620. if (!this._inited) {
  3621. this._startTime = globalTime + this._delay;
  3622. this._inited = true;
  3623. }
  3624. if (this._paused) {
  3625. this._pausedTime += deltaTime;
  3626. return;
  3627. }
  3628. var life = this._life;
  3629. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3630. var percent = elapsedTime / life;
  3631. if (percent < 0) {
  3632. percent = 0;
  3633. }
  3634. percent = Math.min(percent, 1);
  3635. var easingFunc = this.easingFunc;
  3636. var schedule = easingFunc ? easingFunc(percent) : percent;
  3637. this.onframe(schedule);
  3638. if (percent === 1) {
  3639. if (this.loop) {
  3640. var remainder = elapsedTime % life;
  3641. this._startTime = globalTime - remainder;
  3642. this._pausedTime = 0;
  3643. this.onrestart();
  3644. }
  3645. else {
  3646. return true;
  3647. }
  3648. }
  3649. return false;
  3650. };
  3651. Clip.prototype.pause = function () {
  3652. this._paused = true;
  3653. };
  3654. Clip.prototype.resume = function () {
  3655. this._paused = false;
  3656. };
  3657. Clip.prototype.setEasing = function (easing) {
  3658. this.easing = easing;
  3659. this.easingFunc = isFunction(easing)
  3660. ? easing
  3661. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3662. };
  3663. return Clip;
  3664. }());
  3665. var Entry = (function () {
  3666. function Entry(val) {
  3667. this.value = val;
  3668. }
  3669. return Entry;
  3670. }());
  3671. var LinkedList = (function () {
  3672. function LinkedList() {
  3673. this._len = 0;
  3674. }
  3675. LinkedList.prototype.insert = function (val) {
  3676. var entry = new Entry(val);
  3677. this.insertEntry(entry);
  3678. return entry;
  3679. };
  3680. LinkedList.prototype.insertEntry = function (entry) {
  3681. if (!this.head) {
  3682. this.head = this.tail = entry;
  3683. }
  3684. else {
  3685. this.tail.next = entry;
  3686. entry.prev = this.tail;
  3687. entry.next = null;
  3688. this.tail = entry;
  3689. }
  3690. this._len++;
  3691. };
  3692. LinkedList.prototype.remove = function (entry) {
  3693. var prev = entry.prev;
  3694. var next = entry.next;
  3695. if (prev) {
  3696. prev.next = next;
  3697. }
  3698. else {
  3699. this.head = next;
  3700. }
  3701. if (next) {
  3702. next.prev = prev;
  3703. }
  3704. else {
  3705. this.tail = prev;
  3706. }
  3707. entry.next = entry.prev = null;
  3708. this._len--;
  3709. };
  3710. LinkedList.prototype.len = function () {
  3711. return this._len;
  3712. };
  3713. LinkedList.prototype.clear = function () {
  3714. this.head = this.tail = null;
  3715. this._len = 0;
  3716. };
  3717. return LinkedList;
  3718. }());
  3719. var LRU = (function () {
  3720. function LRU(maxSize) {
  3721. this._list = new LinkedList();
  3722. this._maxSize = 10;
  3723. this._map = {};
  3724. this._maxSize = maxSize;
  3725. }
  3726. LRU.prototype.put = function (key, value) {
  3727. var list = this._list;
  3728. var map = this._map;
  3729. var removed = null;
  3730. if (map[key] == null) {
  3731. var len = list.len();
  3732. var entry = this._lastRemovedEntry;
  3733. if (len >= this._maxSize && len > 0) {
  3734. var leastUsedEntry = list.head;
  3735. list.remove(leastUsedEntry);
  3736. delete map[leastUsedEntry.key];
  3737. removed = leastUsedEntry.value;
  3738. this._lastRemovedEntry = leastUsedEntry;
  3739. }
  3740. if (entry) {
  3741. entry.value = value;
  3742. }
  3743. else {
  3744. entry = new Entry(value);
  3745. }
  3746. entry.key = key;
  3747. list.insertEntry(entry);
  3748. map[key] = entry;
  3749. }
  3750. return removed;
  3751. };
  3752. LRU.prototype.get = function (key) {
  3753. var entry = this._map[key];
  3754. var list = this._list;
  3755. if (entry != null) {
  3756. if (entry !== list.tail) {
  3757. list.remove(entry);
  3758. list.insertEntry(entry);
  3759. }
  3760. return entry.value;
  3761. }
  3762. };
  3763. LRU.prototype.clear = function () {
  3764. this._list.clear();
  3765. this._map = {};
  3766. };
  3767. LRU.prototype.len = function () {
  3768. return this._list.len();
  3769. };
  3770. return LRU;
  3771. }());
  3772. var kCSSColorTable = {
  3773. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3774. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3775. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3776. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3777. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3778. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3779. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3780. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3781. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3782. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3783. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3784. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3785. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3786. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3787. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3788. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3789. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3790. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3791. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3792. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3793. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3794. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3795. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3796. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3797. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3798. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3799. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3800. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3801. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3802. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3803. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3804. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3805. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3806. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3807. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3808. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3809. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3810. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3811. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3812. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3813. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3814. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3815. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3816. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3817. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3818. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3819. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3820. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3821. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3822. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3823. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3824. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3825. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3826. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3827. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3828. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3829. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3830. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3831. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3832. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3833. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3834. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3835. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3836. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3837. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3838. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3839. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3840. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3841. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3842. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3843. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3844. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3845. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3846. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3847. };
  3848. function clampCssByte(i) {
  3849. i = Math.round(i);
  3850. return i < 0 ? 0 : i > 255 ? 255 : i;
  3851. }
  3852. function clampCssAngle(i) {
  3853. i = Math.round(i);
  3854. return i < 0 ? 0 : i > 360 ? 360 : i;
  3855. }
  3856. function clampCssFloat(f) {
  3857. return f < 0 ? 0 : f > 1 ? 1 : f;
  3858. }
  3859. function parseCssInt(val) {
  3860. var str = val;
  3861. if (str.length && str.charAt(str.length - 1) === '%') {
  3862. return clampCssByte(parseFloat(str) / 100 * 255);
  3863. }
  3864. return clampCssByte(parseInt(str, 10));
  3865. }
  3866. function parseCssFloat(val) {
  3867. var str = val;
  3868. if (str.length && str.charAt(str.length - 1) === '%') {
  3869. return clampCssFloat(parseFloat(str) / 100);
  3870. }
  3871. return clampCssFloat(parseFloat(str));
  3872. }
  3873. function cssHueToRgb(m1, m2, h) {
  3874. if (h < 0) {
  3875. h += 1;
  3876. }
  3877. else if (h > 1) {
  3878. h -= 1;
  3879. }
  3880. if (h * 6 < 1) {
  3881. return m1 + (m2 - m1) * h * 6;
  3882. }
  3883. if (h * 2 < 1) {
  3884. return m2;
  3885. }
  3886. if (h * 3 < 2) {
  3887. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3888. }
  3889. return m1;
  3890. }
  3891. function lerpNumber(a, b, p) {
  3892. return a + (b - a) * p;
  3893. }
  3894. function setRgba(out, r, g, b, a) {
  3895. out[0] = r;
  3896. out[1] = g;
  3897. out[2] = b;
  3898. out[3] = a;
  3899. return out;
  3900. }
  3901. function copyRgba(out, a) {
  3902. out[0] = a[0];
  3903. out[1] = a[1];
  3904. out[2] = a[2];
  3905. out[3] = a[3];
  3906. return out;
  3907. }
  3908. var colorCache = new LRU(20);
  3909. var lastRemovedArr = null;
  3910. function putToCache(colorStr, rgbaArr) {
  3911. if (lastRemovedArr) {
  3912. copyRgba(lastRemovedArr, rgbaArr);
  3913. }
  3914. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3915. }
  3916. function parse(colorStr, rgbaArr) {
  3917. if (!colorStr) {
  3918. return;
  3919. }
  3920. rgbaArr = rgbaArr || [];
  3921. var cached = colorCache.get(colorStr);
  3922. if (cached) {
  3923. return copyRgba(rgbaArr, cached);
  3924. }
  3925. colorStr = colorStr + '';
  3926. var str = colorStr.replace(/ /g, '').toLowerCase();
  3927. if (str in kCSSColorTable) {
  3928. copyRgba(rgbaArr, kCSSColorTable[str]);
  3929. putToCache(colorStr, rgbaArr);
  3930. return rgbaArr;
  3931. }
  3932. var strLen = str.length;
  3933. if (str.charAt(0) === '#') {
  3934. if (strLen === 4 || strLen === 5) {
  3935. var iv = parseInt(str.slice(1, 4), 16);
  3936. if (!(iv >= 0 && iv <= 0xfff)) {
  3937. setRgba(rgbaArr, 0, 0, 0, 1);
  3938. return;
  3939. }
  3940. 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);
  3941. putToCache(colorStr, rgbaArr);
  3942. return rgbaArr;
  3943. }
  3944. else if (strLen === 7 || strLen === 9) {
  3945. var iv = parseInt(str.slice(1, 7), 16);
  3946. if (!(iv >= 0 && iv <= 0xffffff)) {
  3947. setRgba(rgbaArr, 0, 0, 0, 1);
  3948. return;
  3949. }
  3950. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3951. putToCache(colorStr, rgbaArr);
  3952. return rgbaArr;
  3953. }
  3954. return;
  3955. }
  3956. var op = str.indexOf('(');
  3957. var ep = str.indexOf(')');
  3958. if (op !== -1 && ep + 1 === strLen) {
  3959. var fname = str.substr(0, op);
  3960. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3961. var alpha = 1;
  3962. switch (fname) {
  3963. case 'rgba':
  3964. if (params.length !== 4) {
  3965. return params.length === 3
  3966. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3967. : setRgba(rgbaArr, 0, 0, 0, 1);
  3968. }
  3969. alpha = parseCssFloat(params.pop());
  3970. case 'rgb':
  3971. if (params.length >= 3) {
  3972. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3973. putToCache(colorStr, rgbaArr);
  3974. return rgbaArr;
  3975. }
  3976. else {
  3977. setRgba(rgbaArr, 0, 0, 0, 1);
  3978. return;
  3979. }
  3980. case 'hsla':
  3981. if (params.length !== 4) {
  3982. setRgba(rgbaArr, 0, 0, 0, 1);
  3983. return;
  3984. }
  3985. params[3] = parseCssFloat(params[3]);
  3986. hsla2rgba(params, rgbaArr);
  3987. putToCache(colorStr, rgbaArr);
  3988. return rgbaArr;
  3989. case 'hsl':
  3990. if (params.length !== 3) {
  3991. setRgba(rgbaArr, 0, 0, 0, 1);
  3992. return;
  3993. }
  3994. hsla2rgba(params, rgbaArr);
  3995. putToCache(colorStr, rgbaArr);
  3996. return rgbaArr;
  3997. default:
  3998. return;
  3999. }
  4000. }
  4001. setRgba(rgbaArr, 0, 0, 0, 1);
  4002. return;
  4003. }
  4004. function hsla2rgba(hsla, rgba) {
  4005. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  4006. var s = parseCssFloat(hsla[1]);
  4007. var l = parseCssFloat(hsla[2]);
  4008. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  4009. var m1 = l * 2 - m2;
  4010. rgba = rgba || [];
  4011. 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);
  4012. if (hsla.length === 4) {
  4013. rgba[3] = hsla[3];
  4014. }
  4015. return rgba;
  4016. }
  4017. function rgba2hsla(rgba) {
  4018. if (!rgba) {
  4019. return;
  4020. }
  4021. var R = rgba[0] / 255;
  4022. var G = rgba[1] / 255;
  4023. var B = rgba[2] / 255;
  4024. var vMin = Math.min(R, G, B);
  4025. var vMax = Math.max(R, G, B);
  4026. var delta = vMax - vMin;
  4027. var L = (vMax + vMin) / 2;
  4028. var H;
  4029. var S;
  4030. if (delta === 0) {
  4031. H = 0;
  4032. S = 0;
  4033. }
  4034. else {
  4035. if (L < 0.5) {
  4036. S = delta / (vMax + vMin);
  4037. }
  4038. else {
  4039. S = delta / (2 - vMax - vMin);
  4040. }
  4041. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  4042. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  4043. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  4044. if (R === vMax) {
  4045. H = deltaB - deltaG;
  4046. }
  4047. else if (G === vMax) {
  4048. H = (1 / 3) + deltaR - deltaB;
  4049. }
  4050. else if (B === vMax) {
  4051. H = (2 / 3) + deltaG - deltaR;
  4052. }
  4053. if (H < 0) {
  4054. H += 1;
  4055. }
  4056. if (H > 1) {
  4057. H -= 1;
  4058. }
  4059. }
  4060. var hsla = [H * 360, S, L];
  4061. if (rgba[3] != null) {
  4062. hsla.push(rgba[3]);
  4063. }
  4064. return hsla;
  4065. }
  4066. function lift(color, level) {
  4067. var colorArr = parse(color);
  4068. if (colorArr) {
  4069. for (var i = 0; i < 3; i++) {
  4070. if (level < 0) {
  4071. colorArr[i] = colorArr[i] * (1 - level) | 0;
  4072. }
  4073. else {
  4074. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  4075. }
  4076. if (colorArr[i] > 255) {
  4077. colorArr[i] = 255;
  4078. }
  4079. else if (colorArr[i] < 0) {
  4080. colorArr[i] = 0;
  4081. }
  4082. }
  4083. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  4084. }
  4085. }
  4086. function toHex(color) {
  4087. var colorArr = parse(color);
  4088. if (colorArr) {
  4089. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  4090. }
  4091. }
  4092. function fastLerp(normalizedValue, colors, out) {
  4093. if (!(colors && colors.length)
  4094. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  4095. return;
  4096. }
  4097. out = out || [];
  4098. var value = normalizedValue * (colors.length - 1);
  4099. var leftIndex = Math.floor(value);
  4100. var rightIndex = Math.ceil(value);
  4101. var leftColor = colors[leftIndex];
  4102. var rightColor = colors[rightIndex];
  4103. var dv = value - leftIndex;
  4104. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  4105. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  4106. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  4107. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  4108. return out;
  4109. }
  4110. var fastMapToColor = fastLerp;
  4111. function lerp$1(normalizedValue, colors, fullOutput) {
  4112. if (!(colors && colors.length)
  4113. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  4114. return;
  4115. }
  4116. var value = normalizedValue * (colors.length - 1);
  4117. var leftIndex = Math.floor(value);
  4118. var rightIndex = Math.ceil(value);
  4119. var leftColor = parse(colors[leftIndex]);
  4120. var rightColor = parse(colors[rightIndex]);
  4121. var dv = value - leftIndex;
  4122. var color = stringify([
  4123. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  4124. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  4125. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  4126. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  4127. ], 'rgba');
  4128. return fullOutput
  4129. ? {
  4130. color: color,
  4131. leftIndex: leftIndex,
  4132. rightIndex: rightIndex,
  4133. value: value
  4134. }
  4135. : color;
  4136. }
  4137. var mapToColor = lerp$1;
  4138. function modifyHSL(color, h, s, l) {
  4139. var colorArr = parse(color);
  4140. if (color) {
  4141. colorArr = rgba2hsla(colorArr);
  4142. h != null && (colorArr[0] = clampCssAngle(isFunction(h) ? h(colorArr[0]) : h));
  4143. s != null && (colorArr[1] = parseCssFloat(isFunction(s) ? s(colorArr[1]) : s));
  4144. l != null && (colorArr[2] = parseCssFloat(isFunction(l) ? l(colorArr[2]) : l));
  4145. return stringify(hsla2rgba(colorArr), 'rgba');
  4146. }
  4147. }
  4148. function modifyAlpha(color, alpha) {
  4149. var colorArr = parse(color);
  4150. if (colorArr && alpha != null) {
  4151. colorArr[3] = clampCssFloat(alpha);
  4152. return stringify(colorArr, 'rgba');
  4153. }
  4154. }
  4155. function stringify(arrColor, type) {
  4156. if (!arrColor || !arrColor.length) {
  4157. return;
  4158. }
  4159. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4160. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4161. colorStr += ',' + arrColor[3];
  4162. }
  4163. return type + '(' + colorStr + ')';
  4164. }
  4165. function lum(color, backgroundLum) {
  4166. var arr = parse(color);
  4167. return arr
  4168. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4169. + (1 - arr[3]) * backgroundLum
  4170. : 0;
  4171. }
  4172. function random() {
  4173. return stringify([
  4174. Math.round(Math.random() * 255),
  4175. Math.round(Math.random() * 255),
  4176. Math.round(Math.random() * 255)
  4177. ], 'rgb');
  4178. }
  4179. var liftedColorCache = new LRU(100);
  4180. function liftColor(color) {
  4181. if (isString(color)) {
  4182. var liftedColor = liftedColorCache.get(color);
  4183. if (!liftedColor) {
  4184. liftedColor = lift(color, -0.1);
  4185. liftedColorCache.put(color, liftedColor);
  4186. }
  4187. return liftedColor;
  4188. }
  4189. else if (isGradientObject(color)) {
  4190. var ret = extend({}, color);
  4191. ret.colorStops = map(color.colorStops, function (stop) { return ({
  4192. offset: stop.offset,
  4193. color: lift(stop.color, -0.1)
  4194. }); });
  4195. return ret;
  4196. }
  4197. return color;
  4198. }
  4199. var color = /*#__PURE__*/Object.freeze({
  4200. __proto__: null,
  4201. parseCssInt: parseCssInt,
  4202. parseCssFloat: parseCssFloat,
  4203. parse: parse,
  4204. lift: lift,
  4205. toHex: toHex,
  4206. fastLerp: fastLerp,
  4207. fastMapToColor: fastMapToColor,
  4208. lerp: lerp$1,
  4209. mapToColor: mapToColor,
  4210. modifyHSL: modifyHSL,
  4211. modifyAlpha: modifyAlpha,
  4212. stringify: stringify,
  4213. lum: lum,
  4214. random: random,
  4215. liftColor: liftColor
  4216. });
  4217. var mathRound = Math.round;
  4218. function normalizeColor(color) {
  4219. var opacity;
  4220. if (!color || color === 'transparent') {
  4221. color = 'none';
  4222. }
  4223. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  4224. var arr = parse(color);
  4225. if (arr) {
  4226. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  4227. opacity = arr[3];
  4228. }
  4229. }
  4230. return {
  4231. color: color,
  4232. opacity: opacity == null ? 1 : opacity
  4233. };
  4234. }
  4235. var EPSILON$2 = 1e-4;
  4236. function isAroundZero$1(transform) {
  4237. return transform < EPSILON$2 && transform > -EPSILON$2;
  4238. }
  4239. function round3(transform) {
  4240. return mathRound(transform * 1e3) / 1e3;
  4241. }
  4242. function round4(transform) {
  4243. return mathRound(transform * 1e4) / 1e4;
  4244. }
  4245. function getMatrixStr(m) {
  4246. return 'matrix('
  4247. + round3(m[0]) + ','
  4248. + round3(m[1]) + ','
  4249. + round3(m[2]) + ','
  4250. + round3(m[3]) + ','
  4251. + round4(m[4]) + ','
  4252. + round4(m[5])
  4253. + ')';
  4254. }
  4255. var TEXT_ALIGN_TO_ANCHOR = {
  4256. left: 'start',
  4257. right: 'end',
  4258. center: 'middle',
  4259. middle: 'middle'
  4260. };
  4261. function adjustTextY(y, lineHeight, textBaseline) {
  4262. if (textBaseline === 'top') {
  4263. y += lineHeight / 2;
  4264. }
  4265. else if (textBaseline === 'bottom') {
  4266. y -= lineHeight / 2;
  4267. }
  4268. return y;
  4269. }
  4270. function hasShadow(style) {
  4271. return style
  4272. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  4273. }
  4274. function getShadowKey(displayable) {
  4275. var style = displayable.style;
  4276. var globalScale = displayable.getGlobalScale();
  4277. return [
  4278. style.shadowColor,
  4279. (style.shadowBlur || 0).toFixed(2),
  4280. (style.shadowOffsetX || 0).toFixed(2),
  4281. (style.shadowOffsetY || 0).toFixed(2),
  4282. globalScale[0],
  4283. globalScale[1]
  4284. ].join(',');
  4285. }
  4286. function isImagePattern(val) {
  4287. return val && (!!val.image);
  4288. }
  4289. function isSVGPattern(val) {
  4290. return val && (!!val.svgElement);
  4291. }
  4292. function isPattern(val) {
  4293. return isImagePattern(val) || isSVGPattern(val);
  4294. }
  4295. function isLinearGradient(val) {
  4296. return val.type === 'linear';
  4297. }
  4298. function isRadialGradient(val) {
  4299. return val.type === 'radial';
  4300. }
  4301. function isGradient(val) {
  4302. return val && (val.type === 'linear'
  4303. || val.type === 'radial');
  4304. }
  4305. function getIdURL(id) {
  4306. return "url(#" + id + ")";
  4307. }
  4308. function getPathPrecision(el) {
  4309. var scale = el.getGlobalScale();
  4310. var size = Math.max(scale[0], scale[1]);
  4311. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  4312. }
  4313. function getSRTTransformString(transform) {
  4314. var x = transform.x || 0;
  4315. var y = transform.y || 0;
  4316. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  4317. var scaleX = retrieve2(transform.scaleX, 1);
  4318. var scaleY = retrieve2(transform.scaleY, 1);
  4319. var skewX = transform.skewX || 0;
  4320. var skewY = transform.skewY || 0;
  4321. var res = [];
  4322. if (x || y) {
  4323. res.push("translate(" + x + "px," + y + "px)");
  4324. }
  4325. if (rotation) {
  4326. res.push("rotate(" + rotation + ")");
  4327. }
  4328. if (scaleX !== 1 || scaleY !== 1) {
  4329. res.push("scale(" + scaleX + "," + scaleY + ")");
  4330. }
  4331. if (skewX || skewY) {
  4332. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  4333. }
  4334. return res.join(' ');
  4335. }
  4336. var encodeBase64 = (function () {
  4337. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  4338. return function (str) {
  4339. return window.btoa(unescape(encodeURIComponent(str)));
  4340. };
  4341. }
  4342. if (typeof Buffer !== 'undefined') {
  4343. return function (str) {
  4344. return Buffer.from(str).toString('base64');
  4345. };
  4346. }
  4347. return function (str) {
  4348. if ("development" !== 'production') {
  4349. logError('Base64 isn\'t natively supported in the current environment.');
  4350. }
  4351. return null;
  4352. };
  4353. })();
  4354. var arraySlice = Array.prototype.slice;
  4355. function interpolateNumber(p0, p1, percent) {
  4356. return (p1 - p0) * percent + p0;
  4357. }
  4358. function interpolate1DArray(out, p0, p1, percent) {
  4359. var len = p0.length;
  4360. for (var i = 0; i < len; i++) {
  4361. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4362. }
  4363. return out;
  4364. }
  4365. function interpolate2DArray(out, p0, p1, percent) {
  4366. var len = p0.length;
  4367. var len2 = len && p0[0].length;
  4368. for (var i = 0; i < len; i++) {
  4369. if (!out[i]) {
  4370. out[i] = [];
  4371. }
  4372. for (var j = 0; j < len2; j++) {
  4373. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4374. }
  4375. }
  4376. return out;
  4377. }
  4378. function add1DArray(out, p0, p1, sign) {
  4379. var len = p0.length;
  4380. for (var i = 0; i < len; i++) {
  4381. out[i] = p0[i] + p1[i] * sign;
  4382. }
  4383. return out;
  4384. }
  4385. function add2DArray(out, p0, p1, sign) {
  4386. var len = p0.length;
  4387. var len2 = len && p0[0].length;
  4388. for (var i = 0; i < len; i++) {
  4389. if (!out[i]) {
  4390. out[i] = [];
  4391. }
  4392. for (var j = 0; j < len2; j++) {
  4393. out[i][j] = p0[i][j] + p1[i][j] * sign;
  4394. }
  4395. }
  4396. return out;
  4397. }
  4398. function fillColorStops(val0, val1) {
  4399. var len0 = val0.length;
  4400. var len1 = val1.length;
  4401. var shorterArr = len0 > len1 ? val1 : val0;
  4402. var shorterLen = Math.min(len0, len1);
  4403. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4404. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4405. shorterArr.push({
  4406. offset: last.offset,
  4407. color: last.color.slice()
  4408. });
  4409. }
  4410. }
  4411. function fillArray(val0, val1, arrDim) {
  4412. var arr0 = val0;
  4413. var arr1 = val1;
  4414. if (!arr0.push || !arr1.push) {
  4415. return;
  4416. }
  4417. var arr0Len = arr0.length;
  4418. var arr1Len = arr1.length;
  4419. if (arr0Len !== arr1Len) {
  4420. var isPreviousLarger = arr0Len > arr1Len;
  4421. if (isPreviousLarger) {
  4422. arr0.length = arr1Len;
  4423. }
  4424. else {
  4425. for (var i = arr0Len; i < arr1Len; i++) {
  4426. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4427. }
  4428. }
  4429. }
  4430. var len2 = arr0[0] && arr0[0].length;
  4431. for (var i = 0; i < arr0.length; i++) {
  4432. if (arrDim === 1) {
  4433. if (isNaN(arr0[i])) {
  4434. arr0[i] = arr1[i];
  4435. }
  4436. }
  4437. else {
  4438. for (var j = 0; j < len2; j++) {
  4439. if (isNaN(arr0[i][j])) {
  4440. arr0[i][j] = arr1[i][j];
  4441. }
  4442. }
  4443. }
  4444. }
  4445. }
  4446. function cloneValue(value) {
  4447. if (isArrayLike(value)) {
  4448. var len = value.length;
  4449. if (isArrayLike(value[0])) {
  4450. var ret = [];
  4451. for (var i = 0; i < len; i++) {
  4452. ret.push(arraySlice.call(value[i]));
  4453. }
  4454. return ret;
  4455. }
  4456. return arraySlice.call(value);
  4457. }
  4458. return value;
  4459. }
  4460. function rgba2String(rgba) {
  4461. rgba[0] = Math.floor(rgba[0]) || 0;
  4462. rgba[1] = Math.floor(rgba[1]) || 0;
  4463. rgba[2] = Math.floor(rgba[2]) || 0;
  4464. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4465. return 'rgba(' + rgba.join(',') + ')';
  4466. }
  4467. function guessArrayDim(value) {
  4468. return isArrayLike(value && value[0]) ? 2 : 1;
  4469. }
  4470. var VALUE_TYPE_NUMBER = 0;
  4471. var VALUE_TYPE_1D_ARRAY = 1;
  4472. var VALUE_TYPE_2D_ARRAY = 2;
  4473. var VALUE_TYPE_COLOR = 3;
  4474. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4475. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4476. var VALUE_TYPE_UNKOWN = 6;
  4477. function isGradientValueType(valType) {
  4478. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4479. }
  4480. function isArrayValueType(valType) {
  4481. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4482. }
  4483. var tmpRgba = [0, 0, 0, 0];
  4484. var Track = (function () {
  4485. function Track(propName) {
  4486. this.keyframes = [];
  4487. this.discrete = false;
  4488. this._invalid = false;
  4489. this._needsSort = false;
  4490. this._lastFr = 0;
  4491. this._lastFrP = 0;
  4492. this.propName = propName;
  4493. }
  4494. Track.prototype.isFinished = function () {
  4495. return this._finished;
  4496. };
  4497. Track.prototype.setFinished = function () {
  4498. this._finished = true;
  4499. if (this._additiveTrack) {
  4500. this._additiveTrack.setFinished();
  4501. }
  4502. };
  4503. Track.prototype.needsAnimate = function () {
  4504. return this.keyframes.length >= 1;
  4505. };
  4506. Track.prototype.getAdditiveTrack = function () {
  4507. return this._additiveTrack;
  4508. };
  4509. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4510. this._needsSort = true;
  4511. var keyframes = this.keyframes;
  4512. var len = keyframes.length;
  4513. var discrete = false;
  4514. var valType = VALUE_TYPE_UNKOWN;
  4515. var value = rawValue;
  4516. if (isArrayLike(rawValue)) {
  4517. var arrayDim = guessArrayDim(rawValue);
  4518. valType = arrayDim;
  4519. if (arrayDim === 1 && !isNumber(rawValue[0])
  4520. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4521. discrete = true;
  4522. }
  4523. }
  4524. else {
  4525. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4526. valType = VALUE_TYPE_NUMBER;
  4527. }
  4528. else if (isString(rawValue)) {
  4529. if (!isNaN(+rawValue)) {
  4530. valType = VALUE_TYPE_NUMBER;
  4531. }
  4532. else {
  4533. var colorArray = parse(rawValue);
  4534. if (colorArray) {
  4535. value = colorArray;
  4536. valType = VALUE_TYPE_COLOR;
  4537. }
  4538. }
  4539. }
  4540. else if (isGradientObject(rawValue)) {
  4541. var parsedGradient = extend({}, value);
  4542. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4543. offset: colorStop.offset,
  4544. color: parse(colorStop.color)
  4545. }); });
  4546. if (isLinearGradient(rawValue)) {
  4547. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4548. }
  4549. else if (isRadialGradient(rawValue)) {
  4550. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4551. }
  4552. value = parsedGradient;
  4553. }
  4554. }
  4555. if (len === 0) {
  4556. this.valType = valType;
  4557. }
  4558. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4559. discrete = true;
  4560. }
  4561. this.discrete = this.discrete || discrete;
  4562. var kf = {
  4563. time: time,
  4564. value: value,
  4565. rawValue: rawValue,
  4566. percent: 0
  4567. };
  4568. if (easing) {
  4569. kf.easing = easing;
  4570. kf.easingFunc = isFunction(easing)
  4571. ? easing
  4572. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4573. }
  4574. keyframes.push(kf);
  4575. return kf;
  4576. };
  4577. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4578. var kfs = this.keyframes;
  4579. if (this._needsSort) {
  4580. kfs.sort(function (a, b) {
  4581. return a.time - b.time;
  4582. });
  4583. }
  4584. var valType = this.valType;
  4585. var kfsLen = kfs.length;
  4586. var lastKf = kfs[kfsLen - 1];
  4587. var isDiscrete = this.discrete;
  4588. var isArr = isArrayValueType(valType);
  4589. var isGradient = isGradientValueType(valType);
  4590. for (var i = 0; i < kfsLen; i++) {
  4591. var kf = kfs[i];
  4592. var value = kf.value;
  4593. var lastValue = lastKf.value;
  4594. kf.percent = kf.time / maxTime;
  4595. if (!isDiscrete) {
  4596. if (isArr && i !== kfsLen - 1) {
  4597. fillArray(value, lastValue, valType);
  4598. }
  4599. else if (isGradient) {
  4600. fillColorStops(value.colorStops, lastValue.colorStops);
  4601. }
  4602. }
  4603. }
  4604. if (!isDiscrete
  4605. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4606. && additiveTrack
  4607. && this.needsAnimate()
  4608. && additiveTrack.needsAnimate()
  4609. && valType === additiveTrack.valType
  4610. && !additiveTrack._finished) {
  4611. this._additiveTrack = additiveTrack;
  4612. var startValue = kfs[0].value;
  4613. for (var i = 0; i < kfsLen; i++) {
  4614. if (valType === VALUE_TYPE_NUMBER) {
  4615. kfs[i].additiveValue = kfs[i].value - startValue;
  4616. }
  4617. else if (valType === VALUE_TYPE_COLOR) {
  4618. kfs[i].additiveValue =
  4619. add1DArray([], kfs[i].value, startValue, -1);
  4620. }
  4621. else if (isArrayValueType(valType)) {
  4622. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4623. ? add1DArray([], kfs[i].value, startValue, -1)
  4624. : add2DArray([], kfs[i].value, startValue, -1);
  4625. }
  4626. }
  4627. }
  4628. };
  4629. Track.prototype.step = function (target, percent) {
  4630. if (this._finished) {
  4631. return;
  4632. }
  4633. if (this._additiveTrack && this._additiveTrack._finished) {
  4634. this._additiveTrack = null;
  4635. }
  4636. var isAdditive = this._additiveTrack != null;
  4637. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4638. var valType = this.valType;
  4639. var keyframes = this.keyframes;
  4640. var kfsNum = keyframes.length;
  4641. var propName = this.propName;
  4642. var isValueColor = valType === VALUE_TYPE_COLOR;
  4643. var frameIdx;
  4644. var lastFrame = this._lastFr;
  4645. var mathMin = Math.min;
  4646. var frame;
  4647. var nextFrame;
  4648. if (kfsNum === 1) {
  4649. frame = nextFrame = keyframes[0];
  4650. }
  4651. else {
  4652. if (percent < 0) {
  4653. frameIdx = 0;
  4654. }
  4655. else if (percent < this._lastFrP) {
  4656. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4657. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4658. if (keyframes[frameIdx].percent <= percent) {
  4659. break;
  4660. }
  4661. }
  4662. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4663. }
  4664. else {
  4665. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4666. if (keyframes[frameIdx].percent > percent) {
  4667. break;
  4668. }
  4669. }
  4670. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4671. }
  4672. nextFrame = keyframes[frameIdx + 1];
  4673. frame = keyframes[frameIdx];
  4674. }
  4675. if (!(frame && nextFrame)) {
  4676. return;
  4677. }
  4678. this._lastFr = frameIdx;
  4679. this._lastFrP = percent;
  4680. var interval = (nextFrame.percent - frame.percent);
  4681. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4682. if (nextFrame.easingFunc) {
  4683. w = nextFrame.easingFunc(w);
  4684. }
  4685. var targetArr = isAdditive ? this._additiveValue
  4686. : (isValueColor ? tmpRgba : target[propName]);
  4687. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4688. targetArr = this._additiveValue = [];
  4689. }
  4690. if (this.discrete) {
  4691. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4692. }
  4693. else if (isArrayValueType(valType)) {
  4694. valType === VALUE_TYPE_1D_ARRAY
  4695. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4696. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4697. }
  4698. else if (isGradientValueType(valType)) {
  4699. var val = frame[valueKey];
  4700. var nextVal_1 = nextFrame[valueKey];
  4701. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4702. target[propName] = {
  4703. type: isLinearGradient_1 ? 'linear' : 'radial',
  4704. x: interpolateNumber(val.x, nextVal_1.x, w),
  4705. y: interpolateNumber(val.y, nextVal_1.y, w),
  4706. colorStops: map(val.colorStops, function (colorStop, idx) {
  4707. var nextColorStop = nextVal_1.colorStops[idx];
  4708. return {
  4709. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4710. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4711. };
  4712. }),
  4713. global: nextVal_1.global
  4714. };
  4715. if (isLinearGradient_1) {
  4716. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4717. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4718. }
  4719. else {
  4720. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4721. }
  4722. }
  4723. else if (isValueColor) {
  4724. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4725. if (!isAdditive) {
  4726. target[propName] = rgba2String(targetArr);
  4727. }
  4728. }
  4729. else {
  4730. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4731. if (isAdditive) {
  4732. this._additiveValue = value;
  4733. }
  4734. else {
  4735. target[propName] = value;
  4736. }
  4737. }
  4738. if (isAdditive) {
  4739. this._addToTarget(target);
  4740. }
  4741. };
  4742. Track.prototype._addToTarget = function (target) {
  4743. var valType = this.valType;
  4744. var propName = this.propName;
  4745. var additiveValue = this._additiveValue;
  4746. if (valType === VALUE_TYPE_NUMBER) {
  4747. target[propName] = target[propName] + additiveValue;
  4748. }
  4749. else if (valType === VALUE_TYPE_COLOR) {
  4750. parse(target[propName], tmpRgba);
  4751. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4752. target[propName] = rgba2String(tmpRgba);
  4753. }
  4754. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4755. add1DArray(target[propName], target[propName], additiveValue, 1);
  4756. }
  4757. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4758. add2DArray(target[propName], target[propName], additiveValue, 1);
  4759. }
  4760. };
  4761. return Track;
  4762. }());
  4763. var Animator = (function () {
  4764. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4765. this._tracks = {};
  4766. this._trackKeys = [];
  4767. this._maxTime = 0;
  4768. this._started = 0;
  4769. this._clip = null;
  4770. this._target = target;
  4771. this._loop = loop;
  4772. if (loop && additiveTo) {
  4773. logError('Can\' use additive animation on looped animation.');
  4774. return;
  4775. }
  4776. this._additiveAnimators = additiveTo;
  4777. this._allowDiscrete = allowDiscreteAnimation;
  4778. }
  4779. Animator.prototype.getMaxTime = function () {
  4780. return this._maxTime;
  4781. };
  4782. Animator.prototype.getDelay = function () {
  4783. return this._delay;
  4784. };
  4785. Animator.prototype.getLoop = function () {
  4786. return this._loop;
  4787. };
  4788. Animator.prototype.getTarget = function () {
  4789. return this._target;
  4790. };
  4791. Animator.prototype.changeTarget = function (target) {
  4792. this._target = target;
  4793. };
  4794. Animator.prototype.when = function (time, props, easing) {
  4795. return this.whenWithKeys(time, props, keys(props), easing);
  4796. };
  4797. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4798. var tracks = this._tracks;
  4799. for (var i = 0; i < propNames.length; i++) {
  4800. var propName = propNames[i];
  4801. var track = tracks[propName];
  4802. if (!track) {
  4803. track = tracks[propName] = new Track(propName);
  4804. var initialValue = void 0;
  4805. var additiveTrack = this._getAdditiveTrack(propName);
  4806. if (additiveTrack) {
  4807. var addtiveTrackKfs = additiveTrack.keyframes;
  4808. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4809. initialValue = lastFinalKf && lastFinalKf.value;
  4810. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4811. initialValue = rgba2String(initialValue);
  4812. }
  4813. }
  4814. else {
  4815. initialValue = this._target[propName];
  4816. }
  4817. if (initialValue == null) {
  4818. continue;
  4819. }
  4820. if (time > 0) {
  4821. track.addKeyframe(0, cloneValue(initialValue), easing);
  4822. }
  4823. this._trackKeys.push(propName);
  4824. }
  4825. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4826. }
  4827. this._maxTime = Math.max(this._maxTime, time);
  4828. return this;
  4829. };
  4830. Animator.prototype.pause = function () {
  4831. this._clip.pause();
  4832. this._paused = true;
  4833. };
  4834. Animator.prototype.resume = function () {
  4835. this._clip.resume();
  4836. this._paused = false;
  4837. };
  4838. Animator.prototype.isPaused = function () {
  4839. return !!this._paused;
  4840. };
  4841. Animator.prototype.duration = function (duration) {
  4842. this._maxTime = duration;
  4843. this._force = true;
  4844. return this;
  4845. };
  4846. Animator.prototype._doneCallback = function () {
  4847. this._setTracksFinished();
  4848. this._clip = null;
  4849. var doneList = this._doneCbs;
  4850. if (doneList) {
  4851. var len = doneList.length;
  4852. for (var i = 0; i < len; i++) {
  4853. doneList[i].call(this);
  4854. }
  4855. }
  4856. };
  4857. Animator.prototype._abortedCallback = function () {
  4858. this._setTracksFinished();
  4859. var animation = this.animation;
  4860. var abortedList = this._abortedCbs;
  4861. if (animation) {
  4862. animation.removeClip(this._clip);
  4863. }
  4864. this._clip = null;
  4865. if (abortedList) {
  4866. for (var i = 0; i < abortedList.length; i++) {
  4867. abortedList[i].call(this);
  4868. }
  4869. }
  4870. };
  4871. Animator.prototype._setTracksFinished = function () {
  4872. var tracks = this._tracks;
  4873. var tracksKeys = this._trackKeys;
  4874. for (var i = 0; i < tracksKeys.length; i++) {
  4875. tracks[tracksKeys[i]].setFinished();
  4876. }
  4877. };
  4878. Animator.prototype._getAdditiveTrack = function (trackName) {
  4879. var additiveTrack;
  4880. var additiveAnimators = this._additiveAnimators;
  4881. if (additiveAnimators) {
  4882. for (var i = 0; i < additiveAnimators.length; i++) {
  4883. var track = additiveAnimators[i].getTrack(trackName);
  4884. if (track) {
  4885. additiveTrack = track;
  4886. }
  4887. }
  4888. }
  4889. return additiveTrack;
  4890. };
  4891. Animator.prototype.start = function (easing) {
  4892. if (this._started > 0) {
  4893. return;
  4894. }
  4895. this._started = 1;
  4896. var self = this;
  4897. var tracks = [];
  4898. var maxTime = this._maxTime || 0;
  4899. for (var i = 0; i < this._trackKeys.length; i++) {
  4900. var propName = this._trackKeys[i];
  4901. var track = this._tracks[propName];
  4902. var additiveTrack = this._getAdditiveTrack(propName);
  4903. var kfs = track.keyframes;
  4904. var kfsNum = kfs.length;
  4905. track.prepare(maxTime, additiveTrack);
  4906. if (track.needsAnimate()) {
  4907. if (!this._allowDiscrete && track.discrete) {
  4908. var lastKf = kfs[kfsNum - 1];
  4909. if (lastKf) {
  4910. self._target[track.propName] = lastKf.rawValue;
  4911. }
  4912. track.setFinished();
  4913. }
  4914. else {
  4915. tracks.push(track);
  4916. }
  4917. }
  4918. }
  4919. if (tracks.length || this._force) {
  4920. var clip = new Clip({
  4921. life: maxTime,
  4922. loop: this._loop,
  4923. delay: this._delay || 0,
  4924. onframe: function (percent) {
  4925. self._started = 2;
  4926. var additiveAnimators = self._additiveAnimators;
  4927. if (additiveAnimators) {
  4928. var stillHasAdditiveAnimator = false;
  4929. for (var i = 0; i < additiveAnimators.length; i++) {
  4930. if (additiveAnimators[i]._clip) {
  4931. stillHasAdditiveAnimator = true;
  4932. break;
  4933. }
  4934. }
  4935. if (!stillHasAdditiveAnimator) {
  4936. self._additiveAnimators = null;
  4937. }
  4938. }
  4939. for (var i = 0; i < tracks.length; i++) {
  4940. tracks[i].step(self._target, percent);
  4941. }
  4942. var onframeList = self._onframeCbs;
  4943. if (onframeList) {
  4944. for (var i = 0; i < onframeList.length; i++) {
  4945. onframeList[i](self._target, percent);
  4946. }
  4947. }
  4948. },
  4949. ondestroy: function () {
  4950. self._doneCallback();
  4951. }
  4952. });
  4953. this._clip = clip;
  4954. if (this.animation) {
  4955. this.animation.addClip(clip);
  4956. }
  4957. if (easing) {
  4958. clip.setEasing(easing);
  4959. }
  4960. }
  4961. else {
  4962. this._doneCallback();
  4963. }
  4964. return this;
  4965. };
  4966. Animator.prototype.stop = function (forwardToLast) {
  4967. if (!this._clip) {
  4968. return;
  4969. }
  4970. var clip = this._clip;
  4971. if (forwardToLast) {
  4972. clip.onframe(1);
  4973. }
  4974. this._abortedCallback();
  4975. };
  4976. Animator.prototype.delay = function (time) {
  4977. this._delay = time;
  4978. return this;
  4979. };
  4980. Animator.prototype.during = function (cb) {
  4981. if (cb) {
  4982. if (!this._onframeCbs) {
  4983. this._onframeCbs = [];
  4984. }
  4985. this._onframeCbs.push(cb);
  4986. }
  4987. return this;
  4988. };
  4989. Animator.prototype.done = function (cb) {
  4990. if (cb) {
  4991. if (!this._doneCbs) {
  4992. this._doneCbs = [];
  4993. }
  4994. this._doneCbs.push(cb);
  4995. }
  4996. return this;
  4997. };
  4998. Animator.prototype.aborted = function (cb) {
  4999. if (cb) {
  5000. if (!this._abortedCbs) {
  5001. this._abortedCbs = [];
  5002. }
  5003. this._abortedCbs.push(cb);
  5004. }
  5005. return this;
  5006. };
  5007. Animator.prototype.getClip = function () {
  5008. return this._clip;
  5009. };
  5010. Animator.prototype.getTrack = function (propName) {
  5011. return this._tracks[propName];
  5012. };
  5013. Animator.prototype.getTracks = function () {
  5014. var _this = this;
  5015. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  5016. };
  5017. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  5018. if (!propNames.length || !this._clip) {
  5019. return true;
  5020. }
  5021. var tracks = this._tracks;
  5022. var tracksKeys = this._trackKeys;
  5023. for (var i = 0; i < propNames.length; i++) {
  5024. var track = tracks[propNames[i]];
  5025. if (track && !track.isFinished()) {
  5026. if (forwardToLast) {
  5027. track.step(this._target, 1);
  5028. }
  5029. else if (this._started === 1) {
  5030. track.step(this._target, 0);
  5031. }
  5032. track.setFinished();
  5033. }
  5034. }
  5035. var allAborted = true;
  5036. for (var i = 0; i < tracksKeys.length; i++) {
  5037. if (!tracks[tracksKeys[i]].isFinished()) {
  5038. allAborted = false;
  5039. break;
  5040. }
  5041. }
  5042. if (allAborted) {
  5043. this._abortedCallback();
  5044. }
  5045. return allAborted;
  5046. };
  5047. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  5048. if (!target) {
  5049. return;
  5050. }
  5051. trackKeys = trackKeys || this._trackKeys;
  5052. for (var i = 0; i < trackKeys.length; i++) {
  5053. var propName = trackKeys[i];
  5054. var track = this._tracks[propName];
  5055. if (!track || track.isFinished()) {
  5056. continue;
  5057. }
  5058. var kfs = track.keyframes;
  5059. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  5060. if (kf) {
  5061. target[propName] = cloneValue(kf.rawValue);
  5062. }
  5063. }
  5064. };
  5065. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  5066. trackKeys = trackKeys || keys(finalProps);
  5067. for (var i = 0; i < trackKeys.length; i++) {
  5068. var propName = trackKeys[i];
  5069. var track = this._tracks[propName];
  5070. if (!track) {
  5071. continue;
  5072. }
  5073. var kfs = track.keyframes;
  5074. if (kfs.length > 1) {
  5075. var lastKf = kfs.pop();
  5076. track.addKeyframe(lastKf.time, finalProps[propName]);
  5077. track.prepare(this._maxTime, track.getAdditiveTrack());
  5078. }
  5079. }
  5080. };
  5081. return Animator;
  5082. }());
  5083. function getTime() {
  5084. return new Date().getTime();
  5085. }
  5086. var Animation = (function (_super) {
  5087. __extends(Animation, _super);
  5088. function Animation(opts) {
  5089. var _this = _super.call(this) || this;
  5090. _this._running = false;
  5091. _this._time = 0;
  5092. _this._pausedTime = 0;
  5093. _this._pauseStart = 0;
  5094. _this._paused = false;
  5095. opts = opts || {};
  5096. _this.stage = opts.stage || {};
  5097. return _this;
  5098. }
  5099. Animation.prototype.addClip = function (clip) {
  5100. if (clip.animation) {
  5101. this.removeClip(clip);
  5102. }
  5103. if (!this._head) {
  5104. this._head = this._tail = clip;
  5105. }
  5106. else {
  5107. this._tail.next = clip;
  5108. clip.prev = this._tail;
  5109. clip.next = null;
  5110. this._tail = clip;
  5111. }
  5112. clip.animation = this;
  5113. };
  5114. Animation.prototype.addAnimator = function (animator) {
  5115. animator.animation = this;
  5116. var clip = animator.getClip();
  5117. if (clip) {
  5118. this.addClip(clip);
  5119. }
  5120. };
  5121. Animation.prototype.removeClip = function (clip) {
  5122. if (!clip.animation) {
  5123. return;
  5124. }
  5125. var prev = clip.prev;
  5126. var next = clip.next;
  5127. if (prev) {
  5128. prev.next = next;
  5129. }
  5130. else {
  5131. this._head = next;
  5132. }
  5133. if (next) {
  5134. next.prev = prev;
  5135. }
  5136. else {
  5137. this._tail = prev;
  5138. }
  5139. clip.next = clip.prev = clip.animation = null;
  5140. };
  5141. Animation.prototype.removeAnimator = function (animator) {
  5142. var clip = animator.getClip();
  5143. if (clip) {
  5144. this.removeClip(clip);
  5145. }
  5146. animator.animation = null;
  5147. };
  5148. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  5149. var time = getTime() - this._pausedTime;
  5150. var delta = time - this._time;
  5151. var clip = this._head;
  5152. while (clip) {
  5153. var nextClip = clip.next;
  5154. var finished = clip.step(time, delta);
  5155. if (finished) {
  5156. clip.ondestroy();
  5157. this.removeClip(clip);
  5158. clip = nextClip;
  5159. }
  5160. else {
  5161. clip = nextClip;
  5162. }
  5163. }
  5164. this._time = time;
  5165. if (!notTriggerFrameAndStageUpdate) {
  5166. this.trigger('frame', delta);
  5167. this.stage.update && this.stage.update();
  5168. }
  5169. };
  5170. Animation.prototype._startLoop = function () {
  5171. var self = this;
  5172. this._running = true;
  5173. function step() {
  5174. if (self._running) {
  5175. requestAnimationFrame$1(step);
  5176. !self._paused && self.update();
  5177. }
  5178. }
  5179. requestAnimationFrame$1(step);
  5180. };
  5181. Animation.prototype.start = function () {
  5182. if (this._running) {
  5183. return;
  5184. }
  5185. this._time = getTime();
  5186. this._pausedTime = 0;
  5187. this._startLoop();
  5188. };
  5189. Animation.prototype.stop = function () {
  5190. this._running = false;
  5191. };
  5192. Animation.prototype.pause = function () {
  5193. if (!this._paused) {
  5194. this._pauseStart = getTime();
  5195. this._paused = true;
  5196. }
  5197. };
  5198. Animation.prototype.resume = function () {
  5199. if (this._paused) {
  5200. this._pausedTime += getTime() - this._pauseStart;
  5201. this._paused = false;
  5202. }
  5203. };
  5204. Animation.prototype.clear = function () {
  5205. var clip = this._head;
  5206. while (clip) {
  5207. var nextClip = clip.next;
  5208. clip.prev = clip.next = clip.animation = null;
  5209. clip = nextClip;
  5210. }
  5211. this._head = this._tail = null;
  5212. };
  5213. Animation.prototype.isFinished = function () {
  5214. return this._head == null;
  5215. };
  5216. Animation.prototype.animate = function (target, options) {
  5217. options = options || {};
  5218. this.start();
  5219. var animator = new Animator(target, options.loop);
  5220. this.addAnimator(animator);
  5221. return animator;
  5222. };
  5223. return Animation;
  5224. }(Eventful));
  5225. var TOUCH_CLICK_DELAY = 300;
  5226. var globalEventSupported = env.domSupported;
  5227. var localNativeListenerNames = (function () {
  5228. var mouseHandlerNames = [
  5229. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5230. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5231. ];
  5232. var touchHandlerNames = [
  5233. 'touchstart', 'touchend', 'touchmove'
  5234. ];
  5235. var pointerEventNameMap = {
  5236. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5237. };
  5238. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5239. var nm = name.replace('mouse', 'pointer');
  5240. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5241. });
  5242. return {
  5243. mouse: mouseHandlerNames,
  5244. touch: touchHandlerNames,
  5245. pointer: pointerHandlerNames
  5246. };
  5247. })();
  5248. var globalNativeListenerNames = {
  5249. mouse: ['mousemove', 'mouseup'],
  5250. pointer: ['pointermove', 'pointerup']
  5251. };
  5252. var wheelEventSupported = false;
  5253. function isPointerFromTouch(event) {
  5254. var pointerType = event.pointerType;
  5255. return pointerType === 'pen' || pointerType === 'touch';
  5256. }
  5257. function setTouchTimer(scope) {
  5258. scope.touching = true;
  5259. if (scope.touchTimer != null) {
  5260. clearTimeout(scope.touchTimer);
  5261. scope.touchTimer = null;
  5262. }
  5263. scope.touchTimer = setTimeout(function () {
  5264. scope.touching = false;
  5265. scope.touchTimer = null;
  5266. }, 700);
  5267. }
  5268. function markTouch(event) {
  5269. event && (event.zrByTouch = true);
  5270. }
  5271. function normalizeGlobalEvent(instance, event) {
  5272. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5273. }
  5274. function isLocalEl(instance, el) {
  5275. var elTmp = el;
  5276. var isLocal = false;
  5277. while (elTmp && elTmp.nodeType !== 9
  5278. && !(isLocal = elTmp.domBelongToZr
  5279. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5280. elTmp = elTmp.parentNode;
  5281. }
  5282. return isLocal;
  5283. }
  5284. var FakeGlobalEvent = (function () {
  5285. function FakeGlobalEvent(instance, event) {
  5286. this.stopPropagation = noop;
  5287. this.stopImmediatePropagation = noop;
  5288. this.preventDefault = noop;
  5289. this.type = event.type;
  5290. this.target = this.currentTarget = instance.dom;
  5291. this.pointerType = event.pointerType;
  5292. this.clientX = event.clientX;
  5293. this.clientY = event.clientY;
  5294. }
  5295. return FakeGlobalEvent;
  5296. }());
  5297. var localDOMHandlers = {
  5298. mousedown: function (event) {
  5299. event = normalizeEvent(this.dom, event);
  5300. this.__mayPointerCapture = [event.zrX, event.zrY];
  5301. this.trigger('mousedown', event);
  5302. },
  5303. mousemove: function (event) {
  5304. event = normalizeEvent(this.dom, event);
  5305. var downPoint = this.__mayPointerCapture;
  5306. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5307. this.__togglePointerCapture(true);
  5308. }
  5309. this.trigger('mousemove', event);
  5310. },
  5311. mouseup: function (event) {
  5312. event = normalizeEvent(this.dom, event);
  5313. this.__togglePointerCapture(false);
  5314. this.trigger('mouseup', event);
  5315. },
  5316. mouseout: function (event) {
  5317. event = normalizeEvent(this.dom, event);
  5318. var element = event.toElement || event.relatedTarget;
  5319. if (!isLocalEl(this, element)) {
  5320. if (this.__pointerCapturing) {
  5321. event.zrEventControl = 'no_globalout';
  5322. }
  5323. this.trigger('mouseout', event);
  5324. }
  5325. },
  5326. wheel: function (event) {
  5327. wheelEventSupported = true;
  5328. event = normalizeEvent(this.dom, event);
  5329. this.trigger('mousewheel', event);
  5330. },
  5331. mousewheel: function (event) {
  5332. if (wheelEventSupported) {
  5333. return;
  5334. }
  5335. event = normalizeEvent(this.dom, event);
  5336. this.trigger('mousewheel', event);
  5337. },
  5338. touchstart: function (event) {
  5339. event = normalizeEvent(this.dom, event);
  5340. markTouch(event);
  5341. this.__lastTouchMoment = new Date();
  5342. this.handler.processGesture(event, 'start');
  5343. localDOMHandlers.mousemove.call(this, event);
  5344. localDOMHandlers.mousedown.call(this, event);
  5345. },
  5346. touchmove: function (event) {
  5347. event = normalizeEvent(this.dom, event);
  5348. markTouch(event);
  5349. this.handler.processGesture(event, 'change');
  5350. localDOMHandlers.mousemove.call(this, event);
  5351. },
  5352. touchend: function (event) {
  5353. event = normalizeEvent(this.dom, event);
  5354. markTouch(event);
  5355. this.handler.processGesture(event, 'end');
  5356. localDOMHandlers.mouseup.call(this, event);
  5357. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5358. localDOMHandlers.click.call(this, event);
  5359. }
  5360. },
  5361. pointerdown: function (event) {
  5362. localDOMHandlers.mousedown.call(this, event);
  5363. },
  5364. pointermove: function (event) {
  5365. if (!isPointerFromTouch(event)) {
  5366. localDOMHandlers.mousemove.call(this, event);
  5367. }
  5368. },
  5369. pointerup: function (event) {
  5370. localDOMHandlers.mouseup.call(this, event);
  5371. },
  5372. pointerout: function (event) {
  5373. if (!isPointerFromTouch(event)) {
  5374. localDOMHandlers.mouseout.call(this, event);
  5375. }
  5376. }
  5377. };
  5378. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5379. localDOMHandlers[name] = function (event) {
  5380. event = normalizeEvent(this.dom, event);
  5381. this.trigger(name, event);
  5382. };
  5383. });
  5384. var globalDOMHandlers = {
  5385. pointermove: function (event) {
  5386. if (!isPointerFromTouch(event)) {
  5387. globalDOMHandlers.mousemove.call(this, event);
  5388. }
  5389. },
  5390. pointerup: function (event) {
  5391. globalDOMHandlers.mouseup.call(this, event);
  5392. },
  5393. mousemove: function (event) {
  5394. this.trigger('mousemove', event);
  5395. },
  5396. mouseup: function (event) {
  5397. var pointerCaptureReleasing = this.__pointerCapturing;
  5398. this.__togglePointerCapture(false);
  5399. this.trigger('mouseup', event);
  5400. if (pointerCaptureReleasing) {
  5401. event.zrEventControl = 'only_globalout';
  5402. this.trigger('mouseout', event);
  5403. }
  5404. }
  5405. };
  5406. function mountLocalDOMEventListeners(instance, scope) {
  5407. var domHandlers = scope.domHandlers;
  5408. if (env.pointerEventsSupported) {
  5409. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5410. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5411. domHandlers[nativeEventName].call(instance, event);
  5412. });
  5413. });
  5414. }
  5415. else {
  5416. if (env.touchEventsSupported) {
  5417. each(localNativeListenerNames.touch, function (nativeEventName) {
  5418. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5419. domHandlers[nativeEventName].call(instance, event);
  5420. setTouchTimer(scope);
  5421. });
  5422. });
  5423. }
  5424. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5425. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5426. event = getNativeEvent(event);
  5427. if (!scope.touching) {
  5428. domHandlers[nativeEventName].call(instance, event);
  5429. }
  5430. });
  5431. });
  5432. }
  5433. }
  5434. function mountGlobalDOMEventListeners(instance, scope) {
  5435. if (env.pointerEventsSupported) {
  5436. each(globalNativeListenerNames.pointer, mount);
  5437. }
  5438. else if (!env.touchEventsSupported) {
  5439. each(globalNativeListenerNames.mouse, mount);
  5440. }
  5441. function mount(nativeEventName) {
  5442. function nativeEventListener(event) {
  5443. event = getNativeEvent(event);
  5444. if (!isLocalEl(instance, event.target)) {
  5445. event = normalizeGlobalEvent(instance, event);
  5446. scope.domHandlers[nativeEventName].call(instance, event);
  5447. }
  5448. }
  5449. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5450. }
  5451. }
  5452. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5453. scope.mounted[nativeEventName] = listener;
  5454. scope.listenerOpts[nativeEventName] = opt;
  5455. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5456. }
  5457. function unmountDOMEventListeners(scope) {
  5458. var mounted = scope.mounted;
  5459. for (var nativeEventName in mounted) {
  5460. if (mounted.hasOwnProperty(nativeEventName)) {
  5461. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5462. }
  5463. }
  5464. scope.mounted = {};
  5465. }
  5466. var DOMHandlerScope = (function () {
  5467. function DOMHandlerScope(domTarget, domHandlers) {
  5468. this.mounted = {};
  5469. this.listenerOpts = {};
  5470. this.touching = false;
  5471. this.domTarget = domTarget;
  5472. this.domHandlers = domHandlers;
  5473. }
  5474. return DOMHandlerScope;
  5475. }());
  5476. var HandlerDomProxy = (function (_super) {
  5477. __extends(HandlerDomProxy, _super);
  5478. function HandlerDomProxy(dom, painterRoot) {
  5479. var _this = _super.call(this) || this;
  5480. _this.__pointerCapturing = false;
  5481. _this.dom = dom;
  5482. _this.painterRoot = painterRoot;
  5483. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5484. if (globalEventSupported) {
  5485. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5486. }
  5487. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5488. return _this;
  5489. }
  5490. HandlerDomProxy.prototype.dispose = function () {
  5491. unmountDOMEventListeners(this._localHandlerScope);
  5492. if (globalEventSupported) {
  5493. unmountDOMEventListeners(this._globalHandlerScope);
  5494. }
  5495. };
  5496. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5497. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5498. };
  5499. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5500. this.__mayPointerCapture = null;
  5501. if (globalEventSupported
  5502. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5503. this.__pointerCapturing = isPointerCapturing;
  5504. var globalHandlerScope = this._globalHandlerScope;
  5505. isPointerCapturing
  5506. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5507. : unmountDOMEventListeners(globalHandlerScope);
  5508. }
  5509. };
  5510. return HandlerDomProxy;
  5511. }(Eventful));
  5512. var dpr = 1;
  5513. if (env.hasGlobalWindow) {
  5514. dpr = Math.max(window.devicePixelRatio
  5515. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5516. || 1, 1);
  5517. }
  5518. var devicePixelRatio = dpr;
  5519. var DARK_MODE_THRESHOLD = 0.4;
  5520. var DARK_LABEL_COLOR = '#333';
  5521. var LIGHT_LABEL_COLOR = '#ccc';
  5522. var LIGHTER_LABEL_COLOR = '#eee';
  5523. var mIdentity = identity;
  5524. var EPSILON$3 = 5e-5;
  5525. function isNotAroundZero$1(val) {
  5526. return val > EPSILON$3 || val < -EPSILON$3;
  5527. }
  5528. var scaleTmp = [];
  5529. var tmpTransform = [];
  5530. var originTransform = create$1();
  5531. var abs = Math.abs;
  5532. var Transformable = (function () {
  5533. function Transformable() {
  5534. }
  5535. Transformable.prototype.getLocalTransform = function (m) {
  5536. return Transformable.getLocalTransform(this, m);
  5537. };
  5538. Transformable.prototype.setPosition = function (arr) {
  5539. this.x = arr[0];
  5540. this.y = arr[1];
  5541. };
  5542. Transformable.prototype.setScale = function (arr) {
  5543. this.scaleX = arr[0];
  5544. this.scaleY = arr[1];
  5545. };
  5546. Transformable.prototype.setSkew = function (arr) {
  5547. this.skewX = arr[0];
  5548. this.skewY = arr[1];
  5549. };
  5550. Transformable.prototype.setOrigin = function (arr) {
  5551. this.originX = arr[0];
  5552. this.originY = arr[1];
  5553. };
  5554. Transformable.prototype.needLocalTransform = function () {
  5555. return isNotAroundZero$1(this.rotation)
  5556. || isNotAroundZero$1(this.x)
  5557. || isNotAroundZero$1(this.y)
  5558. || isNotAroundZero$1(this.scaleX - 1)
  5559. || isNotAroundZero$1(this.scaleY - 1)
  5560. || isNotAroundZero$1(this.skewX)
  5561. || isNotAroundZero$1(this.skewY);
  5562. };
  5563. Transformable.prototype.updateTransform = function () {
  5564. var parentTransform = this.parent && this.parent.transform;
  5565. var needLocalTransform = this.needLocalTransform();
  5566. var m = this.transform;
  5567. if (!(needLocalTransform || parentTransform)) {
  5568. if (m) {
  5569. mIdentity(m);
  5570. this.invTransform = null;
  5571. }
  5572. return;
  5573. }
  5574. m = m || create$1();
  5575. if (needLocalTransform) {
  5576. this.getLocalTransform(m);
  5577. }
  5578. else {
  5579. mIdentity(m);
  5580. }
  5581. if (parentTransform) {
  5582. if (needLocalTransform) {
  5583. mul$1(m, parentTransform, m);
  5584. }
  5585. else {
  5586. copy$1(m, parentTransform);
  5587. }
  5588. }
  5589. this.transform = m;
  5590. this._resolveGlobalScaleRatio(m);
  5591. };
  5592. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5593. var globalScaleRatio = this.globalScaleRatio;
  5594. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5595. this.getGlobalScale(scaleTmp);
  5596. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5597. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5598. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5599. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5600. m[0] *= sx;
  5601. m[1] *= sx;
  5602. m[2] *= sy;
  5603. m[3] *= sy;
  5604. }
  5605. this.invTransform = this.invTransform || create$1();
  5606. invert(this.invTransform, m);
  5607. };
  5608. Transformable.prototype.getComputedTransform = function () {
  5609. var transformNode = this;
  5610. var ancestors = [];
  5611. while (transformNode) {
  5612. ancestors.push(transformNode);
  5613. transformNode = transformNode.parent;
  5614. }
  5615. while (transformNode = ancestors.pop()) {
  5616. transformNode.updateTransform();
  5617. }
  5618. return this.transform;
  5619. };
  5620. Transformable.prototype.setLocalTransform = function (m) {
  5621. if (!m) {
  5622. return;
  5623. }
  5624. var sx = m[0] * m[0] + m[1] * m[1];
  5625. var sy = m[2] * m[2] + m[3] * m[3];
  5626. var rotation = Math.atan2(m[1], m[0]);
  5627. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5628. sy = Math.sqrt(sy) * Math.cos(shearX);
  5629. sx = Math.sqrt(sx);
  5630. this.skewX = shearX;
  5631. this.skewY = 0;
  5632. this.rotation = -rotation;
  5633. this.x = +m[4];
  5634. this.y = +m[5];
  5635. this.scaleX = sx;
  5636. this.scaleY = sy;
  5637. this.originX = 0;
  5638. this.originY = 0;
  5639. };
  5640. Transformable.prototype.decomposeTransform = function () {
  5641. if (!this.transform) {
  5642. return;
  5643. }
  5644. var parent = this.parent;
  5645. var m = this.transform;
  5646. if (parent && parent.transform) {
  5647. parent.invTransform = parent.invTransform || create$1();
  5648. mul$1(tmpTransform, parent.invTransform, m);
  5649. m = tmpTransform;
  5650. }
  5651. var ox = this.originX;
  5652. var oy = this.originY;
  5653. if (ox || oy) {
  5654. originTransform[4] = ox;
  5655. originTransform[5] = oy;
  5656. mul$1(tmpTransform, m, originTransform);
  5657. tmpTransform[4] -= ox;
  5658. tmpTransform[5] -= oy;
  5659. m = tmpTransform;
  5660. }
  5661. this.setLocalTransform(m);
  5662. };
  5663. Transformable.prototype.getGlobalScale = function (out) {
  5664. var m = this.transform;
  5665. out = out || [];
  5666. if (!m) {
  5667. out[0] = 1;
  5668. out[1] = 1;
  5669. return out;
  5670. }
  5671. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5672. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5673. if (m[0] < 0) {
  5674. out[0] = -out[0];
  5675. }
  5676. if (m[3] < 0) {
  5677. out[1] = -out[1];
  5678. }
  5679. return out;
  5680. };
  5681. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5682. var v2 = [x, y];
  5683. var invTransform = this.invTransform;
  5684. if (invTransform) {
  5685. applyTransform(v2, v2, invTransform);
  5686. }
  5687. return v2;
  5688. };
  5689. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5690. var v2 = [x, y];
  5691. var transform = this.transform;
  5692. if (transform) {
  5693. applyTransform(v2, v2, transform);
  5694. }
  5695. return v2;
  5696. };
  5697. Transformable.prototype.getLineScale = function () {
  5698. var m = this.transform;
  5699. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5700. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5701. : 1;
  5702. };
  5703. Transformable.prototype.copyTransform = function (source) {
  5704. copyTransform(this, source);
  5705. };
  5706. Transformable.getLocalTransform = function (target, m) {
  5707. m = m || [];
  5708. var ox = target.originX || 0;
  5709. var oy = target.originY || 0;
  5710. var sx = target.scaleX;
  5711. var sy = target.scaleY;
  5712. var ax = target.anchorX;
  5713. var ay = target.anchorY;
  5714. var rotation = target.rotation || 0;
  5715. var x = target.x;
  5716. var y = target.y;
  5717. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5718. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5719. if (ox || oy || ax || ay) {
  5720. var dx = ox + ax;
  5721. var dy = oy + ay;
  5722. m[4] = -dx * sx - skewX * dy * sy;
  5723. m[5] = -dy * sy - skewY * dx * sx;
  5724. }
  5725. else {
  5726. m[4] = m[5] = 0;
  5727. }
  5728. m[0] = sx;
  5729. m[3] = sy;
  5730. m[1] = skewY * sx;
  5731. m[2] = skewX * sy;
  5732. rotation && rotate(m, m, rotation);
  5733. m[4] += ox + x;
  5734. m[5] += oy + y;
  5735. return m;
  5736. };
  5737. Transformable.initDefaultProps = (function () {
  5738. var proto = Transformable.prototype;
  5739. proto.scaleX =
  5740. proto.scaleY =
  5741. proto.globalScaleRatio = 1;
  5742. proto.x =
  5743. proto.y =
  5744. proto.originX =
  5745. proto.originY =
  5746. proto.skewX =
  5747. proto.skewY =
  5748. proto.rotation =
  5749. proto.anchorX =
  5750. proto.anchorY = 0;
  5751. })();
  5752. return Transformable;
  5753. }());
  5754. var TRANSFORMABLE_PROPS = [
  5755. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5756. ];
  5757. function copyTransform(target, source) {
  5758. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5759. var propName = TRANSFORMABLE_PROPS[i];
  5760. target[propName] = source[propName];
  5761. }
  5762. }
  5763. function ensureFontMeasureInfo(font) {
  5764. if (!_fontMeasureInfoCache) {
  5765. _fontMeasureInfoCache = new LRU(100);
  5766. }
  5767. font = font || DEFAULT_FONT;
  5768. var measureInfo = _fontMeasureInfoCache.get(font);
  5769. if (!measureInfo) {
  5770. measureInfo = {
  5771. font: font,
  5772. strWidthCache: new LRU(500),
  5773. asciiWidthMap: null,
  5774. asciiWidthMapTried: false,
  5775. stWideCharWidth: platformApi.measureText('国', font).width,
  5776. asciiCharWidth: platformApi.measureText('a', font).width
  5777. };
  5778. _fontMeasureInfoCache.put(font, measureInfo);
  5779. }
  5780. return measureInfo;
  5781. }
  5782. var _fontMeasureInfoCache;
  5783. function tryCreateASCIIWidthMap(font) {
  5784. if (_getASCIIWidthMapLongCount >= GET_ASCII_WIDTH_LONG_COUNT_MAX) {
  5785. return;
  5786. }
  5787. font = font || DEFAULT_FONT;
  5788. var asciiWidthMap = [];
  5789. var start = +(new Date());
  5790. for (var code = 0; code <= 127; code++) {
  5791. asciiWidthMap[code] = platformApi.measureText(String.fromCharCode(code), font).width;
  5792. }
  5793. var cost = +(new Date()) - start;
  5794. if (cost > 16) {
  5795. _getASCIIWidthMapLongCount = GET_ASCII_WIDTH_LONG_COUNT_MAX;
  5796. }
  5797. else if (cost > 2) {
  5798. _getASCIIWidthMapLongCount++;
  5799. }
  5800. return asciiWidthMap;
  5801. }
  5802. var _getASCIIWidthMapLongCount = 0;
  5803. var GET_ASCII_WIDTH_LONG_COUNT_MAX = 5;
  5804. function measureCharWidth(fontMeasureInfo, charCode) {
  5805. if (!fontMeasureInfo.asciiWidthMapTried) {
  5806. fontMeasureInfo.asciiWidthMap = tryCreateASCIIWidthMap(fontMeasureInfo.font);
  5807. fontMeasureInfo.asciiWidthMapTried = true;
  5808. }
  5809. return (0 <= charCode && charCode <= 127)
  5810. ? (fontMeasureInfo.asciiWidthMap != null
  5811. ? fontMeasureInfo.asciiWidthMap[charCode]
  5812. : fontMeasureInfo.asciiCharWidth)
  5813. : fontMeasureInfo.stWideCharWidth;
  5814. }
  5815. function measureWidth(fontMeasureInfo, text) {
  5816. var strWidthCache = fontMeasureInfo.strWidthCache;
  5817. var width = strWidthCache.get(text);
  5818. if (width == null) {
  5819. width = platformApi.measureText(text, fontMeasureInfo.font).width;
  5820. strWidthCache.put(text, width);
  5821. }
  5822. return width;
  5823. }
  5824. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5825. var width = measureWidth(ensureFontMeasureInfo(font), text);
  5826. var height = getLineHeight(font);
  5827. var x = adjustTextX(0, width, textAlign);
  5828. var y = adjustTextY$1(0, height, textBaseline);
  5829. var rect = new BoundingRect(x, y, width, height);
  5830. return rect;
  5831. }
  5832. function getBoundingRect(text, font, textAlign, textBaseline) {
  5833. var textLines = ((text || '') + '').split('\n');
  5834. var len = textLines.length;
  5835. if (len === 1) {
  5836. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5837. }
  5838. else {
  5839. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5840. for (var i = 0; i < textLines.length; i++) {
  5841. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5842. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5843. }
  5844. return uniondRect;
  5845. }
  5846. }
  5847. function adjustTextX(x, width, textAlign, inverse) {
  5848. if (textAlign === 'right') {
  5849. !inverse ? (x -= width) : (x += width);
  5850. }
  5851. else if (textAlign === 'center') {
  5852. !inverse ? (x -= width / 2) : (x += width / 2);
  5853. }
  5854. return x;
  5855. }
  5856. function adjustTextY$1(y, height, verticalAlign, inverse) {
  5857. if (verticalAlign === 'middle') {
  5858. !inverse ? (y -= height / 2) : (y += height / 2);
  5859. }
  5860. else if (verticalAlign === 'bottom') {
  5861. !inverse ? (y -= height) : (y += height);
  5862. }
  5863. return y;
  5864. }
  5865. function getLineHeight(font) {
  5866. return ensureFontMeasureInfo(font).stWideCharWidth;
  5867. }
  5868. function parsePercent(value, maxValue) {
  5869. if (typeof value === 'string') {
  5870. if (value.lastIndexOf('%') >= 0) {
  5871. return parseFloat(value) / 100 * maxValue;
  5872. }
  5873. return parseFloat(value);
  5874. }
  5875. return value;
  5876. }
  5877. function calculateTextPosition(out, opts, rect) {
  5878. var textPosition = opts.position || 'inside';
  5879. var distance = opts.distance != null ? opts.distance : 5;
  5880. var height = rect.height;
  5881. var width = rect.width;
  5882. var halfHeight = height / 2;
  5883. var x = rect.x;
  5884. var y = rect.y;
  5885. var textAlign = 'left';
  5886. var textVerticalAlign = 'top';
  5887. if (textPosition instanceof Array) {
  5888. x += parsePercent(textPosition[0], rect.width);
  5889. y += parsePercent(textPosition[1], rect.height);
  5890. textAlign = null;
  5891. textVerticalAlign = null;
  5892. }
  5893. else {
  5894. switch (textPosition) {
  5895. case 'left':
  5896. x -= distance;
  5897. y += halfHeight;
  5898. textAlign = 'right';
  5899. textVerticalAlign = 'middle';
  5900. break;
  5901. case 'right':
  5902. x += distance + width;
  5903. y += halfHeight;
  5904. textVerticalAlign = 'middle';
  5905. break;
  5906. case 'top':
  5907. x += width / 2;
  5908. y -= distance;
  5909. textAlign = 'center';
  5910. textVerticalAlign = 'bottom';
  5911. break;
  5912. case 'bottom':
  5913. x += width / 2;
  5914. y += height + distance;
  5915. textAlign = 'center';
  5916. break;
  5917. case 'inside':
  5918. x += width / 2;
  5919. y += halfHeight;
  5920. textAlign = 'center';
  5921. textVerticalAlign = 'middle';
  5922. break;
  5923. case 'insideLeft':
  5924. x += distance;
  5925. y += halfHeight;
  5926. textVerticalAlign = 'middle';
  5927. break;
  5928. case 'insideRight':
  5929. x += width - distance;
  5930. y += halfHeight;
  5931. textAlign = 'right';
  5932. textVerticalAlign = 'middle';
  5933. break;
  5934. case 'insideTop':
  5935. x += width / 2;
  5936. y += distance;
  5937. textAlign = 'center';
  5938. break;
  5939. case 'insideBottom':
  5940. x += width / 2;
  5941. y += height - distance;
  5942. textAlign = 'center';
  5943. textVerticalAlign = 'bottom';
  5944. break;
  5945. case 'insideTopLeft':
  5946. x += distance;
  5947. y += distance;
  5948. break;
  5949. case 'insideTopRight':
  5950. x += width - distance;
  5951. y += distance;
  5952. textAlign = 'right';
  5953. break;
  5954. case 'insideBottomLeft':
  5955. x += distance;
  5956. y += height - distance;
  5957. textVerticalAlign = 'bottom';
  5958. break;
  5959. case 'insideBottomRight':
  5960. x += width - distance;
  5961. y += height - distance;
  5962. textAlign = 'right';
  5963. textVerticalAlign = 'bottom';
  5964. break;
  5965. }
  5966. }
  5967. out = out || {};
  5968. out.x = x;
  5969. out.y = y;
  5970. out.align = textAlign;
  5971. out.verticalAlign = textVerticalAlign;
  5972. return out;
  5973. }
  5974. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5975. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5976. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5977. obj[key] = true;
  5978. return obj;
  5979. }, { ignore: false });
  5980. var tmpTextPosCalcRes = {};
  5981. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5982. var tmpInnerTextTrans = [];
  5983. var Element = (function () {
  5984. function Element(props) {
  5985. this.id = guid();
  5986. this.animators = [];
  5987. this.currentStates = [];
  5988. this.states = {};
  5989. this._init(props);
  5990. }
  5991. Element.prototype._init = function (props) {
  5992. this.attr(props);
  5993. };
  5994. Element.prototype.drift = function (dx, dy, e) {
  5995. switch (this.draggable) {
  5996. case 'horizontal':
  5997. dy = 0;
  5998. break;
  5999. case 'vertical':
  6000. dx = 0;
  6001. break;
  6002. }
  6003. var m = this.transform;
  6004. if (!m) {
  6005. m = this.transform = [1, 0, 0, 1, 0, 0];
  6006. }
  6007. m[4] += dx;
  6008. m[5] += dy;
  6009. this.decomposeTransform();
  6010. this.markRedraw();
  6011. };
  6012. Element.prototype.beforeUpdate = function () { };
  6013. Element.prototype.afterUpdate = function () { };
  6014. Element.prototype.update = function () {
  6015. this.updateTransform();
  6016. if (this.__dirty) {
  6017. this.updateInnerText();
  6018. }
  6019. };
  6020. Element.prototype.updateInnerText = function (forceUpdate) {
  6021. var textEl = this._textContent;
  6022. if (textEl && (!textEl.ignore || forceUpdate)) {
  6023. if (!this.textConfig) {
  6024. this.textConfig = {};
  6025. }
  6026. var textConfig = this.textConfig;
  6027. var isLocal = textConfig.local;
  6028. var innerTransformable = textEl.innerTransformable;
  6029. var textAlign = void 0;
  6030. var textVerticalAlign = void 0;
  6031. var textStyleChanged = false;
  6032. innerTransformable.parent = isLocal ? this : null;
  6033. var innerOrigin = false;
  6034. innerTransformable.copyTransform(textEl);
  6035. var hasPosition = textConfig.position != null;
  6036. var autoOverflowArea = textConfig.autoOverflowArea;
  6037. var layoutRect = void 0;
  6038. if (autoOverflowArea || hasPosition) {
  6039. layoutRect = tmpBoundingRect;
  6040. if (textConfig.layoutRect) {
  6041. layoutRect.copy(textConfig.layoutRect);
  6042. }
  6043. else {
  6044. layoutRect.copy(this.getBoundingRect());
  6045. }
  6046. if (!isLocal) {
  6047. layoutRect.applyTransform(this.transform);
  6048. }
  6049. }
  6050. if (hasPosition) {
  6051. if (this.calculateTextPosition) {
  6052. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  6053. }
  6054. else {
  6055. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  6056. }
  6057. innerTransformable.x = tmpTextPosCalcRes.x;
  6058. innerTransformable.y = tmpTextPosCalcRes.y;
  6059. textAlign = tmpTextPosCalcRes.align;
  6060. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  6061. var textOrigin = textConfig.origin;
  6062. if (textOrigin && textConfig.rotation != null) {
  6063. var relOriginX = void 0;
  6064. var relOriginY = void 0;
  6065. if (textOrigin === 'center') {
  6066. relOriginX = layoutRect.width * 0.5;
  6067. relOriginY = layoutRect.height * 0.5;
  6068. }
  6069. else {
  6070. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  6071. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  6072. }
  6073. innerOrigin = true;
  6074. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  6075. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  6076. }
  6077. }
  6078. if (textConfig.rotation != null) {
  6079. innerTransformable.rotation = textConfig.rotation;
  6080. }
  6081. var textOffset = textConfig.offset;
  6082. if (textOffset) {
  6083. innerTransformable.x += textOffset[0];
  6084. innerTransformable.y += textOffset[1];
  6085. if (!innerOrigin) {
  6086. innerTransformable.originX = -textOffset[0];
  6087. innerTransformable.originY = -textOffset[1];
  6088. }
  6089. }
  6090. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  6091. if (autoOverflowArea) {
  6092. var overflowRect = innerTextDefaultStyle.overflowRect =
  6093. innerTextDefaultStyle.overflowRect || new BoundingRect(0, 0, 0, 0);
  6094. innerTransformable.getLocalTransform(tmpInnerTextTrans);
  6095. invert(tmpInnerTextTrans, tmpInnerTextTrans);
  6096. BoundingRect.copy(overflowRect, layoutRect);
  6097. overflowRect.applyTransform(tmpInnerTextTrans);
  6098. }
  6099. else {
  6100. innerTextDefaultStyle.overflowRect = null;
  6101. }
  6102. var isInside = textConfig.inside == null
  6103. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  6104. : textConfig.inside;
  6105. var textFill = void 0;
  6106. var textStroke = void 0;
  6107. var autoStroke = void 0;
  6108. if (isInside && this.canBeInsideText()) {
  6109. textFill = textConfig.insideFill;
  6110. textStroke = textConfig.insideStroke;
  6111. if (textFill == null || textFill === 'auto') {
  6112. textFill = this.getInsideTextFill();
  6113. }
  6114. if (textStroke == null || textStroke === 'auto') {
  6115. textStroke = this.getInsideTextStroke(textFill);
  6116. autoStroke = true;
  6117. }
  6118. }
  6119. else {
  6120. textFill = textConfig.outsideFill;
  6121. textStroke = textConfig.outsideStroke;
  6122. if (textFill == null || textFill === 'auto') {
  6123. textFill = this.getOutsideFill();
  6124. }
  6125. if (textStroke == null || textStroke === 'auto') {
  6126. textStroke = this.getOutsideStroke(textFill);
  6127. autoStroke = true;
  6128. }
  6129. }
  6130. textFill = textFill || '#000';
  6131. if (textFill !== innerTextDefaultStyle.fill
  6132. || textStroke !== innerTextDefaultStyle.stroke
  6133. || autoStroke !== innerTextDefaultStyle.autoStroke
  6134. || textAlign !== innerTextDefaultStyle.align
  6135. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  6136. textStyleChanged = true;
  6137. innerTextDefaultStyle.fill = textFill;
  6138. innerTextDefaultStyle.stroke = textStroke;
  6139. innerTextDefaultStyle.autoStroke = autoStroke;
  6140. innerTextDefaultStyle.align = textAlign;
  6141. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  6142. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  6143. }
  6144. textEl.__dirty |= REDRAW_BIT;
  6145. if (textStyleChanged) {
  6146. textEl.dirtyStyle(true);
  6147. }
  6148. }
  6149. };
  6150. Element.prototype.canBeInsideText = function () {
  6151. return true;
  6152. };
  6153. Element.prototype.getInsideTextFill = function () {
  6154. return '#fff';
  6155. };
  6156. Element.prototype.getInsideTextStroke = function (textFill) {
  6157. return '#000';
  6158. };
  6159. Element.prototype.getOutsideFill = function () {
  6160. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  6161. };
  6162. Element.prototype.getOutsideStroke = function (textFill) {
  6163. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  6164. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  6165. if (!colorArr) {
  6166. colorArr = [255, 255, 255, 1];
  6167. }
  6168. var alpha = colorArr[3];
  6169. var isDark = this.__zr.isDarkMode();
  6170. for (var i = 0; i < 3; i++) {
  6171. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  6172. }
  6173. colorArr[3] = 1;
  6174. return stringify(colorArr, 'rgba');
  6175. };
  6176. Element.prototype.traverse = function (cb, context) { };
  6177. Element.prototype.attrKV = function (key, value) {
  6178. if (key === 'textConfig') {
  6179. this.setTextConfig(value);
  6180. }
  6181. else if (key === 'textContent') {
  6182. this.setTextContent(value);
  6183. }
  6184. else if (key === 'clipPath') {
  6185. this.setClipPath(value);
  6186. }
  6187. else if (key === 'extra') {
  6188. this.extra = this.extra || {};
  6189. extend(this.extra, value);
  6190. }
  6191. else {
  6192. this[key] = value;
  6193. }
  6194. };
  6195. Element.prototype.hide = function () {
  6196. this.ignore = true;
  6197. this.markRedraw();
  6198. };
  6199. Element.prototype.show = function () {
  6200. this.ignore = false;
  6201. this.markRedraw();
  6202. };
  6203. Element.prototype.attr = function (keyOrObj, value) {
  6204. if (typeof keyOrObj === 'string') {
  6205. this.attrKV(keyOrObj, value);
  6206. }
  6207. else if (isObject(keyOrObj)) {
  6208. var obj = keyOrObj;
  6209. var keysArr = keys(obj);
  6210. for (var i = 0; i < keysArr.length; i++) {
  6211. var key = keysArr[i];
  6212. this.attrKV(key, keyOrObj[key]);
  6213. }
  6214. }
  6215. this.markRedraw();
  6216. return this;
  6217. };
  6218. Element.prototype.saveCurrentToNormalState = function (toState) {
  6219. this._innerSaveToNormal(toState);
  6220. var normalState = this._normalState;
  6221. for (var i = 0; i < this.animators.length; i++) {
  6222. var animator = this.animators[i];
  6223. var fromStateTransition = animator.__fromStateTransition;
  6224. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6225. continue;
  6226. }
  6227. var targetName = animator.targetName;
  6228. var target = targetName
  6229. ? normalState[targetName] : normalState;
  6230. animator.saveTo(target);
  6231. }
  6232. };
  6233. Element.prototype._innerSaveToNormal = function (toState) {
  6234. var normalState = this._normalState;
  6235. if (!normalState) {
  6236. normalState = this._normalState = {};
  6237. }
  6238. if (toState.textConfig && !normalState.textConfig) {
  6239. normalState.textConfig = this.textConfig;
  6240. }
  6241. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6242. };
  6243. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6244. for (var i = 0; i < primaryKeys.length; i++) {
  6245. var key = primaryKeys[i];
  6246. if (toState[key] != null && !(key in normalState)) {
  6247. normalState[key] = this[key];
  6248. }
  6249. }
  6250. };
  6251. Element.prototype.hasState = function () {
  6252. return this.currentStates.length > 0;
  6253. };
  6254. Element.prototype.getState = function (name) {
  6255. return this.states[name];
  6256. };
  6257. Element.prototype.ensureState = function (name) {
  6258. var states = this.states;
  6259. if (!states[name]) {
  6260. states[name] = {};
  6261. }
  6262. return states[name];
  6263. };
  6264. Element.prototype.clearStates = function (noAnimation) {
  6265. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6266. };
  6267. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6268. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6269. var hasStates = this.hasState();
  6270. if (!hasStates && toNormalState) {
  6271. return;
  6272. }
  6273. var currentStates = this.currentStates;
  6274. var animationCfg = this.stateTransition;
  6275. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6276. return;
  6277. }
  6278. var state;
  6279. if (this.stateProxy && !toNormalState) {
  6280. state = this.stateProxy(stateName);
  6281. }
  6282. if (!state) {
  6283. state = (this.states && this.states[stateName]);
  6284. }
  6285. if (!state && !toNormalState) {
  6286. logError("State " + stateName + " not exists.");
  6287. return;
  6288. }
  6289. if (!toNormalState) {
  6290. this.saveCurrentToNormalState(state);
  6291. }
  6292. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6293. if (useHoverLayer) {
  6294. this._toggleHoverLayerFlag(true);
  6295. }
  6296. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6297. var textContent = this._textContent;
  6298. var textGuide = this._textGuide;
  6299. if (textContent) {
  6300. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6301. }
  6302. if (textGuide) {
  6303. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6304. }
  6305. if (toNormalState) {
  6306. this.currentStates = [];
  6307. this._normalState = {};
  6308. }
  6309. else {
  6310. if (!keepCurrentStates) {
  6311. this.currentStates = [stateName];
  6312. }
  6313. else {
  6314. this.currentStates.push(stateName);
  6315. }
  6316. }
  6317. this._updateAnimationTargets();
  6318. this.markRedraw();
  6319. if (!useHoverLayer && this.__inHover) {
  6320. this._toggleHoverLayerFlag(false);
  6321. this.__dirty &= ~REDRAW_BIT;
  6322. }
  6323. return state;
  6324. };
  6325. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6326. if (!states.length) {
  6327. this.clearStates();
  6328. }
  6329. else {
  6330. var stateObjects = [];
  6331. var currentStates = this.currentStates;
  6332. var len = states.length;
  6333. var notChange = len === currentStates.length;
  6334. if (notChange) {
  6335. for (var i = 0; i < len; i++) {
  6336. if (states[i] !== currentStates[i]) {
  6337. notChange = false;
  6338. break;
  6339. }
  6340. }
  6341. }
  6342. if (notChange) {
  6343. return;
  6344. }
  6345. for (var i = 0; i < len; i++) {
  6346. var stateName = states[i];
  6347. var stateObj = void 0;
  6348. if (this.stateProxy) {
  6349. stateObj = this.stateProxy(stateName, states);
  6350. }
  6351. if (!stateObj) {
  6352. stateObj = this.states[stateName];
  6353. }
  6354. if (stateObj) {
  6355. stateObjects.push(stateObj);
  6356. }
  6357. }
  6358. var lastStateObj = stateObjects[len - 1];
  6359. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6360. if (useHoverLayer) {
  6361. this._toggleHoverLayerFlag(true);
  6362. }
  6363. var mergedState = this._mergeStates(stateObjects);
  6364. var animationCfg = this.stateTransition;
  6365. this.saveCurrentToNormalState(mergedState);
  6366. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6367. var textContent = this._textContent;
  6368. var textGuide = this._textGuide;
  6369. if (textContent) {
  6370. textContent.useStates(states, noAnimation, useHoverLayer);
  6371. }
  6372. if (textGuide) {
  6373. textGuide.useStates(states, noAnimation, useHoverLayer);
  6374. }
  6375. this._updateAnimationTargets();
  6376. this.currentStates = states.slice();
  6377. this.markRedraw();
  6378. if (!useHoverLayer && this.__inHover) {
  6379. this._toggleHoverLayerFlag(false);
  6380. this.__dirty &= ~REDRAW_BIT;
  6381. }
  6382. }
  6383. };
  6384. Element.prototype.isSilent = function () {
  6385. var el = this;
  6386. while (el) {
  6387. if (el.silent) {
  6388. return true;
  6389. }
  6390. var hostEl = el.__hostTarget;
  6391. el = hostEl ? (el.ignoreHostSilent ? null : hostEl) : el.parent;
  6392. }
  6393. return false;
  6394. };
  6395. Element.prototype._updateAnimationTargets = function () {
  6396. for (var i = 0; i < this.animators.length; i++) {
  6397. var animator = this.animators[i];
  6398. if (animator.targetName) {
  6399. animator.changeTarget(this[animator.targetName]);
  6400. }
  6401. }
  6402. };
  6403. Element.prototype.removeState = function (state) {
  6404. var idx = indexOf(this.currentStates, state);
  6405. if (idx >= 0) {
  6406. var currentStates = this.currentStates.slice();
  6407. currentStates.splice(idx, 1);
  6408. this.useStates(currentStates);
  6409. }
  6410. };
  6411. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6412. var currentStates = this.currentStates.slice();
  6413. var idx = indexOf(currentStates, oldState);
  6414. var newStateExists = indexOf(currentStates, newState) >= 0;
  6415. if (idx >= 0) {
  6416. if (!newStateExists) {
  6417. currentStates[idx] = newState;
  6418. }
  6419. else {
  6420. currentStates.splice(idx, 1);
  6421. }
  6422. }
  6423. else if (forceAdd && !newStateExists) {
  6424. currentStates.push(newState);
  6425. }
  6426. this.useStates(currentStates);
  6427. };
  6428. Element.prototype.toggleState = function (state, enable) {
  6429. if (enable) {
  6430. this.useState(state, true);
  6431. }
  6432. else {
  6433. this.removeState(state);
  6434. }
  6435. };
  6436. Element.prototype._mergeStates = function (states) {
  6437. var mergedState = {};
  6438. var mergedTextConfig;
  6439. for (var i = 0; i < states.length; i++) {
  6440. var state = states[i];
  6441. extend(mergedState, state);
  6442. if (state.textConfig) {
  6443. mergedTextConfig = mergedTextConfig || {};
  6444. extend(mergedTextConfig, state.textConfig);
  6445. }
  6446. }
  6447. if (mergedTextConfig) {
  6448. mergedState.textConfig = mergedTextConfig;
  6449. }
  6450. return mergedState;
  6451. };
  6452. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6453. var needsRestoreToNormal = !(state && keepCurrentStates);
  6454. if (state && state.textConfig) {
  6455. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6456. extend(this.textConfig, state.textConfig);
  6457. }
  6458. else if (needsRestoreToNormal) {
  6459. if (normalState.textConfig) {
  6460. this.textConfig = normalState.textConfig;
  6461. }
  6462. }
  6463. var transitionTarget = {};
  6464. var hasTransition = false;
  6465. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6466. var key = PRIMARY_STATES_KEYS[i];
  6467. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6468. if (state && state[key] != null) {
  6469. if (propNeedsTransition) {
  6470. hasTransition = true;
  6471. transitionTarget[key] = state[key];
  6472. }
  6473. else {
  6474. this[key] = state[key];
  6475. }
  6476. }
  6477. else if (needsRestoreToNormal) {
  6478. if (normalState[key] != null) {
  6479. if (propNeedsTransition) {
  6480. hasTransition = true;
  6481. transitionTarget[key] = normalState[key];
  6482. }
  6483. else {
  6484. this[key] = normalState[key];
  6485. }
  6486. }
  6487. }
  6488. }
  6489. if (!transition) {
  6490. for (var i = 0; i < this.animators.length; i++) {
  6491. var animator = this.animators[i];
  6492. var targetName = animator.targetName;
  6493. if (!animator.getLoop()) {
  6494. animator.__changeFinalValue(targetName
  6495. ? (state || normalState)[targetName]
  6496. : (state || normalState));
  6497. }
  6498. }
  6499. }
  6500. if (hasTransition) {
  6501. this._transitionState(stateName, transitionTarget, animationCfg);
  6502. }
  6503. };
  6504. Element.prototype._attachComponent = function (componentEl) {
  6505. if (componentEl.__zr && !componentEl.__hostTarget) {
  6506. if ("development" !== 'production') {
  6507. throw new Error('Text element has been added to zrender.');
  6508. }
  6509. return;
  6510. }
  6511. if (componentEl === this) {
  6512. if ("development" !== 'production') {
  6513. throw new Error('Recursive component attachment.');
  6514. }
  6515. return;
  6516. }
  6517. var zr = this.__zr;
  6518. if (zr) {
  6519. componentEl.addSelfToZr(zr);
  6520. }
  6521. componentEl.__zr = zr;
  6522. componentEl.__hostTarget = this;
  6523. };
  6524. Element.prototype._detachComponent = function (componentEl) {
  6525. if (componentEl.__zr) {
  6526. componentEl.removeSelfFromZr(componentEl.__zr);
  6527. }
  6528. componentEl.__zr = null;
  6529. componentEl.__hostTarget = null;
  6530. };
  6531. Element.prototype.getClipPath = function () {
  6532. return this._clipPath;
  6533. };
  6534. Element.prototype.setClipPath = function (clipPath) {
  6535. if (this._clipPath && this._clipPath !== clipPath) {
  6536. this.removeClipPath();
  6537. }
  6538. this._attachComponent(clipPath);
  6539. this._clipPath = clipPath;
  6540. this.markRedraw();
  6541. };
  6542. Element.prototype.removeClipPath = function () {
  6543. var clipPath = this._clipPath;
  6544. if (clipPath) {
  6545. this._detachComponent(clipPath);
  6546. this._clipPath = null;
  6547. this.markRedraw();
  6548. }
  6549. };
  6550. Element.prototype.getTextContent = function () {
  6551. return this._textContent;
  6552. };
  6553. Element.prototype.setTextContent = function (textEl) {
  6554. var previousTextContent = this._textContent;
  6555. if (previousTextContent === textEl) {
  6556. return;
  6557. }
  6558. if (previousTextContent && previousTextContent !== textEl) {
  6559. this.removeTextContent();
  6560. }
  6561. if ("development" !== 'production') {
  6562. if (textEl.__zr && !textEl.__hostTarget) {
  6563. throw new Error('Text element has been added to zrender.');
  6564. }
  6565. }
  6566. textEl.innerTransformable = new Transformable();
  6567. this._attachComponent(textEl);
  6568. this._textContent = textEl;
  6569. this.markRedraw();
  6570. };
  6571. Element.prototype.setTextConfig = function (cfg) {
  6572. if (!this.textConfig) {
  6573. this.textConfig = {};
  6574. }
  6575. extend(this.textConfig, cfg);
  6576. this.markRedraw();
  6577. };
  6578. Element.prototype.removeTextConfig = function () {
  6579. this.textConfig = null;
  6580. this.markRedraw();
  6581. };
  6582. Element.prototype.removeTextContent = function () {
  6583. var textEl = this._textContent;
  6584. if (textEl) {
  6585. textEl.innerTransformable = null;
  6586. this._detachComponent(textEl);
  6587. this._textContent = null;
  6588. this._innerTextDefaultStyle = null;
  6589. this.markRedraw();
  6590. }
  6591. };
  6592. Element.prototype.getTextGuideLine = function () {
  6593. return this._textGuide;
  6594. };
  6595. Element.prototype.setTextGuideLine = function (guideLine) {
  6596. if (this._textGuide && this._textGuide !== guideLine) {
  6597. this.removeTextGuideLine();
  6598. }
  6599. this._attachComponent(guideLine);
  6600. this._textGuide = guideLine;
  6601. this.markRedraw();
  6602. };
  6603. Element.prototype.removeTextGuideLine = function () {
  6604. var textGuide = this._textGuide;
  6605. if (textGuide) {
  6606. this._detachComponent(textGuide);
  6607. this._textGuide = null;
  6608. this.markRedraw();
  6609. }
  6610. };
  6611. Element.prototype.markRedraw = function () {
  6612. this.__dirty |= REDRAW_BIT;
  6613. var zr = this.__zr;
  6614. if (zr) {
  6615. if (this.__inHover) {
  6616. zr.refreshHover();
  6617. }
  6618. else {
  6619. zr.refresh();
  6620. }
  6621. }
  6622. if (this.__hostTarget) {
  6623. this.__hostTarget.markRedraw();
  6624. }
  6625. };
  6626. Element.prototype.dirty = function () {
  6627. this.markRedraw();
  6628. };
  6629. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6630. this.__inHover = inHover;
  6631. var textContent = this._textContent;
  6632. var textGuide = this._textGuide;
  6633. if (textContent) {
  6634. textContent.__inHover = inHover;
  6635. }
  6636. if (textGuide) {
  6637. textGuide.__inHover = inHover;
  6638. }
  6639. };
  6640. Element.prototype.addSelfToZr = function (zr) {
  6641. if (this.__zr === zr) {
  6642. return;
  6643. }
  6644. this.__zr = zr;
  6645. var animators = this.animators;
  6646. if (animators) {
  6647. for (var i = 0; i < animators.length; i++) {
  6648. zr.animation.addAnimator(animators[i]);
  6649. }
  6650. }
  6651. if (this._clipPath) {
  6652. this._clipPath.addSelfToZr(zr);
  6653. }
  6654. if (this._textContent) {
  6655. this._textContent.addSelfToZr(zr);
  6656. }
  6657. if (this._textGuide) {
  6658. this._textGuide.addSelfToZr(zr);
  6659. }
  6660. };
  6661. Element.prototype.removeSelfFromZr = function (zr) {
  6662. if (!this.__zr) {
  6663. return;
  6664. }
  6665. this.__zr = null;
  6666. var animators = this.animators;
  6667. if (animators) {
  6668. for (var i = 0; i < animators.length; i++) {
  6669. zr.animation.removeAnimator(animators[i]);
  6670. }
  6671. }
  6672. if (this._clipPath) {
  6673. this._clipPath.removeSelfFromZr(zr);
  6674. }
  6675. if (this._textContent) {
  6676. this._textContent.removeSelfFromZr(zr);
  6677. }
  6678. if (this._textGuide) {
  6679. this._textGuide.removeSelfFromZr(zr);
  6680. }
  6681. };
  6682. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6683. var target = key ? this[key] : this;
  6684. if ("development" !== 'production') {
  6685. if (!target) {
  6686. logError('Property "'
  6687. + key
  6688. + '" is not existed in element '
  6689. + this.id);
  6690. return;
  6691. }
  6692. }
  6693. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6694. key && (animator.targetName = key);
  6695. this.addAnimator(animator, key);
  6696. return animator;
  6697. };
  6698. Element.prototype.addAnimator = function (animator, key) {
  6699. var zr = this.__zr;
  6700. var el = this;
  6701. animator.during(function () {
  6702. el.updateDuringAnimation(key);
  6703. }).done(function () {
  6704. var animators = el.animators;
  6705. var idx = indexOf(animators, animator);
  6706. if (idx >= 0) {
  6707. animators.splice(idx, 1);
  6708. }
  6709. });
  6710. this.animators.push(animator);
  6711. if (zr) {
  6712. zr.animation.addAnimator(animator);
  6713. }
  6714. zr && zr.wakeUp();
  6715. };
  6716. Element.prototype.updateDuringAnimation = function (key) {
  6717. this.markRedraw();
  6718. };
  6719. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6720. var animators = this.animators;
  6721. var len = animators.length;
  6722. var leftAnimators = [];
  6723. for (var i = 0; i < len; i++) {
  6724. var animator = animators[i];
  6725. if (!scope || scope === animator.scope) {
  6726. animator.stop(forwardToLast);
  6727. }
  6728. else {
  6729. leftAnimators.push(animator);
  6730. }
  6731. }
  6732. this.animators = leftAnimators;
  6733. return this;
  6734. };
  6735. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6736. animateTo(this, target, cfg, animationProps);
  6737. };
  6738. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6739. animateTo(this, target, cfg, animationProps, true);
  6740. };
  6741. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6742. var animators = animateTo(this, target, cfg, animationProps);
  6743. for (var i = 0; i < animators.length; i++) {
  6744. animators[i].__fromStateTransition = stateName;
  6745. }
  6746. };
  6747. Element.prototype.getBoundingRect = function () {
  6748. return null;
  6749. };
  6750. Element.prototype.getPaintRect = function () {
  6751. return null;
  6752. };
  6753. Element.initDefaultProps = (function () {
  6754. var elProto = Element.prototype;
  6755. elProto.type = 'element';
  6756. elProto.name = '';
  6757. elProto.ignore =
  6758. elProto.silent =
  6759. elProto.ignoreHostSilent =
  6760. elProto.isGroup =
  6761. elProto.draggable =
  6762. elProto.dragging =
  6763. elProto.ignoreClip =
  6764. elProto.__inHover = false;
  6765. elProto.__dirty = REDRAW_BIT;
  6766. var logs = {};
  6767. function logDeprecatedError(key, xKey, yKey) {
  6768. if (!logs[key + xKey + yKey]) {
  6769. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6770. logs[key + xKey + yKey] = true;
  6771. }
  6772. }
  6773. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6774. Object.defineProperty(elProto, key, {
  6775. get: function () {
  6776. if ("development" !== 'production') {
  6777. logDeprecatedError(key, xKey, yKey);
  6778. }
  6779. if (!this[privateKey]) {
  6780. var pos = this[privateKey] = [];
  6781. enhanceArray(this, pos);
  6782. }
  6783. return this[privateKey];
  6784. },
  6785. set: function (pos) {
  6786. if ("development" !== 'production') {
  6787. logDeprecatedError(key, xKey, yKey);
  6788. }
  6789. this[xKey] = pos[0];
  6790. this[yKey] = pos[1];
  6791. this[privateKey] = pos;
  6792. enhanceArray(this, pos);
  6793. }
  6794. });
  6795. function enhanceArray(self, pos) {
  6796. Object.defineProperty(pos, 0, {
  6797. get: function () {
  6798. return self[xKey];
  6799. },
  6800. set: function (val) {
  6801. self[xKey] = val;
  6802. }
  6803. });
  6804. Object.defineProperty(pos, 1, {
  6805. get: function () {
  6806. return self[yKey];
  6807. },
  6808. set: function (val) {
  6809. self[yKey] = val;
  6810. }
  6811. });
  6812. }
  6813. }
  6814. if (Object.defineProperty) {
  6815. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6816. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6817. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6818. }
  6819. })();
  6820. return Element;
  6821. }());
  6822. mixin(Element, Eventful);
  6823. mixin(Element, Transformable);
  6824. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6825. cfg = cfg || {};
  6826. var animators = [];
  6827. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6828. var finishCount = animators.length;
  6829. var doneHappened = false;
  6830. var cfgDone = cfg.done;
  6831. var cfgAborted = cfg.aborted;
  6832. var doneCb = function () {
  6833. doneHappened = true;
  6834. finishCount--;
  6835. if (finishCount <= 0) {
  6836. doneHappened
  6837. ? (cfgDone && cfgDone())
  6838. : (cfgAborted && cfgAborted());
  6839. }
  6840. };
  6841. var abortedCb = function () {
  6842. finishCount--;
  6843. if (finishCount <= 0) {
  6844. doneHappened
  6845. ? (cfgDone && cfgDone())
  6846. : (cfgAborted && cfgAborted());
  6847. }
  6848. };
  6849. if (!finishCount) {
  6850. cfgDone && cfgDone();
  6851. }
  6852. if (animators.length > 0 && cfg.during) {
  6853. animators[0].during(function (target, percent) {
  6854. cfg.during(percent);
  6855. });
  6856. }
  6857. for (var i = 0; i < animators.length; i++) {
  6858. var animator = animators[i];
  6859. if (doneCb) {
  6860. animator.done(doneCb);
  6861. }
  6862. if (abortedCb) {
  6863. animator.aborted(abortedCb);
  6864. }
  6865. if (cfg.force) {
  6866. animator.duration(cfg.duration);
  6867. }
  6868. animator.start(cfg.easing);
  6869. }
  6870. return animators;
  6871. }
  6872. function copyArrShallow(source, target, len) {
  6873. for (var i = 0; i < len; i++) {
  6874. source[i] = target[i];
  6875. }
  6876. }
  6877. function is2DArray(value) {
  6878. return isArrayLike(value[0]);
  6879. }
  6880. function copyValue(target, source, key) {
  6881. if (isArrayLike(source[key])) {
  6882. if (!isArrayLike(target[key])) {
  6883. target[key] = [];
  6884. }
  6885. if (isTypedArray(source[key])) {
  6886. var len = source[key].length;
  6887. if (target[key].length !== len) {
  6888. target[key] = new (source[key].constructor)(len);
  6889. copyArrShallow(target[key], source[key], len);
  6890. }
  6891. }
  6892. else {
  6893. var sourceArr = source[key];
  6894. var targetArr = target[key];
  6895. var len0 = sourceArr.length;
  6896. if (is2DArray(sourceArr)) {
  6897. var len1 = sourceArr[0].length;
  6898. for (var i = 0; i < len0; i++) {
  6899. if (!targetArr[i]) {
  6900. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6901. }
  6902. else {
  6903. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6904. }
  6905. }
  6906. }
  6907. else {
  6908. copyArrShallow(targetArr, sourceArr, len0);
  6909. }
  6910. targetArr.length = sourceArr.length;
  6911. }
  6912. }
  6913. else {
  6914. target[key] = source[key];
  6915. }
  6916. }
  6917. function isValueSame(val1, val2) {
  6918. return val1 === val2
  6919. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6920. }
  6921. function is1DArraySame(arr0, arr1) {
  6922. var len = arr0.length;
  6923. if (len !== arr1.length) {
  6924. return false;
  6925. }
  6926. for (var i = 0; i < len; i++) {
  6927. if (arr0[i] !== arr1[i]) {
  6928. return false;
  6929. }
  6930. }
  6931. return true;
  6932. }
  6933. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6934. var targetKeys = keys(target);
  6935. var duration = cfg.duration;
  6936. var delay = cfg.delay;
  6937. var additive = cfg.additive;
  6938. var setToFinal = cfg.setToFinal;
  6939. var animateAll = !isObject(animationProps);
  6940. var existsAnimators = animatable.animators;
  6941. var animationKeys = [];
  6942. for (var k = 0; k < targetKeys.length; k++) {
  6943. var innerKey = targetKeys[k];
  6944. var targetVal = target[innerKey];
  6945. if (targetVal != null && animateObj[innerKey] != null
  6946. && (animateAll || animationProps[innerKey])) {
  6947. if (isObject(targetVal)
  6948. && !isArrayLike(targetVal)
  6949. && !isGradientObject(targetVal)) {
  6950. if (topKey) {
  6951. if (!reverse) {
  6952. animateObj[innerKey] = targetVal;
  6953. animatable.updateDuringAnimation(topKey);
  6954. }
  6955. continue;
  6956. }
  6957. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6958. }
  6959. else {
  6960. animationKeys.push(innerKey);
  6961. }
  6962. }
  6963. else if (!reverse) {
  6964. animateObj[innerKey] = targetVal;
  6965. animatable.updateDuringAnimation(topKey);
  6966. animationKeys.push(innerKey);
  6967. }
  6968. }
  6969. var keyLen = animationKeys.length;
  6970. if (!additive && keyLen) {
  6971. for (var i = 0; i < existsAnimators.length; i++) {
  6972. var animator = existsAnimators[i];
  6973. if (animator.targetName === topKey) {
  6974. var allAborted = animator.stopTracks(animationKeys);
  6975. if (allAborted) {
  6976. var idx = indexOf(existsAnimators, animator);
  6977. existsAnimators.splice(idx, 1);
  6978. }
  6979. }
  6980. }
  6981. }
  6982. if (!cfg.force) {
  6983. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6984. keyLen = animationKeys.length;
  6985. }
  6986. if (keyLen > 0
  6987. || (cfg.force && !animators.length)) {
  6988. var revertedSource = void 0;
  6989. var reversedTarget = void 0;
  6990. var sourceClone = void 0;
  6991. if (reverse) {
  6992. reversedTarget = {};
  6993. if (setToFinal) {
  6994. revertedSource = {};
  6995. }
  6996. for (var i = 0; i < keyLen; i++) {
  6997. var innerKey = animationKeys[i];
  6998. reversedTarget[innerKey] = animateObj[innerKey];
  6999. if (setToFinal) {
  7000. revertedSource[innerKey] = target[innerKey];
  7001. }
  7002. else {
  7003. animateObj[innerKey] = target[innerKey];
  7004. }
  7005. }
  7006. }
  7007. else if (setToFinal) {
  7008. sourceClone = {};
  7009. for (var i = 0; i < keyLen; i++) {
  7010. var innerKey = animationKeys[i];
  7011. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  7012. copyValue(animateObj, target, innerKey);
  7013. }
  7014. }
  7015. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  7016. animator.targetName = topKey;
  7017. if (cfg.scope) {
  7018. animator.scope = cfg.scope;
  7019. }
  7020. if (setToFinal && revertedSource) {
  7021. animator.whenWithKeys(0, revertedSource, animationKeys);
  7022. }
  7023. if (sourceClone) {
  7024. animator.whenWithKeys(0, sourceClone, animationKeys);
  7025. }
  7026. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  7027. animatable.addAnimator(animator, topKey);
  7028. animators.push(animator);
  7029. }
  7030. }
  7031. var Group = (function (_super) {
  7032. __extends(Group, _super);
  7033. function Group(opts) {
  7034. var _this = _super.call(this) || this;
  7035. _this.isGroup = true;
  7036. _this._children = [];
  7037. _this.attr(opts);
  7038. return _this;
  7039. }
  7040. Group.prototype.childrenRef = function () {
  7041. return this._children;
  7042. };
  7043. Group.prototype.children = function () {
  7044. return this._children.slice();
  7045. };
  7046. Group.prototype.childAt = function (idx) {
  7047. return this._children[idx];
  7048. };
  7049. Group.prototype.childOfName = function (name) {
  7050. var children = this._children;
  7051. for (var i = 0; i < children.length; i++) {
  7052. if (children[i].name === name) {
  7053. return children[i];
  7054. }
  7055. }
  7056. };
  7057. Group.prototype.childCount = function () {
  7058. return this._children.length;
  7059. };
  7060. Group.prototype.add = function (child) {
  7061. if (child) {
  7062. if (child !== this && child.parent !== this) {
  7063. this._children.push(child);
  7064. this._doAdd(child);
  7065. }
  7066. if ("development" !== 'production') {
  7067. if (child.__hostTarget) {
  7068. throw 'This elemenet has been used as an attachment';
  7069. }
  7070. }
  7071. }
  7072. return this;
  7073. };
  7074. Group.prototype.addBefore = function (child, nextSibling) {
  7075. if (child && child !== this && child.parent !== this
  7076. && nextSibling && nextSibling.parent === this) {
  7077. var children = this._children;
  7078. var idx = children.indexOf(nextSibling);
  7079. if (idx >= 0) {
  7080. children.splice(idx, 0, child);
  7081. this._doAdd(child);
  7082. }
  7083. }
  7084. return this;
  7085. };
  7086. Group.prototype.replace = function (oldChild, newChild) {
  7087. var idx = indexOf(this._children, oldChild);
  7088. if (idx >= 0) {
  7089. this.replaceAt(newChild, idx);
  7090. }
  7091. return this;
  7092. };
  7093. Group.prototype.replaceAt = function (child, index) {
  7094. var children = this._children;
  7095. var old = children[index];
  7096. if (child && child !== this && child.parent !== this && child !== old) {
  7097. children[index] = child;
  7098. old.parent = null;
  7099. var zr = this.__zr;
  7100. if (zr) {
  7101. old.removeSelfFromZr(zr);
  7102. }
  7103. this._doAdd(child);
  7104. }
  7105. return this;
  7106. };
  7107. Group.prototype._doAdd = function (child) {
  7108. if (child.parent) {
  7109. child.parent.remove(child);
  7110. }
  7111. child.parent = this;
  7112. var zr = this.__zr;
  7113. if (zr && zr !== child.__zr) {
  7114. child.addSelfToZr(zr);
  7115. }
  7116. zr && zr.refresh();
  7117. };
  7118. Group.prototype.remove = function (child) {
  7119. var zr = this.__zr;
  7120. var children = this._children;
  7121. var idx = indexOf(children, child);
  7122. if (idx < 0) {
  7123. return this;
  7124. }
  7125. children.splice(idx, 1);
  7126. child.parent = null;
  7127. if (zr) {
  7128. child.removeSelfFromZr(zr);
  7129. }
  7130. zr && zr.refresh();
  7131. return this;
  7132. };
  7133. Group.prototype.removeAll = function () {
  7134. var children = this._children;
  7135. var zr = this.__zr;
  7136. for (var i = 0; i < children.length; i++) {
  7137. var child = children[i];
  7138. if (zr) {
  7139. child.removeSelfFromZr(zr);
  7140. }
  7141. child.parent = null;
  7142. }
  7143. children.length = 0;
  7144. return this;
  7145. };
  7146. Group.prototype.eachChild = function (cb, context) {
  7147. var children = this._children;
  7148. for (var i = 0; i < children.length; i++) {
  7149. var child = children[i];
  7150. cb.call(context, child, i);
  7151. }
  7152. return this;
  7153. };
  7154. Group.prototype.traverse = function (cb, context) {
  7155. for (var i = 0; i < this._children.length; i++) {
  7156. var child = this._children[i];
  7157. var stopped = cb.call(context, child);
  7158. if (child.isGroup && !stopped) {
  7159. child.traverse(cb, context);
  7160. }
  7161. }
  7162. return this;
  7163. };
  7164. Group.prototype.addSelfToZr = function (zr) {
  7165. _super.prototype.addSelfToZr.call(this, zr);
  7166. for (var i = 0; i < this._children.length; i++) {
  7167. var child = this._children[i];
  7168. child.addSelfToZr(zr);
  7169. }
  7170. };
  7171. Group.prototype.removeSelfFromZr = function (zr) {
  7172. _super.prototype.removeSelfFromZr.call(this, zr);
  7173. for (var i = 0; i < this._children.length; i++) {
  7174. var child = this._children[i];
  7175. child.removeSelfFromZr(zr);
  7176. }
  7177. };
  7178. Group.prototype.getBoundingRect = function (includeChildren) {
  7179. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7180. var children = includeChildren || this._children;
  7181. var tmpMat = [];
  7182. var rect = null;
  7183. for (var i = 0; i < children.length; i++) {
  7184. var child = children[i];
  7185. if (child.ignore || child.invisible) {
  7186. continue;
  7187. }
  7188. var childRect = child.getBoundingRect();
  7189. var transform = child.getLocalTransform(tmpMat);
  7190. if (transform) {
  7191. BoundingRect.applyTransform(tmpRect, childRect, transform);
  7192. rect = rect || tmpRect.clone();
  7193. rect.union(tmpRect);
  7194. }
  7195. else {
  7196. rect = rect || childRect.clone();
  7197. rect.union(childRect);
  7198. }
  7199. }
  7200. return rect || tmpRect;
  7201. };
  7202. return Group;
  7203. }(Element));
  7204. Group.prototype.type = 'group';
  7205. /*!
  7206. * ZRender, a high performance 2d drawing library.
  7207. *
  7208. * Copyright (c) 2013, Baidu Inc.
  7209. * All rights reserved.
  7210. *
  7211. * LICENSE
  7212. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  7213. */
  7214. var painterCtors = {};
  7215. var instances = {};
  7216. function delInstance(id) {
  7217. delete instances[id];
  7218. }
  7219. function isDarkMode(backgroundColor) {
  7220. if (!backgroundColor) {
  7221. return false;
  7222. }
  7223. if (typeof backgroundColor === 'string') {
  7224. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  7225. }
  7226. else if (backgroundColor.colorStops) {
  7227. var colorStops = backgroundColor.colorStops;
  7228. var totalLum = 0;
  7229. var len = colorStops.length;
  7230. for (var i = 0; i < len; i++) {
  7231. totalLum += lum(colorStops[i].color, 1);
  7232. }
  7233. totalLum /= len;
  7234. return totalLum < DARK_MODE_THRESHOLD;
  7235. }
  7236. return false;
  7237. }
  7238. var ZRender = (function () {
  7239. function ZRender(id, dom, opts) {
  7240. var _this = this;
  7241. this._sleepAfterStill = 10;
  7242. this._stillFrameAccum = 0;
  7243. this._needsRefresh = true;
  7244. this._needsRefreshHover = true;
  7245. this._darkMode = false;
  7246. opts = opts || {};
  7247. this.dom = dom;
  7248. this.id = id;
  7249. var storage = new Storage();
  7250. var rendererType = opts.renderer || 'canvas';
  7251. if (!painterCtors[rendererType]) {
  7252. rendererType = keys(painterCtors)[0];
  7253. }
  7254. if ("development" !== 'production') {
  7255. if (!painterCtors[rendererType]) {
  7256. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7257. }
  7258. }
  7259. opts.useDirtyRect = opts.useDirtyRect == null
  7260. ? false
  7261. : opts.useDirtyRect;
  7262. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7263. var ssrMode = opts.ssr || painter.ssrOnly;
  7264. this.storage = storage;
  7265. this.painter = painter;
  7266. var handlerProxy = (!env.node && !env.worker && !ssrMode)
  7267. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7268. : null;
  7269. var useCoarsePointer = opts.useCoarsePointer;
  7270. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7271. ? env.touchEventsSupported
  7272. : !!useCoarsePointer;
  7273. var defaultPointerSize = 44;
  7274. var pointerSize;
  7275. if (usePointerSize) {
  7276. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7277. }
  7278. this.handler = new Handler(storage, painter, handlerProxy, painter.root, pointerSize);
  7279. this.animation = new Animation({
  7280. stage: {
  7281. update: ssrMode ? null : function () { return _this._flush(true); }
  7282. }
  7283. });
  7284. if (!ssrMode) {
  7285. this.animation.start();
  7286. }
  7287. }
  7288. ZRender.prototype.add = function (el) {
  7289. if (this._disposed || !el) {
  7290. return;
  7291. }
  7292. this.storage.addRoot(el);
  7293. el.addSelfToZr(this);
  7294. this.refresh();
  7295. };
  7296. ZRender.prototype.remove = function (el) {
  7297. if (this._disposed || !el) {
  7298. return;
  7299. }
  7300. this.storage.delRoot(el);
  7301. el.removeSelfFromZr(this);
  7302. this.refresh();
  7303. };
  7304. ZRender.prototype.configLayer = function (zLevel, config) {
  7305. if (this._disposed) {
  7306. return;
  7307. }
  7308. if (this.painter.configLayer) {
  7309. this.painter.configLayer(zLevel, config);
  7310. }
  7311. this.refresh();
  7312. };
  7313. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7314. if (this._disposed) {
  7315. return;
  7316. }
  7317. if (this.painter.setBackgroundColor) {
  7318. this.painter.setBackgroundColor(backgroundColor);
  7319. }
  7320. this.refresh();
  7321. this._backgroundColor = backgroundColor;
  7322. this._darkMode = isDarkMode(backgroundColor);
  7323. };
  7324. ZRender.prototype.getBackgroundColor = function () {
  7325. return this._backgroundColor;
  7326. };
  7327. ZRender.prototype.setDarkMode = function (darkMode) {
  7328. this._darkMode = darkMode;
  7329. };
  7330. ZRender.prototype.isDarkMode = function () {
  7331. return this._darkMode;
  7332. };
  7333. ZRender.prototype.refreshImmediately = function (fromInside) {
  7334. if (this._disposed) {
  7335. return;
  7336. }
  7337. if (!fromInside) {
  7338. this.animation.update(true);
  7339. }
  7340. this._needsRefresh = false;
  7341. this.painter.refresh();
  7342. this._needsRefresh = false;
  7343. };
  7344. ZRender.prototype.refresh = function () {
  7345. if (this._disposed) {
  7346. return;
  7347. }
  7348. this._needsRefresh = true;
  7349. this.animation.start();
  7350. };
  7351. ZRender.prototype.flush = function () {
  7352. if (this._disposed) {
  7353. return;
  7354. }
  7355. this._flush(false);
  7356. };
  7357. ZRender.prototype._flush = function (fromInside) {
  7358. var triggerRendered;
  7359. var start = getTime();
  7360. if (this._needsRefresh) {
  7361. triggerRendered = true;
  7362. this.refreshImmediately(fromInside);
  7363. }
  7364. if (this._needsRefreshHover) {
  7365. triggerRendered = true;
  7366. this.refreshHoverImmediately();
  7367. }
  7368. var end = getTime();
  7369. if (triggerRendered) {
  7370. this._stillFrameAccum = 0;
  7371. this.trigger('rendered', {
  7372. elapsedTime: end - start
  7373. });
  7374. }
  7375. else if (this._sleepAfterStill > 0) {
  7376. this._stillFrameAccum++;
  7377. if (this._stillFrameAccum > this._sleepAfterStill) {
  7378. this.animation.stop();
  7379. }
  7380. }
  7381. };
  7382. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7383. this._sleepAfterStill = stillFramesCount;
  7384. };
  7385. ZRender.prototype.wakeUp = function () {
  7386. if (this._disposed) {
  7387. return;
  7388. }
  7389. this.animation.start();
  7390. this._stillFrameAccum = 0;
  7391. };
  7392. ZRender.prototype.refreshHover = function () {
  7393. this._needsRefreshHover = true;
  7394. };
  7395. ZRender.prototype.refreshHoverImmediately = function () {
  7396. if (this._disposed) {
  7397. return;
  7398. }
  7399. this._needsRefreshHover = false;
  7400. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7401. this.painter.refreshHover();
  7402. }
  7403. };
  7404. ZRender.prototype.resize = function (opts) {
  7405. if (this._disposed) {
  7406. return;
  7407. }
  7408. opts = opts || {};
  7409. this.painter.resize(opts.width, opts.height);
  7410. this.handler.resize();
  7411. };
  7412. ZRender.prototype.clearAnimation = function () {
  7413. if (this._disposed) {
  7414. return;
  7415. }
  7416. this.animation.clear();
  7417. };
  7418. ZRender.prototype.getWidth = function () {
  7419. if (this._disposed) {
  7420. return;
  7421. }
  7422. return this.painter.getWidth();
  7423. };
  7424. ZRender.prototype.getHeight = function () {
  7425. if (this._disposed) {
  7426. return;
  7427. }
  7428. return this.painter.getHeight();
  7429. };
  7430. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7431. if (this._disposed) {
  7432. return;
  7433. }
  7434. this.handler.setCursorStyle(cursorStyle);
  7435. };
  7436. ZRender.prototype.findHover = function (x, y) {
  7437. if (this._disposed) {
  7438. return;
  7439. }
  7440. return this.handler.findHover(x, y);
  7441. };
  7442. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7443. if (!this._disposed) {
  7444. this.handler.on(eventName, eventHandler, context);
  7445. }
  7446. return this;
  7447. };
  7448. ZRender.prototype.off = function (eventName, eventHandler) {
  7449. if (this._disposed) {
  7450. return;
  7451. }
  7452. this.handler.off(eventName, eventHandler);
  7453. };
  7454. ZRender.prototype.trigger = function (eventName, event) {
  7455. if (this._disposed) {
  7456. return;
  7457. }
  7458. this.handler.trigger(eventName, event);
  7459. };
  7460. ZRender.prototype.clear = function () {
  7461. if (this._disposed) {
  7462. return;
  7463. }
  7464. var roots = this.storage.getRoots();
  7465. for (var i = 0; i < roots.length; i++) {
  7466. if (roots[i] instanceof Group) {
  7467. roots[i].removeSelfFromZr(this);
  7468. }
  7469. }
  7470. this.storage.delAllRoots();
  7471. this.painter.clear();
  7472. };
  7473. ZRender.prototype.dispose = function () {
  7474. if (this._disposed) {
  7475. return;
  7476. }
  7477. this.animation.stop();
  7478. this.clear();
  7479. this.storage.dispose();
  7480. this.painter.dispose();
  7481. this.handler.dispose();
  7482. this.animation =
  7483. this.storage =
  7484. this.painter =
  7485. this.handler = null;
  7486. this._disposed = true;
  7487. delInstance(this.id);
  7488. };
  7489. return ZRender;
  7490. }());
  7491. function init(dom, opts) {
  7492. var zr = new ZRender(guid(), dom, opts);
  7493. instances[zr.id] = zr;
  7494. return zr;
  7495. }
  7496. function dispose(zr) {
  7497. zr.dispose();
  7498. }
  7499. function disposeAll() {
  7500. for (var key in instances) {
  7501. if (instances.hasOwnProperty(key)) {
  7502. instances[key].dispose();
  7503. }
  7504. }
  7505. instances = {};
  7506. }
  7507. function getInstance(id) {
  7508. return instances[id];
  7509. }
  7510. function registerPainter(name, Ctor) {
  7511. painterCtors[name] = Ctor;
  7512. }
  7513. var ssrDataGetter;
  7514. function getElementSSRData(el) {
  7515. if (typeof ssrDataGetter === 'function') {
  7516. return ssrDataGetter(el);
  7517. }
  7518. }
  7519. function registerSSRDataGetter(getter) {
  7520. ssrDataGetter = getter;
  7521. }
  7522. var version = '6.0.0';
  7523. var zrender = /*#__PURE__*/Object.freeze({
  7524. __proto__: null,
  7525. init: init,
  7526. dispose: dispose,
  7527. disposeAll: disposeAll,
  7528. getInstance: getInstance,
  7529. registerPainter: registerPainter,
  7530. getElementSSRData: getElementSSRData,
  7531. registerSSRDataGetter: registerSSRDataGetter,
  7532. version: version
  7533. });
  7534. var RADIAN_EPSILON = 1e-4;
  7535. // Although chrome already enlarge this number to 100 for `toFixed`, but
  7536. // we sill follow the spec for compatibility.
  7537. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7538. function _trim(str) {
  7539. return str.replace(/^\s+|\s+$/g, '');
  7540. }
  7541. var mathMin$1 = Math.min;
  7542. var mathMax$1 = Math.max;
  7543. var mathAbs$1 = Math.abs;
  7544. /**
  7545. * Linear mapping a value from domain to range
  7546. * @param val
  7547. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7548. * @param range Range extent range[0] can be bigger than range[1]
  7549. * @param clamp Default to be false
  7550. */
  7551. function linearMap(val, domain, range, clamp) {
  7552. var d0 = domain[0];
  7553. var d1 = domain[1];
  7554. var r0 = range[0];
  7555. var r1 = range[1];
  7556. var subDomain = d1 - d0;
  7557. var subRange = r1 - r0;
  7558. if (subDomain === 0) {
  7559. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7560. }
  7561. // Avoid accuracy problem in edge, such as
  7562. // 146.39 - 62.83 === 83.55999999999999.
  7563. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7564. // It is a little verbose for efficiency considering this method
  7565. // is a hotspot.
  7566. if (clamp) {
  7567. if (subDomain > 0) {
  7568. if (val <= d0) {
  7569. return r0;
  7570. } else if (val >= d1) {
  7571. return r1;
  7572. }
  7573. } else {
  7574. if (val >= d0) {
  7575. return r0;
  7576. } else if (val <= d1) {
  7577. return r1;
  7578. }
  7579. }
  7580. } else {
  7581. if (val === d0) {
  7582. return r0;
  7583. }
  7584. if (val === d1) {
  7585. return r1;
  7586. }
  7587. }
  7588. return (val - d0) / subDomain * subRange + r0;
  7589. }
  7590. /**
  7591. * Preserve the name `parsePercent` for backward compatibility,
  7592. * and it's effectively published as `echarts.number.parsePercent`.
  7593. */
  7594. var parsePercent$1 = parsePositionOption;
  7595. /**
  7596. * @see {parsePositionSizeOption} and also accept a string preset.
  7597. * @see {PositionSizeOption}
  7598. */
  7599. function parsePositionOption(option, percentBase, percentOffset) {
  7600. switch (option) {
  7601. case 'center':
  7602. case 'middle':
  7603. option = '50%';
  7604. break;
  7605. case 'left':
  7606. case 'top':
  7607. option = '0%';
  7608. break;
  7609. case 'right':
  7610. case 'bottom':
  7611. option = '100%';
  7612. break;
  7613. }
  7614. return parsePositionSizeOption(option, percentBase, percentOffset);
  7615. }
  7616. /**
  7617. * Accept number, or numeric stirng (`'123'`), or percentage ('100%'), as x/y/width/height pixel number.
  7618. * If null/undefined or invalid, return NaN.
  7619. * (But allow JS type coercion (`+option`) due to backward compatibility)
  7620. * @see {PositionSizeOption}
  7621. */
  7622. function parsePositionSizeOption(option, percentBase, percentOffset) {
  7623. if (isString(option)) {
  7624. if (_trim(option).match(/%$/)) {
  7625. return parseFloat(option) / 100 * percentBase + (percentOffset || 0);
  7626. }
  7627. return parseFloat(option);
  7628. }
  7629. // Allow flexible input due to backward compatibility.
  7630. return option == null ? NaN : +option;
  7631. }
  7632. function round(x, precision, returnStr) {
  7633. if (precision == null) {
  7634. // FIXME: the default precision should not be provided, since there is no universally adaptable
  7635. // precision. The caller need to input a precision according to the scenarios.
  7636. precision = 10;
  7637. }
  7638. // Avoid range error
  7639. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX);
  7640. // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7641. x = (+x).toFixed(precision);
  7642. return returnStr ? x : +x;
  7643. }
  7644. /**
  7645. * Inplacd asc sort arr.
  7646. * The input arr will be modified.
  7647. */
  7648. function asc(arr) {
  7649. arr.sort(function (a, b) {
  7650. return a - b;
  7651. });
  7652. return arr;
  7653. }
  7654. /**
  7655. * Get precision.
  7656. */
  7657. function getPrecision(val) {
  7658. val = +val;
  7659. if (isNaN(val)) {
  7660. return 0;
  7661. }
  7662. // It is much faster than methods converting number to string as follows
  7663. // let tmp = val.toString();
  7664. // return tmp.length - 1 - tmp.indexOf('.');
  7665. // especially when precision is low
  7666. // Notice:
  7667. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7668. // (see https://jsbench.me/2vkpcekkvw/1)
  7669. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7670. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7671. if (val > 1e-14) {
  7672. var e = 1;
  7673. for (var i = 0; i < 15; i++, e *= 10) {
  7674. if (Math.round(val * e) / e === val) {
  7675. return i;
  7676. }
  7677. }
  7678. }
  7679. return getPrecisionSafe(val);
  7680. }
  7681. /**
  7682. * Get precision with slow but safe method
  7683. */
  7684. function getPrecisionSafe(val) {
  7685. // toLowerCase for: '3.4E-12'
  7686. var str = val.toString().toLowerCase();
  7687. // Consider scientific notation: '3.4e-12' '3.4e+12'
  7688. var eIndex = str.indexOf('e');
  7689. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7690. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7691. var dotIndex = str.indexOf('.');
  7692. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7693. return Math.max(0, decimalPartLen - exp);
  7694. }
  7695. /**
  7696. * Minimal dicernible data precisioin according to a single pixel.
  7697. */
  7698. function getPixelPrecision(dataExtent, pixelExtent) {
  7699. var log = Math.log;
  7700. var LN10 = Math.LN10;
  7701. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7702. var sizeQuantity = Math.round(log(mathAbs$1(pixelExtent[1] - pixelExtent[0])) / LN10);
  7703. // toFixed() digits argument must be between 0 and 20.
  7704. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7705. return !isFinite(precision) ? 20 : precision;
  7706. }
  7707. /**
  7708. * Get a data of given precision, assuring the sum of percentages
  7709. * in valueList is 1.
  7710. * The largest remainder method is used.
  7711. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7712. *
  7713. * @param valueList a list of all data
  7714. * @param idx index of the data to be processed in valueList
  7715. * @param precision integer number showing digits of precision
  7716. * @return percent ranging from 0 to 100
  7717. */
  7718. function getPercentWithPrecision(valueList, idx, precision) {
  7719. if (!valueList[idx]) {
  7720. return 0;
  7721. }
  7722. var seats = getPercentSeats(valueList, precision);
  7723. return seats[idx] || 0;
  7724. }
  7725. /**
  7726. * Get a data of given precision, assuring the sum of percentages
  7727. * in valueList is 1.
  7728. * The largest remainder method is used.
  7729. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7730. *
  7731. * @param valueList a list of all data
  7732. * @param precision integer number showing digits of precision
  7733. * @return {Array<number>}
  7734. */
  7735. function getPercentSeats(valueList, precision) {
  7736. var sum = reduce(valueList, function (acc, val) {
  7737. return acc + (isNaN(val) ? 0 : val);
  7738. }, 0);
  7739. if (sum === 0) {
  7740. return [];
  7741. }
  7742. var digits = Math.pow(10, precision);
  7743. var votesPerQuota = map(valueList, function (val) {
  7744. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7745. });
  7746. var targetSeats = digits * 100;
  7747. var seats = map(votesPerQuota, function (votes) {
  7748. // Assign automatic seats.
  7749. return Math.floor(votes);
  7750. });
  7751. var currentSum = reduce(seats, function (acc, val) {
  7752. return acc + val;
  7753. }, 0);
  7754. var remainder = map(votesPerQuota, function (votes, idx) {
  7755. return votes - seats[idx];
  7756. });
  7757. // Has remainding votes.
  7758. while (currentSum < targetSeats) {
  7759. // Find next largest remainder.
  7760. var max = Number.NEGATIVE_INFINITY;
  7761. var maxId = null;
  7762. for (var i = 0, len = remainder.length; i < len; ++i) {
  7763. if (remainder[i] > max) {
  7764. max = remainder[i];
  7765. maxId = i;
  7766. }
  7767. }
  7768. // Add a vote to max remainder.
  7769. ++seats[maxId];
  7770. remainder[maxId] = 0;
  7771. ++currentSum;
  7772. }
  7773. return map(seats, function (seat) {
  7774. return seat / digits;
  7775. });
  7776. }
  7777. /**
  7778. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7779. * See <http://0.30000000000000004.com/>
  7780. */
  7781. function addSafe(val0, val1) {
  7782. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1));
  7783. // const multiplier = Math.pow(10, maxPrecision);
  7784. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7785. var sum = val0 + val1;
  7786. // // PENDING: support more?
  7787. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7788. }
  7789. // Number.MAX_SAFE_INTEGER, ie do not support.
  7790. var MAX_SAFE_INTEGER = 9007199254740991;
  7791. /**
  7792. * To 0 - 2 * PI, considering negative radian.
  7793. */
  7794. function remRadian(radian) {
  7795. var pi2 = Math.PI * 2;
  7796. return (radian % pi2 + pi2) % pi2;
  7797. }
  7798. /**
  7799. * @param {type} radian
  7800. * @return {boolean}
  7801. */
  7802. function isRadianAroundZero(val) {
  7803. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7804. }
  7805. // eslint-disable-next-line
  7806. 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
  7807. /**
  7808. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7809. * These values can be accepted:
  7810. * + An instance of Date, represent a time in its own time zone.
  7811. * + Or string in a subset of ISO 8601, only including:
  7812. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7813. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7814. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7815. * all of which will be treated as local time if time zone is not specified
  7816. * (see <https://momentjs.com/>).
  7817. * + Or other string format, including (all of which will be treated as local time):
  7818. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7819. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7820. * + a timestamp, which represent a time in UTC.
  7821. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7822. */
  7823. function parseDate(value) {
  7824. if (value instanceof Date) {
  7825. return value;
  7826. } else if (isString(value)) {
  7827. // Different browsers parse date in different way, so we parse it manually.
  7828. // Some other issues:
  7829. // new Date('1970-01-01') is UTC,
  7830. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7831. // See issue #3623
  7832. var match = TIME_REG.exec(value);
  7833. if (!match) {
  7834. // return Invalid Date.
  7835. return new Date(NaN);
  7836. }
  7837. // Use local time when no timezone offset is specified.
  7838. if (!match[8]) {
  7839. // match[n] can only be string or undefined.
  7840. // But take care of '12' + 1 => '121'.
  7841. 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);
  7842. }
  7843. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7844. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7845. // For example, system timezone is set as "Time Zone: America/Toronto",
  7846. // then these code will get different result:
  7847. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7848. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7849. // So we should not use `new Date`, but use `Date.UTC`.
  7850. else {
  7851. var hour = +match[4] || 0;
  7852. if (match[8].toUpperCase() !== 'Z') {
  7853. hour -= +match[8].slice(0, 3);
  7854. }
  7855. 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));
  7856. }
  7857. } else if (value == null) {
  7858. return new Date(NaN);
  7859. }
  7860. return new Date(Math.round(value));
  7861. }
  7862. /**
  7863. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7864. *
  7865. * @param val
  7866. * @return
  7867. */
  7868. function quantity(val) {
  7869. return Math.pow(10, quantityExponent(val));
  7870. }
  7871. /**
  7872. * Exponent of the quantity of a number
  7873. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7874. *
  7875. * @param val non-negative value
  7876. * @return
  7877. */
  7878. function quantityExponent(val) {
  7879. if (val === 0) {
  7880. return 0;
  7881. }
  7882. var exp = Math.floor(Math.log(val) / Math.LN10);
  7883. /**
  7884. * exp is expected to be the rounded-down result of the base-10 log of val.
  7885. * But due to the precision loss with Math.log(val), we need to restore it
  7886. * using 10^exp to make sure we can get val back from exp. #11249
  7887. */
  7888. if (val / Math.pow(10, exp) >= 10) {
  7889. exp++;
  7890. }
  7891. return exp;
  7892. }
  7893. /**
  7894. * find a “nice” number approximately equal to x. Round the number if round = true,
  7895. * take ceiling if round = false. The primary observation is that the “nicest”
  7896. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7897. *
  7898. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7899. *
  7900. * @param val Non-negative value.
  7901. * @param round
  7902. * @return Niced number
  7903. */
  7904. function nice(val, round) {
  7905. var exponent = quantityExponent(val);
  7906. var exp10 = Math.pow(10, exponent);
  7907. var f = val / exp10; // 1 <= f < 10
  7908. var nf;
  7909. if (round) {
  7910. if (f < 1.5) {
  7911. nf = 1;
  7912. } else if (f < 2.5) {
  7913. nf = 2;
  7914. } else if (f < 4) {
  7915. nf = 3;
  7916. } else if (f < 7) {
  7917. nf = 5;
  7918. } else {
  7919. nf = 10;
  7920. }
  7921. } else {
  7922. if (f < 1) {
  7923. nf = 1;
  7924. } else if (f < 2) {
  7925. nf = 2;
  7926. } else if (f < 3) {
  7927. nf = 3;
  7928. } else if (f < 5) {
  7929. nf = 5;
  7930. } else {
  7931. nf = 10;
  7932. }
  7933. }
  7934. val = nf * exp10;
  7935. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7936. // 20 is the uppper bound of toFixed.
  7937. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7938. }
  7939. /**
  7940. * This code was copied from "d3.js"
  7941. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7942. * See the license statement at the head of this file.
  7943. * @param ascArr
  7944. */
  7945. function quantile(ascArr, p) {
  7946. var H = (ascArr.length - 1) * p + 1;
  7947. var h = Math.floor(H);
  7948. var v = +ascArr[h - 1];
  7949. var e = H - h;
  7950. return e ? v + e * (ascArr[h] - v) : v;
  7951. }
  7952. /**
  7953. * Order intervals asc, and split them when overlap.
  7954. * expect(numberUtil.reformIntervals([
  7955. * {interval: [18, 62], close: [1, 1]},
  7956. * {interval: [-Infinity, -70], close: [0, 0]},
  7957. * {interval: [-70, -26], close: [1, 1]},
  7958. * {interval: [-26, 18], close: [1, 1]},
  7959. * {interval: [62, 150], close: [1, 1]},
  7960. * {interval: [106, 150], close: [1, 1]},
  7961. * {interval: [150, Infinity], close: [0, 0]}
  7962. * ])).toEqual([
  7963. * {interval: [-Infinity, -70], close: [0, 0]},
  7964. * {interval: [-70, -26], close: [1, 1]},
  7965. * {interval: [-26, 18], close: [0, 1]},
  7966. * {interval: [18, 62], close: [0, 1]},
  7967. * {interval: [62, 150], close: [0, 1]},
  7968. * {interval: [150, Infinity], close: [0, 0]}
  7969. * ]);
  7970. * @param list, where `close` mean open or close
  7971. * of the interval, and Infinity can be used.
  7972. * @return The origin list, which has been reformed.
  7973. */
  7974. function reformIntervals(list) {
  7975. list.sort(function (a, b) {
  7976. return littleThan(a, b, 0) ? -1 : 1;
  7977. });
  7978. var curr = -Infinity;
  7979. var currClose = 1;
  7980. for (var i = 0; i < list.length;) {
  7981. var interval = list[i].interval;
  7982. var close_1 = list[i].close;
  7983. for (var lg = 0; lg < 2; lg++) {
  7984. if (interval[lg] <= curr) {
  7985. interval[lg] = curr;
  7986. close_1[lg] = !lg ? 1 - currClose : 1;
  7987. }
  7988. curr = interval[lg];
  7989. currClose = close_1[lg];
  7990. }
  7991. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7992. list.splice(i, 1);
  7993. } else {
  7994. i++;
  7995. }
  7996. }
  7997. return list;
  7998. function littleThan(a, b, lg) {
  7999. 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));
  8000. }
  8001. }
  8002. /**
  8003. * [Numeric is defined as]:
  8004. * `parseFloat(val) == val`
  8005. * For example:
  8006. * numeric:
  8007. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  8008. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  8009. * not-numeric:
  8010. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  8011. * empty string, string with only white-spaces or line-terminal (see es spec),
  8012. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  8013. * non-string, ...
  8014. *
  8015. * @test See full test cases in `test/ut/spec/util/number.js`.
  8016. * @return Must be a typeof number. If not numeric, return NaN.
  8017. */
  8018. function numericToNumber(val) {
  8019. var valFloat = parseFloat(val);
  8020. return valFloat == val // eslint-disable-line eqeqeq
  8021. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  8022. ? valFloat : NaN;
  8023. }
  8024. /**
  8025. * Definition of "numeric": see `numericToNumber`.
  8026. */
  8027. function isNumeric(val) {
  8028. return !isNaN(numericToNumber(val));
  8029. }
  8030. /**
  8031. * Use random base to prevent users hard code depending on
  8032. * this auto generated marker id.
  8033. * @return An positive integer.
  8034. */
  8035. function getRandomIdBase() {
  8036. return Math.round(Math.random() * 9);
  8037. }
  8038. /**
  8039. * Get the greatest common divisor.
  8040. *
  8041. * @param {number} a one number
  8042. * @param {number} b the other number
  8043. */
  8044. function getGreatestCommonDividor(a, b) {
  8045. if (b === 0) {
  8046. return a;
  8047. }
  8048. return getGreatestCommonDividor(b, a % b);
  8049. }
  8050. /**
  8051. * Get the least common multiple.
  8052. *
  8053. * @param {number} a one number
  8054. * @param {number} b the other number
  8055. */
  8056. function getLeastCommonMultiple(a, b) {
  8057. if (a == null) {
  8058. return b;
  8059. }
  8060. if (b == null) {
  8061. return a;
  8062. }
  8063. return a * b / getGreatestCommonDividor(a, b);
  8064. }
  8065. var ECHARTS_PREFIX = '[ECharts] ';
  8066. var storedLogs = {};
  8067. var hasConsole = typeof console !== 'undefined'
  8068. // eslint-disable-next-line
  8069. && console.warn && console.log;
  8070. function outputLog(type, str, onlyOnce) {
  8071. if (hasConsole) {
  8072. if (onlyOnce) {
  8073. if (storedLogs[str]) {
  8074. return;
  8075. }
  8076. storedLogs[str] = true;
  8077. }
  8078. // eslint-disable-next-line
  8079. console[type](ECHARTS_PREFIX + str);
  8080. }
  8081. }
  8082. function log(str, onlyOnce) {
  8083. outputLog('log', str, onlyOnce);
  8084. }
  8085. function warn(str, onlyOnce) {
  8086. outputLog('warn', str, onlyOnce);
  8087. }
  8088. function error(str, onlyOnce) {
  8089. outputLog('error', str, onlyOnce);
  8090. }
  8091. function deprecateLog(str) {
  8092. if ("development" !== 'production') {
  8093. // Not display duplicate message.
  8094. outputLog('warn', 'DEPRECATED: ' + str, true);
  8095. }
  8096. }
  8097. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  8098. if ("development" !== 'production') {
  8099. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated; use " + newOpt + " instead."));
  8100. }
  8101. }
  8102. /**
  8103. * If in __DEV__ environment, get console printable message for users hint.
  8104. * Parameters are separated by ' '.
  8105. * @usage
  8106. * makePrintable('This is an error on', someVar, someObj);
  8107. *
  8108. * @param hintInfo anything about the current execution context to hint users.
  8109. * @throws Error
  8110. */
  8111. function makePrintable() {
  8112. var hintInfo = [];
  8113. for (var _i = 0; _i < arguments.length; _i++) {
  8114. hintInfo[_i] = arguments[_i];
  8115. }
  8116. var msg = '';
  8117. if ("development" !== 'production') {
  8118. // Fuzzy stringify for print.
  8119. // This code only exist in dev environment.
  8120. var makePrintableStringIfPossible_1 = function (val) {
  8121. 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;
  8122. };
  8123. msg = map(hintInfo, function (arg) {
  8124. if (isString(arg)) {
  8125. // Print without quotation mark for some statement.
  8126. return arg;
  8127. } else {
  8128. var printableStr = makePrintableStringIfPossible_1(arg);
  8129. if (printableStr != null) {
  8130. return printableStr;
  8131. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  8132. try {
  8133. return JSON.stringify(arg, function (n, val) {
  8134. var printableStr = makePrintableStringIfPossible_1(val);
  8135. return printableStr == null ? val : printableStr;
  8136. });
  8137. // In most cases the info object is small, so do not line break.
  8138. } catch (err) {
  8139. return '?';
  8140. }
  8141. } else {
  8142. return '?';
  8143. }
  8144. }
  8145. }).join(' ');
  8146. }
  8147. return msg;
  8148. }
  8149. /**
  8150. * @throws Error
  8151. */
  8152. function throwError(msg) {
  8153. throw new Error(msg);
  8154. }
  8155. function interpolateNumber$1(p0, p1, percent) {
  8156. return (p1 - p0) * percent + p0;
  8157. }
  8158. /**
  8159. * Make the name displayable. But we should
  8160. * make sure it is not duplicated with user
  8161. * specified name, so use '\0';
  8162. */
  8163. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  8164. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  8165. /**
  8166. * If value is not array, then translate it to array.
  8167. * @param {*} value
  8168. * @return {Array} [value] or value
  8169. */
  8170. function normalizeToArray(value) {
  8171. return value instanceof Array ? value : value == null ? [] : [value];
  8172. }
  8173. /**
  8174. * Sync default option between normal and emphasis like `position` and `show`
  8175. * In case some one will write code like
  8176. * label: {
  8177. * show: false,
  8178. * position: 'outside',
  8179. * fontSize: 18
  8180. * },
  8181. * emphasis: {
  8182. * label: { show: true }
  8183. * }
  8184. */
  8185. function defaultEmphasis(opt, key, subOpts) {
  8186. // Caution: performance sensitive.
  8187. if (opt) {
  8188. opt[key] = opt[key] || {};
  8189. opt.emphasis = opt.emphasis || {};
  8190. opt.emphasis[key] = opt.emphasis[key] || {};
  8191. // Default emphasis option from normal
  8192. for (var i = 0, len = subOpts.length; i < len; i++) {
  8193. var subOptName = subOpts[i];
  8194. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  8195. opt.emphasis[key][subOptName] = opt[key][subOptName];
  8196. }
  8197. }
  8198. }
  8199. }
  8200. 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'];
  8201. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  8202. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  8203. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  8204. // // FIXME: deprecated, check and remove it.
  8205. // 'textStyle'
  8206. // ]);
  8207. /**
  8208. * The method does not ensure performance.
  8209. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  8210. * This helper method retrieves value from data.
  8211. */
  8212. function getDataItemValue(dataItem) {
  8213. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  8214. }
  8215. /**
  8216. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  8217. * This helper method determine if dataItem has extra option besides value
  8218. */
  8219. function isDataItemOption(dataItem) {
  8220. return isObject(dataItem) && !(dataItem instanceof Array);
  8221. // // markLine data can be array
  8222. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  8223. }
  8224. /**
  8225. * Mapping to existings for merge.
  8226. *
  8227. * Mode "normalMege":
  8228. * The mapping result (merge result) will keep the order of the existing
  8229. * component, rather than the order of new option. Because we should ensure
  8230. * some specified index reference (like xAxisIndex) keep work.
  8231. * And in most cases, "merge option" is used to update partial option but not
  8232. * be expected to change the order.
  8233. *
  8234. * Mode "replaceMege":
  8235. * (1) Only the id mapped components will be merged.
  8236. * (2) Other existing components (except internal components) will be removed.
  8237. * (3) Other new options will be used to create new component.
  8238. * (4) The index of the existing components will not be modified.
  8239. * That means their might be "hole" after the removal.
  8240. * The new components are created first at those available index.
  8241. *
  8242. * Mode "replaceAll":
  8243. * This mode try to support that reproduce an echarts instance from another
  8244. * echarts instance (via `getOption`) in some simple cases.
  8245. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  8246. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  8247. * the "hole" in `newCmptOptions` will also be kept.
  8248. * On the contrary, other modes try best to eliminate holes.
  8249. * PENDING: This is an experimental mode yet.
  8250. *
  8251. * @return See the comment of <MappingResult>.
  8252. */
  8253. function mappingToExists(existings, newCmptOptions, mode) {
  8254. var isNormalMergeMode = mode === 'normalMerge';
  8255. var isReplaceMergeMode = mode === 'replaceMerge';
  8256. var isReplaceAllMode = mode === 'replaceAll';
  8257. existings = existings || [];
  8258. newCmptOptions = (newCmptOptions || []).slice();
  8259. var existingIdIdxMap = createHashMap();
  8260. // Validate id and name on user input option.
  8261. each(newCmptOptions, function (cmptOption, index) {
  8262. if (!isObject(cmptOption)) {
  8263. newCmptOptions[index] = null;
  8264. return;
  8265. }
  8266. if ("development" !== 'production') {
  8267. // There is some legacy case that name is set as `false`.
  8268. // But should work normally rather than throw error.
  8269. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  8270. warnInvalidateIdOrName(cmptOption.id);
  8271. }
  8272. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  8273. warnInvalidateIdOrName(cmptOption.name);
  8274. }
  8275. }
  8276. });
  8277. var result = prepareResult(existings, existingIdIdxMap, mode);
  8278. if (isNormalMergeMode || isReplaceMergeMode) {
  8279. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  8280. }
  8281. if (isNormalMergeMode) {
  8282. mappingByName(result, newCmptOptions);
  8283. }
  8284. if (isNormalMergeMode || isReplaceMergeMode) {
  8285. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  8286. } else if (isReplaceAllMode) {
  8287. mappingInReplaceAllMode(result, newCmptOptions);
  8288. }
  8289. makeIdAndName(result);
  8290. // The array `result` MUST NOT contain elided items, otherwise the
  8291. // forEach will omit those items and result in incorrect result.
  8292. return result;
  8293. }
  8294. function prepareResult(existings, existingIdIdxMap, mode) {
  8295. var result = [];
  8296. if (mode === 'replaceAll') {
  8297. return result;
  8298. }
  8299. // Do not use native `map` to in case that the array `existings`
  8300. // contains elided items, which will be omitted.
  8301. for (var index = 0; index < existings.length; index++) {
  8302. var existing = existings[index];
  8303. // Because of replaceMerge, `existing` may be null/undefined.
  8304. if (existing && existing.id != null) {
  8305. existingIdIdxMap.set(existing.id, index);
  8306. }
  8307. // For non-internal-componnets:
  8308. // Mode "normalMerge": all existings kept.
  8309. // Mode "replaceMerge": all existing removed unless mapped by id.
  8310. // For internal-components:
  8311. // go with "replaceMerge" approach in both mode.
  8312. result.push({
  8313. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  8314. newOption: null,
  8315. keyInfo: null,
  8316. brandNew: null
  8317. });
  8318. }
  8319. return result;
  8320. }
  8321. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  8322. // Mapping by id if specified.
  8323. each(newCmptOptions, function (cmptOption, index) {
  8324. if (!cmptOption || cmptOption.id == null) {
  8325. return;
  8326. }
  8327. var optionId = makeComparableKey(cmptOption.id);
  8328. var existingIdx = existingIdIdxMap.get(optionId);
  8329. if (existingIdx != null) {
  8330. var resultItem = result[existingIdx];
  8331. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  8332. resultItem.newOption = cmptOption;
  8333. // In both mode, if id matched, new option will be merged to
  8334. // the existings rather than creating new component model.
  8335. resultItem.existing = existings[existingIdx];
  8336. newCmptOptions[index] = null;
  8337. }
  8338. });
  8339. }
  8340. function mappingByName(result, newCmptOptions) {
  8341. // Mapping by name if specified.
  8342. each(newCmptOptions, function (cmptOption, index) {
  8343. if (!cmptOption || cmptOption.name == null) {
  8344. return;
  8345. }
  8346. for (var i = 0; i < result.length; i++) {
  8347. var existing = result[i].existing;
  8348. if (!result[i].newOption // Consider name: two map to one.
  8349. // Can not match when both ids existing but different.
  8350. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8351. result[i].newOption = cmptOption;
  8352. newCmptOptions[index] = null;
  8353. return;
  8354. }
  8355. }
  8356. });
  8357. }
  8358. function mappingByIndex(result, newCmptOptions, brandNew) {
  8359. each(newCmptOptions, function (cmptOption) {
  8360. if (!cmptOption) {
  8361. return;
  8362. }
  8363. // Find the first place that not mapped by id and not internal component (consider the "hole").
  8364. var resultItem;
  8365. var nextIdx = 0;
  8366. while (
  8367. // Be `!resultItem` only when `nextIdx >= result.length`.
  8368. (resultItem = result[nextIdx]
  8369. // (1) Existing models that already have id should be able to mapped to. Because
  8370. // after mapping performed, model will always be assigned with an id if user not given.
  8371. // After that all models have id.
  8372. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8373. // not be merged to the existings with different id. Because id should not be overwritten.
  8374. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8375. ) && (resultItem.newOption || isComponentIdInternal(resultItem.existing) ||
  8376. // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8377. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8378. nextIdx++;
  8379. }
  8380. if (resultItem) {
  8381. resultItem.newOption = cmptOption;
  8382. resultItem.brandNew = brandNew;
  8383. } else {
  8384. result.push({
  8385. newOption: cmptOption,
  8386. brandNew: brandNew,
  8387. existing: null,
  8388. keyInfo: null
  8389. });
  8390. }
  8391. nextIdx++;
  8392. });
  8393. }
  8394. function mappingInReplaceAllMode(result, newCmptOptions) {
  8395. each(newCmptOptions, function (cmptOption) {
  8396. // The feature "reproduce" requires "hole" will also reproduced
  8397. // in case that component index referring are broken.
  8398. result.push({
  8399. newOption: cmptOption,
  8400. brandNew: true,
  8401. existing: null,
  8402. keyInfo: null
  8403. });
  8404. });
  8405. }
  8406. /**
  8407. * Make id and name for mapping result (result of mappingToExists)
  8408. * into `keyInfo` field.
  8409. */
  8410. function makeIdAndName(mapResult) {
  8411. // We use this id to hash component models and view instances
  8412. // in echarts. id can be specified by user, or auto generated.
  8413. // The id generation rule ensures new view instance are able
  8414. // to mapped to old instance when setOption are called in
  8415. // no-merge mode. So we generate model id by name and plus
  8416. // type in view id.
  8417. // name can be duplicated among components, which is convenient
  8418. // to specify multi components (like series) by one name.
  8419. // Ensure that each id is distinct.
  8420. var idMap = createHashMap();
  8421. each(mapResult, function (item) {
  8422. var existing = item.existing;
  8423. existing && idMap.set(existing.id, item);
  8424. });
  8425. each(mapResult, function (item) {
  8426. var opt = item.newOption;
  8427. // Force ensure id not duplicated.
  8428. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8429. opt && opt.id != null && idMap.set(opt.id, item);
  8430. !item.keyInfo && (item.keyInfo = {});
  8431. });
  8432. // Make name and id.
  8433. each(mapResult, function (item, index) {
  8434. var existing = item.existing;
  8435. var opt = item.newOption;
  8436. var keyInfo = item.keyInfo;
  8437. if (!isObject(opt)) {
  8438. return;
  8439. }
  8440. // Name can be overwritten. Consider case: axis.name = '20km'.
  8441. // But id generated by name will not be changed, which affect
  8442. // only in that case: setOption with 'not merge mode' and view
  8443. // instance will be recreated, which can be accepted.
  8444. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name
  8445. // Avoid that different series has the same name,
  8446. // because name may be used like in color pallet.
  8447. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8448. if (existing) {
  8449. keyInfo.id = makeComparableKey(existing.id);
  8450. } else if (opt.id != null) {
  8451. keyInfo.id = makeComparableKey(opt.id);
  8452. } else {
  8453. // Consider this situatoin:
  8454. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8455. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8456. // Series with the same name between optionA and optionB
  8457. // should be mapped.
  8458. var idNum = 0;
  8459. do {
  8460. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8461. } while (idMap.get(keyInfo.id));
  8462. }
  8463. idMap.set(keyInfo.id, item);
  8464. });
  8465. }
  8466. function keyExistAndEqual(attr, obj1, obj2) {
  8467. var key1 = convertOptionIdName(obj1[attr], null);
  8468. var key2 = convertOptionIdName(obj2[attr], null);
  8469. // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8470. return key1 != null && key2 != null && key1 === key2;
  8471. }
  8472. /**
  8473. * @return return null if not exist.
  8474. */
  8475. function makeComparableKey(val) {
  8476. if ("development" !== 'production') {
  8477. if (val == null) {
  8478. throw new Error();
  8479. }
  8480. }
  8481. return convertOptionIdName(val, '');
  8482. }
  8483. function convertOptionIdName(idOrName, defaultValue) {
  8484. if (idOrName == null) {
  8485. return defaultValue;
  8486. }
  8487. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8488. }
  8489. function warnInvalidateIdOrName(idOrName) {
  8490. if ("development" !== 'production') {
  8491. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8492. }
  8493. }
  8494. function isValidIdOrName(idOrName) {
  8495. return isStringSafe(idOrName) || isNumeric(idOrName);
  8496. }
  8497. function isNameSpecified(componentModel) {
  8498. var name = componentModel.name;
  8499. // Is specified when `indexOf` get -1 or > 0.
  8500. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8501. }
  8502. /**
  8503. * @public
  8504. * @param {Object} cmptOption
  8505. * @return {boolean}
  8506. */
  8507. function isComponentIdInternal(cmptOption) {
  8508. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8509. }
  8510. function makeInternalComponentId(idSuffix) {
  8511. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8512. }
  8513. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8514. // Set mainType and complete subType.
  8515. each(mappingResult, function (item) {
  8516. var newOption = item.newOption;
  8517. if (isObject(newOption)) {
  8518. item.keyInfo.mainType = mainType;
  8519. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8520. }
  8521. });
  8522. }
  8523. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8524. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType
  8525. // Use determineSubType only when there is no existComponent.
  8526. : componentModelCtor.determineSubType(mainType, newCmptOption);
  8527. // tooltip, markline, markpoint may always has no subType
  8528. return subType;
  8529. }
  8530. /**
  8531. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8532. * each of which can be Array or primary type.
  8533. * @return dataIndex If not found, return undefined/null.
  8534. */
  8535. function queryDataIndex(data, payload) {
  8536. if (payload.dataIndexInside != null) {
  8537. return payload.dataIndexInside;
  8538. } else if (payload.dataIndex != null) {
  8539. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8540. return data.indexOfRawIndex(value);
  8541. }) : data.indexOfRawIndex(payload.dataIndex);
  8542. } else if (payload.name != null) {
  8543. return isArray(payload.name) ? map(payload.name, function (value) {
  8544. return data.indexOfName(value);
  8545. }) : data.indexOfName(payload.name);
  8546. }
  8547. }
  8548. /**
  8549. * Enable property storage to any host object.
  8550. * Notice: Serialization is not supported.
  8551. *
  8552. * For example:
  8553. * let inner = zrUitl.makeInner();
  8554. *
  8555. * function some1(hostObj) {
  8556. * inner(hostObj).someProperty = 1212;
  8557. * ...
  8558. * }
  8559. * function some2() {
  8560. * let fields = inner(this);
  8561. * fields.someProperty1 = 1212;
  8562. * fields.someProperty2 = 'xx';
  8563. * ...
  8564. * }
  8565. *
  8566. * @return {Function}
  8567. */
  8568. function makeInner() {
  8569. var key = '__ec_inner_' + innerUniqueIndex++;
  8570. return function (hostObj) {
  8571. return hostObj[key] || (hostObj[key] = {});
  8572. };
  8573. }
  8574. var innerUniqueIndex = getRandomIdBase();
  8575. /**
  8576. * The same behavior as `component.getReferringComponents`.
  8577. */
  8578. function parseFinder(ecModel, finderInput, opt) {
  8579. var _a = preParseFinder(finderInput, opt),
  8580. mainTypeSpecified = _a.mainTypeSpecified,
  8581. queryOptionMap = _a.queryOptionMap,
  8582. others = _a.others;
  8583. var result = others;
  8584. var defaultMainType = opt ? opt.defaultMainType : null;
  8585. if (!mainTypeSpecified && defaultMainType) {
  8586. queryOptionMap.set(defaultMainType, {});
  8587. }
  8588. queryOptionMap.each(function (queryOption, mainType) {
  8589. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8590. useDefault: defaultMainType === mainType,
  8591. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8592. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8593. });
  8594. result[mainType + 'Models'] = queryResult.models;
  8595. result[mainType + 'Model'] = queryResult.models[0];
  8596. });
  8597. return result;
  8598. }
  8599. function preParseFinder(finderInput, opt) {
  8600. var finder;
  8601. if (isString(finderInput)) {
  8602. var obj = {};
  8603. obj[finderInput + 'Index'] = 0;
  8604. finder = obj;
  8605. } else {
  8606. finder = finderInput;
  8607. }
  8608. var queryOptionMap = createHashMap();
  8609. var others = {};
  8610. var mainTypeSpecified = false;
  8611. each(finder, function (value, key) {
  8612. // Exclude 'dataIndex' and other illegal keys.
  8613. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8614. others[key] = value;
  8615. return;
  8616. }
  8617. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8618. var mainType = parsedKey[1];
  8619. var queryType = (parsedKey[2] || '').toLowerCase();
  8620. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8621. return;
  8622. }
  8623. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8624. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8625. queryOption[queryType] = value;
  8626. });
  8627. return {
  8628. mainTypeSpecified: mainTypeSpecified,
  8629. queryOptionMap: queryOptionMap,
  8630. others: others
  8631. };
  8632. }
  8633. var SINGLE_REFERRING = {
  8634. useDefault: true,
  8635. enableAll: false,
  8636. enableNone: false
  8637. };
  8638. var MULTIPLE_REFERRING = {
  8639. useDefault: false,
  8640. enableAll: true,
  8641. enableNone: true
  8642. };
  8643. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8644. opt = opt || SINGLE_REFERRING;
  8645. var indexOption = userOption.index;
  8646. var idOption = userOption.id;
  8647. var nameOption = userOption.name;
  8648. var result = {
  8649. models: null,
  8650. specified: indexOption != null || idOption != null || nameOption != null
  8651. };
  8652. if (!result.specified) {
  8653. // Use the first as default if `useDefault`.
  8654. var firstCmpt = void 0;
  8655. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8656. return result;
  8657. }
  8658. if (indexOption === 'none' || indexOption === false) {
  8659. if (opt.enableNone) {
  8660. result.models = [];
  8661. return result;
  8662. } else {
  8663. // Do not throw; consider if some component previously does not use this method,
  8664. // and start to use it, need to be fault-tolerant for backward compatibility.
  8665. if ("development" !== 'production') {
  8666. error('`"none"` or `false` is not a valid value on index option.');
  8667. }
  8668. indexOption = -1; // Can not query by index but may still query by id/name if specified.
  8669. }
  8670. }
  8671. // `queryComponents` will return all components if
  8672. // both all of index/id/name are null/undefined.
  8673. if (indexOption === 'all') {
  8674. if (opt.enableAll) {
  8675. indexOption = idOption = nameOption = null;
  8676. } else {
  8677. if ("development" !== 'production') {
  8678. error('`"all"` is not a valid value on index option.');
  8679. }
  8680. indexOption = -1;
  8681. }
  8682. }
  8683. result.models = ecModel.queryComponents({
  8684. mainType: mainType,
  8685. index: indexOption,
  8686. id: idOption,
  8687. name: nameOption
  8688. });
  8689. return result;
  8690. }
  8691. function setAttribute(dom, key, value) {
  8692. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8693. }
  8694. function getAttribute(dom, key) {
  8695. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8696. }
  8697. function getTooltipRenderMode(renderModeOption) {
  8698. if (renderModeOption === 'auto') {
  8699. // Using html when `document` exists, use richText otherwise
  8700. return env.domSupported ? 'html' : 'richText';
  8701. } else {
  8702. return renderModeOption || 'html';
  8703. }
  8704. }
  8705. /**
  8706. * Interpolate raw values of a series with percent
  8707. *
  8708. * @param data data
  8709. * @param labelModel label model of the text element
  8710. * @param sourceValue start value. May be null/undefined when init.
  8711. * @param targetValue end value
  8712. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8713. * @return interpolated values
  8714. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8715. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8716. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8717. * Other cases do not supported.
  8718. */
  8719. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8720. var isAutoPrecision = precision == null || precision === 'auto';
  8721. if (targetValue == null) {
  8722. return targetValue;
  8723. }
  8724. if (isNumber(targetValue)) {
  8725. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8726. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8727. } else if (isString(targetValue)) {
  8728. return percent < 1 ? sourceValue : targetValue;
  8729. } else {
  8730. var interpolated = [];
  8731. var leftArr = sourceValue;
  8732. var rightArr = targetValue;
  8733. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8734. for (var i = 0; i < length_1; ++i) {
  8735. var info = data.getDimensionInfo(i);
  8736. // Don't interpolate ordinal dims
  8737. if (info && info.type === 'ordinal') {
  8738. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8739. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8740. } else {
  8741. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8742. var rightVal = rightArr[i];
  8743. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8744. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8745. }
  8746. }
  8747. return interpolated;
  8748. }
  8749. }
  8750. var TYPE_DELIMITER = '.';
  8751. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8752. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8753. /**
  8754. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8755. * @public
  8756. */
  8757. function parseClassType(componentType) {
  8758. var ret = {
  8759. main: '',
  8760. sub: ''
  8761. };
  8762. if (componentType) {
  8763. var typeArr = componentType.split(TYPE_DELIMITER);
  8764. ret.main = typeArr[0] || '';
  8765. ret.sub = typeArr[1] || '';
  8766. }
  8767. return ret;
  8768. }
  8769. /**
  8770. * @public
  8771. */
  8772. function checkClassType(componentType) {
  8773. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8774. }
  8775. function isExtendedClass(clz) {
  8776. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8777. }
  8778. /**
  8779. * Implements `ExtendableConstructor` for `rootClz`.
  8780. *
  8781. * @usage
  8782. * ```ts
  8783. * class Xxx {}
  8784. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8785. * enableClassExtend(Xxx as XxxConstructor);
  8786. * ```
  8787. */
  8788. function enableClassExtend(rootClz, mandatoryMethods) {
  8789. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8790. rootClz.extend = function (proto) {
  8791. if ("development" !== 'production') {
  8792. each(mandatoryMethods, function (method) {
  8793. if (!proto[method]) {
  8794. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8795. }
  8796. });
  8797. }
  8798. var superClass = this;
  8799. var ExtendedClass;
  8800. if (isESClass(superClass)) {
  8801. ExtendedClass = /** @class */function (_super) {
  8802. __extends(class_1, _super);
  8803. function class_1() {
  8804. return _super.apply(this, arguments) || this;
  8805. }
  8806. return class_1;
  8807. }(superClass);
  8808. } else {
  8809. // For backward compat, we both support ts class inheritance and this
  8810. // "extend" approach.
  8811. // The constructor should keep the same behavior as ts class inheritance:
  8812. // If this constructor/$constructor is not declared, auto invoke the super
  8813. // constructor.
  8814. // If this constructor/$constructor is declared, it is responsible for
  8815. // calling the super constructor.
  8816. ExtendedClass = function () {
  8817. (proto.$constructor || superClass).apply(this, arguments);
  8818. };
  8819. inherits(ExtendedClass, this);
  8820. }
  8821. extend(ExtendedClass.prototype, proto);
  8822. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8823. ExtendedClass.extend = this.extend;
  8824. ExtendedClass.superCall = superCall;
  8825. ExtendedClass.superApply = superApply;
  8826. ExtendedClass.superClass = superClass;
  8827. return ExtendedClass;
  8828. };
  8829. }
  8830. function isESClass(fn) {
  8831. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8832. }
  8833. /**
  8834. * A work around to both support ts extend and this extend mechanism.
  8835. * on sub-class.
  8836. * @usage
  8837. * ```ts
  8838. * class Component { ... }
  8839. * classUtil.enableClassExtend(Component);
  8840. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8841. *
  8842. * class Series extends Component { ... }
  8843. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8844. * Component.markExtend(Series);
  8845. * ```
  8846. */
  8847. function mountExtend(SubClz, SupperClz) {
  8848. SubClz.extend = SupperClz.extend;
  8849. }
  8850. // A random offset.
  8851. var classBase = Math.round(Math.random() * 10);
  8852. /**
  8853. * Implements `CheckableConstructor` for `target`.
  8854. * Can not use instanceof, consider different scope by
  8855. * cross domain or es module import in ec extensions.
  8856. * Mount a method "isInstance()" to Clz.
  8857. *
  8858. * @usage
  8859. * ```ts
  8860. * class Xxx {}
  8861. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8862. * enableClassCheck(Xxx as XxxConstructor)
  8863. * ```
  8864. */
  8865. function enableClassCheck(target) {
  8866. var classAttr = ['__\0is_clz', classBase++].join('_');
  8867. target.prototype[classAttr] = true;
  8868. if ("development" !== 'production') {
  8869. assert(!target.isInstance, 'The method "is" can not be defined.');
  8870. }
  8871. target.isInstance = function (obj) {
  8872. return !!(obj && obj[classAttr]);
  8873. };
  8874. }
  8875. // superCall should have class info, which can not be fetched from 'this'.
  8876. // Consider this case:
  8877. // class A has method f,
  8878. // class B inherits class A, overrides method f, f call superApply('f'),
  8879. // class C inherits class B, does not override method f,
  8880. // then when method of class C is called, dead loop occurred.
  8881. function superCall(context, methodName) {
  8882. var args = [];
  8883. for (var _i = 2; _i < arguments.length; _i++) {
  8884. args[_i - 2] = arguments[_i];
  8885. }
  8886. return this.superClass.prototype[methodName].apply(context, args);
  8887. }
  8888. function superApply(context, methodName, args) {
  8889. return this.superClass.prototype[methodName].apply(context, args);
  8890. }
  8891. /**
  8892. * Implements `ClassManager` for `target`
  8893. *
  8894. * @usage
  8895. * ```ts
  8896. * class Xxx {}
  8897. * type XxxConstructor = typeof Xxx & ClassManager
  8898. * enableClassManagement(Xxx as XxxConstructor);
  8899. * ```
  8900. */
  8901. function enableClassManagement(target) {
  8902. /**
  8903. * Component model classes
  8904. * key: componentType,
  8905. * value:
  8906. * componentClass, when componentType is 'a'
  8907. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8908. */
  8909. var storage = {};
  8910. target.registerClass = function (clz) {
  8911. // `type` should not be a "instance member".
  8912. // If using TS class, should better declared as `static type = 'series.pie'`.
  8913. // otherwise users have to mount `type` on prototype manually.
  8914. // For backward compat and enable instance visit type via `this.type`,
  8915. // we still support fetch `type` from prototype.
  8916. var componentFullType = clz.type || clz.prototype.type;
  8917. if (componentFullType) {
  8918. checkClassType(componentFullType);
  8919. // If only static type declared, we assign it to prototype mandatorily.
  8920. clz.prototype.type = componentFullType;
  8921. var componentTypeInfo = parseClassType(componentFullType);
  8922. if (!componentTypeInfo.sub) {
  8923. if ("development" !== 'production') {
  8924. if (storage[componentTypeInfo.main]) {
  8925. console.warn(componentTypeInfo.main + ' exists.');
  8926. }
  8927. }
  8928. storage[componentTypeInfo.main] = clz;
  8929. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8930. var container = makeContainer(componentTypeInfo);
  8931. container[componentTypeInfo.sub] = clz;
  8932. }
  8933. }
  8934. return clz;
  8935. };
  8936. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8937. var clz = storage[mainType];
  8938. if (clz && clz[IS_CONTAINER]) {
  8939. clz = subType ? clz[subType] : null;
  8940. }
  8941. if (throwWhenNotFound && !clz) {
  8942. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8943. }
  8944. return clz;
  8945. };
  8946. target.getClassesByMainType = function (componentType) {
  8947. var componentTypeInfo = parseClassType(componentType);
  8948. var result = [];
  8949. var obj = storage[componentTypeInfo.main];
  8950. if (obj && obj[IS_CONTAINER]) {
  8951. each(obj, function (o, type) {
  8952. type !== IS_CONTAINER && result.push(o);
  8953. });
  8954. } else {
  8955. result.push(obj);
  8956. }
  8957. return result;
  8958. };
  8959. target.hasClass = function (componentType) {
  8960. // Just consider componentType.main.
  8961. var componentTypeInfo = parseClassType(componentType);
  8962. return !!storage[componentTypeInfo.main];
  8963. };
  8964. /**
  8965. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8966. */
  8967. target.getAllClassMainTypes = function () {
  8968. var types = [];
  8969. each(storage, function (obj, type) {
  8970. types.push(type);
  8971. });
  8972. return types;
  8973. };
  8974. /**
  8975. * If a main type is container and has sub types
  8976. */
  8977. target.hasSubTypes = function (componentType) {
  8978. var componentTypeInfo = parseClassType(componentType);
  8979. var obj = storage[componentTypeInfo.main];
  8980. return obj && obj[IS_CONTAINER];
  8981. };
  8982. function makeContainer(componentTypeInfo) {
  8983. var container = storage[componentTypeInfo.main];
  8984. if (!container || !container[IS_CONTAINER]) {
  8985. container = storage[componentTypeInfo.main] = {};
  8986. container[IS_CONTAINER] = true;
  8987. }
  8988. return container;
  8989. }
  8990. }
  8991. // /**
  8992. // * @param {string|Array.<string>} properties
  8993. // */
  8994. // export function setReadOnly(obj, properties) {
  8995. // FIXME It seems broken in IE8 simulation of IE11
  8996. // if (!zrUtil.isArray(properties)) {
  8997. // properties = properties != null ? [properties] : [];
  8998. // }
  8999. // zrUtil.each(properties, function (prop) {
  9000. // let value = obj[prop];
  9001. // Object.defineProperty
  9002. // && Object.defineProperty(obj, prop, {
  9003. // value: value, writable: false
  9004. // });
  9005. // zrUtil.isArray(obj[prop])
  9006. // && Object.freeze
  9007. // && Object.freeze(obj[prop]);
  9008. // });
  9009. // }
  9010. function makeStyleMapper(properties, ignoreParent) {
  9011. // Normalize
  9012. for (var i = 0; i < properties.length; i++) {
  9013. if (!properties[i][1]) {
  9014. properties[i][1] = properties[i][0];
  9015. }
  9016. }
  9017. ignoreParent = ignoreParent || false;
  9018. return function (model, excludes, includes) {
  9019. var style = {};
  9020. for (var i = 0; i < properties.length; i++) {
  9021. var propName = properties[i][1];
  9022. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  9023. continue;
  9024. }
  9025. var val = model.getShallow(propName, ignoreParent);
  9026. if (val != null) {
  9027. style[properties[i][0]] = val;
  9028. }
  9029. }
  9030. // TODO Text or image?
  9031. return style;
  9032. };
  9033. }
  9034. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor']
  9035. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  9036. // So do not transfer decal directly.
  9037. ];
  9038. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  9039. var AreaStyleMixin = /** @class */function () {
  9040. function AreaStyleMixin() {}
  9041. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  9042. return getAreaStyle(this, excludes, includes);
  9043. };
  9044. return AreaStyleMixin;
  9045. }();
  9046. var globalImageCache = new LRU(50);
  9047. function findExistImage(newImageOrSrc) {
  9048. if (typeof newImageOrSrc === 'string') {
  9049. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  9050. return cachedImgObj && cachedImgObj.image;
  9051. }
  9052. else {
  9053. return newImageOrSrc;
  9054. }
  9055. }
  9056. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  9057. if (!newImageOrSrc) {
  9058. return image;
  9059. }
  9060. else if (typeof newImageOrSrc === 'string') {
  9061. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  9062. return image;
  9063. }
  9064. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  9065. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  9066. if (cachedImgObj) {
  9067. image = cachedImgObj.image;
  9068. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  9069. }
  9070. else {
  9071. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  9072. image.__zrImageSrc = newImageOrSrc;
  9073. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  9074. image: image,
  9075. pending: [pendingWrap]
  9076. });
  9077. }
  9078. return image;
  9079. }
  9080. else {
  9081. return newImageOrSrc;
  9082. }
  9083. }
  9084. function imageOnLoad() {
  9085. var cachedImgObj = this.__cachedImgObj;
  9086. this.onload = this.onerror = this.__cachedImgObj = null;
  9087. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  9088. var pendingWrap = cachedImgObj.pending[i];
  9089. var cb = pendingWrap.cb;
  9090. cb && cb(this, pendingWrap.cbPayload);
  9091. pendingWrap.hostEl.dirty();
  9092. }
  9093. cachedImgObj.pending.length = 0;
  9094. }
  9095. function isImageReady(image) {
  9096. return image && image.width && image.height;
  9097. }
  9098. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  9099. function truncateText(text, containerWidth, font, ellipsis, options) {
  9100. var out = {};
  9101. truncateText2(out, text, containerWidth, font, ellipsis, options);
  9102. return out.text;
  9103. }
  9104. function truncateText2(out, text, containerWidth, font, ellipsis, options) {
  9105. if (!containerWidth) {
  9106. out.text = '';
  9107. out.isTruncated = false;
  9108. return;
  9109. }
  9110. var textLines = (text + '').split('\n');
  9111. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  9112. var isTruncated = false;
  9113. var truncateOut = {};
  9114. for (var i = 0, len = textLines.length; i < len; i++) {
  9115. truncateSingleLine(truncateOut, textLines[i], options);
  9116. textLines[i] = truncateOut.textLine;
  9117. isTruncated = isTruncated || truncateOut.isTruncated;
  9118. }
  9119. out.text = textLines.join('\n');
  9120. out.isTruncated = isTruncated;
  9121. }
  9122. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  9123. options = options || {};
  9124. var preparedOpts = extend({}, options);
  9125. ellipsis = retrieve2(ellipsis, '...');
  9126. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  9127. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  9128. var fontMeasureInfo = preparedOpts.fontMeasureInfo = ensureFontMeasureInfo(font);
  9129. var ascCharWidth = fontMeasureInfo.asciiCharWidth;
  9130. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  9131. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  9132. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  9133. contentWidth -= ascCharWidth;
  9134. }
  9135. var ellipsisWidth = measureWidth(fontMeasureInfo, ellipsis);
  9136. if (ellipsisWidth > contentWidth) {
  9137. ellipsis = '';
  9138. ellipsisWidth = 0;
  9139. }
  9140. contentWidth = containerWidth - ellipsisWidth;
  9141. preparedOpts.ellipsis = ellipsis;
  9142. preparedOpts.ellipsisWidth = ellipsisWidth;
  9143. preparedOpts.contentWidth = contentWidth;
  9144. preparedOpts.containerWidth = containerWidth;
  9145. return preparedOpts;
  9146. }
  9147. function truncateSingleLine(out, textLine, options) {
  9148. var containerWidth = options.containerWidth;
  9149. var contentWidth = options.contentWidth;
  9150. var fontMeasureInfo = options.fontMeasureInfo;
  9151. if (!containerWidth) {
  9152. out.textLine = '';
  9153. out.isTruncated = false;
  9154. return;
  9155. }
  9156. var lineWidth = measureWidth(fontMeasureInfo, textLine);
  9157. if (lineWidth <= containerWidth) {
  9158. out.textLine = textLine;
  9159. out.isTruncated = false;
  9160. return;
  9161. }
  9162. for (var j = 0;; j++) {
  9163. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  9164. textLine += options.ellipsis;
  9165. break;
  9166. }
  9167. var subLength = j === 0
  9168. ? estimateLength(textLine, contentWidth, fontMeasureInfo)
  9169. : lineWidth > 0
  9170. ? Math.floor(textLine.length * contentWidth / lineWidth)
  9171. : 0;
  9172. textLine = textLine.substr(0, subLength);
  9173. lineWidth = measureWidth(fontMeasureInfo, textLine);
  9174. }
  9175. if (textLine === '') {
  9176. textLine = options.placeholder;
  9177. }
  9178. out.textLine = textLine;
  9179. out.isTruncated = true;
  9180. }
  9181. function estimateLength(text, contentWidth, fontMeasureInfo) {
  9182. var width = 0;
  9183. var i = 0;
  9184. for (var len = text.length; i < len && width < contentWidth; i++) {
  9185. width += measureCharWidth(fontMeasureInfo, text.charCodeAt(i));
  9186. }
  9187. return i;
  9188. }
  9189. function parsePlainText(rawText, style, defaultOuterWidth, defaultOuterHeight) {
  9190. var text = formatText(rawText);
  9191. var overflow = style.overflow;
  9192. var padding = style.padding;
  9193. var paddingH = padding ? padding[1] + padding[3] : 0;
  9194. var paddingV = padding ? padding[0] + padding[2] : 0;
  9195. var font = style.font;
  9196. var truncate = overflow === 'truncate';
  9197. var calculatedLineHeight = getLineHeight(font);
  9198. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  9199. var truncateLineOverflow = style.lineOverflow === 'truncate';
  9200. var isTruncated = false;
  9201. var width = style.width;
  9202. if (width == null && defaultOuterWidth != null) {
  9203. width = defaultOuterWidth - paddingH;
  9204. }
  9205. var height = style.height;
  9206. if (height == null && defaultOuterHeight != null) {
  9207. height = defaultOuterHeight - paddingV;
  9208. }
  9209. var lines;
  9210. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  9211. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  9212. }
  9213. else {
  9214. lines = text ? text.split('\n') : [];
  9215. }
  9216. var contentHeight = lines.length * lineHeight;
  9217. if (height == null) {
  9218. height = contentHeight;
  9219. }
  9220. if (contentHeight > height && truncateLineOverflow) {
  9221. var lineCount = Math.floor(height / lineHeight);
  9222. isTruncated = isTruncated || (lines.length > lineCount);
  9223. lines = lines.slice(0, lineCount);
  9224. contentHeight = lines.length * lineHeight;
  9225. }
  9226. if (text && truncate && width != null) {
  9227. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  9228. minChar: style.truncateMinChar,
  9229. placeholder: style.placeholder
  9230. });
  9231. var singleOut = {};
  9232. for (var i = 0; i < lines.length; i++) {
  9233. truncateSingleLine(singleOut, lines[i], options);
  9234. lines[i] = singleOut.textLine;
  9235. isTruncated = isTruncated || singleOut.isTruncated;
  9236. }
  9237. }
  9238. var outerHeight = height;
  9239. var contentWidth = 0;
  9240. var fontMeasureInfo = ensureFontMeasureInfo(font);
  9241. for (var i = 0; i < lines.length; i++) {
  9242. contentWidth = Math.max(measureWidth(fontMeasureInfo, lines[i]), contentWidth);
  9243. }
  9244. if (width == null) {
  9245. width = contentWidth;
  9246. }
  9247. var outerWidth = width;
  9248. outerHeight += paddingV;
  9249. outerWidth += paddingH;
  9250. return {
  9251. lines: lines,
  9252. height: height,
  9253. outerWidth: outerWidth,
  9254. outerHeight: outerHeight,
  9255. lineHeight: lineHeight,
  9256. calculatedLineHeight: calculatedLineHeight,
  9257. contentWidth: contentWidth,
  9258. contentHeight: contentHeight,
  9259. width: width,
  9260. isTruncated: isTruncated
  9261. };
  9262. }
  9263. var RichTextToken = (function () {
  9264. function RichTextToken() {
  9265. }
  9266. return RichTextToken;
  9267. }());
  9268. var RichTextLine = (function () {
  9269. function RichTextLine(tokens) {
  9270. this.tokens = [];
  9271. if (tokens) {
  9272. this.tokens = tokens;
  9273. }
  9274. }
  9275. return RichTextLine;
  9276. }());
  9277. var RichTextContentBlock = (function () {
  9278. function RichTextContentBlock() {
  9279. this.width = 0;
  9280. this.height = 0;
  9281. this.contentWidth = 0;
  9282. this.contentHeight = 0;
  9283. this.outerWidth = 0;
  9284. this.outerHeight = 0;
  9285. this.lines = [];
  9286. this.isTruncated = false;
  9287. }
  9288. return RichTextContentBlock;
  9289. }());
  9290. function parseRichText(rawText, style, defaultOuterWidth, defaultOuterHeight, topTextAlign) {
  9291. var contentBlock = new RichTextContentBlock();
  9292. var text = formatText(rawText);
  9293. if (!text) {
  9294. return contentBlock;
  9295. }
  9296. var stlPadding = style.padding;
  9297. var stlPaddingH = stlPadding ? stlPadding[1] + stlPadding[3] : 0;
  9298. var stlPaddingV = stlPadding ? stlPadding[0] + stlPadding[2] : 0;
  9299. var topWidth = style.width;
  9300. if (topWidth == null && defaultOuterWidth != null) {
  9301. topWidth = defaultOuterWidth - stlPaddingH;
  9302. }
  9303. var topHeight = style.height;
  9304. if (topHeight == null && defaultOuterHeight != null) {
  9305. topHeight = defaultOuterHeight - stlPaddingV;
  9306. }
  9307. var overflow = style.overflow;
  9308. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  9309. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  9310. : null;
  9311. var lastIndex = STYLE_REG.lastIndex = 0;
  9312. var result;
  9313. while ((result = STYLE_REG.exec(text)) != null) {
  9314. var matchedIndex = result.index;
  9315. if (matchedIndex > lastIndex) {
  9316. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  9317. }
  9318. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  9319. lastIndex = STYLE_REG.lastIndex;
  9320. }
  9321. if (lastIndex < text.length) {
  9322. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  9323. }
  9324. var pendingList = [];
  9325. var calculatedHeight = 0;
  9326. var calculatedWidth = 0;
  9327. var truncate = overflow === 'truncate';
  9328. var truncateLine = style.lineOverflow === 'truncate';
  9329. var tmpTruncateOut = {};
  9330. function finishLine(line, lineWidth, lineHeight) {
  9331. line.width = lineWidth;
  9332. line.lineHeight = lineHeight;
  9333. calculatedHeight += lineHeight;
  9334. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  9335. }
  9336. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  9337. var line = contentBlock.lines[i];
  9338. var lineHeight = 0;
  9339. var lineWidth = 0;
  9340. for (var j = 0; j < line.tokens.length; j++) {
  9341. var token = line.tokens[j];
  9342. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  9343. var textPadding = token.textPadding = tokenStyle.padding;
  9344. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  9345. var font = token.font = tokenStyle.font || style.font;
  9346. token.contentHeight = getLineHeight(font);
  9347. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  9348. token.innerHeight = tokenHeight;
  9349. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  9350. token.height = tokenHeight;
  9351. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  9352. token.align = tokenStyle && tokenStyle.align || topTextAlign;
  9353. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  9354. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  9355. var originalLength = contentBlock.lines.length;
  9356. if (j > 0) {
  9357. line.tokens = line.tokens.slice(0, j);
  9358. finishLine(line, lineWidth, lineHeight);
  9359. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  9360. }
  9361. else {
  9362. contentBlock.lines = contentBlock.lines.slice(0, i);
  9363. }
  9364. contentBlock.isTruncated = contentBlock.isTruncated || (contentBlock.lines.length < originalLength);
  9365. break outer;
  9366. }
  9367. var styleTokenWidth = tokenStyle.width;
  9368. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  9369. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  9370. token.percentWidth = styleTokenWidth;
  9371. pendingList.push(token);
  9372. token.contentWidth = measureWidth(ensureFontMeasureInfo(font), token.text);
  9373. }
  9374. else {
  9375. if (tokenWidthNotSpecified) {
  9376. var textBackgroundColor = tokenStyle.backgroundColor;
  9377. var bgImg = textBackgroundColor && textBackgroundColor.image;
  9378. if (bgImg) {
  9379. bgImg = findExistImage(bgImg);
  9380. if (isImageReady(bgImg)) {
  9381. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  9382. }
  9383. }
  9384. }
  9385. var remainTruncWidth = truncate && topWidth != null
  9386. ? topWidth - lineWidth : null;
  9387. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  9388. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  9389. token.text = '';
  9390. token.width = token.contentWidth = 0;
  9391. }
  9392. else {
  9393. truncateText2(tmpTruncateOut, token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  9394. token.text = tmpTruncateOut.text;
  9395. contentBlock.isTruncated = contentBlock.isTruncated || tmpTruncateOut.isTruncated;
  9396. token.width = token.contentWidth = measureWidth(ensureFontMeasureInfo(font), token.text);
  9397. }
  9398. }
  9399. else {
  9400. token.contentWidth = measureWidth(ensureFontMeasureInfo(font), token.text);
  9401. }
  9402. }
  9403. token.width += paddingH;
  9404. lineWidth += token.width;
  9405. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  9406. }
  9407. finishLine(line, lineWidth, lineHeight);
  9408. }
  9409. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  9410. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  9411. contentBlock.contentHeight = calculatedHeight;
  9412. contentBlock.contentWidth = calculatedWidth;
  9413. contentBlock.outerWidth += stlPaddingH;
  9414. contentBlock.outerHeight += stlPaddingV;
  9415. for (var i = 0; i < pendingList.length; i++) {
  9416. var token = pendingList[i];
  9417. var percentWidth = token.percentWidth;
  9418. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9419. }
  9420. return contentBlock;
  9421. }
  9422. function pushTokens(block, str, style, wrapInfo, styleName) {
  9423. var isEmptyStr = str === '';
  9424. var tokenStyle = styleName && style.rich[styleName] || {};
  9425. var lines = block.lines;
  9426. var font = tokenStyle.font || style.font;
  9427. var newLine = false;
  9428. var strLines;
  9429. var linesWidths;
  9430. if (wrapInfo) {
  9431. var tokenPadding = tokenStyle.padding;
  9432. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9433. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9434. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9435. if (lines.length > 0) {
  9436. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9437. strLines = str.split('\n');
  9438. newLine = true;
  9439. }
  9440. }
  9441. wrapInfo.accumWidth = outerWidth_1;
  9442. }
  9443. else {
  9444. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9445. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9446. linesWidths = res.linesWidths;
  9447. strLines = res.lines;
  9448. }
  9449. }
  9450. if (!strLines) {
  9451. strLines = str.split('\n');
  9452. }
  9453. var fontMeasureInfo = ensureFontMeasureInfo(font);
  9454. for (var i = 0; i < strLines.length; i++) {
  9455. var text = strLines[i];
  9456. var token = new RichTextToken();
  9457. token.styleName = styleName;
  9458. token.text = text;
  9459. token.isLineHolder = !text && !isEmptyStr;
  9460. if (typeof tokenStyle.width === 'number') {
  9461. token.width = tokenStyle.width;
  9462. }
  9463. else {
  9464. token.width = linesWidths
  9465. ? linesWidths[i]
  9466. : measureWidth(fontMeasureInfo, text);
  9467. }
  9468. if (!i && !newLine) {
  9469. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9470. var tokensLen = tokens.length;
  9471. (tokensLen === 1 && tokens[0].isLineHolder)
  9472. ? (tokens[0] = token)
  9473. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9474. }
  9475. else {
  9476. lines.push(new RichTextLine([token]));
  9477. }
  9478. }
  9479. }
  9480. function isAlphabeticLetter(ch) {
  9481. var code = ch.charCodeAt(0);
  9482. return code >= 0x20 && code <= 0x24F
  9483. || code >= 0x370 && code <= 0x10FF
  9484. || code >= 0x1200 && code <= 0x13FF
  9485. || code >= 0x1E00 && code <= 0x206F;
  9486. }
  9487. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9488. obj[ch] = true;
  9489. return obj;
  9490. }, {});
  9491. function isWordBreakChar(ch) {
  9492. if (isAlphabeticLetter(ch)) {
  9493. if (breakCharMap[ch]) {
  9494. return true;
  9495. }
  9496. return false;
  9497. }
  9498. return true;
  9499. }
  9500. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9501. var lines = [];
  9502. var linesWidths = [];
  9503. var line = '';
  9504. var currentWord = '';
  9505. var currentWordWidth = 0;
  9506. var accumWidth = 0;
  9507. var fontMeasureInfo = ensureFontMeasureInfo(font);
  9508. for (var i = 0; i < text.length; i++) {
  9509. var ch = text.charAt(i);
  9510. if (ch === '\n') {
  9511. if (currentWord) {
  9512. line += currentWord;
  9513. accumWidth += currentWordWidth;
  9514. }
  9515. lines.push(line);
  9516. linesWidths.push(accumWidth);
  9517. line = '';
  9518. currentWord = '';
  9519. currentWordWidth = 0;
  9520. accumWidth = 0;
  9521. continue;
  9522. }
  9523. var chWidth = measureCharWidth(fontMeasureInfo, ch.charCodeAt(0));
  9524. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9525. if (!lines.length
  9526. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9527. : accumWidth + chWidth > lineWidth) {
  9528. if (!accumWidth) {
  9529. if (inWord) {
  9530. lines.push(currentWord);
  9531. linesWidths.push(currentWordWidth);
  9532. currentWord = ch;
  9533. currentWordWidth = chWidth;
  9534. }
  9535. else {
  9536. lines.push(ch);
  9537. linesWidths.push(chWidth);
  9538. }
  9539. }
  9540. else if (line || currentWord) {
  9541. if (inWord) {
  9542. if (!line) {
  9543. line = currentWord;
  9544. currentWord = '';
  9545. currentWordWidth = 0;
  9546. accumWidth = currentWordWidth;
  9547. }
  9548. lines.push(line);
  9549. linesWidths.push(accumWidth - currentWordWidth);
  9550. currentWord += ch;
  9551. currentWordWidth += chWidth;
  9552. line = '';
  9553. accumWidth = currentWordWidth;
  9554. }
  9555. else {
  9556. if (currentWord) {
  9557. line += currentWord;
  9558. currentWord = '';
  9559. currentWordWidth = 0;
  9560. }
  9561. lines.push(line);
  9562. linesWidths.push(accumWidth);
  9563. line = ch;
  9564. accumWidth = chWidth;
  9565. }
  9566. }
  9567. continue;
  9568. }
  9569. accumWidth += chWidth;
  9570. if (inWord) {
  9571. currentWord += ch;
  9572. currentWordWidth += chWidth;
  9573. }
  9574. else {
  9575. if (currentWord) {
  9576. line += currentWord;
  9577. currentWord = '';
  9578. currentWordWidth = 0;
  9579. }
  9580. line += ch;
  9581. }
  9582. }
  9583. if (currentWord) {
  9584. line += currentWord;
  9585. }
  9586. if (line) {
  9587. lines.push(line);
  9588. linesWidths.push(accumWidth);
  9589. }
  9590. if (lines.length === 1) {
  9591. accumWidth += lastAccumWidth;
  9592. }
  9593. return {
  9594. accumWidth: accumWidth,
  9595. lines: lines,
  9596. linesWidths: linesWidths
  9597. };
  9598. }
  9599. function calcInnerTextOverflowArea(out, overflowRect, baseX, baseY, textAlign, textVerticalAlign) {
  9600. out.baseX = baseX;
  9601. out.baseY = baseY;
  9602. out.outerWidth = out.outerHeight = null;
  9603. if (!overflowRect) {
  9604. return;
  9605. }
  9606. var textWidth = overflowRect.width * 2;
  9607. var textHeight = overflowRect.height * 2;
  9608. BoundingRect.set(tmpCITCTextRect, adjustTextX(baseX, textWidth, textAlign), adjustTextY$1(baseY, textHeight, textVerticalAlign), textWidth, textHeight);
  9609. BoundingRect.intersect(overflowRect, tmpCITCTextRect, null, tmpCITCIntersectRectOpt);
  9610. var outIntersectRect = tmpCITCIntersectRectOpt.outIntersectRect;
  9611. out.outerWidth = outIntersectRect.width;
  9612. out.outerHeight = outIntersectRect.height;
  9613. out.baseX = adjustTextX(outIntersectRect.x, outIntersectRect.width, textAlign, true);
  9614. out.baseY = adjustTextY$1(outIntersectRect.y, outIntersectRect.height, textVerticalAlign, true);
  9615. }
  9616. var tmpCITCTextRect = new BoundingRect(0, 0, 0, 0);
  9617. var tmpCITCIntersectRectOpt = { outIntersectRect: {}, clamp: true };
  9618. function formatText(text) {
  9619. return text != null ? (text += '') : (text = '');
  9620. }
  9621. function tSpanCreateBoundingRect(style) {
  9622. var text = formatText(style.text);
  9623. var font = style.font;
  9624. var contentWidth = measureWidth(ensureFontMeasureInfo(font), text);
  9625. var contentHeight = getLineHeight(font);
  9626. return tSpanCreateBoundingRect2(style, contentWidth, contentHeight, null);
  9627. }
  9628. function tSpanCreateBoundingRect2(style, contentWidth, contentHeight, forceLineWidth) {
  9629. var rect = new BoundingRect(adjustTextX(style.x || 0, contentWidth, style.textAlign), adjustTextY$1(style.y || 0, contentHeight, style.textBaseline), contentWidth, contentHeight);
  9630. var lineWidth = forceLineWidth != null
  9631. ? forceLineWidth
  9632. : (tSpanHasStroke(style) ? style.lineWidth : 0);
  9633. if (lineWidth > 0) {
  9634. rect.x -= lineWidth / 2;
  9635. rect.y -= lineWidth / 2;
  9636. rect.width += lineWidth;
  9637. rect.height += lineWidth;
  9638. }
  9639. return rect;
  9640. }
  9641. function tSpanHasStroke(style) {
  9642. var stroke = style.stroke;
  9643. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  9644. }
  9645. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9646. var DEFAULT_COMMON_STYLE = {
  9647. shadowBlur: 0,
  9648. shadowOffsetX: 0,
  9649. shadowOffsetY: 0,
  9650. shadowColor: '#000',
  9651. opacity: 1,
  9652. blend: 'source-over'
  9653. };
  9654. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9655. style: {
  9656. shadowBlur: true,
  9657. shadowOffsetX: true,
  9658. shadowOffsetY: true,
  9659. shadowColor: true,
  9660. opacity: true
  9661. }
  9662. };
  9663. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9664. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9665. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9666. var Displayable = (function (_super) {
  9667. __extends(Displayable, _super);
  9668. function Displayable(props) {
  9669. return _super.call(this, props) || this;
  9670. }
  9671. Displayable.prototype._init = function (props) {
  9672. var keysArr = keys(props);
  9673. for (var i = 0; i < keysArr.length; i++) {
  9674. var key = keysArr[i];
  9675. if (key === 'style') {
  9676. this.useStyle(props[key]);
  9677. }
  9678. else {
  9679. _super.prototype.attrKV.call(this, key, props[key]);
  9680. }
  9681. }
  9682. if (!this.style) {
  9683. this.useStyle({});
  9684. }
  9685. };
  9686. Displayable.prototype.beforeBrush = function () { };
  9687. Displayable.prototype.afterBrush = function () { };
  9688. Displayable.prototype.innerBeforeBrush = function () { };
  9689. Displayable.prototype.innerAfterBrush = function () { };
  9690. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9691. var m = this.transform;
  9692. if (this.ignore
  9693. || this.invisible
  9694. || this.style.opacity === 0
  9695. || (this.culling
  9696. && isDisplayableCulled(this, viewWidth, viewHeight))
  9697. || (m && !m[0] && !m[3])) {
  9698. return false;
  9699. }
  9700. if (considerClipPath && this.__clipPaths && this.__clipPaths.length) {
  9701. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9702. if (this.__clipPaths[i].isZeroArea()) {
  9703. return false;
  9704. }
  9705. }
  9706. }
  9707. if (considerAncestors && this.parent) {
  9708. var parent_1 = this.parent;
  9709. while (parent_1) {
  9710. if (parent_1.ignore) {
  9711. return false;
  9712. }
  9713. parent_1 = parent_1.parent;
  9714. }
  9715. }
  9716. return true;
  9717. };
  9718. Displayable.prototype.contain = function (x, y) {
  9719. return this.rectContain(x, y);
  9720. };
  9721. Displayable.prototype.traverse = function (cb, context) {
  9722. cb.call(context, this);
  9723. };
  9724. Displayable.prototype.rectContain = function (x, y) {
  9725. var coord = this.transformCoordToLocal(x, y);
  9726. var rect = this.getBoundingRect();
  9727. return rect.contain(coord[0], coord[1]);
  9728. };
  9729. Displayable.prototype.getPaintRect = function () {
  9730. var rect = this._paintRect;
  9731. if (!this._paintRect || this.__dirty) {
  9732. var transform = this.transform;
  9733. var elRect = this.getBoundingRect();
  9734. var style = this.style;
  9735. var shadowSize = style.shadowBlur || 0;
  9736. var shadowOffsetX = style.shadowOffsetX || 0;
  9737. var shadowOffsetY = style.shadowOffsetY || 0;
  9738. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9739. if (transform) {
  9740. BoundingRect.applyTransform(rect, elRect, transform);
  9741. }
  9742. else {
  9743. rect.copy(elRect);
  9744. }
  9745. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9746. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9747. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9748. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9749. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9750. }
  9751. var tolerance = this.dirtyRectTolerance;
  9752. if (!rect.isZero()) {
  9753. rect.x = Math.floor(rect.x - tolerance);
  9754. rect.y = Math.floor(rect.y - tolerance);
  9755. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9756. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9757. }
  9758. }
  9759. return rect;
  9760. };
  9761. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9762. if (paintRect) {
  9763. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9764. this._prevPaintRect.copy(paintRect);
  9765. }
  9766. else {
  9767. this._prevPaintRect = null;
  9768. }
  9769. };
  9770. Displayable.prototype.getPrevPaintRect = function () {
  9771. return this._prevPaintRect;
  9772. };
  9773. Displayable.prototype.animateStyle = function (loop) {
  9774. return this.animate('style', loop);
  9775. };
  9776. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9777. if (targetKey === 'style') {
  9778. this.dirtyStyle();
  9779. }
  9780. else {
  9781. this.markRedraw();
  9782. }
  9783. };
  9784. Displayable.prototype.attrKV = function (key, value) {
  9785. if (key !== 'style') {
  9786. _super.prototype.attrKV.call(this, key, value);
  9787. }
  9788. else {
  9789. if (!this.style) {
  9790. this.useStyle(value);
  9791. }
  9792. else {
  9793. this.setStyle(value);
  9794. }
  9795. }
  9796. };
  9797. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9798. if (typeof keyOrObj === 'string') {
  9799. this.style[keyOrObj] = value;
  9800. }
  9801. else {
  9802. extend(this.style, keyOrObj);
  9803. }
  9804. this.dirtyStyle();
  9805. return this;
  9806. };
  9807. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9808. if (!notRedraw) {
  9809. this.markRedraw();
  9810. }
  9811. this.__dirty |= STYLE_CHANGED_BIT;
  9812. if (this._rect) {
  9813. this._rect = null;
  9814. }
  9815. };
  9816. Displayable.prototype.dirty = function () {
  9817. this.dirtyStyle();
  9818. };
  9819. Displayable.prototype.styleChanged = function () {
  9820. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9821. };
  9822. Displayable.prototype.styleUpdated = function () {
  9823. this.__dirty &= ~STYLE_CHANGED_BIT;
  9824. };
  9825. Displayable.prototype.createStyle = function (obj) {
  9826. return createObject(DEFAULT_COMMON_STYLE, obj);
  9827. };
  9828. Displayable.prototype.useStyle = function (obj) {
  9829. if (!obj[STYLE_MAGIC_KEY]) {
  9830. obj = this.createStyle(obj);
  9831. }
  9832. if (this.__inHover) {
  9833. this.__hoverStyle = obj;
  9834. }
  9835. else {
  9836. this.style = obj;
  9837. }
  9838. this.dirtyStyle();
  9839. };
  9840. Displayable.prototype.isStyleObject = function (obj) {
  9841. return obj[STYLE_MAGIC_KEY];
  9842. };
  9843. Displayable.prototype._innerSaveToNormal = function (toState) {
  9844. _super.prototype._innerSaveToNormal.call(this, toState);
  9845. var normalState = this._normalState;
  9846. if (toState.style && !normalState.style) {
  9847. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9848. }
  9849. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9850. };
  9851. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9852. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9853. var needsRestoreToNormal = !(state && keepCurrentStates);
  9854. var targetStyle;
  9855. if (state && state.style) {
  9856. if (transition) {
  9857. if (keepCurrentStates) {
  9858. targetStyle = state.style;
  9859. }
  9860. else {
  9861. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9862. this._mergeStyle(targetStyle, state.style);
  9863. }
  9864. }
  9865. else {
  9866. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9867. this._mergeStyle(targetStyle, state.style);
  9868. }
  9869. }
  9870. else if (needsRestoreToNormal) {
  9871. targetStyle = normalState.style;
  9872. }
  9873. if (targetStyle) {
  9874. if (transition) {
  9875. var sourceStyle = this.style;
  9876. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9877. if (needsRestoreToNormal) {
  9878. var changedKeys = keys(sourceStyle);
  9879. for (var i = 0; i < changedKeys.length; i++) {
  9880. var key = changedKeys[i];
  9881. if (key in targetStyle) {
  9882. targetStyle[key] = targetStyle[key];
  9883. this.style[key] = sourceStyle[key];
  9884. }
  9885. }
  9886. }
  9887. var targetKeys = keys(targetStyle);
  9888. for (var i = 0; i < targetKeys.length; i++) {
  9889. var key = targetKeys[i];
  9890. this.style[key] = this.style[key];
  9891. }
  9892. this._transitionState(stateName, {
  9893. style: targetStyle
  9894. }, animationCfg, this.getAnimationStyleProps());
  9895. }
  9896. else {
  9897. this.useStyle(targetStyle);
  9898. }
  9899. }
  9900. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9901. for (var i = 0; i < statesKeys.length; i++) {
  9902. var key = statesKeys[i];
  9903. if (state && state[key] != null) {
  9904. this[key] = state[key];
  9905. }
  9906. else if (needsRestoreToNormal) {
  9907. if (normalState[key] != null) {
  9908. this[key] = normalState[key];
  9909. }
  9910. }
  9911. }
  9912. };
  9913. Displayable.prototype._mergeStates = function (states) {
  9914. var mergedState = _super.prototype._mergeStates.call(this, states);
  9915. var mergedStyle;
  9916. for (var i = 0; i < states.length; i++) {
  9917. var state = states[i];
  9918. if (state.style) {
  9919. mergedStyle = mergedStyle || {};
  9920. this._mergeStyle(mergedStyle, state.style);
  9921. }
  9922. }
  9923. if (mergedStyle) {
  9924. mergedState.style = mergedStyle;
  9925. }
  9926. return mergedState;
  9927. };
  9928. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9929. extend(targetStyle, sourceStyle);
  9930. return targetStyle;
  9931. };
  9932. Displayable.prototype.getAnimationStyleProps = function () {
  9933. return DEFAULT_COMMON_ANIMATION_PROPS;
  9934. };
  9935. Displayable.initDefaultProps = (function () {
  9936. var dispProto = Displayable.prototype;
  9937. dispProto.type = 'displayable';
  9938. dispProto.invisible = false;
  9939. dispProto.z = 0;
  9940. dispProto.z2 = 0;
  9941. dispProto.zlevel = 0;
  9942. dispProto.culling = false;
  9943. dispProto.cursor = 'pointer';
  9944. dispProto.rectHover = false;
  9945. dispProto.incremental = false;
  9946. dispProto._rect = null;
  9947. dispProto.dirtyRectTolerance = 0;
  9948. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9949. })();
  9950. return Displayable;
  9951. }(Element));
  9952. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9953. var viewRect = new BoundingRect(0, 0, 0, 0);
  9954. function isDisplayableCulled(el, width, height) {
  9955. tmpRect$1.copy(el.getBoundingRect());
  9956. if (el.transform) {
  9957. tmpRect$1.applyTransform(el.transform);
  9958. }
  9959. viewRect.width = width;
  9960. viewRect.height = height;
  9961. return !tmpRect$1.intersect(viewRect);
  9962. }
  9963. var mathMin$2 = Math.min;
  9964. var mathMax$2 = Math.max;
  9965. var mathSin = Math.sin;
  9966. var mathCos = Math.cos;
  9967. var PI2 = Math.PI * 2;
  9968. var start = create();
  9969. var end = create();
  9970. var extremity = create();
  9971. function fromLine(x0, y0, x1, y1, min, max) {
  9972. min[0] = mathMin$2(x0, x1);
  9973. min[1] = mathMin$2(y0, y1);
  9974. max[0] = mathMax$2(x0, x1);
  9975. max[1] = mathMax$2(y0, y1);
  9976. }
  9977. var xDim = [];
  9978. var yDim = [];
  9979. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9980. var cubicExtrema$1 = cubicExtrema;
  9981. var cubicAt$1 = cubicAt;
  9982. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9983. min[0] = Infinity;
  9984. min[1] = Infinity;
  9985. max[0] = -Infinity;
  9986. max[1] = -Infinity;
  9987. for (var i = 0; i < n; i++) {
  9988. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9989. min[0] = mathMin$2(x, min[0]);
  9990. max[0] = mathMax$2(x, max[0]);
  9991. }
  9992. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9993. for (var i = 0; i < n; i++) {
  9994. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9995. min[1] = mathMin$2(y, min[1]);
  9996. max[1] = mathMax$2(y, max[1]);
  9997. }
  9998. min[0] = mathMin$2(x0, min[0]);
  9999. max[0] = mathMax$2(x0, max[0]);
  10000. min[0] = mathMin$2(x3, min[0]);
  10001. max[0] = mathMax$2(x3, max[0]);
  10002. min[1] = mathMin$2(y0, min[1]);
  10003. max[1] = mathMax$2(y0, max[1]);
  10004. min[1] = mathMin$2(y3, min[1]);
  10005. max[1] = mathMax$2(y3, max[1]);
  10006. }
  10007. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  10008. var quadraticExtremum$1 = quadraticExtremum;
  10009. var quadraticAt$1 = quadraticAt;
  10010. var tx = mathMax$2(mathMin$2(quadraticExtremum$1(x0, x1, x2), 1), 0);
  10011. var ty = mathMax$2(mathMin$2(quadraticExtremum$1(y0, y1, y2), 1), 0);
  10012. var x = quadraticAt$1(x0, x1, x2, tx);
  10013. var y = quadraticAt$1(y0, y1, y2, ty);
  10014. min[0] = mathMin$2(x0, x2, x);
  10015. min[1] = mathMin$2(y0, y2, y);
  10016. max[0] = mathMax$2(x0, x2, x);
  10017. max[1] = mathMax$2(y0, y2, y);
  10018. }
  10019. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  10020. var vec2Min = min;
  10021. var vec2Max = max;
  10022. var diff = Math.abs(startAngle - endAngle);
  10023. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10024. min$1[0] = x - rx;
  10025. min$1[1] = y - ry;
  10026. max$1[0] = x + rx;
  10027. max$1[1] = y + ry;
  10028. return;
  10029. }
  10030. start[0] = mathCos(startAngle) * rx + x;
  10031. start[1] = mathSin(startAngle) * ry + y;
  10032. end[0] = mathCos(endAngle) * rx + x;
  10033. end[1] = mathSin(endAngle) * ry + y;
  10034. vec2Min(min$1, start, end);
  10035. vec2Max(max$1, start, end);
  10036. startAngle = startAngle % (PI2);
  10037. if (startAngle < 0) {
  10038. startAngle = startAngle + PI2;
  10039. }
  10040. endAngle = endAngle % (PI2);
  10041. if (endAngle < 0) {
  10042. endAngle = endAngle + PI2;
  10043. }
  10044. if (startAngle > endAngle && !anticlockwise) {
  10045. endAngle += PI2;
  10046. }
  10047. else if (startAngle < endAngle && anticlockwise) {
  10048. startAngle += PI2;
  10049. }
  10050. if (anticlockwise) {
  10051. var tmp = endAngle;
  10052. endAngle = startAngle;
  10053. startAngle = tmp;
  10054. }
  10055. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10056. if (angle > startAngle) {
  10057. extremity[0] = mathCos(angle) * rx + x;
  10058. extremity[1] = mathSin(angle) * ry + y;
  10059. vec2Min(min$1, extremity, min$1);
  10060. vec2Max(max$1, extremity, max$1);
  10061. }
  10062. }
  10063. }
  10064. var CMD = {
  10065. M: 1,
  10066. L: 2,
  10067. C: 3,
  10068. Q: 4,
  10069. A: 5,
  10070. Z: 6,
  10071. R: 7
  10072. };
  10073. var tmpOutX = [];
  10074. var tmpOutY = [];
  10075. var min$1 = [];
  10076. var max$1 = [];
  10077. var min2 = [];
  10078. var max2 = [];
  10079. var mathMin$3 = Math.min;
  10080. var mathMax$3 = Math.max;
  10081. var mathCos$1 = Math.cos;
  10082. var mathSin$1 = Math.sin;
  10083. var mathAbs$2 = Math.abs;
  10084. var PI = Math.PI;
  10085. var PI2$1 = PI * 2;
  10086. var hasTypedArray = typeof Float32Array !== 'undefined';
  10087. var tmpAngles = [];
  10088. function modPI2(radian) {
  10089. var n = Math.round(radian / PI * 1e8) / 1e8;
  10090. return (n % 2) * PI;
  10091. }
  10092. function normalizeArcAngles(angles, anticlockwise) {
  10093. var newStartAngle = modPI2(angles[0]);
  10094. if (newStartAngle < 0) {
  10095. newStartAngle += PI2$1;
  10096. }
  10097. var delta = newStartAngle - angles[0];
  10098. var newEndAngle = angles[1];
  10099. newEndAngle += delta;
  10100. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  10101. newEndAngle = newStartAngle + PI2$1;
  10102. }
  10103. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  10104. newEndAngle = newStartAngle - PI2$1;
  10105. }
  10106. else if (!anticlockwise && newStartAngle > newEndAngle) {
  10107. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  10108. }
  10109. else if (anticlockwise && newStartAngle < newEndAngle) {
  10110. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  10111. }
  10112. angles[0] = newStartAngle;
  10113. angles[1] = newEndAngle;
  10114. }
  10115. var PathProxy = (function () {
  10116. function PathProxy(notSaveData) {
  10117. this.dpr = 1;
  10118. this._xi = 0;
  10119. this._yi = 0;
  10120. this._x0 = 0;
  10121. this._y0 = 0;
  10122. this._len = 0;
  10123. if (notSaveData) {
  10124. this._saveData = false;
  10125. }
  10126. if (this._saveData) {
  10127. this.data = [];
  10128. }
  10129. }
  10130. PathProxy.prototype.increaseVersion = function () {
  10131. this._version++;
  10132. };
  10133. PathProxy.prototype.getVersion = function () {
  10134. return this._version;
  10135. };
  10136. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  10137. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  10138. if (segmentIgnoreThreshold > 0) {
  10139. this._ux = mathAbs$2(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  10140. this._uy = mathAbs$2(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  10141. }
  10142. };
  10143. PathProxy.prototype.setDPR = function (dpr) {
  10144. this.dpr = dpr;
  10145. };
  10146. PathProxy.prototype.setContext = function (ctx) {
  10147. this._ctx = ctx;
  10148. };
  10149. PathProxy.prototype.getContext = function () {
  10150. return this._ctx;
  10151. };
  10152. PathProxy.prototype.beginPath = function () {
  10153. this._ctx && this._ctx.beginPath();
  10154. this.reset();
  10155. return this;
  10156. };
  10157. PathProxy.prototype.reset = function () {
  10158. if (this._saveData) {
  10159. this._len = 0;
  10160. }
  10161. if (this._pathSegLen) {
  10162. this._pathSegLen = null;
  10163. this._pathLen = 0;
  10164. }
  10165. this._version++;
  10166. };
  10167. PathProxy.prototype.moveTo = function (x, y) {
  10168. this._drawPendingPt();
  10169. this.addData(CMD.M, x, y);
  10170. this._ctx && this._ctx.moveTo(x, y);
  10171. this._x0 = x;
  10172. this._y0 = y;
  10173. this._xi = x;
  10174. this._yi = y;
  10175. return this;
  10176. };
  10177. PathProxy.prototype.lineTo = function (x, y) {
  10178. var dx = mathAbs$2(x - this._xi);
  10179. var dy = mathAbs$2(y - this._yi);
  10180. var exceedUnit = dx > this._ux || dy > this._uy;
  10181. this.addData(CMD.L, x, y);
  10182. if (this._ctx && exceedUnit) {
  10183. this._ctx.lineTo(x, y);
  10184. }
  10185. if (exceedUnit) {
  10186. this._xi = x;
  10187. this._yi = y;
  10188. this._pendingPtDist = 0;
  10189. }
  10190. else {
  10191. var d2 = dx * dx + dy * dy;
  10192. if (d2 > this._pendingPtDist) {
  10193. this._pendingPtX = x;
  10194. this._pendingPtY = y;
  10195. this._pendingPtDist = d2;
  10196. }
  10197. }
  10198. return this;
  10199. };
  10200. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  10201. this._drawPendingPt();
  10202. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  10203. if (this._ctx) {
  10204. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10205. }
  10206. this._xi = x3;
  10207. this._yi = y3;
  10208. return this;
  10209. };
  10210. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  10211. this._drawPendingPt();
  10212. this.addData(CMD.Q, x1, y1, x2, y2);
  10213. if (this._ctx) {
  10214. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  10215. }
  10216. this._xi = x2;
  10217. this._yi = y2;
  10218. return this;
  10219. };
  10220. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  10221. this._drawPendingPt();
  10222. tmpAngles[0] = startAngle;
  10223. tmpAngles[1] = endAngle;
  10224. normalizeArcAngles(tmpAngles, anticlockwise);
  10225. startAngle = tmpAngles[0];
  10226. endAngle = tmpAngles[1];
  10227. var delta = endAngle - startAngle;
  10228. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  10229. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10230. this._xi = mathCos$1(endAngle) * r + cx;
  10231. this._yi = mathSin$1(endAngle) * r + cy;
  10232. return this;
  10233. };
  10234. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  10235. this._drawPendingPt();
  10236. if (this._ctx) {
  10237. this._ctx.arcTo(x1, y1, x2, y2, radius);
  10238. }
  10239. return this;
  10240. };
  10241. PathProxy.prototype.rect = function (x, y, w, h) {
  10242. this._drawPendingPt();
  10243. this._ctx && this._ctx.rect(x, y, w, h);
  10244. this.addData(CMD.R, x, y, w, h);
  10245. return this;
  10246. };
  10247. PathProxy.prototype.closePath = function () {
  10248. this._drawPendingPt();
  10249. this.addData(CMD.Z);
  10250. var ctx = this._ctx;
  10251. var x0 = this._x0;
  10252. var y0 = this._y0;
  10253. if (ctx) {
  10254. ctx.closePath();
  10255. }
  10256. this._xi = x0;
  10257. this._yi = y0;
  10258. return this;
  10259. };
  10260. PathProxy.prototype.fill = function (ctx) {
  10261. ctx && ctx.fill();
  10262. this.toStatic();
  10263. };
  10264. PathProxy.prototype.stroke = function (ctx) {
  10265. ctx && ctx.stroke();
  10266. this.toStatic();
  10267. };
  10268. PathProxy.prototype.len = function () {
  10269. return this._len;
  10270. };
  10271. PathProxy.prototype.setData = function (data) {
  10272. if (!this._saveData) {
  10273. return;
  10274. }
  10275. var len = data.length;
  10276. if (!(this.data && this.data.length === len) && hasTypedArray) {
  10277. this.data = new Float32Array(len);
  10278. }
  10279. for (var i = 0; i < len; i++) {
  10280. this.data[i] = data[i];
  10281. }
  10282. this._len = len;
  10283. };
  10284. PathProxy.prototype.appendPath = function (path) {
  10285. if (!this._saveData) {
  10286. return;
  10287. }
  10288. if (!(path instanceof Array)) {
  10289. path = [path];
  10290. }
  10291. var len = path.length;
  10292. var appendSize = 0;
  10293. var offset = this._len;
  10294. for (var i = 0; i < len; i++) {
  10295. appendSize += path[i].len();
  10296. }
  10297. var oldData = this.data;
  10298. if (hasTypedArray && (oldData instanceof Float32Array || !oldData)) {
  10299. this.data = new Float32Array(offset + appendSize);
  10300. if (offset > 0 && oldData) {
  10301. for (var k = 0; k < offset; k++) {
  10302. this.data[k] = oldData[k];
  10303. }
  10304. }
  10305. }
  10306. for (var i = 0; i < len; i++) {
  10307. var appendPathData = path[i].data;
  10308. for (var k = 0; k < appendPathData.length; k++) {
  10309. this.data[offset++] = appendPathData[k];
  10310. }
  10311. }
  10312. this._len = offset;
  10313. };
  10314. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  10315. if (!this._saveData) {
  10316. return;
  10317. }
  10318. var data = this.data;
  10319. if (this._len + arguments.length > data.length) {
  10320. this._expandData();
  10321. data = this.data;
  10322. }
  10323. for (var i = 0; i < arguments.length; i++) {
  10324. data[this._len++] = arguments[i];
  10325. }
  10326. };
  10327. PathProxy.prototype._drawPendingPt = function () {
  10328. if (this._pendingPtDist > 0) {
  10329. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  10330. this._pendingPtDist = 0;
  10331. }
  10332. };
  10333. PathProxy.prototype._expandData = function () {
  10334. if (!(this.data instanceof Array)) {
  10335. var newData = [];
  10336. for (var i = 0; i < this._len; i++) {
  10337. newData[i] = this.data[i];
  10338. }
  10339. this.data = newData;
  10340. }
  10341. };
  10342. PathProxy.prototype.toStatic = function () {
  10343. if (!this._saveData) {
  10344. return;
  10345. }
  10346. this._drawPendingPt();
  10347. var data = this.data;
  10348. if (data instanceof Array) {
  10349. data.length = this._len;
  10350. if (hasTypedArray && this._len > 11) {
  10351. this.data = new Float32Array(data);
  10352. }
  10353. }
  10354. };
  10355. PathProxy.prototype.getBoundingRect = function () {
  10356. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  10357. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  10358. var data = this.data;
  10359. var xi = 0;
  10360. var yi = 0;
  10361. var x0 = 0;
  10362. var y0 = 0;
  10363. var i;
  10364. for (i = 0; i < this._len;) {
  10365. var cmd = data[i++];
  10366. var isFirst = i === 1;
  10367. if (isFirst) {
  10368. xi = data[i];
  10369. yi = data[i + 1];
  10370. x0 = xi;
  10371. y0 = yi;
  10372. }
  10373. switch (cmd) {
  10374. case CMD.M:
  10375. xi = x0 = data[i++];
  10376. yi = y0 = data[i++];
  10377. min2[0] = x0;
  10378. min2[1] = y0;
  10379. max2[0] = x0;
  10380. max2[1] = y0;
  10381. break;
  10382. case CMD.L:
  10383. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  10384. xi = data[i++];
  10385. yi = data[i++];
  10386. break;
  10387. case CMD.C:
  10388. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10389. xi = data[i++];
  10390. yi = data[i++];
  10391. break;
  10392. case CMD.Q:
  10393. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10394. xi = data[i++];
  10395. yi = data[i++];
  10396. break;
  10397. case CMD.A:
  10398. var cx = data[i++];
  10399. var cy = data[i++];
  10400. var rx = data[i++];
  10401. var ry = data[i++];
  10402. var startAngle = data[i++];
  10403. var endAngle = data[i++] + startAngle;
  10404. i += 1;
  10405. var anticlockwise = !data[i++];
  10406. if (isFirst) {
  10407. x0 = mathCos$1(startAngle) * rx + cx;
  10408. y0 = mathSin$1(startAngle) * ry + cy;
  10409. }
  10410. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  10411. xi = mathCos$1(endAngle) * rx + cx;
  10412. yi = mathSin$1(endAngle) * ry + cy;
  10413. break;
  10414. case CMD.R:
  10415. x0 = xi = data[i++];
  10416. y0 = yi = data[i++];
  10417. var width = data[i++];
  10418. var height = data[i++];
  10419. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10420. break;
  10421. case CMD.Z:
  10422. xi = x0;
  10423. yi = y0;
  10424. break;
  10425. }
  10426. min(min$1, min$1, min2);
  10427. max(max$1, max$1, max2);
  10428. }
  10429. if (i === 0) {
  10430. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10431. }
  10432. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  10433. };
  10434. PathProxy.prototype._calculateLength = function () {
  10435. var data = this.data;
  10436. var len = this._len;
  10437. var ux = this._ux;
  10438. var uy = this._uy;
  10439. var xi = 0;
  10440. var yi = 0;
  10441. var x0 = 0;
  10442. var y0 = 0;
  10443. if (!this._pathSegLen) {
  10444. this._pathSegLen = [];
  10445. }
  10446. var pathSegLen = this._pathSegLen;
  10447. var pathTotalLen = 0;
  10448. var segCount = 0;
  10449. for (var i = 0; i < len;) {
  10450. var cmd = data[i++];
  10451. var isFirst = i === 1;
  10452. if (isFirst) {
  10453. xi = data[i];
  10454. yi = data[i + 1];
  10455. x0 = xi;
  10456. y0 = yi;
  10457. }
  10458. var l = -1;
  10459. switch (cmd) {
  10460. case CMD.M:
  10461. xi = x0 = data[i++];
  10462. yi = y0 = data[i++];
  10463. break;
  10464. case CMD.L: {
  10465. var x2 = data[i++];
  10466. var y2 = data[i++];
  10467. var dx = x2 - xi;
  10468. var dy = y2 - yi;
  10469. if (mathAbs$2(dx) > ux || mathAbs$2(dy) > uy || i === len - 1) {
  10470. l = Math.sqrt(dx * dx + dy * dy);
  10471. xi = x2;
  10472. yi = y2;
  10473. }
  10474. break;
  10475. }
  10476. case CMD.C: {
  10477. var x1 = data[i++];
  10478. var y1 = data[i++];
  10479. var x2 = data[i++];
  10480. var y2 = data[i++];
  10481. var x3 = data[i++];
  10482. var y3 = data[i++];
  10483. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10484. xi = x3;
  10485. yi = y3;
  10486. break;
  10487. }
  10488. case CMD.Q: {
  10489. var x1 = data[i++];
  10490. var y1 = data[i++];
  10491. var x2 = data[i++];
  10492. var y2 = data[i++];
  10493. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10494. xi = x2;
  10495. yi = y2;
  10496. break;
  10497. }
  10498. case CMD.A:
  10499. var cx = data[i++];
  10500. var cy = data[i++];
  10501. var rx = data[i++];
  10502. var ry = data[i++];
  10503. var startAngle = data[i++];
  10504. var delta = data[i++];
  10505. var endAngle = delta + startAngle;
  10506. i += 1;
  10507. if (isFirst) {
  10508. x0 = mathCos$1(startAngle) * rx + cx;
  10509. y0 = mathSin$1(startAngle) * ry + cy;
  10510. }
  10511. l = mathMax$3(rx, ry) * mathMin$3(PI2$1, Math.abs(delta));
  10512. xi = mathCos$1(endAngle) * rx + cx;
  10513. yi = mathSin$1(endAngle) * ry + cy;
  10514. break;
  10515. case CMD.R: {
  10516. x0 = xi = data[i++];
  10517. y0 = yi = data[i++];
  10518. var width = data[i++];
  10519. var height = data[i++];
  10520. l = width * 2 + height * 2;
  10521. break;
  10522. }
  10523. case CMD.Z: {
  10524. var dx = x0 - xi;
  10525. var dy = y0 - yi;
  10526. l = Math.sqrt(dx * dx + dy * dy);
  10527. xi = x0;
  10528. yi = y0;
  10529. break;
  10530. }
  10531. }
  10532. if (l >= 0) {
  10533. pathSegLen[segCount++] = l;
  10534. pathTotalLen += l;
  10535. }
  10536. }
  10537. this._pathLen = pathTotalLen;
  10538. return pathTotalLen;
  10539. };
  10540. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10541. var d = this.data;
  10542. var ux = this._ux;
  10543. var uy = this._uy;
  10544. var len = this._len;
  10545. var x0;
  10546. var y0;
  10547. var xi;
  10548. var yi;
  10549. var x;
  10550. var y;
  10551. var drawPart = percent < 1;
  10552. var pathSegLen;
  10553. var pathTotalLen;
  10554. var accumLength = 0;
  10555. var segCount = 0;
  10556. var displayedLength;
  10557. var pendingPtDist = 0;
  10558. var pendingPtX;
  10559. var pendingPtY;
  10560. if (drawPart) {
  10561. if (!this._pathSegLen) {
  10562. this._calculateLength();
  10563. }
  10564. pathSegLen = this._pathSegLen;
  10565. pathTotalLen = this._pathLen;
  10566. displayedLength = percent * pathTotalLen;
  10567. if (!displayedLength) {
  10568. return;
  10569. }
  10570. }
  10571. lo: for (var i = 0; i < len;) {
  10572. var cmd = d[i++];
  10573. var isFirst = i === 1;
  10574. if (isFirst) {
  10575. xi = d[i];
  10576. yi = d[i + 1];
  10577. x0 = xi;
  10578. y0 = yi;
  10579. }
  10580. if (cmd !== CMD.L && pendingPtDist > 0) {
  10581. ctx.lineTo(pendingPtX, pendingPtY);
  10582. pendingPtDist = 0;
  10583. }
  10584. switch (cmd) {
  10585. case CMD.M:
  10586. x0 = xi = d[i++];
  10587. y0 = yi = d[i++];
  10588. ctx.moveTo(xi, yi);
  10589. break;
  10590. case CMD.L: {
  10591. x = d[i++];
  10592. y = d[i++];
  10593. var dx = mathAbs$2(x - xi);
  10594. var dy = mathAbs$2(y - yi);
  10595. if (dx > ux || dy > uy) {
  10596. if (drawPart) {
  10597. var l = pathSegLen[segCount++];
  10598. if (accumLength + l > displayedLength) {
  10599. var t = (displayedLength - accumLength) / l;
  10600. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10601. break lo;
  10602. }
  10603. accumLength += l;
  10604. }
  10605. ctx.lineTo(x, y);
  10606. xi = x;
  10607. yi = y;
  10608. pendingPtDist = 0;
  10609. }
  10610. else {
  10611. var d2 = dx * dx + dy * dy;
  10612. if (d2 > pendingPtDist) {
  10613. pendingPtX = x;
  10614. pendingPtY = y;
  10615. pendingPtDist = d2;
  10616. }
  10617. }
  10618. break;
  10619. }
  10620. case CMD.C: {
  10621. var x1 = d[i++];
  10622. var y1 = d[i++];
  10623. var x2 = d[i++];
  10624. var y2 = d[i++];
  10625. var x3 = d[i++];
  10626. var y3 = d[i++];
  10627. if (drawPart) {
  10628. var l = pathSegLen[segCount++];
  10629. if (accumLength + l > displayedLength) {
  10630. var t = (displayedLength - accumLength) / l;
  10631. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10632. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10633. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10634. break lo;
  10635. }
  10636. accumLength += l;
  10637. }
  10638. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10639. xi = x3;
  10640. yi = y3;
  10641. break;
  10642. }
  10643. case CMD.Q: {
  10644. var x1 = d[i++];
  10645. var y1 = d[i++];
  10646. var x2 = d[i++];
  10647. var y2 = d[i++];
  10648. if (drawPart) {
  10649. var l = pathSegLen[segCount++];
  10650. if (accumLength + l > displayedLength) {
  10651. var t = (displayedLength - accumLength) / l;
  10652. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10653. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10654. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10655. break lo;
  10656. }
  10657. accumLength += l;
  10658. }
  10659. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10660. xi = x2;
  10661. yi = y2;
  10662. break;
  10663. }
  10664. case CMD.A:
  10665. var cx = d[i++];
  10666. var cy = d[i++];
  10667. var rx = d[i++];
  10668. var ry = d[i++];
  10669. var startAngle = d[i++];
  10670. var delta = d[i++];
  10671. var psi = d[i++];
  10672. var anticlockwise = !d[i++];
  10673. var r = (rx > ry) ? rx : ry;
  10674. var isEllipse = mathAbs$2(rx - ry) > 1e-3;
  10675. var endAngle = startAngle + delta;
  10676. var breakBuild = false;
  10677. if (drawPart) {
  10678. var l = pathSegLen[segCount++];
  10679. if (accumLength + l > displayedLength) {
  10680. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10681. breakBuild = true;
  10682. }
  10683. accumLength += l;
  10684. }
  10685. if (isEllipse && ctx.ellipse) {
  10686. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10687. }
  10688. else {
  10689. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10690. }
  10691. if (breakBuild) {
  10692. break lo;
  10693. }
  10694. if (isFirst) {
  10695. x0 = mathCos$1(startAngle) * rx + cx;
  10696. y0 = mathSin$1(startAngle) * ry + cy;
  10697. }
  10698. xi = mathCos$1(endAngle) * rx + cx;
  10699. yi = mathSin$1(endAngle) * ry + cy;
  10700. break;
  10701. case CMD.R:
  10702. x0 = xi = d[i];
  10703. y0 = yi = d[i + 1];
  10704. x = d[i++];
  10705. y = d[i++];
  10706. var width = d[i++];
  10707. var height = d[i++];
  10708. if (drawPart) {
  10709. var l = pathSegLen[segCount++];
  10710. if (accumLength + l > displayedLength) {
  10711. var d_1 = displayedLength - accumLength;
  10712. ctx.moveTo(x, y);
  10713. ctx.lineTo(x + mathMin$3(d_1, width), y);
  10714. d_1 -= width;
  10715. if (d_1 > 0) {
  10716. ctx.lineTo(x + width, y + mathMin$3(d_1, height));
  10717. }
  10718. d_1 -= height;
  10719. if (d_1 > 0) {
  10720. ctx.lineTo(x + mathMax$3(width - d_1, 0), y + height);
  10721. }
  10722. d_1 -= width;
  10723. if (d_1 > 0) {
  10724. ctx.lineTo(x, y + mathMax$3(height - d_1, 0));
  10725. }
  10726. break lo;
  10727. }
  10728. accumLength += l;
  10729. }
  10730. ctx.rect(x, y, width, height);
  10731. break;
  10732. case CMD.Z:
  10733. if (drawPart) {
  10734. var l = pathSegLen[segCount++];
  10735. if (accumLength + l > displayedLength) {
  10736. var t = (displayedLength - accumLength) / l;
  10737. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10738. break lo;
  10739. }
  10740. accumLength += l;
  10741. }
  10742. ctx.closePath();
  10743. xi = x0;
  10744. yi = y0;
  10745. }
  10746. }
  10747. };
  10748. PathProxy.prototype.clone = function () {
  10749. var newProxy = new PathProxy();
  10750. var data = this.data;
  10751. newProxy.data = data.slice ? data.slice()
  10752. : Array.prototype.slice.call(data);
  10753. newProxy._len = this._len;
  10754. return newProxy;
  10755. };
  10756. PathProxy.prototype.canSave = function () {
  10757. return !!this._saveData;
  10758. };
  10759. PathProxy.CMD = CMD;
  10760. PathProxy.initDefaultProps = (function () {
  10761. var proto = PathProxy.prototype;
  10762. proto._saveData = true;
  10763. proto._ux = 0;
  10764. proto._uy = 0;
  10765. proto._pendingPtDist = 0;
  10766. proto._version = 0;
  10767. })();
  10768. return PathProxy;
  10769. }());
  10770. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10771. if (lineWidth === 0) {
  10772. return false;
  10773. }
  10774. var _l = lineWidth;
  10775. var _a = 0;
  10776. var _b = x0;
  10777. if ((y > y0 + _l && y > y1 + _l)
  10778. || (y < y0 - _l && y < y1 - _l)
  10779. || (x > x0 + _l && x > x1 + _l)
  10780. || (x < x0 - _l && x < x1 - _l)) {
  10781. return false;
  10782. }
  10783. if (x0 !== x1) {
  10784. _a = (y0 - y1) / (x0 - x1);
  10785. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10786. }
  10787. else {
  10788. return Math.abs(x - x0) <= _l / 2;
  10789. }
  10790. var tmp = _a * x - y + _b;
  10791. var _s = tmp * tmp / (_a * _a + 1);
  10792. return _s <= _l / 2 * _l / 2;
  10793. }
  10794. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10795. if (lineWidth === 0) {
  10796. return false;
  10797. }
  10798. var _l = lineWidth;
  10799. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10800. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10801. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10802. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10803. return false;
  10804. }
  10805. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10806. return d <= _l / 2;
  10807. }
  10808. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10809. if (lineWidth === 0) {
  10810. return false;
  10811. }
  10812. var _l = lineWidth;
  10813. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10814. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10815. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10816. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10817. return false;
  10818. }
  10819. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10820. return d <= _l / 2;
  10821. }
  10822. var PI2$2 = Math.PI * 2;
  10823. function normalizeRadian(angle) {
  10824. angle %= PI2$2;
  10825. if (angle < 0) {
  10826. angle += PI2$2;
  10827. }
  10828. return angle;
  10829. }
  10830. var PI2$3 = Math.PI * 2;
  10831. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10832. if (lineWidth === 0) {
  10833. return false;
  10834. }
  10835. var _l = lineWidth;
  10836. x -= cx;
  10837. y -= cy;
  10838. var d = Math.sqrt(x * x + y * y);
  10839. if ((d - _l > r) || (d + _l < r)) {
  10840. return false;
  10841. }
  10842. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10843. return true;
  10844. }
  10845. if (anticlockwise) {
  10846. var tmp = startAngle;
  10847. startAngle = normalizeRadian(endAngle);
  10848. endAngle = normalizeRadian(tmp);
  10849. }
  10850. else {
  10851. startAngle = normalizeRadian(startAngle);
  10852. endAngle = normalizeRadian(endAngle);
  10853. }
  10854. if (startAngle > endAngle) {
  10855. endAngle += PI2$3;
  10856. }
  10857. var angle = Math.atan2(y, x);
  10858. if (angle < 0) {
  10859. angle += PI2$3;
  10860. }
  10861. return (angle >= startAngle && angle <= endAngle)
  10862. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10863. }
  10864. function windingLine(x0, y0, x1, y1, x, y) {
  10865. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10866. return 0;
  10867. }
  10868. if (y1 === y0) {
  10869. return 0;
  10870. }
  10871. var t = (y - y0) / (y1 - y0);
  10872. var dir = y1 < y0 ? 1 : -1;
  10873. if (t === 1 || t === 0) {
  10874. dir = y1 < y0 ? 0.5 : -0.5;
  10875. }
  10876. var x_ = t * (x1 - x0) + x0;
  10877. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10878. }
  10879. var CMD$1 = PathProxy.CMD;
  10880. var PI2$4 = Math.PI * 2;
  10881. var EPSILON$4 = 1e-4;
  10882. function isAroundEqual(a, b) {
  10883. return Math.abs(a - b) < EPSILON$4;
  10884. }
  10885. var roots = [-1, -1, -1];
  10886. var extrema = [-1, -1];
  10887. function swapExtrema() {
  10888. var tmp = extrema[0];
  10889. extrema[0] = extrema[1];
  10890. extrema[1] = tmp;
  10891. }
  10892. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10893. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10894. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10895. return 0;
  10896. }
  10897. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10898. if (nRoots === 0) {
  10899. return 0;
  10900. }
  10901. else {
  10902. var w = 0;
  10903. var nExtrema = -1;
  10904. var y0_ = void 0;
  10905. var y1_ = void 0;
  10906. for (var i = 0; i < nRoots; i++) {
  10907. var t = roots[i];
  10908. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10909. var x_ = cubicAt(x0, x1, x2, x3, t);
  10910. if (x_ < x) {
  10911. continue;
  10912. }
  10913. if (nExtrema < 0) {
  10914. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10915. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10916. swapExtrema();
  10917. }
  10918. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10919. if (nExtrema > 1) {
  10920. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10921. }
  10922. }
  10923. if (nExtrema === 2) {
  10924. if (t < extrema[0]) {
  10925. w += y0_ < y0 ? unit : -unit;
  10926. }
  10927. else if (t < extrema[1]) {
  10928. w += y1_ < y0_ ? unit : -unit;
  10929. }
  10930. else {
  10931. w += y3 < y1_ ? unit : -unit;
  10932. }
  10933. }
  10934. else {
  10935. if (t < extrema[0]) {
  10936. w += y0_ < y0 ? unit : -unit;
  10937. }
  10938. else {
  10939. w += y3 < y0_ ? unit : -unit;
  10940. }
  10941. }
  10942. }
  10943. return w;
  10944. }
  10945. }
  10946. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10947. if ((y > y0 && y > y1 && y > y2)
  10948. || (y < y0 && y < y1 && y < y2)) {
  10949. return 0;
  10950. }
  10951. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10952. if (nRoots === 0) {
  10953. return 0;
  10954. }
  10955. else {
  10956. var t = quadraticExtremum(y0, y1, y2);
  10957. if (t >= 0 && t <= 1) {
  10958. var w = 0;
  10959. var y_ = quadraticAt(y0, y1, y2, t);
  10960. for (var i = 0; i < nRoots; i++) {
  10961. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10962. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10963. if (x_ < x) {
  10964. continue;
  10965. }
  10966. if (roots[i] < t) {
  10967. w += y_ < y0 ? unit : -unit;
  10968. }
  10969. else {
  10970. w += y2 < y_ ? unit : -unit;
  10971. }
  10972. }
  10973. return w;
  10974. }
  10975. else {
  10976. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10977. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10978. if (x_ < x) {
  10979. return 0;
  10980. }
  10981. return y2 < y0 ? unit : -unit;
  10982. }
  10983. }
  10984. }
  10985. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10986. y -= cy;
  10987. if (y > r || y < -r) {
  10988. return 0;
  10989. }
  10990. var tmp = Math.sqrt(r * r - y * y);
  10991. roots[0] = -tmp;
  10992. roots[1] = tmp;
  10993. var dTheta = Math.abs(startAngle - endAngle);
  10994. if (dTheta < 1e-4) {
  10995. return 0;
  10996. }
  10997. if (dTheta >= PI2$4 - 1e-4) {
  10998. startAngle = 0;
  10999. endAngle = PI2$4;
  11000. var dir = anticlockwise ? 1 : -1;
  11001. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11002. return dir;
  11003. }
  11004. else {
  11005. return 0;
  11006. }
  11007. }
  11008. if (startAngle > endAngle) {
  11009. var tmp_1 = startAngle;
  11010. startAngle = endAngle;
  11011. endAngle = tmp_1;
  11012. }
  11013. if (startAngle < 0) {
  11014. startAngle += PI2$4;
  11015. endAngle += PI2$4;
  11016. }
  11017. var w = 0;
  11018. for (var i = 0; i < 2; i++) {
  11019. var x_ = roots[i];
  11020. if (x_ + cx > x) {
  11021. var angle = Math.atan2(y, x_);
  11022. var dir = anticlockwise ? 1 : -1;
  11023. if (angle < 0) {
  11024. angle = PI2$4 + angle;
  11025. }
  11026. if ((angle >= startAngle && angle <= endAngle)
  11027. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  11028. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11029. dir = -dir;
  11030. }
  11031. w += dir;
  11032. }
  11033. }
  11034. }
  11035. return w;
  11036. }
  11037. function containPath(path, lineWidth, isStroke, x, y) {
  11038. var data = path.data;
  11039. var len = path.len();
  11040. var w = 0;
  11041. var xi = 0;
  11042. var yi = 0;
  11043. var x0 = 0;
  11044. var y0 = 0;
  11045. var x1;
  11046. var y1;
  11047. for (var i = 0; i < len;) {
  11048. var cmd = data[i++];
  11049. var isFirst = i === 1;
  11050. if (cmd === CMD$1.M && i > 1) {
  11051. if (!isStroke) {
  11052. w += windingLine(xi, yi, x0, y0, x, y);
  11053. }
  11054. }
  11055. if (isFirst) {
  11056. xi = data[i];
  11057. yi = data[i + 1];
  11058. x0 = xi;
  11059. y0 = yi;
  11060. }
  11061. switch (cmd) {
  11062. case CMD$1.M:
  11063. x0 = data[i++];
  11064. y0 = data[i++];
  11065. xi = x0;
  11066. yi = y0;
  11067. break;
  11068. case CMD$1.L:
  11069. if (isStroke) {
  11070. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11071. return true;
  11072. }
  11073. }
  11074. else {
  11075. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11076. }
  11077. xi = data[i++];
  11078. yi = data[i++];
  11079. break;
  11080. case CMD$1.C:
  11081. if (isStroke) {
  11082. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  11083. return true;
  11084. }
  11085. }
  11086. else {
  11087. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  11088. }
  11089. xi = data[i++];
  11090. yi = data[i++];
  11091. break;
  11092. case CMD$1.Q:
  11093. if (isStroke) {
  11094. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  11095. return true;
  11096. }
  11097. }
  11098. else {
  11099. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  11100. }
  11101. xi = data[i++];
  11102. yi = data[i++];
  11103. break;
  11104. case CMD$1.A:
  11105. var cx = data[i++];
  11106. var cy = data[i++];
  11107. var rx = data[i++];
  11108. var ry = data[i++];
  11109. var theta = data[i++];
  11110. var dTheta = data[i++];
  11111. i += 1;
  11112. var anticlockwise = !!(1 - data[i++]);
  11113. x1 = Math.cos(theta) * rx + cx;
  11114. y1 = Math.sin(theta) * ry + cy;
  11115. if (!isFirst) {
  11116. w += windingLine(xi, yi, x1, y1, x, y);
  11117. }
  11118. else {
  11119. x0 = x1;
  11120. y0 = y1;
  11121. }
  11122. var _x = (x - cx) * ry / rx + cx;
  11123. if (isStroke) {
  11124. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  11125. return true;
  11126. }
  11127. }
  11128. else {
  11129. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  11130. }
  11131. xi = Math.cos(theta + dTheta) * rx + cx;
  11132. yi = Math.sin(theta + dTheta) * ry + cy;
  11133. break;
  11134. case CMD$1.R:
  11135. x0 = xi = data[i++];
  11136. y0 = yi = data[i++];
  11137. var width = data[i++];
  11138. var height = data[i++];
  11139. x1 = x0 + width;
  11140. y1 = y0 + height;
  11141. if (isStroke) {
  11142. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  11143. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  11144. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  11145. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  11146. return true;
  11147. }
  11148. }
  11149. else {
  11150. w += windingLine(x1, y0, x1, y1, x, y);
  11151. w += windingLine(x0, y1, x0, y0, x, y);
  11152. }
  11153. break;
  11154. case CMD$1.Z:
  11155. if (isStroke) {
  11156. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  11157. return true;
  11158. }
  11159. }
  11160. else {
  11161. w += windingLine(xi, yi, x0, y0, x, y);
  11162. }
  11163. xi = x0;
  11164. yi = y0;
  11165. break;
  11166. }
  11167. }
  11168. if (!isStroke && !isAroundEqual(yi, y0)) {
  11169. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  11170. }
  11171. return w !== 0;
  11172. }
  11173. function contain(pathProxy, x, y) {
  11174. return containPath(pathProxy, 0, false, x, y);
  11175. }
  11176. function containStroke$4(pathProxy, lineWidth, x, y) {
  11177. return containPath(pathProxy, lineWidth, true, x, y);
  11178. }
  11179. var DEFAULT_PATH_STYLE = defaults({
  11180. fill: '#000',
  11181. stroke: null,
  11182. strokePercent: 1,
  11183. fillOpacity: 1,
  11184. strokeOpacity: 1,
  11185. lineDashOffset: 0,
  11186. lineWidth: 1,
  11187. lineCap: 'butt',
  11188. miterLimit: 10,
  11189. strokeNoScale: false,
  11190. strokeFirst: false
  11191. }, DEFAULT_COMMON_STYLE);
  11192. var DEFAULT_PATH_ANIMATION_PROPS = {
  11193. style: defaults({
  11194. fill: true,
  11195. stroke: true,
  11196. strokePercent: true,
  11197. fillOpacity: true,
  11198. strokeOpacity: true,
  11199. lineDashOffset: true,
  11200. lineWidth: true,
  11201. miterLimit: true
  11202. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11203. };
  11204. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  11205. 'culling', 'z', 'z2', 'zlevel', 'parent'
  11206. ]);
  11207. var Path = (function (_super) {
  11208. __extends(Path, _super);
  11209. function Path(opts) {
  11210. return _super.call(this, opts) || this;
  11211. }
  11212. Path.prototype.update = function () {
  11213. var _this = this;
  11214. _super.prototype.update.call(this);
  11215. var style = this.style;
  11216. if (style.decal) {
  11217. var decalEl = this._decalEl = this._decalEl || new Path();
  11218. if (decalEl.buildPath === Path.prototype.buildPath) {
  11219. decalEl.buildPath = function (ctx) {
  11220. _this.buildPath(ctx, _this.shape);
  11221. };
  11222. }
  11223. decalEl.silent = true;
  11224. var decalElStyle = decalEl.style;
  11225. for (var key in style) {
  11226. if (decalElStyle[key] !== style[key]) {
  11227. decalElStyle[key] = style[key];
  11228. }
  11229. }
  11230. decalElStyle.fill = style.fill ? style.decal : null;
  11231. decalElStyle.decal = null;
  11232. decalElStyle.shadowColor = null;
  11233. style.strokeFirst && (decalElStyle.stroke = null);
  11234. for (var i = 0; i < pathCopyParams.length; ++i) {
  11235. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  11236. }
  11237. decalEl.__dirty |= REDRAW_BIT;
  11238. }
  11239. else if (this._decalEl) {
  11240. this._decalEl = null;
  11241. }
  11242. };
  11243. Path.prototype.getDecalElement = function () {
  11244. return this._decalEl;
  11245. };
  11246. Path.prototype._init = function (props) {
  11247. var keysArr = keys(props);
  11248. this.shape = this.getDefaultShape();
  11249. var defaultStyle = this.getDefaultStyle();
  11250. if (defaultStyle) {
  11251. this.useStyle(defaultStyle);
  11252. }
  11253. for (var i = 0; i < keysArr.length; i++) {
  11254. var key = keysArr[i];
  11255. var value = props[key];
  11256. if (key === 'style') {
  11257. if (!this.style) {
  11258. this.useStyle(value);
  11259. }
  11260. else {
  11261. extend(this.style, value);
  11262. }
  11263. }
  11264. else if (key === 'shape') {
  11265. extend(this.shape, value);
  11266. }
  11267. else {
  11268. _super.prototype.attrKV.call(this, key, value);
  11269. }
  11270. }
  11271. if (!this.style) {
  11272. this.useStyle({});
  11273. }
  11274. };
  11275. Path.prototype.getDefaultStyle = function () {
  11276. return null;
  11277. };
  11278. Path.prototype.getDefaultShape = function () {
  11279. return {};
  11280. };
  11281. Path.prototype.canBeInsideText = function () {
  11282. return this.hasFill();
  11283. };
  11284. Path.prototype.getInsideTextFill = function () {
  11285. var pathFill = this.style.fill;
  11286. if (pathFill !== 'none') {
  11287. if (isString(pathFill)) {
  11288. var fillLum = lum(pathFill, 0);
  11289. if (fillLum > 0.5) {
  11290. return DARK_LABEL_COLOR;
  11291. }
  11292. else if (fillLum > 0.2) {
  11293. return LIGHTER_LABEL_COLOR;
  11294. }
  11295. return LIGHT_LABEL_COLOR;
  11296. }
  11297. else if (pathFill) {
  11298. return LIGHT_LABEL_COLOR;
  11299. }
  11300. }
  11301. return DARK_LABEL_COLOR;
  11302. };
  11303. Path.prototype.getInsideTextStroke = function (textFill) {
  11304. var pathFill = this.style.fill;
  11305. if (isString(pathFill)) {
  11306. var zr = this.__zr;
  11307. var isDarkMode = !!(zr && zr.isDarkMode());
  11308. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  11309. if (isDarkMode === isDarkLabel) {
  11310. return pathFill;
  11311. }
  11312. }
  11313. };
  11314. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  11315. Path.prototype.pathUpdated = function () {
  11316. this.__dirty &= ~SHAPE_CHANGED_BIT;
  11317. };
  11318. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  11319. !this.path && this.createPathProxy();
  11320. this.path.beginPath();
  11321. this.buildPath(this.path, this.shape, inBatch);
  11322. return this.path;
  11323. };
  11324. Path.prototype.createPathProxy = function () {
  11325. this.path = new PathProxy(false);
  11326. };
  11327. Path.prototype.hasStroke = function () {
  11328. var style = this.style;
  11329. var stroke = style.stroke;
  11330. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  11331. };
  11332. Path.prototype.hasFill = function () {
  11333. var style = this.style;
  11334. var fill = style.fill;
  11335. return fill != null && fill !== 'none';
  11336. };
  11337. Path.prototype.getBoundingRect = function () {
  11338. var rect = this._rect;
  11339. var style = this.style;
  11340. var needsUpdateRect = !rect;
  11341. if (needsUpdateRect) {
  11342. var firstInvoke = false;
  11343. if (!this.path) {
  11344. firstInvoke = true;
  11345. this.createPathProxy();
  11346. }
  11347. var path = this.path;
  11348. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  11349. path.beginPath();
  11350. this.buildPath(path, this.shape, false);
  11351. this.pathUpdated();
  11352. }
  11353. rect = path.getBoundingRect();
  11354. }
  11355. this._rect = rect;
  11356. if (this.hasStroke() && this.path && this.path.len() > 0) {
  11357. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  11358. if (this.__dirty || needsUpdateRect) {
  11359. rectStroke.copy(rect);
  11360. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11361. var w = style.lineWidth;
  11362. if (!this.hasFill()) {
  11363. var strokeContainThreshold = this.strokeContainThreshold;
  11364. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  11365. }
  11366. if (lineScale > 1e-10) {
  11367. rectStroke.width += w / lineScale;
  11368. rectStroke.height += w / lineScale;
  11369. rectStroke.x -= w / lineScale / 2;
  11370. rectStroke.y -= w / lineScale / 2;
  11371. }
  11372. }
  11373. return rectStroke;
  11374. }
  11375. return rect;
  11376. };
  11377. Path.prototype.contain = function (x, y) {
  11378. var localPos = this.transformCoordToLocal(x, y);
  11379. var rect = this.getBoundingRect();
  11380. var style = this.style;
  11381. x = localPos[0];
  11382. y = localPos[1];
  11383. if (rect.contain(x, y)) {
  11384. var pathProxy = this.path;
  11385. if (this.hasStroke()) {
  11386. var lineWidth = style.lineWidth;
  11387. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11388. if (lineScale > 1e-10) {
  11389. if (!this.hasFill()) {
  11390. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11391. }
  11392. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  11393. return true;
  11394. }
  11395. }
  11396. }
  11397. if (this.hasFill()) {
  11398. return contain(pathProxy, x, y);
  11399. }
  11400. }
  11401. return false;
  11402. };
  11403. Path.prototype.dirtyShape = function () {
  11404. this.__dirty |= SHAPE_CHANGED_BIT;
  11405. if (this._rect) {
  11406. this._rect = null;
  11407. }
  11408. if (this._decalEl) {
  11409. this._decalEl.dirtyShape();
  11410. }
  11411. this.markRedraw();
  11412. };
  11413. Path.prototype.dirty = function () {
  11414. this.dirtyStyle();
  11415. this.dirtyShape();
  11416. };
  11417. Path.prototype.animateShape = function (loop) {
  11418. return this.animate('shape', loop);
  11419. };
  11420. Path.prototype.updateDuringAnimation = function (targetKey) {
  11421. if (targetKey === 'style') {
  11422. this.dirtyStyle();
  11423. }
  11424. else if (targetKey === 'shape') {
  11425. this.dirtyShape();
  11426. }
  11427. else {
  11428. this.markRedraw();
  11429. }
  11430. };
  11431. Path.prototype.attrKV = function (key, value) {
  11432. if (key === 'shape') {
  11433. this.setShape(value);
  11434. }
  11435. else {
  11436. _super.prototype.attrKV.call(this, key, value);
  11437. }
  11438. };
  11439. Path.prototype.setShape = function (keyOrObj, value) {
  11440. var shape = this.shape;
  11441. if (!shape) {
  11442. shape = this.shape = {};
  11443. }
  11444. if (typeof keyOrObj === 'string') {
  11445. shape[keyOrObj] = value;
  11446. }
  11447. else {
  11448. extend(shape, keyOrObj);
  11449. }
  11450. this.dirtyShape();
  11451. return this;
  11452. };
  11453. Path.prototype.shapeChanged = function () {
  11454. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  11455. };
  11456. Path.prototype.createStyle = function (obj) {
  11457. return createObject(DEFAULT_PATH_STYLE, obj);
  11458. };
  11459. Path.prototype._innerSaveToNormal = function (toState) {
  11460. _super.prototype._innerSaveToNormal.call(this, toState);
  11461. var normalState = this._normalState;
  11462. if (toState.shape && !normalState.shape) {
  11463. normalState.shape = extend({}, this.shape);
  11464. }
  11465. };
  11466. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  11467. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  11468. var needsRestoreToNormal = !(state && keepCurrentStates);
  11469. var targetShape;
  11470. if (state && state.shape) {
  11471. if (transition) {
  11472. if (keepCurrentStates) {
  11473. targetShape = state.shape;
  11474. }
  11475. else {
  11476. targetShape = extend({}, normalState.shape);
  11477. extend(targetShape, state.shape);
  11478. }
  11479. }
  11480. else {
  11481. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11482. extend(targetShape, state.shape);
  11483. }
  11484. }
  11485. else if (needsRestoreToNormal) {
  11486. targetShape = normalState.shape;
  11487. }
  11488. if (targetShape) {
  11489. if (transition) {
  11490. this.shape = extend({}, this.shape);
  11491. var targetShapePrimaryProps = {};
  11492. var shapeKeys = keys(targetShape);
  11493. for (var i = 0; i < shapeKeys.length; i++) {
  11494. var key = shapeKeys[i];
  11495. if (typeof targetShape[key] === 'object') {
  11496. this.shape[key] = targetShape[key];
  11497. }
  11498. else {
  11499. targetShapePrimaryProps[key] = targetShape[key];
  11500. }
  11501. }
  11502. this._transitionState(stateName, {
  11503. shape: targetShapePrimaryProps
  11504. }, animationCfg);
  11505. }
  11506. else {
  11507. this.shape = targetShape;
  11508. this.dirtyShape();
  11509. }
  11510. }
  11511. };
  11512. Path.prototype._mergeStates = function (states) {
  11513. var mergedState = _super.prototype._mergeStates.call(this, states);
  11514. var mergedShape;
  11515. for (var i = 0; i < states.length; i++) {
  11516. var state = states[i];
  11517. if (state.shape) {
  11518. mergedShape = mergedShape || {};
  11519. this._mergeStyle(mergedShape, state.shape);
  11520. }
  11521. }
  11522. if (mergedShape) {
  11523. mergedState.shape = mergedShape;
  11524. }
  11525. return mergedState;
  11526. };
  11527. Path.prototype.getAnimationStyleProps = function () {
  11528. return DEFAULT_PATH_ANIMATION_PROPS;
  11529. };
  11530. Path.prototype.isZeroArea = function () {
  11531. return false;
  11532. };
  11533. Path.extend = function (defaultProps) {
  11534. var Sub = (function (_super) {
  11535. __extends(Sub, _super);
  11536. function Sub(opts) {
  11537. var _this = _super.call(this, opts) || this;
  11538. defaultProps.init && defaultProps.init.call(_this, opts);
  11539. return _this;
  11540. }
  11541. Sub.prototype.getDefaultStyle = function () {
  11542. return clone(defaultProps.style);
  11543. };
  11544. Sub.prototype.getDefaultShape = function () {
  11545. return clone(defaultProps.shape);
  11546. };
  11547. return Sub;
  11548. }(Path));
  11549. for (var key in defaultProps) {
  11550. if (typeof defaultProps[key] === 'function') {
  11551. Sub.prototype[key] = defaultProps[key];
  11552. }
  11553. }
  11554. return Sub;
  11555. };
  11556. Path.initDefaultProps = (function () {
  11557. var pathProto = Path.prototype;
  11558. pathProto.type = 'path';
  11559. pathProto.strokeContainThreshold = 5;
  11560. pathProto.segmentIgnoreThreshold = 0;
  11561. pathProto.subPixelOptimize = false;
  11562. pathProto.autoBatch = false;
  11563. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11564. })();
  11565. return Path;
  11566. }(Displayable));
  11567. var DEFAULT_TSPAN_STYLE = defaults({
  11568. strokeFirst: true,
  11569. font: DEFAULT_FONT,
  11570. x: 0,
  11571. y: 0,
  11572. textAlign: 'left',
  11573. textBaseline: 'top',
  11574. miterLimit: 2
  11575. }, DEFAULT_PATH_STYLE);
  11576. var TSpan = (function (_super) {
  11577. __extends(TSpan, _super);
  11578. function TSpan() {
  11579. return _super !== null && _super.apply(this, arguments) || this;
  11580. }
  11581. TSpan.prototype.hasStroke = function () {
  11582. return tSpanHasStroke(this.style);
  11583. };
  11584. TSpan.prototype.hasFill = function () {
  11585. var style = this.style;
  11586. var fill = style.fill;
  11587. return fill != null && fill !== 'none';
  11588. };
  11589. TSpan.prototype.createStyle = function (obj) {
  11590. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11591. };
  11592. TSpan.prototype.setBoundingRect = function (rect) {
  11593. this._rect = rect;
  11594. };
  11595. TSpan.prototype.getBoundingRect = function () {
  11596. if (!this._rect) {
  11597. this._rect = tSpanCreateBoundingRect(this.style);
  11598. }
  11599. return this._rect;
  11600. };
  11601. TSpan.initDefaultProps = (function () {
  11602. var tspanProto = TSpan.prototype;
  11603. tspanProto.dirtyRectTolerance = 10;
  11604. })();
  11605. return TSpan;
  11606. }(Displayable));
  11607. TSpan.prototype.type = 'tspan';
  11608. var DEFAULT_IMAGE_STYLE = defaults({
  11609. x: 0,
  11610. y: 0
  11611. }, DEFAULT_COMMON_STYLE);
  11612. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11613. style: defaults({
  11614. x: true,
  11615. y: true,
  11616. width: true,
  11617. height: true,
  11618. sx: true,
  11619. sy: true,
  11620. sWidth: true,
  11621. sHeight: true
  11622. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11623. };
  11624. function isImageLike(source) {
  11625. return !!(source
  11626. && typeof source !== 'string'
  11627. && source.width && source.height);
  11628. }
  11629. var ZRImage = (function (_super) {
  11630. __extends(ZRImage, _super);
  11631. function ZRImage() {
  11632. return _super !== null && _super.apply(this, arguments) || this;
  11633. }
  11634. ZRImage.prototype.createStyle = function (obj) {
  11635. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11636. };
  11637. ZRImage.prototype._getSize = function (dim) {
  11638. var style = this.style;
  11639. var size = style[dim];
  11640. if (size != null) {
  11641. return size;
  11642. }
  11643. var imageSource = isImageLike(style.image)
  11644. ? style.image : this.__image;
  11645. if (!imageSource) {
  11646. return 0;
  11647. }
  11648. var otherDim = dim === 'width' ? 'height' : 'width';
  11649. var otherDimSize = style[otherDim];
  11650. if (otherDimSize == null) {
  11651. return imageSource[dim];
  11652. }
  11653. else {
  11654. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11655. }
  11656. };
  11657. ZRImage.prototype.getWidth = function () {
  11658. return this._getSize('width');
  11659. };
  11660. ZRImage.prototype.getHeight = function () {
  11661. return this._getSize('height');
  11662. };
  11663. ZRImage.prototype.getAnimationStyleProps = function () {
  11664. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11665. };
  11666. ZRImage.prototype.getBoundingRect = function () {
  11667. var style = this.style;
  11668. if (!this._rect) {
  11669. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11670. }
  11671. return this._rect;
  11672. };
  11673. return ZRImage;
  11674. }(Displayable));
  11675. ZRImage.prototype.type = 'image';
  11676. function buildPath(ctx, shape) {
  11677. var x = shape.x;
  11678. var y = shape.y;
  11679. var width = shape.width;
  11680. var height = shape.height;
  11681. var r = shape.r;
  11682. var r1;
  11683. var r2;
  11684. var r3;
  11685. var r4;
  11686. if (width < 0) {
  11687. x = x + width;
  11688. width = -width;
  11689. }
  11690. if (height < 0) {
  11691. y = y + height;
  11692. height = -height;
  11693. }
  11694. if (typeof r === 'number') {
  11695. r1 = r2 = r3 = r4 = r;
  11696. }
  11697. else if (r instanceof Array) {
  11698. if (r.length === 1) {
  11699. r1 = r2 = r3 = r4 = r[0];
  11700. }
  11701. else if (r.length === 2) {
  11702. r1 = r3 = r[0];
  11703. r2 = r4 = r[1];
  11704. }
  11705. else if (r.length === 3) {
  11706. r1 = r[0];
  11707. r2 = r4 = r[1];
  11708. r3 = r[2];
  11709. }
  11710. else {
  11711. r1 = r[0];
  11712. r2 = r[1];
  11713. r3 = r[2];
  11714. r4 = r[3];
  11715. }
  11716. }
  11717. else {
  11718. r1 = r2 = r3 = r4 = 0;
  11719. }
  11720. var total;
  11721. if (r1 + r2 > width) {
  11722. total = r1 + r2;
  11723. r1 *= width / total;
  11724. r2 *= width / total;
  11725. }
  11726. if (r3 + r4 > width) {
  11727. total = r3 + r4;
  11728. r3 *= width / total;
  11729. r4 *= width / total;
  11730. }
  11731. if (r2 + r3 > height) {
  11732. total = r2 + r3;
  11733. r2 *= height / total;
  11734. r3 *= height / total;
  11735. }
  11736. if (r1 + r4 > height) {
  11737. total = r1 + r4;
  11738. r1 *= height / total;
  11739. r4 *= height / total;
  11740. }
  11741. ctx.moveTo(x + r1, y);
  11742. ctx.lineTo(x + width - r2, y);
  11743. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11744. ctx.lineTo(x + width, y + height - r3);
  11745. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11746. ctx.lineTo(x + r4, y + height);
  11747. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11748. ctx.lineTo(x, y + r1);
  11749. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11750. }
  11751. var round$1 = Math.round;
  11752. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11753. if (!inputShape) {
  11754. return;
  11755. }
  11756. var x1 = inputShape.x1;
  11757. var x2 = inputShape.x2;
  11758. var y1 = inputShape.y1;
  11759. var y2 = inputShape.y2;
  11760. outputShape.x1 = x1;
  11761. outputShape.x2 = x2;
  11762. outputShape.y1 = y1;
  11763. outputShape.y2 = y2;
  11764. var lineWidth = style && style.lineWidth;
  11765. if (!lineWidth) {
  11766. return outputShape;
  11767. }
  11768. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11769. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11770. }
  11771. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11772. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11773. }
  11774. return outputShape;
  11775. }
  11776. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11777. if (!inputShape) {
  11778. return;
  11779. }
  11780. var originX = inputShape.x;
  11781. var originY = inputShape.y;
  11782. var originWidth = inputShape.width;
  11783. var originHeight = inputShape.height;
  11784. outputShape.x = originX;
  11785. outputShape.y = originY;
  11786. outputShape.width = originWidth;
  11787. outputShape.height = originHeight;
  11788. var lineWidth = style && style.lineWidth;
  11789. if (!lineWidth) {
  11790. return outputShape;
  11791. }
  11792. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11793. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11794. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11795. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11796. return outputShape;
  11797. }
  11798. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11799. if (!lineWidth) {
  11800. return position;
  11801. }
  11802. var doubledPosition = round$1(position * 2);
  11803. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11804. ? doubledPosition / 2
  11805. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11806. }
  11807. var RectShape = (function () {
  11808. function RectShape() {
  11809. this.x = 0;
  11810. this.y = 0;
  11811. this.width = 0;
  11812. this.height = 0;
  11813. }
  11814. return RectShape;
  11815. }());
  11816. var subPixelOptimizeOutputShape = {};
  11817. var Rect = (function (_super) {
  11818. __extends(Rect, _super);
  11819. function Rect(opts) {
  11820. return _super.call(this, opts) || this;
  11821. }
  11822. Rect.prototype.getDefaultShape = function () {
  11823. return new RectShape();
  11824. };
  11825. Rect.prototype.buildPath = function (ctx, shape) {
  11826. var x;
  11827. var y;
  11828. var width;
  11829. var height;
  11830. if (this.subPixelOptimize) {
  11831. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11832. x = optimizedShape.x;
  11833. y = optimizedShape.y;
  11834. width = optimizedShape.width;
  11835. height = optimizedShape.height;
  11836. optimizedShape.r = shape.r;
  11837. shape = optimizedShape;
  11838. }
  11839. else {
  11840. x = shape.x;
  11841. y = shape.y;
  11842. width = shape.width;
  11843. height = shape.height;
  11844. }
  11845. if (!shape.r) {
  11846. ctx.rect(x, y, width, height);
  11847. }
  11848. else {
  11849. buildPath(ctx, shape);
  11850. }
  11851. };
  11852. Rect.prototype.isZeroArea = function () {
  11853. return !this.shape.width || !this.shape.height;
  11854. };
  11855. return Rect;
  11856. }(Path));
  11857. Rect.prototype.type = 'rect';
  11858. var DEFAULT_RICH_TEXT_COLOR = {
  11859. fill: '#000'
  11860. };
  11861. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11862. var tmpCITOverflowAreaOut = {};
  11863. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11864. style: defaults({
  11865. fill: true,
  11866. stroke: true,
  11867. fillOpacity: true,
  11868. strokeOpacity: true,
  11869. lineWidth: true,
  11870. fontSize: true,
  11871. lineHeight: true,
  11872. width: true,
  11873. height: true,
  11874. textShadowColor: true,
  11875. textShadowBlur: true,
  11876. textShadowOffsetX: true,
  11877. textShadowOffsetY: true,
  11878. backgroundColor: true,
  11879. padding: true,
  11880. borderColor: true,
  11881. borderWidth: true,
  11882. borderRadius: true
  11883. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11884. };
  11885. var ZRText = (function (_super) {
  11886. __extends(ZRText, _super);
  11887. function ZRText(opts) {
  11888. var _this = _super.call(this) || this;
  11889. _this.type = 'text';
  11890. _this._children = [];
  11891. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11892. _this.attr(opts);
  11893. return _this;
  11894. }
  11895. ZRText.prototype.childrenRef = function () {
  11896. return this._children;
  11897. };
  11898. ZRText.prototype.update = function () {
  11899. _super.prototype.update.call(this);
  11900. if (this.styleChanged()) {
  11901. this._updateSubTexts();
  11902. }
  11903. for (var i = 0; i < this._children.length; i++) {
  11904. var child = this._children[i];
  11905. child.zlevel = this.zlevel;
  11906. child.z = this.z;
  11907. child.z2 = this.z2;
  11908. child.culling = this.culling;
  11909. child.cursor = this.cursor;
  11910. child.invisible = this.invisible;
  11911. }
  11912. };
  11913. ZRText.prototype.updateTransform = function () {
  11914. var innerTransformable = this.innerTransformable;
  11915. if (innerTransformable) {
  11916. innerTransformable.updateTransform();
  11917. if (innerTransformable.transform) {
  11918. this.transform = innerTransformable.transform;
  11919. }
  11920. }
  11921. else {
  11922. _super.prototype.updateTransform.call(this);
  11923. }
  11924. };
  11925. ZRText.prototype.getLocalTransform = function (m) {
  11926. var innerTransformable = this.innerTransformable;
  11927. return innerTransformable
  11928. ? innerTransformable.getLocalTransform(m)
  11929. : _super.prototype.getLocalTransform.call(this, m);
  11930. };
  11931. ZRText.prototype.getComputedTransform = function () {
  11932. if (this.__hostTarget) {
  11933. this.__hostTarget.getComputedTransform();
  11934. this.__hostTarget.updateInnerText(true);
  11935. }
  11936. return _super.prototype.getComputedTransform.call(this);
  11937. };
  11938. ZRText.prototype._updateSubTexts = function () {
  11939. this._childCursor = 0;
  11940. normalizeTextStyle(this.style);
  11941. this.style.rich
  11942. ? this._updateRichTexts()
  11943. : this._updatePlainTexts();
  11944. this._children.length = this._childCursor;
  11945. this.styleUpdated();
  11946. };
  11947. ZRText.prototype.addSelfToZr = function (zr) {
  11948. _super.prototype.addSelfToZr.call(this, zr);
  11949. for (var i = 0; i < this._children.length; i++) {
  11950. this._children[i].__zr = zr;
  11951. }
  11952. };
  11953. ZRText.prototype.removeSelfFromZr = function (zr) {
  11954. _super.prototype.removeSelfFromZr.call(this, zr);
  11955. for (var i = 0; i < this._children.length; i++) {
  11956. this._children[i].__zr = null;
  11957. }
  11958. };
  11959. ZRText.prototype.getBoundingRect = function () {
  11960. if (this.styleChanged()) {
  11961. this._updateSubTexts();
  11962. }
  11963. if (!this._rect) {
  11964. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11965. var children = this._children;
  11966. var tmpMat = [];
  11967. var rect = null;
  11968. for (var i = 0; i < children.length; i++) {
  11969. var child = children[i];
  11970. var childRect = child.getBoundingRect();
  11971. var transform = child.getLocalTransform(tmpMat);
  11972. if (transform) {
  11973. tmpRect.copy(childRect);
  11974. tmpRect.applyTransform(transform);
  11975. rect = rect || tmpRect.clone();
  11976. rect.union(tmpRect);
  11977. }
  11978. else {
  11979. rect = rect || childRect.clone();
  11980. rect.union(childRect);
  11981. }
  11982. }
  11983. this._rect = rect || tmpRect;
  11984. }
  11985. return this._rect;
  11986. };
  11987. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11988. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11989. };
  11990. ZRText.prototype.setTextContent = function (textContent) {
  11991. if ("development" !== 'production') {
  11992. throw new Error('Can\'t attach text on another text');
  11993. }
  11994. };
  11995. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11996. if (!sourceStyle) {
  11997. return targetStyle;
  11998. }
  11999. var sourceRich = sourceStyle.rich;
  12000. var targetRich = targetStyle.rich || (sourceRich && {});
  12001. extend(targetStyle, sourceStyle);
  12002. if (sourceRich && targetRich) {
  12003. this._mergeRich(targetRich, sourceRich);
  12004. targetStyle.rich = targetRich;
  12005. }
  12006. else if (targetRich) {
  12007. targetStyle.rich = targetRich;
  12008. }
  12009. return targetStyle;
  12010. };
  12011. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  12012. var richNames = keys(sourceRich);
  12013. for (var i = 0; i < richNames.length; i++) {
  12014. var richName = richNames[i];
  12015. targetRich[richName] = targetRich[richName] || {};
  12016. extend(targetRich[richName], sourceRich[richName]);
  12017. }
  12018. };
  12019. ZRText.prototype.getAnimationStyleProps = function () {
  12020. return DEFAULT_TEXT_ANIMATION_PROPS;
  12021. };
  12022. ZRText.prototype._getOrCreateChild = function (Ctor) {
  12023. var child = this._children[this._childCursor];
  12024. if (!child || !(child instanceof Ctor)) {
  12025. child = new Ctor();
  12026. }
  12027. this._children[this._childCursor++] = child;
  12028. child.__zr = this.__zr;
  12029. child.parent = this;
  12030. return child;
  12031. };
  12032. ZRText.prototype._updatePlainTexts = function () {
  12033. var style = this.style;
  12034. var textFont = style.font || DEFAULT_FONT;
  12035. var textPadding = style.padding;
  12036. var defaultStyle = this._defaultStyle;
  12037. var baseX = style.x || 0;
  12038. var baseY = style.y || 0;
  12039. var textAlign = style.align || defaultStyle.align || 'left';
  12040. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  12041. calcInnerTextOverflowArea(tmpCITOverflowAreaOut, defaultStyle.overflowRect, baseX, baseY, textAlign, verticalAlign);
  12042. baseX = tmpCITOverflowAreaOut.baseX;
  12043. baseY = tmpCITOverflowAreaOut.baseY;
  12044. var text = getStyleText(style);
  12045. var contentBlock = parsePlainText(text, style, tmpCITOverflowAreaOut.outerWidth, tmpCITOverflowAreaOut.outerHeight);
  12046. var needDrawBg = needDrawBackground(style);
  12047. var bgColorDrawn = !!(style.backgroundColor);
  12048. var outerHeight = contentBlock.outerHeight;
  12049. var outerWidth = contentBlock.outerWidth;
  12050. var textLines = contentBlock.lines;
  12051. var lineHeight = contentBlock.lineHeight;
  12052. this.isTruncated = !!contentBlock.isTruncated;
  12053. var textX = baseX;
  12054. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  12055. if (needDrawBg || textPadding) {
  12056. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  12057. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  12058. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  12059. }
  12060. textY += lineHeight / 2;
  12061. if (textPadding) {
  12062. textX = getTextXForPadding(baseX, textAlign, textPadding);
  12063. if (verticalAlign === 'top') {
  12064. textY += textPadding[0];
  12065. }
  12066. else if (verticalAlign === 'bottom') {
  12067. textY -= textPadding[2];
  12068. }
  12069. }
  12070. var defaultLineWidth = 0;
  12071. var usingDefaultStroke = false;
  12072. var useDefaultFill = false;
  12073. var textFill = getFill('fill' in style
  12074. ? style.fill
  12075. : (useDefaultFill = true, defaultStyle.fill));
  12076. var textStroke = getStroke('stroke' in style
  12077. ? style.stroke
  12078. : (!bgColorDrawn
  12079. && (!defaultStyle.autoStroke || useDefaultFill))
  12080. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, usingDefaultStroke = true, defaultStyle.stroke)
  12081. : null);
  12082. var hasShadow = style.textShadowBlur > 0;
  12083. for (var i = 0; i < textLines.length; i++) {
  12084. var el = this._getOrCreateChild(TSpan);
  12085. var subElStyle = el.createStyle();
  12086. el.useStyle(subElStyle);
  12087. subElStyle.text = textLines[i];
  12088. subElStyle.x = textX;
  12089. subElStyle.y = textY;
  12090. if (textAlign) {
  12091. subElStyle.textAlign = textAlign;
  12092. }
  12093. subElStyle.textBaseline = 'middle';
  12094. subElStyle.opacity = style.opacity;
  12095. subElStyle.strokeFirst = true;
  12096. if (hasShadow) {
  12097. subElStyle.shadowBlur = style.textShadowBlur || 0;
  12098. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  12099. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  12100. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  12101. }
  12102. subElStyle.stroke = textStroke;
  12103. subElStyle.fill = textFill;
  12104. if (textStroke) {
  12105. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  12106. subElStyle.lineDash = style.lineDash;
  12107. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  12108. }
  12109. subElStyle.font = textFont;
  12110. setSeparateFont(subElStyle, style);
  12111. textY += lineHeight;
  12112. el.setBoundingRect(tSpanCreateBoundingRect2(subElStyle, contentBlock.contentWidth, contentBlock.calculatedLineHeight, usingDefaultStroke ? 0 : null));
  12113. }
  12114. };
  12115. ZRText.prototype._updateRichTexts = function () {
  12116. var style = this.style;
  12117. var defaultStyle = this._defaultStyle;
  12118. var textAlign = style.align || defaultStyle.align;
  12119. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  12120. var baseX = style.x || 0;
  12121. var baseY = style.y || 0;
  12122. calcInnerTextOverflowArea(tmpCITOverflowAreaOut, defaultStyle.overflowRect, baseX, baseY, textAlign, verticalAlign);
  12123. baseX = tmpCITOverflowAreaOut.baseX;
  12124. baseY = tmpCITOverflowAreaOut.baseY;
  12125. var text = getStyleText(style);
  12126. var contentBlock = parseRichText(text, style, tmpCITOverflowAreaOut.outerWidth, tmpCITOverflowAreaOut.outerHeight, textAlign);
  12127. var contentWidth = contentBlock.width;
  12128. var outerWidth = contentBlock.outerWidth;
  12129. var outerHeight = contentBlock.outerHeight;
  12130. var textPadding = style.padding;
  12131. this.isTruncated = !!contentBlock.isTruncated;
  12132. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  12133. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  12134. var xLeft = boxX;
  12135. var lineTop = boxY;
  12136. if (textPadding) {
  12137. xLeft += textPadding[3];
  12138. lineTop += textPadding[0];
  12139. }
  12140. var xRight = xLeft + contentWidth;
  12141. if (needDrawBackground(style)) {
  12142. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  12143. }
  12144. var bgColorDrawn = !!(style.backgroundColor);
  12145. for (var i = 0; i < contentBlock.lines.length; i++) {
  12146. var line = contentBlock.lines[i];
  12147. var tokens = line.tokens;
  12148. var tokenCount = tokens.length;
  12149. var lineHeight = line.lineHeight;
  12150. var remainedWidth = line.width;
  12151. var leftIndex = 0;
  12152. var lineXLeft = xLeft;
  12153. var lineXRight = xRight;
  12154. var rightIndex = tokenCount - 1;
  12155. var token = void 0;
  12156. while (leftIndex < tokenCount
  12157. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  12158. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  12159. remainedWidth -= token.width;
  12160. lineXLeft += token.width;
  12161. leftIndex++;
  12162. }
  12163. while (rightIndex >= 0
  12164. && (token = tokens[rightIndex], token.align === 'right')) {
  12165. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  12166. remainedWidth -= token.width;
  12167. lineXRight -= token.width;
  12168. rightIndex--;
  12169. }
  12170. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  12171. while (leftIndex <= rightIndex) {
  12172. token = tokens[leftIndex];
  12173. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  12174. lineXLeft += token.width;
  12175. leftIndex++;
  12176. }
  12177. lineTop += lineHeight;
  12178. }
  12179. };
  12180. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  12181. var tokenStyle = style.rich[token.styleName] || {};
  12182. tokenStyle.text = token.text;
  12183. var verticalAlign = token.verticalAlign;
  12184. var y = lineTop + lineHeight / 2;
  12185. if (verticalAlign === 'top') {
  12186. y = lineTop + token.height / 2;
  12187. }
  12188. else if (verticalAlign === 'bottom') {
  12189. y = lineTop + lineHeight - token.height / 2;
  12190. }
  12191. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  12192. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  12193. ? x - token.width
  12194. : textAlign === 'center'
  12195. ? x - token.width / 2
  12196. : x, y - token.height / 2, token.width, token.height);
  12197. var bgColorDrawn = !!tokenStyle.backgroundColor;
  12198. var textPadding = token.textPadding;
  12199. if (textPadding) {
  12200. x = getTextXForPadding(x, textAlign, textPadding);
  12201. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  12202. }
  12203. var el = this._getOrCreateChild(TSpan);
  12204. var subElStyle = el.createStyle();
  12205. el.useStyle(subElStyle);
  12206. var defaultStyle = this._defaultStyle;
  12207. var useDefaultFill = false;
  12208. var defaultLineWidth = 0;
  12209. var usingDefaultStroke = false;
  12210. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  12211. : 'fill' in style ? style.fill
  12212. : (useDefaultFill = true, defaultStyle.fill));
  12213. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  12214. : 'stroke' in style ? style.stroke
  12215. : (!bgColorDrawn
  12216. && !parentBgColorDrawn
  12217. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, usingDefaultStroke = true, defaultStyle.stroke)
  12218. : null);
  12219. var hasShadow = tokenStyle.textShadowBlur > 0
  12220. || style.textShadowBlur > 0;
  12221. subElStyle.text = token.text;
  12222. subElStyle.x = x;
  12223. subElStyle.y = y;
  12224. if (hasShadow) {
  12225. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  12226. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  12227. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  12228. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  12229. }
  12230. subElStyle.textAlign = textAlign;
  12231. subElStyle.textBaseline = 'middle';
  12232. subElStyle.font = token.font || DEFAULT_FONT;
  12233. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  12234. setSeparateFont(subElStyle, tokenStyle);
  12235. if (textStroke) {
  12236. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  12237. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  12238. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  12239. subElStyle.stroke = textStroke;
  12240. }
  12241. if (textFill) {
  12242. subElStyle.fill = textFill;
  12243. }
  12244. el.setBoundingRect(tSpanCreateBoundingRect2(subElStyle, token.contentWidth, token.contentHeight, usingDefaultStroke ? 0 : null));
  12245. };
  12246. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  12247. var textBackgroundColor = style.backgroundColor;
  12248. var textBorderWidth = style.borderWidth;
  12249. var textBorderColor = style.borderColor;
  12250. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  12251. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  12252. var textBorderRadius = style.borderRadius;
  12253. var self = this;
  12254. var rectEl;
  12255. var imgEl;
  12256. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  12257. rectEl = this._getOrCreateChild(Rect);
  12258. rectEl.useStyle(rectEl.createStyle());
  12259. rectEl.style.fill = null;
  12260. var rectShape = rectEl.shape;
  12261. rectShape.x = x;
  12262. rectShape.y = y;
  12263. rectShape.width = width;
  12264. rectShape.height = height;
  12265. rectShape.r = textBorderRadius;
  12266. rectEl.dirtyShape();
  12267. }
  12268. if (isPlainOrGradientBg) {
  12269. var rectStyle = rectEl.style;
  12270. rectStyle.fill = textBackgroundColor || null;
  12271. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  12272. }
  12273. else if (isImageBg) {
  12274. imgEl = this._getOrCreateChild(ZRImage);
  12275. imgEl.onload = function () {
  12276. self.dirtyStyle();
  12277. };
  12278. var imgStyle = imgEl.style;
  12279. imgStyle.image = textBackgroundColor.image;
  12280. imgStyle.x = x;
  12281. imgStyle.y = y;
  12282. imgStyle.width = width;
  12283. imgStyle.height = height;
  12284. }
  12285. if (textBorderWidth && textBorderColor) {
  12286. var rectStyle = rectEl.style;
  12287. rectStyle.lineWidth = textBorderWidth;
  12288. rectStyle.stroke = textBorderColor;
  12289. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  12290. rectStyle.lineDash = style.borderDash;
  12291. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  12292. rectEl.strokeContainThreshold = 0;
  12293. if (rectEl.hasFill() && rectEl.hasStroke()) {
  12294. rectStyle.strokeFirst = true;
  12295. rectStyle.lineWidth *= 2;
  12296. }
  12297. }
  12298. var commonStyle = (rectEl || imgEl).style;
  12299. commonStyle.shadowBlur = style.shadowBlur || 0;
  12300. commonStyle.shadowColor = style.shadowColor || 'transparent';
  12301. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  12302. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  12303. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  12304. };
  12305. ZRText.makeFont = function (style) {
  12306. var font = '';
  12307. if (hasSeparateFont(style)) {
  12308. font = [
  12309. style.fontStyle,
  12310. style.fontWeight,
  12311. parseFontSize(style.fontSize),
  12312. style.fontFamily || 'sans-serif'
  12313. ].join(' ');
  12314. }
  12315. return font && trim(font) || style.textFont || style.font;
  12316. };
  12317. return ZRText;
  12318. }(Displayable));
  12319. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  12320. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  12321. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  12322. function parseFontSize(fontSize) {
  12323. if (typeof fontSize === 'string'
  12324. && (fontSize.indexOf('px') !== -1
  12325. || fontSize.indexOf('rem') !== -1
  12326. || fontSize.indexOf('em') !== -1)) {
  12327. return fontSize;
  12328. }
  12329. else if (!isNaN(+fontSize)) {
  12330. return fontSize + 'px';
  12331. }
  12332. else {
  12333. return DEFAULT_FONT_SIZE + 'px';
  12334. }
  12335. }
  12336. function setSeparateFont(targetStyle, sourceStyle) {
  12337. for (var i = 0; i < FONT_PARTS.length; i++) {
  12338. var fontProp = FONT_PARTS[i];
  12339. var val = sourceStyle[fontProp];
  12340. if (val != null) {
  12341. targetStyle[fontProp] = val;
  12342. }
  12343. }
  12344. }
  12345. function hasSeparateFont(style) {
  12346. return style.fontSize != null || style.fontFamily || style.fontWeight;
  12347. }
  12348. function normalizeTextStyle(style) {
  12349. normalizeStyle(style);
  12350. each(style.rich, normalizeStyle);
  12351. return style;
  12352. }
  12353. function normalizeStyle(style) {
  12354. if (style) {
  12355. style.font = ZRText.makeFont(style);
  12356. var textAlign = style.align;
  12357. textAlign === 'middle' && (textAlign = 'center');
  12358. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  12359. var verticalAlign = style.verticalAlign;
  12360. verticalAlign === 'center' && (verticalAlign = 'middle');
  12361. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  12362. var textPadding = style.padding;
  12363. if (textPadding) {
  12364. style.padding = normalizeCssArray(style.padding);
  12365. }
  12366. }
  12367. }
  12368. function getStroke(stroke, lineWidth) {
  12369. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  12370. ? null
  12371. : (stroke.image || stroke.colorStops)
  12372. ? '#000'
  12373. : stroke;
  12374. }
  12375. function getFill(fill) {
  12376. return (fill == null || fill === 'none')
  12377. ? null
  12378. : (fill.image || fill.colorStops)
  12379. ? '#000'
  12380. : fill;
  12381. }
  12382. function getTextXForPadding(x, textAlign, textPadding) {
  12383. return textAlign === 'right'
  12384. ? (x - textPadding[1])
  12385. : textAlign === 'center'
  12386. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  12387. : (x + textPadding[3]);
  12388. }
  12389. function getStyleText(style) {
  12390. var text = style.text;
  12391. text != null && (text += '');
  12392. return text;
  12393. }
  12394. function needDrawBackground(style) {
  12395. return !!(style.backgroundColor
  12396. || style.lineHeight
  12397. || (style.borderWidth && style.borderColor));
  12398. }
  12399. var getECData = makeInner();
  12400. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  12401. if (el) {
  12402. var ecData = getECData(el);
  12403. // Add data index and series index for indexing the data by element
  12404. // Useful in tooltip
  12405. ecData.dataIndex = dataIdx;
  12406. ecData.dataType = dataType;
  12407. ecData.seriesIndex = seriesIndex;
  12408. ecData.ssrType = 'chart';
  12409. // TODO: not store dataIndex on children.
  12410. if (el.type === 'group') {
  12411. el.traverse(function (child) {
  12412. var childECData = getECData(child);
  12413. childECData.seriesIndex = seriesIndex;
  12414. childECData.dataIndex = dataIdx;
  12415. childECData.dataType = dataType;
  12416. childECData.ssrType = 'chart';
  12417. });
  12418. }
  12419. }
  12420. };
  12421. // Reserve 0 as default.
  12422. var _highlightNextDigit = 1;
  12423. var _highlightKeyMap = {};
  12424. var getSavedStates = makeInner();
  12425. var getComponentStates = makeInner();
  12426. var HOVER_STATE_NORMAL = 0;
  12427. var HOVER_STATE_BLUR = 1;
  12428. var HOVER_STATE_EMPHASIS = 2;
  12429. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  12430. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  12431. var Z2_EMPHASIS_LIFT = 10;
  12432. var Z2_SELECT_LIFT = 9;
  12433. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  12434. var DOWNPLAY_ACTION_TYPE = 'downplay';
  12435. var SELECT_ACTION_TYPE = 'select';
  12436. var UNSELECT_ACTION_TYPE = 'unselect';
  12437. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  12438. var SELECT_CHANGED_EVENT_TYPE = 'selectchanged';
  12439. function hasFillOrStroke(fillOrStroke) {
  12440. return fillOrStroke != null && fillOrStroke !== 'none';
  12441. }
  12442. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12443. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12444. el.onHoverStateChange(stateName);
  12445. }
  12446. el.hoverState = hoverStateEnum;
  12447. }
  12448. function singleEnterEmphasis(el) {
  12449. // Only mark the flag.
  12450. // States will be applied in the echarts.ts in next frame.
  12451. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12452. }
  12453. function singleLeaveEmphasis(el) {
  12454. // Only mark the flag.
  12455. // States will be applied in the echarts.ts in next frame.
  12456. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12457. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12458. }
  12459. }
  12460. function singleEnterBlur(el) {
  12461. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12462. }
  12463. function singleLeaveBlur(el) {
  12464. if (el.hoverState === HOVER_STATE_BLUR) {
  12465. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12466. }
  12467. }
  12468. function singleEnterSelect(el) {
  12469. el.selected = true;
  12470. }
  12471. function singleLeaveSelect(el) {
  12472. el.selected = false;
  12473. }
  12474. function updateElementState(el, updater, commonParam) {
  12475. updater(el, commonParam);
  12476. }
  12477. function traverseUpdateState(el, updater, commonParam) {
  12478. updateElementState(el, updater, commonParam);
  12479. el.isGroup && el.traverse(function (child) {
  12480. updateElementState(child, updater, commonParam);
  12481. });
  12482. }
  12483. function setStatesFlag(el, stateName) {
  12484. switch (stateName) {
  12485. case 'emphasis':
  12486. el.hoverState = HOVER_STATE_EMPHASIS;
  12487. break;
  12488. case 'normal':
  12489. el.hoverState = HOVER_STATE_NORMAL;
  12490. break;
  12491. case 'blur':
  12492. el.hoverState = HOVER_STATE_BLUR;
  12493. break;
  12494. case 'select':
  12495. el.selected = true;
  12496. }
  12497. }
  12498. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12499. var style = el.style;
  12500. var fromState = {};
  12501. for (var i = 0; i < props.length; i++) {
  12502. var propName = props[i];
  12503. var val = style[propName];
  12504. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12505. }
  12506. for (var i = 0; i < el.animators.length; i++) {
  12507. var animator = el.animators[i];
  12508. if (animator.__fromStateTransition
  12509. // Don't consider the animation to emphasis state.
  12510. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12511. animator.saveTo(fromState, props);
  12512. }
  12513. }
  12514. return fromState;
  12515. }
  12516. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12517. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12518. var cloned = false;
  12519. if (el instanceof Path) {
  12520. var store = getSavedStates(el);
  12521. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12522. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12523. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12524. state = state || {};
  12525. var emphasisStyle = state.style || {};
  12526. // inherit case
  12527. if (emphasisStyle.fill === 'inherit') {
  12528. cloned = true;
  12529. state = extend({}, state);
  12530. emphasisStyle = extend({}, emphasisStyle);
  12531. emphasisStyle.fill = fromFill;
  12532. }
  12533. // Apply default color lift
  12534. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12535. cloned = true;
  12536. // Not modify the original value.
  12537. state = extend({}, state);
  12538. emphasisStyle = extend({}, emphasisStyle);
  12539. // Already being applied 'emphasis'. DON'T lift color multiple times.
  12540. emphasisStyle.fill = liftColor(fromFill);
  12541. }
  12542. // Not highlight stroke if fill has been highlighted.
  12543. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12544. if (!cloned) {
  12545. state = extend({}, state);
  12546. emphasisStyle = extend({}, emphasisStyle);
  12547. }
  12548. emphasisStyle.stroke = liftColor(fromStroke);
  12549. }
  12550. state.style = emphasisStyle;
  12551. }
  12552. }
  12553. if (state) {
  12554. // TODO Share with textContent?
  12555. if (state.z2 == null) {
  12556. if (!cloned) {
  12557. state = extend({}, state);
  12558. }
  12559. var z2EmphasisLift = el.z2EmphasisLift;
  12560. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12561. }
  12562. }
  12563. return state;
  12564. }
  12565. function createSelectDefaultState(el, stateName, state) {
  12566. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12567. if (state) {
  12568. // TODO Share with textContent?
  12569. if (state.z2 == null) {
  12570. state = extend({}, state);
  12571. var z2SelectLift = el.z2SelectLift;
  12572. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12573. }
  12574. }
  12575. return state;
  12576. }
  12577. function createBlurDefaultState(el, stateName, state) {
  12578. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12579. var currentOpacity = el.style.opacity;
  12580. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12581. opacity: 1
  12582. }) : null;
  12583. state = state || {};
  12584. var blurStyle = state.style || {};
  12585. if (blurStyle.opacity == null) {
  12586. // clone state
  12587. state = extend({}, state);
  12588. blurStyle = extend({
  12589. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12590. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12591. }, blurStyle);
  12592. state.style = blurStyle;
  12593. }
  12594. return state;
  12595. }
  12596. function elementStateProxy(stateName, targetStates) {
  12597. var state = this.states[stateName];
  12598. if (this.style) {
  12599. if (stateName === 'emphasis') {
  12600. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12601. } else if (stateName === 'blur') {
  12602. return createBlurDefaultState(this, stateName, state);
  12603. } else if (stateName === 'select') {
  12604. return createSelectDefaultState(this, stateName, state);
  12605. }
  12606. }
  12607. return state;
  12608. }
  12609. /**
  12610. * Set hover style (namely "emphasis style") of element.
  12611. * @param el Should not be `zrender/graphic/Group`.
  12612. * @param focus 'self' | 'selfInSeries' | 'series'
  12613. */
  12614. function setDefaultStateProxy(el) {
  12615. el.stateProxy = elementStateProxy;
  12616. var textContent = el.getTextContent();
  12617. var textGuide = el.getTextGuideLine();
  12618. if (textContent) {
  12619. textContent.stateProxy = elementStateProxy;
  12620. }
  12621. if (textGuide) {
  12622. textGuide.stateProxy = elementStateProxy;
  12623. }
  12624. }
  12625. function enterEmphasisWhenMouseOver(el, e) {
  12626. !shouldSilent(el, e)
  12627. // "emphasis" event highlight has higher priority than mouse highlight.
  12628. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12629. }
  12630. function leaveEmphasisWhenMouseOut(el, e) {
  12631. !shouldSilent(el, e)
  12632. // "emphasis" event highlight has higher priority than mouse highlight.
  12633. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12634. }
  12635. function enterEmphasis(el, highlightDigit) {
  12636. el.__highByOuter |= 1 << (highlightDigit || 0);
  12637. traverseUpdateState(el, singleEnterEmphasis);
  12638. }
  12639. function leaveEmphasis(el, highlightDigit) {
  12640. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12641. }
  12642. function enterBlur(el) {
  12643. traverseUpdateState(el, singleEnterBlur);
  12644. }
  12645. function leaveBlur(el) {
  12646. traverseUpdateState(el, singleLeaveBlur);
  12647. }
  12648. function enterSelect(el) {
  12649. traverseUpdateState(el, singleEnterSelect);
  12650. }
  12651. function leaveSelect(el) {
  12652. traverseUpdateState(el, singleLeaveSelect);
  12653. }
  12654. function shouldSilent(el, e) {
  12655. return el.__highDownSilentOnTouch && e.zrByTouch;
  12656. }
  12657. function allLeaveBlur(api) {
  12658. var model = api.getModel();
  12659. var leaveBlurredSeries = [];
  12660. var allComponentViews = [];
  12661. model.eachComponent(function (componentType, componentModel) {
  12662. var componentStates = getComponentStates(componentModel);
  12663. var isSeries = componentType === 'series';
  12664. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12665. !isSeries && allComponentViews.push(view);
  12666. if (componentStates.isBlured) {
  12667. // Leave blur anyway
  12668. view.group.traverse(function (child) {
  12669. singleLeaveBlur(child);
  12670. });
  12671. isSeries && leaveBlurredSeries.push(componentModel);
  12672. }
  12673. componentStates.isBlured = false;
  12674. });
  12675. each(allComponentViews, function (view) {
  12676. if (view && view.toggleBlurSeries) {
  12677. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12678. }
  12679. });
  12680. }
  12681. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12682. var ecModel = api.getModel();
  12683. blurScope = blurScope || 'coordinateSystem';
  12684. function leaveBlurOfIndices(data, dataIndices) {
  12685. for (var i = 0; i < dataIndices.length; i++) {
  12686. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12687. itemEl && leaveBlur(itemEl);
  12688. }
  12689. }
  12690. if (targetSeriesIndex == null) {
  12691. return;
  12692. }
  12693. if (!focus || focus === 'none') {
  12694. return;
  12695. }
  12696. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12697. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12698. if (targetCoordSys && targetCoordSys.master) {
  12699. targetCoordSys = targetCoordSys.master;
  12700. }
  12701. var blurredSeries = [];
  12702. ecModel.eachSeries(function (seriesModel) {
  12703. var sameSeries = targetSeriesModel === seriesModel;
  12704. var coordSys = seriesModel.coordinateSystem;
  12705. if (coordSys && coordSys.master) {
  12706. coordSys = coordSys.master;
  12707. }
  12708. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12709. if (!(
  12710. // Not blur other series if blurScope series
  12711. blurScope === 'series' && !sameSeries
  12712. // Not blur other coordinate system if blurScope is coordinateSystem
  12713. || blurScope === 'coordinateSystem' && !sameCoordSys
  12714. // Not blur self series if focus is series.
  12715. || focus === 'series' && sameSeries
  12716. // TODO blurScope: coordinate system
  12717. )) {
  12718. var view = api.getViewOfSeriesModel(seriesModel);
  12719. view.group.traverse(function (child) {
  12720. // For the elements that have been triggered by other components,
  12721. // and are still required to be highlighted,
  12722. // because the current is directly forced to blur the element,
  12723. // it will cause the focus self to be unable to highlight, so skip the blur of this element.
  12724. if (child.__highByOuter && sameSeries && focus === 'self') {
  12725. return;
  12726. }
  12727. singleEnterBlur(child);
  12728. });
  12729. if (isArrayLike(focus)) {
  12730. leaveBlurOfIndices(seriesModel.getData(), focus);
  12731. } else if (isObject(focus)) {
  12732. var dataTypes = keys(focus);
  12733. for (var d = 0; d < dataTypes.length; d++) {
  12734. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12735. }
  12736. }
  12737. blurredSeries.push(seriesModel);
  12738. getComponentStates(seriesModel).isBlured = true;
  12739. }
  12740. });
  12741. ecModel.eachComponent(function (componentType, componentModel) {
  12742. if (componentType === 'series') {
  12743. return;
  12744. }
  12745. var view = api.getViewOfComponentModel(componentModel);
  12746. if (view && view.toggleBlurSeries) {
  12747. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12748. }
  12749. });
  12750. }
  12751. function blurComponent(componentMainType, componentIndex, api) {
  12752. if (componentMainType == null || componentIndex == null) {
  12753. return;
  12754. }
  12755. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12756. if (!componentModel) {
  12757. return;
  12758. }
  12759. getComponentStates(componentModel).isBlured = true;
  12760. var view = api.getViewOfComponentModel(componentModel);
  12761. if (!view || !view.focusBlurEnabled) {
  12762. return;
  12763. }
  12764. view.group.traverse(function (child) {
  12765. singleEnterBlur(child);
  12766. });
  12767. }
  12768. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12769. var seriesIndex = seriesModel.seriesIndex;
  12770. var data = seriesModel.getData(payload.dataType);
  12771. if (!data) {
  12772. if ("development" !== 'production') {
  12773. error("Unknown dataType " + payload.dataType);
  12774. }
  12775. return;
  12776. }
  12777. var dataIndex = queryDataIndex(data, payload);
  12778. // Pick the first one if there is multiple/none exists.
  12779. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12780. var el = data.getItemGraphicEl(dataIndex);
  12781. if (!el) {
  12782. var count = data.count();
  12783. var current = 0;
  12784. // If data on dataIndex is NaN.
  12785. while (!el && current < count) {
  12786. el = data.getItemGraphicEl(current++);
  12787. }
  12788. }
  12789. if (el) {
  12790. var ecData = getECData(el);
  12791. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12792. } else {
  12793. // If there is no element put on the data. Try getting it from raw option
  12794. // TODO Should put it on seriesModel?
  12795. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12796. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12797. if (focus_1 != null) {
  12798. blurSeries(seriesIndex, focus_1, blurScope, api);
  12799. }
  12800. }
  12801. }
  12802. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12803. var ret = {
  12804. focusSelf: false,
  12805. dispatchers: null
  12806. };
  12807. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12808. return ret;
  12809. }
  12810. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12811. if (!componentModel) {
  12812. return ret;
  12813. }
  12814. var view = api.getViewOfComponentModel(componentModel);
  12815. if (!view || !view.findHighDownDispatchers) {
  12816. return ret;
  12817. }
  12818. var dispatchers = view.findHighDownDispatchers(name);
  12819. // At presnet, the component (like Geo) only blur inside itself.
  12820. // So we do not use `blurScope` in component.
  12821. var focusSelf;
  12822. for (var i = 0; i < dispatchers.length; i++) {
  12823. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12824. error('param should be highDownDispatcher');
  12825. }
  12826. if (getECData(dispatchers[i]).focus === 'self') {
  12827. focusSelf = true;
  12828. break;
  12829. }
  12830. }
  12831. return {
  12832. focusSelf: focusSelf,
  12833. dispatchers: dispatchers
  12834. };
  12835. }
  12836. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12837. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12838. error('param should be highDownDispatcher');
  12839. }
  12840. var ecData = getECData(dispatcher);
  12841. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12842. dispatchers = _a.dispatchers,
  12843. focusSelf = _a.focusSelf;
  12844. // If `findHighDownDispatchers` is supported on the component,
  12845. // highlight/downplay elements with the same name.
  12846. if (dispatchers) {
  12847. if (focusSelf) {
  12848. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12849. }
  12850. each(dispatchers, function (dispatcher) {
  12851. return enterEmphasisWhenMouseOver(dispatcher, e);
  12852. });
  12853. } else {
  12854. // Try blur all in the related series. Then emphasis the hoverred.
  12855. // TODO. progressive mode.
  12856. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12857. if (ecData.focus === 'self') {
  12858. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12859. }
  12860. // Other than series, component that not support `findHighDownDispatcher` will
  12861. // also use it. But in this case, highlight/downplay are only supported in
  12862. // mouse hover but not in dispatchAction.
  12863. enterEmphasisWhenMouseOver(dispatcher, e);
  12864. }
  12865. }
  12866. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12867. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12868. error('param should be highDownDispatcher');
  12869. }
  12870. allLeaveBlur(api);
  12871. var ecData = getECData(dispatcher);
  12872. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12873. if (dispatchers) {
  12874. each(dispatchers, function (dispatcher) {
  12875. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12876. });
  12877. } else {
  12878. leaveEmphasisWhenMouseOut(dispatcher, e);
  12879. }
  12880. }
  12881. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12882. if (!isSelectChangePayload(payload)) {
  12883. return;
  12884. }
  12885. var dataType = payload.dataType;
  12886. var data = seriesModel.getData(dataType);
  12887. var dataIndex = queryDataIndex(data, payload);
  12888. if (!isArray(dataIndex)) {
  12889. dataIndex = [dataIndex];
  12890. }
  12891. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12892. }
  12893. function updateSeriesElementSelection(seriesModel) {
  12894. var allData = seriesModel.getAllData();
  12895. each(allData, function (_a) {
  12896. var data = _a.data,
  12897. type = _a.type;
  12898. data.eachItemGraphicEl(function (el, idx) {
  12899. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12900. });
  12901. });
  12902. }
  12903. function getAllSelectedIndices(ecModel) {
  12904. var ret = [];
  12905. ecModel.eachSeries(function (seriesModel) {
  12906. var allData = seriesModel.getAllData();
  12907. each(allData, function (_a) {
  12908. var data = _a.data,
  12909. type = _a.type;
  12910. var dataIndices = seriesModel.getSelectedDataIndices();
  12911. if (dataIndices.length > 0) {
  12912. var item = {
  12913. dataIndex: dataIndices,
  12914. seriesIndex: seriesModel.seriesIndex
  12915. };
  12916. if (type != null) {
  12917. item.dataType = type;
  12918. }
  12919. ret.push(item);
  12920. }
  12921. });
  12922. });
  12923. return ret;
  12924. }
  12925. /**
  12926. * Enable the function that mouseover will trigger the emphasis state.
  12927. *
  12928. * NOTE:
  12929. * This function should be used on the element with dataIndex, seriesIndex.
  12930. *
  12931. */
  12932. function enableHoverEmphasis(el, focus, blurScope) {
  12933. setAsHighDownDispatcher(el, true);
  12934. traverseUpdateState(el, setDefaultStateProxy);
  12935. enableHoverFocus(el, focus, blurScope);
  12936. }
  12937. function disableHoverEmphasis(el) {
  12938. setAsHighDownDispatcher(el, false);
  12939. }
  12940. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12941. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12942. }
  12943. function enableHoverFocus(el, focus, blurScope) {
  12944. var ecData = getECData(el);
  12945. if (focus != null) {
  12946. // TODO dataIndex may be set after this function. This check is not useful.
  12947. // if (ecData.dataIndex == null) {
  12948. // if (__DEV__) {
  12949. // console.warn('focus can only been set on element with dataIndex');
  12950. // }
  12951. // }
  12952. // else {
  12953. ecData.focus = focus;
  12954. ecData.blurScope = blurScope;
  12955. // }
  12956. } else if (ecData.focus) {
  12957. ecData.focus = null;
  12958. }
  12959. }
  12960. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12961. var defaultStyleGetterMap = {
  12962. itemStyle: 'getItemStyle',
  12963. lineStyle: 'getLineStyle',
  12964. areaStyle: 'getAreaStyle'
  12965. };
  12966. /**
  12967. * Set emphasis/blur/selected states of element.
  12968. */
  12969. function setStatesStylesFromModel(el, itemModel, styleType,
  12970. // default itemStyle
  12971. getter) {
  12972. styleType = styleType || 'itemStyle';
  12973. for (var i = 0; i < OTHER_STATES.length; i++) {
  12974. var stateName = OTHER_STATES[i];
  12975. var model = itemModel.getModel([stateName, styleType]);
  12976. var state = el.ensureState(stateName);
  12977. // Let it throw error if getterType is not found.
  12978. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12979. }
  12980. }
  12981. /**
  12982. *
  12983. * Set element as highlight / downplay dispatcher.
  12984. * It will be checked when element received mouseover event or from highlight action.
  12985. * It's in change of all highlight/downplay behavior of it's children.
  12986. *
  12987. * @param el
  12988. * @param el.highDownSilentOnTouch
  12989. * In touch device, mouseover event will be trigger on touchstart event
  12990. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12991. * conveniently use hoverStyle when tap on touch screen without additional
  12992. * code for compatibility.
  12993. * But if the chart/component has select feature, which usually also use
  12994. * hoverStyle, there might be conflict between 'select-highlight' and
  12995. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12996. * In this case, `highDownSilentOnTouch` should be used to disable
  12997. * hover-highlight on touch device.
  12998. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12999. */
  13000. function setAsHighDownDispatcher(el, asDispatcher) {
  13001. var disable = asDispatcher === false;
  13002. var extendedEl = el;
  13003. // Make `highDownSilentOnTouch` and `onStateChange` only work after
  13004. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  13005. if (el.highDownSilentOnTouch) {
  13006. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  13007. }
  13008. // Simple optimize, since this method might be
  13009. // called for each elements of a group in some cases.
  13010. if (!disable || extendedEl.__highDownDispatcher) {
  13011. // Emphasis, normal can be triggered manually by API or other components like hover link.
  13012. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  13013. // Also keep previous record.
  13014. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  13015. extendedEl.__highDownDispatcher = !disable;
  13016. }
  13017. }
  13018. function isHighDownDispatcher(el) {
  13019. return !!(el && el.__highDownDispatcher);
  13020. }
  13021. /**
  13022. * Support highlight/downplay record on each elements.
  13023. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  13024. * user triggered highlight/downplay should not conflict.
  13025. * Only all of the highlightDigit cleared, return to normal.
  13026. * @param {string} highlightKey
  13027. * @return {number} highlightDigit
  13028. */
  13029. function getHighlightDigit(highlightKey) {
  13030. var highlightDigit = _highlightKeyMap[highlightKey];
  13031. if (highlightDigit == null && _highlightNextDigit <= 32) {
  13032. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  13033. }
  13034. return highlightDigit;
  13035. }
  13036. function isSelectChangePayload(payload) {
  13037. var payloadType = payload.type;
  13038. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  13039. }
  13040. function isHighDownPayload(payload) {
  13041. var payloadType = payload.type;
  13042. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  13043. }
  13044. function savePathStates(el) {
  13045. var store = getSavedStates(el);
  13046. store.normalFill = el.style.fill;
  13047. store.normalStroke = el.style.stroke;
  13048. var selectState = el.states.select || {};
  13049. store.selectFill = selectState.style && selectState.style.fill || null;
  13050. store.selectStroke = selectState.style && selectState.style.stroke || null;
  13051. }
  13052. var CMD$2 = PathProxy.CMD;
  13053. var points = [[], [], []];
  13054. var mathSqrt$1 = Math.sqrt;
  13055. var mathAtan2 = Math.atan2;
  13056. function transformPath(path, m) {
  13057. if (!m) {
  13058. return;
  13059. }
  13060. var data = path.data;
  13061. var len = path.len();
  13062. var cmd;
  13063. var nPoint;
  13064. var i;
  13065. var j;
  13066. var k;
  13067. var p;
  13068. var M = CMD$2.M;
  13069. var C = CMD$2.C;
  13070. var L = CMD$2.L;
  13071. var R = CMD$2.R;
  13072. var A = CMD$2.A;
  13073. var Q = CMD$2.Q;
  13074. for (i = 0, j = 0; i < len;) {
  13075. cmd = data[i++];
  13076. j = i;
  13077. nPoint = 0;
  13078. switch (cmd) {
  13079. case M:
  13080. nPoint = 1;
  13081. break;
  13082. case L:
  13083. nPoint = 1;
  13084. break;
  13085. case C:
  13086. nPoint = 3;
  13087. break;
  13088. case Q:
  13089. nPoint = 2;
  13090. break;
  13091. case A:
  13092. var x = m[4];
  13093. var y = m[5];
  13094. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  13095. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  13096. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13097. data[i] *= sx;
  13098. data[i++] += x;
  13099. data[i] *= sy;
  13100. data[i++] += y;
  13101. data[i++] *= sx;
  13102. data[i++] *= sy;
  13103. data[i++] += angle;
  13104. data[i++] += angle;
  13105. i += 2;
  13106. j = i;
  13107. break;
  13108. case R:
  13109. p[0] = data[i++];
  13110. p[1] = data[i++];
  13111. applyTransform(p, p, m);
  13112. data[j++] = p[0];
  13113. data[j++] = p[1];
  13114. p[0] += data[i++];
  13115. p[1] += data[i++];
  13116. applyTransform(p, p, m);
  13117. data[j++] = p[0];
  13118. data[j++] = p[1];
  13119. }
  13120. for (k = 0; k < nPoint; k++) {
  13121. var p_1 = points[k];
  13122. p_1[0] = data[i++];
  13123. p_1[1] = data[i++];
  13124. applyTransform(p_1, p_1, m);
  13125. data[j++] = p_1[0];
  13126. data[j++] = p_1[1];
  13127. }
  13128. }
  13129. path.increaseVersion();
  13130. }
  13131. var mathSqrt$2 = Math.sqrt;
  13132. var mathSin$2 = Math.sin;
  13133. var mathCos$2 = Math.cos;
  13134. var PI$1 = Math.PI;
  13135. function vMag(v) {
  13136. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13137. }
  13138. function vRatio(u, v) {
  13139. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13140. }
  13141. function vAngle(u, v) {
  13142. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13143. * Math.acos(vRatio(u, v));
  13144. }
  13145. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13146. var psi = psiDeg * (PI$1 / 180.0);
  13147. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  13148. + mathSin$2(psi) * (y1 - y2) / 2.0;
  13149. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  13150. + mathCos$2(psi) * (y1 - y2) / 2.0;
  13151. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13152. if (lambda > 1) {
  13153. rx *= mathSqrt$2(lambda);
  13154. ry *= mathSqrt$2(lambda);
  13155. }
  13156. var f = (fa === fs ? -1 : 1)
  13157. * mathSqrt$2((((rx * rx) * (ry * ry))
  13158. - ((rx * rx) * (yp * yp))
  13159. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13160. + (ry * ry) * (xp * xp))) || 0;
  13161. var cxp = f * rx * yp / ry;
  13162. var cyp = f * -ry * xp / rx;
  13163. var cx = (x1 + x2) / 2.0
  13164. + mathCos$2(psi) * cxp
  13165. - mathSin$2(psi) * cyp;
  13166. var cy = (y1 + y2) / 2.0
  13167. + mathSin$2(psi) * cxp
  13168. + mathCos$2(psi) * cyp;
  13169. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  13170. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  13171. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  13172. var dTheta = vAngle(u, v);
  13173. if (vRatio(u, v) <= -1) {
  13174. dTheta = PI$1;
  13175. }
  13176. if (vRatio(u, v) >= 1) {
  13177. dTheta = 0;
  13178. }
  13179. if (dTheta < 0) {
  13180. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  13181. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  13182. }
  13183. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13184. }
  13185. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13186. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13187. function createPathProxyFromString(data) {
  13188. var path = new PathProxy();
  13189. if (!data) {
  13190. return path;
  13191. }
  13192. var cpx = 0;
  13193. var cpy = 0;
  13194. var subpathX = cpx;
  13195. var subpathY = cpy;
  13196. var prevCmd;
  13197. var CMD = PathProxy.CMD;
  13198. var cmdList = data.match(commandReg);
  13199. if (!cmdList) {
  13200. return path;
  13201. }
  13202. for (var l = 0; l < cmdList.length; l++) {
  13203. var cmdText = cmdList[l];
  13204. var cmdStr = cmdText.charAt(0);
  13205. var cmd = void 0;
  13206. var p = cmdText.match(numberReg) || [];
  13207. var pLen = p.length;
  13208. for (var i = 0; i < pLen; i++) {
  13209. p[i] = parseFloat(p[i]);
  13210. }
  13211. var off = 0;
  13212. while (off < pLen) {
  13213. var ctlPtx = void 0;
  13214. var ctlPty = void 0;
  13215. var rx = void 0;
  13216. var ry = void 0;
  13217. var psi = void 0;
  13218. var fa = void 0;
  13219. var fs = void 0;
  13220. var x1 = cpx;
  13221. var y1 = cpy;
  13222. var len = void 0;
  13223. var pathData = void 0;
  13224. switch (cmdStr) {
  13225. case 'l':
  13226. cpx += p[off++];
  13227. cpy += p[off++];
  13228. cmd = CMD.L;
  13229. path.addData(cmd, cpx, cpy);
  13230. break;
  13231. case 'L':
  13232. cpx = p[off++];
  13233. cpy = p[off++];
  13234. cmd = CMD.L;
  13235. path.addData(cmd, cpx, cpy);
  13236. break;
  13237. case 'm':
  13238. cpx += p[off++];
  13239. cpy += p[off++];
  13240. cmd = CMD.M;
  13241. path.addData(cmd, cpx, cpy);
  13242. subpathX = cpx;
  13243. subpathY = cpy;
  13244. cmdStr = 'l';
  13245. break;
  13246. case 'M':
  13247. cpx = p[off++];
  13248. cpy = p[off++];
  13249. cmd = CMD.M;
  13250. path.addData(cmd, cpx, cpy);
  13251. subpathX = cpx;
  13252. subpathY = cpy;
  13253. cmdStr = 'L';
  13254. break;
  13255. case 'h':
  13256. cpx += p[off++];
  13257. cmd = CMD.L;
  13258. path.addData(cmd, cpx, cpy);
  13259. break;
  13260. case 'H':
  13261. cpx = p[off++];
  13262. cmd = CMD.L;
  13263. path.addData(cmd, cpx, cpy);
  13264. break;
  13265. case 'v':
  13266. cpy += p[off++];
  13267. cmd = CMD.L;
  13268. path.addData(cmd, cpx, cpy);
  13269. break;
  13270. case 'V':
  13271. cpy = p[off++];
  13272. cmd = CMD.L;
  13273. path.addData(cmd, cpx, cpy);
  13274. break;
  13275. case 'C':
  13276. cmd = CMD.C;
  13277. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  13278. cpx = p[off - 2];
  13279. cpy = p[off - 1];
  13280. break;
  13281. case 'c':
  13282. cmd = CMD.C;
  13283. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  13284. cpx += p[off - 2];
  13285. cpy += p[off - 1];
  13286. break;
  13287. case 'S':
  13288. ctlPtx = cpx;
  13289. ctlPty = cpy;
  13290. len = path.len();
  13291. pathData = path.data;
  13292. if (prevCmd === CMD.C) {
  13293. ctlPtx += cpx - pathData[len - 4];
  13294. ctlPty += cpy - pathData[len - 3];
  13295. }
  13296. cmd = CMD.C;
  13297. x1 = p[off++];
  13298. y1 = p[off++];
  13299. cpx = p[off++];
  13300. cpy = p[off++];
  13301. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13302. break;
  13303. case 's':
  13304. ctlPtx = cpx;
  13305. ctlPty = cpy;
  13306. len = path.len();
  13307. pathData = path.data;
  13308. if (prevCmd === CMD.C) {
  13309. ctlPtx += cpx - pathData[len - 4];
  13310. ctlPty += cpy - pathData[len - 3];
  13311. }
  13312. cmd = CMD.C;
  13313. x1 = cpx + p[off++];
  13314. y1 = cpy + p[off++];
  13315. cpx += p[off++];
  13316. cpy += p[off++];
  13317. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13318. break;
  13319. case 'Q':
  13320. x1 = p[off++];
  13321. y1 = p[off++];
  13322. cpx = p[off++];
  13323. cpy = p[off++];
  13324. cmd = CMD.Q;
  13325. path.addData(cmd, x1, y1, cpx, cpy);
  13326. break;
  13327. case 'q':
  13328. x1 = p[off++] + cpx;
  13329. y1 = p[off++] + cpy;
  13330. cpx += p[off++];
  13331. cpy += p[off++];
  13332. cmd = CMD.Q;
  13333. path.addData(cmd, x1, y1, cpx, cpy);
  13334. break;
  13335. case 'T':
  13336. ctlPtx = cpx;
  13337. ctlPty = cpy;
  13338. len = path.len();
  13339. pathData = path.data;
  13340. if (prevCmd === CMD.Q) {
  13341. ctlPtx += cpx - pathData[len - 4];
  13342. ctlPty += cpy - pathData[len - 3];
  13343. }
  13344. cpx = p[off++];
  13345. cpy = p[off++];
  13346. cmd = CMD.Q;
  13347. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13348. break;
  13349. case 't':
  13350. ctlPtx = cpx;
  13351. ctlPty = cpy;
  13352. len = path.len();
  13353. pathData = path.data;
  13354. if (prevCmd === CMD.Q) {
  13355. ctlPtx += cpx - pathData[len - 4];
  13356. ctlPty += cpy - pathData[len - 3];
  13357. }
  13358. cpx += p[off++];
  13359. cpy += p[off++];
  13360. cmd = CMD.Q;
  13361. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13362. break;
  13363. case 'A':
  13364. rx = p[off++];
  13365. ry = p[off++];
  13366. psi = p[off++];
  13367. fa = p[off++];
  13368. fs = p[off++];
  13369. x1 = cpx, y1 = cpy;
  13370. cpx = p[off++];
  13371. cpy = p[off++];
  13372. cmd = CMD.A;
  13373. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13374. break;
  13375. case 'a':
  13376. rx = p[off++];
  13377. ry = p[off++];
  13378. psi = p[off++];
  13379. fa = p[off++];
  13380. fs = p[off++];
  13381. x1 = cpx, y1 = cpy;
  13382. cpx += p[off++];
  13383. cpy += p[off++];
  13384. cmd = CMD.A;
  13385. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13386. break;
  13387. }
  13388. }
  13389. if (cmdStr === 'z' || cmdStr === 'Z') {
  13390. cmd = CMD.Z;
  13391. path.addData(cmd);
  13392. cpx = subpathX;
  13393. cpy = subpathY;
  13394. }
  13395. prevCmd = cmd;
  13396. }
  13397. path.toStatic();
  13398. return path;
  13399. }
  13400. var SVGPath = (function (_super) {
  13401. __extends(SVGPath, _super);
  13402. function SVGPath() {
  13403. return _super !== null && _super.apply(this, arguments) || this;
  13404. }
  13405. SVGPath.prototype.applyTransform = function (m) { };
  13406. return SVGPath;
  13407. }(Path));
  13408. function isPathProxy(path) {
  13409. return path.setData != null;
  13410. }
  13411. function createPathOptions(str, opts) {
  13412. var pathProxy = createPathProxyFromString(str);
  13413. var innerOpts = extend({}, opts);
  13414. innerOpts.buildPath = function (path) {
  13415. var beProxy = isPathProxy(path);
  13416. if (beProxy && path.canSave()) {
  13417. path.appendPath(pathProxy);
  13418. var ctx = path.getContext();
  13419. if (ctx) {
  13420. path.rebuildPath(ctx, 1);
  13421. }
  13422. }
  13423. else {
  13424. var ctx = beProxy ? path.getContext() : path;
  13425. if (ctx) {
  13426. pathProxy.rebuildPath(ctx, 1);
  13427. }
  13428. }
  13429. };
  13430. innerOpts.applyTransform = function (m) {
  13431. transformPath(pathProxy, m);
  13432. this.dirtyShape();
  13433. };
  13434. return innerOpts;
  13435. }
  13436. function createFromString(str, opts) {
  13437. return new SVGPath(createPathOptions(str, opts));
  13438. }
  13439. function extendFromString(str, defaultOpts) {
  13440. var innerOpts = createPathOptions(str, defaultOpts);
  13441. var Sub = (function (_super) {
  13442. __extends(Sub, _super);
  13443. function Sub(opts) {
  13444. var _this = _super.call(this, opts) || this;
  13445. _this.applyTransform = innerOpts.applyTransform;
  13446. _this.buildPath = innerOpts.buildPath;
  13447. return _this;
  13448. }
  13449. return Sub;
  13450. }(SVGPath));
  13451. return Sub;
  13452. }
  13453. function mergePath(pathEls, opts) {
  13454. var pathList = [];
  13455. var len = pathEls.length;
  13456. for (var i = 0; i < len; i++) {
  13457. var pathEl = pathEls[i];
  13458. pathList.push(pathEl.getUpdatedPathProxy(true));
  13459. }
  13460. var pathBundle = new Path(opts);
  13461. pathBundle.createPathProxy();
  13462. pathBundle.buildPath = function (path) {
  13463. if (isPathProxy(path)) {
  13464. path.appendPath(pathList);
  13465. var ctx = path.getContext();
  13466. if (ctx) {
  13467. path.rebuildPath(ctx, 1);
  13468. }
  13469. }
  13470. };
  13471. return pathBundle;
  13472. }
  13473. var CircleShape = (function () {
  13474. function CircleShape() {
  13475. this.cx = 0;
  13476. this.cy = 0;
  13477. this.r = 0;
  13478. }
  13479. return CircleShape;
  13480. }());
  13481. var Circle = (function (_super) {
  13482. __extends(Circle, _super);
  13483. function Circle(opts) {
  13484. return _super.call(this, opts) || this;
  13485. }
  13486. Circle.prototype.getDefaultShape = function () {
  13487. return new CircleShape();
  13488. };
  13489. Circle.prototype.buildPath = function (ctx, shape) {
  13490. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13491. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13492. };
  13493. return Circle;
  13494. }(Path));
  13495. Circle.prototype.type = 'circle';
  13496. var EllipseShape = (function () {
  13497. function EllipseShape() {
  13498. this.cx = 0;
  13499. this.cy = 0;
  13500. this.rx = 0;
  13501. this.ry = 0;
  13502. }
  13503. return EllipseShape;
  13504. }());
  13505. var Ellipse = (function (_super) {
  13506. __extends(Ellipse, _super);
  13507. function Ellipse(opts) {
  13508. return _super.call(this, opts) || this;
  13509. }
  13510. Ellipse.prototype.getDefaultShape = function () {
  13511. return new EllipseShape();
  13512. };
  13513. Ellipse.prototype.buildPath = function (ctx, shape) {
  13514. var k = 0.5522848;
  13515. var x = shape.cx;
  13516. var y = shape.cy;
  13517. var a = shape.rx;
  13518. var b = shape.ry;
  13519. var ox = a * k;
  13520. var oy = b * k;
  13521. ctx.moveTo(x - a, y);
  13522. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13523. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13524. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13525. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13526. ctx.closePath();
  13527. };
  13528. return Ellipse;
  13529. }(Path));
  13530. Ellipse.prototype.type = 'ellipse';
  13531. var PI$2 = Math.PI;
  13532. var PI2$5 = PI$2 * 2;
  13533. var mathSin$3 = Math.sin;
  13534. var mathCos$3 = Math.cos;
  13535. var mathACos = Math.acos;
  13536. var mathATan2 = Math.atan2;
  13537. var mathAbs$3 = Math.abs;
  13538. var mathSqrt$3 = Math.sqrt;
  13539. var mathMax$4 = Math.max;
  13540. var mathMin$4 = Math.min;
  13541. var e = 1e-4;
  13542. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13543. var dx10 = x1 - x0;
  13544. var dy10 = y1 - y0;
  13545. var dx32 = x3 - x2;
  13546. var dy32 = y3 - y2;
  13547. var t = dy32 * dx10 - dx32 * dy10;
  13548. if (t * t < e) {
  13549. return;
  13550. }
  13551. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13552. return [x0 + t * dx10, y0 + t * dy10];
  13553. }
  13554. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13555. var x01 = x0 - x1;
  13556. var y01 = y0 - y1;
  13557. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13558. var ox = lo * y01;
  13559. var oy = -lo * x01;
  13560. var x11 = x0 + ox;
  13561. var y11 = y0 + oy;
  13562. var x10 = x1 + ox;
  13563. var y10 = y1 + oy;
  13564. var x00 = (x11 + x10) / 2;
  13565. var y00 = (y11 + y10) / 2;
  13566. var dx = x10 - x11;
  13567. var dy = y10 - y11;
  13568. var d2 = dx * dx + dy * dy;
  13569. var r = radius - cr;
  13570. var s = x11 * y10 - x10 * y11;
  13571. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$4(0, r * r * d2 - s * s));
  13572. var cx0 = (s * dy - dx * d) / d2;
  13573. var cy0 = (-s * dx - dy * d) / d2;
  13574. var cx1 = (s * dy + dx * d) / d2;
  13575. var cy1 = (-s * dx + dy * d) / d2;
  13576. var dx0 = cx0 - x00;
  13577. var dy0 = cy0 - y00;
  13578. var dx1 = cx1 - x00;
  13579. var dy1 = cy1 - y00;
  13580. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13581. cx0 = cx1;
  13582. cy0 = cy1;
  13583. }
  13584. return {
  13585. cx: cx0,
  13586. cy: cy0,
  13587. x0: -ox,
  13588. y0: -oy,
  13589. x1: cx0 * (radius / r - 1),
  13590. y1: cy0 * (radius / r - 1)
  13591. };
  13592. }
  13593. function normalizeCornerRadius(cr) {
  13594. var arr;
  13595. if (isArray(cr)) {
  13596. var len = cr.length;
  13597. if (!len) {
  13598. return cr;
  13599. }
  13600. if (len === 1) {
  13601. arr = [cr[0], cr[0], 0, 0];
  13602. }
  13603. else if (len === 2) {
  13604. arr = [cr[0], cr[0], cr[1], cr[1]];
  13605. }
  13606. else if (len === 3) {
  13607. arr = cr.concat(cr[2]);
  13608. }
  13609. else {
  13610. arr = cr;
  13611. }
  13612. }
  13613. else {
  13614. arr = [cr, cr, cr, cr];
  13615. }
  13616. return arr;
  13617. }
  13618. function buildPath$1(ctx, shape) {
  13619. var _a;
  13620. var radius = mathMax$4(shape.r, 0);
  13621. var innerRadius = mathMax$4(shape.r0 || 0, 0);
  13622. var hasRadius = radius > 0;
  13623. var hasInnerRadius = innerRadius > 0;
  13624. if (!hasRadius && !hasInnerRadius) {
  13625. return;
  13626. }
  13627. if (!hasRadius) {
  13628. radius = innerRadius;
  13629. innerRadius = 0;
  13630. }
  13631. if (innerRadius > radius) {
  13632. var tmp = radius;
  13633. radius = innerRadius;
  13634. innerRadius = tmp;
  13635. }
  13636. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13637. if (isNaN(startAngle) || isNaN(endAngle)) {
  13638. return;
  13639. }
  13640. var cx = shape.cx, cy = shape.cy;
  13641. var clockwise = !!shape.clockwise;
  13642. var arc = mathAbs$3(endAngle - startAngle);
  13643. var mod = arc > PI2$5 && arc % PI2$5;
  13644. mod > e && (arc = mod);
  13645. if (!(radius > e)) {
  13646. ctx.moveTo(cx, cy);
  13647. }
  13648. else if (arc > PI2$5 - e) {
  13649. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13650. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13651. if (innerRadius > e) {
  13652. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13653. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13654. }
  13655. }
  13656. else {
  13657. var icrStart = void 0;
  13658. var icrEnd = void 0;
  13659. var ocrStart = void 0;
  13660. var ocrEnd = void 0;
  13661. var ocrs = void 0;
  13662. var ocre = void 0;
  13663. var icrs = void 0;
  13664. var icre = void 0;
  13665. var ocrMax = void 0;
  13666. var icrMax = void 0;
  13667. var limitedOcrMax = void 0;
  13668. var limitedIcrMax = void 0;
  13669. var xre = void 0;
  13670. var yre = void 0;
  13671. var xirs = void 0;
  13672. var yirs = void 0;
  13673. var xrs = radius * mathCos$3(startAngle);
  13674. var yrs = radius * mathSin$3(startAngle);
  13675. var xire = innerRadius * mathCos$3(endAngle);
  13676. var yire = innerRadius * mathSin$3(endAngle);
  13677. var hasArc = arc > e;
  13678. if (hasArc) {
  13679. var cornerRadius = shape.cornerRadius;
  13680. if (cornerRadius) {
  13681. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13682. }
  13683. var halfRd = mathAbs$3(radius - innerRadius) / 2;
  13684. ocrs = mathMin$4(halfRd, ocrStart);
  13685. ocre = mathMin$4(halfRd, ocrEnd);
  13686. icrs = mathMin$4(halfRd, icrStart);
  13687. icre = mathMin$4(halfRd, icrEnd);
  13688. limitedOcrMax = ocrMax = mathMax$4(ocrs, ocre);
  13689. limitedIcrMax = icrMax = mathMax$4(icrs, icre);
  13690. if (ocrMax > e || icrMax > e) {
  13691. xre = radius * mathCos$3(endAngle);
  13692. yre = radius * mathSin$3(endAngle);
  13693. xirs = innerRadius * mathCos$3(startAngle);
  13694. yirs = innerRadius * mathSin$3(startAngle);
  13695. if (arc < PI$2) {
  13696. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13697. if (it_1) {
  13698. var x0 = xrs - it_1[0];
  13699. var y0 = yrs - it_1[1];
  13700. var x1 = xre - it_1[0];
  13701. var y1 = yre - it_1[1];
  13702. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13703. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13704. limitedOcrMax = mathMin$4(ocrMax, (radius - b) / (a + 1));
  13705. limitedIcrMax = mathMin$4(icrMax, (innerRadius - b) / (a - 1));
  13706. }
  13707. }
  13708. }
  13709. }
  13710. if (!hasArc) {
  13711. ctx.moveTo(cx + xrs, cy + yrs);
  13712. }
  13713. else if (limitedOcrMax > e) {
  13714. var crStart = mathMin$4(ocrStart, limitedOcrMax);
  13715. var crEnd = mathMin$4(ocrEnd, limitedOcrMax);
  13716. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13717. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13718. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13719. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13720. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13721. }
  13722. else {
  13723. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13724. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13725. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13726. }
  13727. }
  13728. else {
  13729. ctx.moveTo(cx + xrs, cy + yrs);
  13730. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13731. }
  13732. if (!(innerRadius > e) || !hasArc) {
  13733. ctx.lineTo(cx + xire, cy + yire);
  13734. }
  13735. else if (limitedIcrMax > e) {
  13736. var crStart = mathMin$4(icrStart, limitedIcrMax);
  13737. var crEnd = mathMin$4(icrEnd, limitedIcrMax);
  13738. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13739. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13740. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13741. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13742. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13743. }
  13744. else {
  13745. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13746. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13747. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13748. }
  13749. }
  13750. else {
  13751. ctx.lineTo(cx + xire, cy + yire);
  13752. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13753. }
  13754. }
  13755. ctx.closePath();
  13756. }
  13757. var SectorShape = (function () {
  13758. function SectorShape() {
  13759. this.cx = 0;
  13760. this.cy = 0;
  13761. this.r0 = 0;
  13762. this.r = 0;
  13763. this.startAngle = 0;
  13764. this.endAngle = Math.PI * 2;
  13765. this.clockwise = true;
  13766. this.cornerRadius = 0;
  13767. }
  13768. return SectorShape;
  13769. }());
  13770. var Sector = (function (_super) {
  13771. __extends(Sector, _super);
  13772. function Sector(opts) {
  13773. return _super.call(this, opts) || this;
  13774. }
  13775. Sector.prototype.getDefaultShape = function () {
  13776. return new SectorShape();
  13777. };
  13778. Sector.prototype.buildPath = function (ctx, shape) {
  13779. buildPath$1(ctx, shape);
  13780. };
  13781. Sector.prototype.isZeroArea = function () {
  13782. return this.shape.startAngle === this.shape.endAngle
  13783. || this.shape.r === this.shape.r0;
  13784. };
  13785. return Sector;
  13786. }(Path));
  13787. Sector.prototype.type = 'sector';
  13788. var RingShape = (function () {
  13789. function RingShape() {
  13790. this.cx = 0;
  13791. this.cy = 0;
  13792. this.r = 0;
  13793. this.r0 = 0;
  13794. }
  13795. return RingShape;
  13796. }());
  13797. var Ring = (function (_super) {
  13798. __extends(Ring, _super);
  13799. function Ring(opts) {
  13800. return _super.call(this, opts) || this;
  13801. }
  13802. Ring.prototype.getDefaultShape = function () {
  13803. return new RingShape();
  13804. };
  13805. Ring.prototype.buildPath = function (ctx, shape) {
  13806. var x = shape.cx;
  13807. var y = shape.cy;
  13808. var PI2 = Math.PI * 2;
  13809. ctx.moveTo(x + shape.r, y);
  13810. ctx.arc(x, y, shape.r, 0, PI2, false);
  13811. ctx.moveTo(x + shape.r0, y);
  13812. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13813. };
  13814. return Ring;
  13815. }(Path));
  13816. Ring.prototype.type = 'ring';
  13817. function smoothBezier(points, smooth, isLoop, constraint) {
  13818. var cps = [];
  13819. var v = [];
  13820. var v1 = [];
  13821. var v2 = [];
  13822. var prevPoint;
  13823. var nextPoint;
  13824. var min$1;
  13825. var max$1;
  13826. if (constraint) {
  13827. min$1 = [Infinity, Infinity];
  13828. max$1 = [-Infinity, -Infinity];
  13829. for (var i = 0, len = points.length; i < len; i++) {
  13830. min(min$1, min$1, points[i]);
  13831. max(max$1, max$1, points[i]);
  13832. }
  13833. min(min$1, min$1, constraint[0]);
  13834. max(max$1, max$1, constraint[1]);
  13835. }
  13836. for (var i = 0, len = points.length; i < len; i++) {
  13837. var point = points[i];
  13838. if (isLoop) {
  13839. prevPoint = points[i ? i - 1 : len - 1];
  13840. nextPoint = points[(i + 1) % len];
  13841. }
  13842. else {
  13843. if (i === 0 || i === len - 1) {
  13844. cps.push(clone$1(points[i]));
  13845. continue;
  13846. }
  13847. else {
  13848. prevPoint = points[i - 1];
  13849. nextPoint = points[i + 1];
  13850. }
  13851. }
  13852. sub(v, nextPoint, prevPoint);
  13853. scale(v, v, smooth);
  13854. var d0 = distance(point, prevPoint);
  13855. var d1 = distance(point, nextPoint);
  13856. var sum = d0 + d1;
  13857. if (sum !== 0) {
  13858. d0 /= sum;
  13859. d1 /= sum;
  13860. }
  13861. scale(v1, v, -d0);
  13862. scale(v2, v, d1);
  13863. var cp0 = add([], point, v1);
  13864. var cp1 = add([], point, v2);
  13865. if (constraint) {
  13866. max(cp0, cp0, min$1);
  13867. min(cp0, cp0, max$1);
  13868. max(cp1, cp1, min$1);
  13869. min(cp1, cp1, max$1);
  13870. }
  13871. cps.push(cp0);
  13872. cps.push(cp1);
  13873. }
  13874. if (isLoop) {
  13875. cps.push(cps.shift());
  13876. }
  13877. return cps;
  13878. }
  13879. function buildPath$2(ctx, shape, closePath) {
  13880. var smooth = shape.smooth;
  13881. var points = shape.points;
  13882. if (points && points.length >= 2) {
  13883. if (smooth) {
  13884. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13885. ctx.moveTo(points[0][0], points[0][1]);
  13886. var len = points.length;
  13887. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13888. var cp1 = controlPoints[i * 2];
  13889. var cp2 = controlPoints[i * 2 + 1];
  13890. var p = points[(i + 1) % len];
  13891. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13892. }
  13893. }
  13894. else {
  13895. ctx.moveTo(points[0][0], points[0][1]);
  13896. for (var i = 1, l = points.length; i < l; i++) {
  13897. ctx.lineTo(points[i][0], points[i][1]);
  13898. }
  13899. }
  13900. closePath && ctx.closePath();
  13901. }
  13902. }
  13903. var PolygonShape = (function () {
  13904. function PolygonShape() {
  13905. this.points = null;
  13906. this.smooth = 0;
  13907. this.smoothConstraint = null;
  13908. }
  13909. return PolygonShape;
  13910. }());
  13911. var Polygon = (function (_super) {
  13912. __extends(Polygon, _super);
  13913. function Polygon(opts) {
  13914. return _super.call(this, opts) || this;
  13915. }
  13916. Polygon.prototype.getDefaultShape = function () {
  13917. return new PolygonShape();
  13918. };
  13919. Polygon.prototype.buildPath = function (ctx, shape) {
  13920. buildPath$2(ctx, shape, true);
  13921. };
  13922. return Polygon;
  13923. }(Path));
  13924. Polygon.prototype.type = 'polygon';
  13925. var PolylineShape = (function () {
  13926. function PolylineShape() {
  13927. this.points = null;
  13928. this.percent = 1;
  13929. this.smooth = 0;
  13930. this.smoothConstraint = null;
  13931. }
  13932. return PolylineShape;
  13933. }());
  13934. var Polyline = (function (_super) {
  13935. __extends(Polyline, _super);
  13936. function Polyline(opts) {
  13937. return _super.call(this, opts) || this;
  13938. }
  13939. Polyline.prototype.getDefaultStyle = function () {
  13940. return {
  13941. stroke: '#000',
  13942. fill: null
  13943. };
  13944. };
  13945. Polyline.prototype.getDefaultShape = function () {
  13946. return new PolylineShape();
  13947. };
  13948. Polyline.prototype.buildPath = function (ctx, shape) {
  13949. buildPath$2(ctx, shape, false);
  13950. };
  13951. return Polyline;
  13952. }(Path));
  13953. Polyline.prototype.type = 'polyline';
  13954. var subPixelOptimizeOutputShape$1 = {};
  13955. var LineShape = (function () {
  13956. function LineShape() {
  13957. this.x1 = 0;
  13958. this.y1 = 0;
  13959. this.x2 = 0;
  13960. this.y2 = 0;
  13961. this.percent = 1;
  13962. }
  13963. return LineShape;
  13964. }());
  13965. var Line = (function (_super) {
  13966. __extends(Line, _super);
  13967. function Line(opts) {
  13968. return _super.call(this, opts) || this;
  13969. }
  13970. Line.prototype.getDefaultStyle = function () {
  13971. return {
  13972. stroke: '#000',
  13973. fill: null
  13974. };
  13975. };
  13976. Line.prototype.getDefaultShape = function () {
  13977. return new LineShape();
  13978. };
  13979. Line.prototype.buildPath = function (ctx, shape) {
  13980. var x1;
  13981. var y1;
  13982. var x2;
  13983. var y2;
  13984. if (this.subPixelOptimize) {
  13985. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13986. x1 = optimizedShape.x1;
  13987. y1 = optimizedShape.y1;
  13988. x2 = optimizedShape.x2;
  13989. y2 = optimizedShape.y2;
  13990. }
  13991. else {
  13992. x1 = shape.x1;
  13993. y1 = shape.y1;
  13994. x2 = shape.x2;
  13995. y2 = shape.y2;
  13996. }
  13997. var percent = shape.percent;
  13998. if (percent === 0) {
  13999. return;
  14000. }
  14001. ctx.moveTo(x1, y1);
  14002. if (percent < 1) {
  14003. x2 = x1 * (1 - percent) + x2 * percent;
  14004. y2 = y1 * (1 - percent) + y2 * percent;
  14005. }
  14006. ctx.lineTo(x2, y2);
  14007. };
  14008. Line.prototype.pointAt = function (p) {
  14009. var shape = this.shape;
  14010. return [
  14011. shape.x1 * (1 - p) + shape.x2 * p,
  14012. shape.y1 * (1 - p) + shape.y2 * p
  14013. ];
  14014. };
  14015. return Line;
  14016. }(Path));
  14017. Line.prototype.type = 'line';
  14018. var out = [];
  14019. var BezierCurveShape = (function () {
  14020. function BezierCurveShape() {
  14021. this.x1 = 0;
  14022. this.y1 = 0;
  14023. this.x2 = 0;
  14024. this.y2 = 0;
  14025. this.cpx1 = 0;
  14026. this.cpy1 = 0;
  14027. this.percent = 1;
  14028. }
  14029. return BezierCurveShape;
  14030. }());
  14031. function someVectorAt(shape, t, isTangent) {
  14032. var cpx2 = shape.cpx2;
  14033. var cpy2 = shape.cpy2;
  14034. if (cpx2 != null || cpy2 != null) {
  14035. return [
  14036. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14037. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14038. ];
  14039. }
  14040. else {
  14041. return [
  14042. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14043. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14044. ];
  14045. }
  14046. }
  14047. var BezierCurve = (function (_super) {
  14048. __extends(BezierCurve, _super);
  14049. function BezierCurve(opts) {
  14050. return _super.call(this, opts) || this;
  14051. }
  14052. BezierCurve.prototype.getDefaultStyle = function () {
  14053. return {
  14054. stroke: '#000',
  14055. fill: null
  14056. };
  14057. };
  14058. BezierCurve.prototype.getDefaultShape = function () {
  14059. return new BezierCurveShape();
  14060. };
  14061. BezierCurve.prototype.buildPath = function (ctx, shape) {
  14062. var x1 = shape.x1;
  14063. var y1 = shape.y1;
  14064. var x2 = shape.x2;
  14065. var y2 = shape.y2;
  14066. var cpx1 = shape.cpx1;
  14067. var cpy1 = shape.cpy1;
  14068. var cpx2 = shape.cpx2;
  14069. var cpy2 = shape.cpy2;
  14070. var percent = shape.percent;
  14071. if (percent === 0) {
  14072. return;
  14073. }
  14074. ctx.moveTo(x1, y1);
  14075. if (cpx2 == null || cpy2 == null) {
  14076. if (percent < 1) {
  14077. quadraticSubdivide(x1, cpx1, x2, percent, out);
  14078. cpx1 = out[1];
  14079. x2 = out[2];
  14080. quadraticSubdivide(y1, cpy1, y2, percent, out);
  14081. cpy1 = out[1];
  14082. y2 = out[2];
  14083. }
  14084. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  14085. }
  14086. else {
  14087. if (percent < 1) {
  14088. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  14089. cpx1 = out[1];
  14090. cpx2 = out[2];
  14091. x2 = out[3];
  14092. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  14093. cpy1 = out[1];
  14094. cpy2 = out[2];
  14095. y2 = out[3];
  14096. }
  14097. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  14098. }
  14099. };
  14100. BezierCurve.prototype.pointAt = function (t) {
  14101. return someVectorAt(this.shape, t, false);
  14102. };
  14103. BezierCurve.prototype.tangentAt = function (t) {
  14104. var p = someVectorAt(this.shape, t, true);
  14105. return normalize(p, p);
  14106. };
  14107. return BezierCurve;
  14108. }(Path));
  14109. BezierCurve.prototype.type = 'bezier-curve';
  14110. var ArcShape = (function () {
  14111. function ArcShape() {
  14112. this.cx = 0;
  14113. this.cy = 0;
  14114. this.r = 0;
  14115. this.startAngle = 0;
  14116. this.endAngle = Math.PI * 2;
  14117. this.clockwise = true;
  14118. }
  14119. return ArcShape;
  14120. }());
  14121. var Arc = (function (_super) {
  14122. __extends(Arc, _super);
  14123. function Arc(opts) {
  14124. return _super.call(this, opts) || this;
  14125. }
  14126. Arc.prototype.getDefaultStyle = function () {
  14127. return {
  14128. stroke: '#000',
  14129. fill: null
  14130. };
  14131. };
  14132. Arc.prototype.getDefaultShape = function () {
  14133. return new ArcShape();
  14134. };
  14135. Arc.prototype.buildPath = function (ctx, shape) {
  14136. var x = shape.cx;
  14137. var y = shape.cy;
  14138. var r = Math.max(shape.r, 0);
  14139. var startAngle = shape.startAngle;
  14140. var endAngle = shape.endAngle;
  14141. var clockwise = shape.clockwise;
  14142. var unitX = Math.cos(startAngle);
  14143. var unitY = Math.sin(startAngle);
  14144. ctx.moveTo(unitX * r + x, unitY * r + y);
  14145. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14146. };
  14147. return Arc;
  14148. }(Path));
  14149. Arc.prototype.type = 'arc';
  14150. var CompoundPath = (function (_super) {
  14151. __extends(CompoundPath, _super);
  14152. function CompoundPath() {
  14153. var _this = _super !== null && _super.apply(this, arguments) || this;
  14154. _this.type = 'compound';
  14155. return _this;
  14156. }
  14157. CompoundPath.prototype._updatePathDirty = function () {
  14158. var paths = this.shape.paths;
  14159. var dirtyPath = this.shapeChanged();
  14160. for (var i = 0; i < paths.length; i++) {
  14161. dirtyPath = dirtyPath || paths[i].shapeChanged();
  14162. }
  14163. if (dirtyPath) {
  14164. this.dirtyShape();
  14165. }
  14166. };
  14167. CompoundPath.prototype.beforeBrush = function () {
  14168. this._updatePathDirty();
  14169. var paths = this.shape.paths || [];
  14170. var scale = this.getGlobalScale();
  14171. for (var i = 0; i < paths.length; i++) {
  14172. if (!paths[i].path) {
  14173. paths[i].createPathProxy();
  14174. }
  14175. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14176. }
  14177. };
  14178. CompoundPath.prototype.buildPath = function (ctx, shape) {
  14179. var paths = shape.paths || [];
  14180. for (var i = 0; i < paths.length; i++) {
  14181. paths[i].buildPath(ctx, paths[i].shape, true);
  14182. }
  14183. };
  14184. CompoundPath.prototype.afterBrush = function () {
  14185. var paths = this.shape.paths || [];
  14186. for (var i = 0; i < paths.length; i++) {
  14187. paths[i].pathUpdated();
  14188. }
  14189. };
  14190. CompoundPath.prototype.getBoundingRect = function () {
  14191. this._updatePathDirty.call(this);
  14192. return Path.prototype.getBoundingRect.call(this);
  14193. };
  14194. return CompoundPath;
  14195. }(Path));
  14196. var Gradient = (function () {
  14197. function Gradient(colorStops) {
  14198. this.colorStops = colorStops || [];
  14199. }
  14200. Gradient.prototype.addColorStop = function (offset, color) {
  14201. this.colorStops.push({
  14202. offset: offset,
  14203. color: color
  14204. });
  14205. };
  14206. return Gradient;
  14207. }());
  14208. var LinearGradient = (function (_super) {
  14209. __extends(LinearGradient, _super);
  14210. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  14211. var _this = _super.call(this, colorStops) || this;
  14212. _this.x = x == null ? 0 : x;
  14213. _this.y = y == null ? 0 : y;
  14214. _this.x2 = x2 == null ? 1 : x2;
  14215. _this.y2 = y2 == null ? 0 : y2;
  14216. _this.type = 'linear';
  14217. _this.global = globalCoord || false;
  14218. return _this;
  14219. }
  14220. return LinearGradient;
  14221. }(Gradient));
  14222. var RadialGradient = (function (_super) {
  14223. __extends(RadialGradient, _super);
  14224. function RadialGradient(x, y, r, colorStops, globalCoord) {
  14225. var _this = _super.call(this, colorStops) || this;
  14226. _this.x = x == null ? 0.5 : x;
  14227. _this.y = y == null ? 0.5 : y;
  14228. _this.r = r == null ? 0.5 : r;
  14229. _this.type = 'radial';
  14230. _this.global = globalCoord || false;
  14231. return _this;
  14232. }
  14233. return RadialGradient;
  14234. }(Gradient));
  14235. var mathMin$5 = Math.min;
  14236. var mathMax$5 = Math.max;
  14237. var mathAbs$4 = Math.abs;
  14238. var _extent = [0, 0];
  14239. var _extent2 = [0, 0];
  14240. var _intersectCtx$1 = createIntersectContext();
  14241. var _minTv$1 = _intersectCtx$1.minTv;
  14242. var _maxTv$1 = _intersectCtx$1.maxTv;
  14243. var OrientedBoundingRect = (function () {
  14244. function OrientedBoundingRect(rect, transform) {
  14245. this._corners = [];
  14246. this._axes = [];
  14247. this._origin = [0, 0];
  14248. for (var i = 0; i < 4; i++) {
  14249. this._corners[i] = new Point();
  14250. }
  14251. for (var i = 0; i < 2; i++) {
  14252. this._axes[i] = new Point();
  14253. }
  14254. if (rect) {
  14255. this.fromBoundingRect(rect, transform);
  14256. }
  14257. }
  14258. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  14259. var corners = this._corners;
  14260. var axes = this._axes;
  14261. var x = rect.x;
  14262. var y = rect.y;
  14263. var x2 = x + rect.width;
  14264. var y2 = y + rect.height;
  14265. corners[0].set(x, y);
  14266. corners[1].set(x2, y);
  14267. corners[2].set(x2, y2);
  14268. corners[3].set(x, y2);
  14269. if (transform) {
  14270. for (var i = 0; i < 4; i++) {
  14271. corners[i].transform(transform);
  14272. }
  14273. }
  14274. Point.sub(axes[0], corners[1], corners[0]);
  14275. Point.sub(axes[1], corners[3], corners[0]);
  14276. axes[0].normalize();
  14277. axes[1].normalize();
  14278. for (var i = 0; i < 2; i++) {
  14279. this._origin[i] = axes[i].dot(corners[0]);
  14280. }
  14281. };
  14282. OrientedBoundingRect.prototype.intersect = function (other, mtv, opt) {
  14283. var overlapped = true;
  14284. var noMtv = !mtv;
  14285. if (mtv) {
  14286. Point.set(mtv, 0, 0);
  14287. }
  14288. _intersectCtx$1.reset(opt, !noMtv);
  14289. if (!this._intersectCheckOneSide(this, other, noMtv, 1)) {
  14290. overlapped = false;
  14291. if (noMtv) {
  14292. return overlapped;
  14293. }
  14294. }
  14295. if (!this._intersectCheckOneSide(other, this, noMtv, -1)) {
  14296. overlapped = false;
  14297. if (noMtv) {
  14298. return overlapped;
  14299. }
  14300. }
  14301. if (!noMtv && !_intersectCtx$1.negativeSize) {
  14302. Point.copy(mtv, overlapped
  14303. ? (_intersectCtx$1.useDir ? _intersectCtx$1.dirMinTv : _minTv$1)
  14304. : _maxTv$1);
  14305. }
  14306. return overlapped;
  14307. };
  14308. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, noMtv, inverse) {
  14309. var overlapped = true;
  14310. for (var i = 0; i < 2; i++) {
  14311. var axis = self._axes[i];
  14312. self._getProjMinMaxOnAxis(i, self._corners, _extent);
  14313. self._getProjMinMaxOnAxis(i, other._corners, _extent2);
  14314. if (_intersectCtx$1.negativeSize || _extent[1] < _extent2[0] || _extent[0] > _extent2[1]) {
  14315. overlapped = false;
  14316. if (_intersectCtx$1.negativeSize || noMtv) {
  14317. return overlapped;
  14318. }
  14319. var dist0 = mathAbs$4(_extent2[0] - _extent[1]);
  14320. var dist1 = mathAbs$4(_extent[0] - _extent2[1]);
  14321. if (mathMin$5(dist0, dist1) > _maxTv$1.len()) {
  14322. if (dist0 < dist1) {
  14323. Point.scale(_maxTv$1, axis, -dist0 * inverse);
  14324. }
  14325. else {
  14326. Point.scale(_maxTv$1, axis, dist1 * inverse);
  14327. }
  14328. }
  14329. }
  14330. else if (!noMtv) {
  14331. var dist0 = mathAbs$4(_extent2[0] - _extent[1]);
  14332. var dist1 = mathAbs$4(_extent[0] - _extent2[1]);
  14333. if (_intersectCtx$1.useDir || mathMin$5(dist0, dist1) < _minTv$1.len()) {
  14334. if (dist0 < dist1 || !_intersectCtx$1.bidirectional) {
  14335. Point.scale(_minTv$1, axis, dist0 * inverse);
  14336. if (_intersectCtx$1.useDir) {
  14337. _intersectCtx$1.calcDirMTV();
  14338. }
  14339. }
  14340. if (dist0 >= dist1 || !_intersectCtx$1.bidirectional) {
  14341. Point.scale(_minTv$1, axis, -dist1 * inverse);
  14342. if (_intersectCtx$1.useDir) {
  14343. _intersectCtx$1.calcDirMTV();
  14344. }
  14345. }
  14346. }
  14347. }
  14348. }
  14349. return overlapped;
  14350. };
  14351. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  14352. var axis = this._axes[dim];
  14353. var origin = this._origin;
  14354. var proj = corners[0].dot(axis) + origin[dim];
  14355. var min = proj;
  14356. var max = proj;
  14357. for (var i = 1; i < corners.length; i++) {
  14358. var proj_1 = corners[i].dot(axis) + origin[dim];
  14359. min = mathMin$5(proj_1, min);
  14360. max = mathMax$5(proj_1, max);
  14361. }
  14362. out[0] = min + _intersectCtx$1.touchThreshold;
  14363. out[1] = max - _intersectCtx$1.touchThreshold;
  14364. _intersectCtx$1.negativeSize = out[1] < out[0];
  14365. };
  14366. return OrientedBoundingRect;
  14367. }());
  14368. var m = [];
  14369. var IncrementalDisplayable = (function (_super) {
  14370. __extends(IncrementalDisplayable, _super);
  14371. function IncrementalDisplayable() {
  14372. var _this = _super !== null && _super.apply(this, arguments) || this;
  14373. _this.notClear = true;
  14374. _this.incremental = true;
  14375. _this._displayables = [];
  14376. _this._temporaryDisplayables = [];
  14377. _this._cursor = 0;
  14378. return _this;
  14379. }
  14380. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  14381. cb.call(context, this);
  14382. };
  14383. IncrementalDisplayable.prototype.useStyle = function () {
  14384. this.style = {};
  14385. };
  14386. IncrementalDisplayable.prototype.getCursor = function () {
  14387. return this._cursor;
  14388. };
  14389. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  14390. this._cursor = this._displayables.length;
  14391. };
  14392. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  14393. this._displayables = [];
  14394. this._temporaryDisplayables = [];
  14395. this._cursor = 0;
  14396. this.markRedraw();
  14397. this.notClear = false;
  14398. };
  14399. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  14400. this._temporaryDisplayables = [];
  14401. };
  14402. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  14403. if (notPersistent) {
  14404. this._temporaryDisplayables.push(displayable);
  14405. }
  14406. else {
  14407. this._displayables.push(displayable);
  14408. }
  14409. this.markRedraw();
  14410. };
  14411. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  14412. notPersistent = notPersistent || false;
  14413. for (var i = 0; i < displayables.length; i++) {
  14414. this.addDisplayable(displayables[i], notPersistent);
  14415. }
  14416. };
  14417. IncrementalDisplayable.prototype.getDisplayables = function () {
  14418. return this._displayables;
  14419. };
  14420. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  14421. return this._temporaryDisplayables;
  14422. };
  14423. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  14424. for (var i = this._cursor; i < this._displayables.length; i++) {
  14425. cb && cb(this._displayables[i]);
  14426. }
  14427. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14428. cb && cb(this._temporaryDisplayables[i]);
  14429. }
  14430. };
  14431. IncrementalDisplayable.prototype.update = function () {
  14432. this.updateTransform();
  14433. for (var i = this._cursor; i < this._displayables.length; i++) {
  14434. var displayable = this._displayables[i];
  14435. displayable.parent = this;
  14436. displayable.update();
  14437. displayable.parent = null;
  14438. }
  14439. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14440. var displayable = this._temporaryDisplayables[i];
  14441. displayable.parent = this;
  14442. displayable.update();
  14443. displayable.parent = null;
  14444. }
  14445. };
  14446. IncrementalDisplayable.prototype.getBoundingRect = function () {
  14447. if (!this._rect) {
  14448. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14449. for (var i = 0; i < this._displayables.length; i++) {
  14450. var displayable = this._displayables[i];
  14451. var childRect = displayable.getBoundingRect().clone();
  14452. if (displayable.needLocalTransform()) {
  14453. childRect.applyTransform(displayable.getLocalTransform(m));
  14454. }
  14455. rect.union(childRect);
  14456. }
  14457. this._rect = rect;
  14458. }
  14459. return this._rect;
  14460. };
  14461. IncrementalDisplayable.prototype.contain = function (x, y) {
  14462. var localPos = this.transformCoordToLocal(x, y);
  14463. var rect = this.getBoundingRect();
  14464. if (rect.contain(localPos[0], localPos[1])) {
  14465. for (var i = 0; i < this._displayables.length; i++) {
  14466. var displayable = this._displayables[i];
  14467. if (displayable.contain(x, y)) {
  14468. return true;
  14469. }
  14470. }
  14471. }
  14472. return false;
  14473. };
  14474. return IncrementalDisplayable;
  14475. }(Displayable));
  14476. // Stored properties for further transition.
  14477. var transitionStore = makeInner();
  14478. /**
  14479. * Return null if animation is disabled.
  14480. */
  14481. function getAnimationConfig(animationType, animatableModel, dataIndex,
  14482. // Extra opts can override the option in animatable model.
  14483. extraOpts,
  14484. // TODO It's only for pictorial bar now.
  14485. extraDelayParams) {
  14486. var animationPayload;
  14487. // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14488. // If animation is enabled. Will use this animation config in payload.
  14489. // If animation is disabled. Just ignore it.
  14490. if (animatableModel && animatableModel.ecModel) {
  14491. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14492. animationPayload = updatePayload && updatePayload.animation;
  14493. }
  14494. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14495. var isUpdate = animationType === 'update';
  14496. if (animationEnabled) {
  14497. var duration = void 0;
  14498. var easing = void 0;
  14499. var delay = void 0;
  14500. if (extraOpts) {
  14501. duration = retrieve2(extraOpts.duration, 200);
  14502. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14503. delay = 0;
  14504. } else {
  14505. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14506. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14507. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14508. }
  14509. // animation from payload has highest priority.
  14510. if (animationPayload) {
  14511. animationPayload.duration != null && (duration = animationPayload.duration);
  14512. animationPayload.easing != null && (easing = animationPayload.easing);
  14513. animationPayload.delay != null && (delay = animationPayload.delay);
  14514. }
  14515. if (isFunction(delay)) {
  14516. delay = delay(dataIndex, extraDelayParams);
  14517. }
  14518. if (isFunction(duration)) {
  14519. duration = duration(dataIndex);
  14520. }
  14521. var config = {
  14522. duration: duration || 0,
  14523. delay: delay,
  14524. easing: easing
  14525. };
  14526. return config;
  14527. } else {
  14528. return null;
  14529. }
  14530. }
  14531. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14532. var isFrom = false;
  14533. var removeOpt;
  14534. if (isFunction(dataIndex)) {
  14535. during = cb;
  14536. cb = dataIndex;
  14537. dataIndex = null;
  14538. } else if (isObject(dataIndex)) {
  14539. cb = dataIndex.cb;
  14540. during = dataIndex.during;
  14541. isFrom = dataIndex.isFrom;
  14542. removeOpt = dataIndex.removeOpt;
  14543. dataIndex = dataIndex.dataIndex;
  14544. }
  14545. var isRemove = animationType === 'leave';
  14546. if (!isRemove) {
  14547. // Must stop the remove animation.
  14548. el.stopAnimation('leave');
  14549. }
  14550. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14551. if (animationConfig && animationConfig.duration > 0) {
  14552. var duration = animationConfig.duration;
  14553. var animationDelay = animationConfig.delay;
  14554. var animationEasing = animationConfig.easing;
  14555. var animateConfig = {
  14556. duration: duration,
  14557. delay: animationDelay || 0,
  14558. easing: animationEasing,
  14559. done: cb,
  14560. force: !!cb || !!during,
  14561. // Set to final state in update/init animation.
  14562. // So the post processing based on the path shape can be done correctly.
  14563. setToFinal: !isRemove,
  14564. scope: animationType,
  14565. during: during
  14566. };
  14567. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14568. } else {
  14569. el.stopAnimation();
  14570. // If `isFrom`, the props is the "from" props.
  14571. !isFrom && el.attr(props);
  14572. // Call during at least once.
  14573. during && during(1);
  14574. cb && cb();
  14575. }
  14576. }
  14577. /**
  14578. * Update graphic element properties with or without animation according to the
  14579. * configuration in series.
  14580. *
  14581. * Caution: this method will stop previous animation.
  14582. * So do not use this method to one element twice before
  14583. * animation starts, unless you know what you are doing.
  14584. * @example
  14585. * graphic.updateProps(el, {
  14586. * position: [100, 100]
  14587. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14588. * // Or
  14589. * graphic.updateProps(el, {
  14590. * position: [100, 100]
  14591. * }, seriesModel, function () { console.log('Animation done!'); });
  14592. */
  14593. function updateProps(el, props,
  14594. // TODO: TYPE AnimatableModel
  14595. animatableModel, dataIndex, cb, during) {
  14596. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14597. }
  14598. /**
  14599. * Init graphic element properties with or without animation according to the
  14600. * configuration in series.
  14601. *
  14602. * Caution: this method will stop previous animation.
  14603. * So do not use this method to one element twice before
  14604. * animation starts, unless you know what you are doing.
  14605. */
  14606. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14607. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14608. }
  14609. /**
  14610. * If element is removed.
  14611. * It can determine if element is having remove animation.
  14612. */
  14613. function isElementRemoved(el) {
  14614. if (!el.__zr) {
  14615. return true;
  14616. }
  14617. for (var i = 0; i < el.animators.length; i++) {
  14618. var animator = el.animators[i];
  14619. if (animator.scope === 'leave') {
  14620. return true;
  14621. }
  14622. }
  14623. return false;
  14624. }
  14625. /**
  14626. * Remove graphic element
  14627. */
  14628. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14629. // Don't do remove animation twice.
  14630. if (isElementRemoved(el)) {
  14631. return;
  14632. }
  14633. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14634. }
  14635. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14636. el.removeTextContent();
  14637. el.removeTextGuideLine();
  14638. removeElement(el, {
  14639. style: {
  14640. opacity: 0
  14641. }
  14642. }, animatableModel, dataIndex, done);
  14643. }
  14644. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14645. function doRemove() {
  14646. el.parent && el.parent.remove(el);
  14647. }
  14648. // Hide label and labelLine first
  14649. // TODO Also use fade out animation?
  14650. if (!el.isGroup) {
  14651. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14652. } else {
  14653. el.traverse(function (disp) {
  14654. if (!disp.isGroup) {
  14655. // Can invoke doRemove multiple times.
  14656. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14657. }
  14658. });
  14659. }
  14660. }
  14661. /**
  14662. * Save old style for style transition in universalTransition module.
  14663. * It's used when element will be reused in each render.
  14664. * For chart like map, heatmap, which will always create new element.
  14665. * We don't need to save this because universalTransition can get old style from the old element
  14666. */
  14667. function saveOldStyle(el) {
  14668. transitionStore(el).oldStyle = el.style;
  14669. }
  14670. var _customShapeMap = {};
  14671. var XY$1 = ['x', 'y'];
  14672. var WH$1 = ['width', 'height'];
  14673. /**
  14674. * Extend shape with parameters
  14675. */
  14676. function extendShape(opts) {
  14677. return Path.extend(opts);
  14678. }
  14679. var extendPathFromString = extendFromString;
  14680. /**
  14681. * Extend path
  14682. */
  14683. function extendPath(pathData, opts) {
  14684. return extendPathFromString(pathData, opts);
  14685. }
  14686. /**
  14687. * Register a user defined shape.
  14688. * The shape class can be fetched by `getShapeClass`
  14689. * This method will overwrite the registered shapes, including
  14690. * the registered built-in shapes, if using the same `name`.
  14691. * The shape can be used in `custom series` and
  14692. * `graphic component` by declaring `{type: name}`.
  14693. *
  14694. * @param name
  14695. * @param ShapeClass Can be generated by `extendShape`.
  14696. */
  14697. function registerShape(name, ShapeClass) {
  14698. _customShapeMap[name] = ShapeClass;
  14699. }
  14700. /**
  14701. * Find shape class registered by `registerShape`. Usually used in
  14702. * fetching user defined shape.
  14703. *
  14704. * [Caution]:
  14705. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14706. * to use user registered shapes.
  14707. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14708. * `registerShape` by default. That enables users to get both built-in
  14709. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14710. * the built-in shapes by using names like 'circle', 'rect' via calling
  14711. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14712. * in case that it is overwritten by users, except that some features, like
  14713. * `custom series`, `graphic component`, do it deliberately.
  14714. *
  14715. * (2) In the features like `custom series`, `graphic component`, the user input
  14716. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14717. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14718. * are reserved names, that is, if some user registers a shape named `'image'`,
  14719. * the shape will not be used. If we intending to add some more reserved names
  14720. * in feature, that might bring break changes (disable some existing user shape
  14721. * names). But that case probably rarely happens. So we don't make more mechanism
  14722. * to resolve this issue here.
  14723. *
  14724. * @param name
  14725. * @return The shape class. If not found, return nothing.
  14726. */
  14727. function getShapeClass(name) {
  14728. if (_customShapeMap.hasOwnProperty(name)) {
  14729. return _customShapeMap[name];
  14730. }
  14731. }
  14732. /**
  14733. * Create a path element from path data string
  14734. * @param pathData
  14735. * @param opts
  14736. * @param rect
  14737. * @param layout 'center' or 'cover' default to be cover
  14738. */
  14739. function makePath(pathData, opts, rect, layout) {
  14740. var path = createFromString(pathData, opts);
  14741. if (rect) {
  14742. if (layout === 'center') {
  14743. rect = centerGraphic(rect, path.getBoundingRect());
  14744. }
  14745. resizePath(path, rect);
  14746. }
  14747. return path;
  14748. }
  14749. /**
  14750. * Create a image element from image url
  14751. * @param imageUrl image url
  14752. * @param opts options
  14753. * @param rect constrain rect
  14754. * @param layout 'center' or 'cover'. Default to be 'cover'
  14755. */
  14756. function makeImage(imageUrl, rect, layout) {
  14757. var zrImg = new ZRImage({
  14758. style: {
  14759. image: imageUrl,
  14760. x: rect.x,
  14761. y: rect.y,
  14762. width: rect.width,
  14763. height: rect.height
  14764. },
  14765. onload: function (img) {
  14766. if (layout === 'center') {
  14767. var boundingRect = {
  14768. width: img.width,
  14769. height: img.height
  14770. };
  14771. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14772. }
  14773. }
  14774. });
  14775. return zrImg;
  14776. }
  14777. /**
  14778. * Get position of centered element in bounding box.
  14779. *
  14780. * @param rect element local bounding box
  14781. * @param boundingRect constraint bounding box
  14782. * @return element position containing x, y, width, and height
  14783. */
  14784. function centerGraphic(rect, boundingRect) {
  14785. // Set rect to center, keep width / height ratio.
  14786. var aspect = boundingRect.width / boundingRect.height;
  14787. var width = rect.height * aspect;
  14788. var height;
  14789. if (width <= rect.width) {
  14790. height = rect.height;
  14791. } else {
  14792. width = rect.width;
  14793. height = width / aspect;
  14794. }
  14795. var cx = rect.x + rect.width / 2;
  14796. var cy = rect.y + rect.height / 2;
  14797. return {
  14798. x: cx - width / 2,
  14799. y: cy - height / 2,
  14800. width: width,
  14801. height: height
  14802. };
  14803. }
  14804. var mergePath$1 = mergePath;
  14805. /**
  14806. * Resize a path to fit the rect
  14807. * @param path
  14808. * @param rect
  14809. */
  14810. function resizePath(path, rect) {
  14811. if (!path.applyTransform) {
  14812. return;
  14813. }
  14814. var pathRect = path.getBoundingRect();
  14815. var m = pathRect.calculateTransform(rect);
  14816. path.applyTransform(m);
  14817. }
  14818. /**
  14819. * Sub pixel optimize line for canvas
  14820. */
  14821. function subPixelOptimizeLine$1(shape, lineWidth) {
  14822. subPixelOptimizeLine(shape, shape, {
  14823. lineWidth: lineWidth
  14824. });
  14825. return shape;
  14826. }
  14827. /**
  14828. * Sub pixel optimize rect for canvas
  14829. */
  14830. function subPixelOptimizeRect$1(shape, style) {
  14831. subPixelOptimizeRect(shape, shape, style);
  14832. return shape;
  14833. }
  14834. /**
  14835. * Sub pixel optimize for canvas
  14836. *
  14837. * @param position Coordinate, such as x, y
  14838. * @param lineWidth Should be nonnegative integer.
  14839. * @param positiveOrNegative Default false (negative).
  14840. * @return Optimized position.
  14841. */
  14842. var subPixelOptimize$1 = subPixelOptimize;
  14843. /**
  14844. * Get transform matrix of target (param target),
  14845. * in coordinate of its ancestor (param ancestor)
  14846. *
  14847. * @param target
  14848. * @param [ancestor]
  14849. */
  14850. function getTransform(target, ancestor) {
  14851. var mat = identity([]);
  14852. while (target && target !== ancestor) {
  14853. mul$1(mat, target.getLocalTransform(), mat);
  14854. target = target.parent;
  14855. }
  14856. return mat;
  14857. }
  14858. /**
  14859. * Apply transform to an vertex.
  14860. * @param target [x, y]
  14861. * @param transform Can be:
  14862. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14863. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14864. * @param invert Whether use invert matrix.
  14865. * @return [x, y]
  14866. */
  14867. function applyTransform$1(target, transform, invert$1) {
  14868. if (transform && !isArrayLike(transform)) {
  14869. transform = Transformable.getLocalTransform(transform);
  14870. }
  14871. if (invert$1) {
  14872. transform = invert([], transform);
  14873. }
  14874. return applyTransform([], target, transform);
  14875. }
  14876. /**
  14877. * @param direction 'left' 'right' 'top' 'bottom'
  14878. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14879. * @param invert Whether use invert matrix.
  14880. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14881. */
  14882. function transformDirection(direction, transform, invert) {
  14883. // Pick a base, ensure that transform result will not be (0, 0).
  14884. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : mathAbs$1(2 * transform[4] / transform[0]);
  14885. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : mathAbs$1(2 * transform[4] / transform[2]);
  14886. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14887. vertex = applyTransform$1(vertex, transform, invert);
  14888. return mathAbs$1(vertex[0]) > mathAbs$1(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14889. }
  14890. function isNotGroup(el) {
  14891. return !el.isGroup;
  14892. }
  14893. function isPath(el) {
  14894. return el.shape != null;
  14895. }
  14896. /**
  14897. * Apply group transition animation from g1 to g2.
  14898. * If no animatableModel, no animation.
  14899. */
  14900. function groupTransition(g1, g2, animatableModel) {
  14901. if (!g1 || !g2) {
  14902. return;
  14903. }
  14904. function getElMap(g) {
  14905. var elMap = {};
  14906. g.traverse(function (el) {
  14907. if (isNotGroup(el) && el.anid) {
  14908. elMap[el.anid] = el;
  14909. }
  14910. });
  14911. return elMap;
  14912. }
  14913. function getAnimatableProps(el) {
  14914. var obj = {
  14915. x: el.x,
  14916. y: el.y,
  14917. rotation: el.rotation
  14918. };
  14919. if (isPath(el)) {
  14920. obj.shape = clone(el.shape);
  14921. }
  14922. return obj;
  14923. }
  14924. var elMap1 = getElMap(g1);
  14925. g2.traverse(function (el) {
  14926. if (isNotGroup(el) && el.anid) {
  14927. var oldEl = elMap1[el.anid];
  14928. if (oldEl) {
  14929. var newProp = getAnimatableProps(el);
  14930. el.attr(getAnimatableProps(oldEl));
  14931. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14932. }
  14933. }
  14934. });
  14935. }
  14936. function clipPointsByRect(points, rect) {
  14937. // FIXME: This way might be incorrect when graphic clipped by a corner
  14938. // and when element has a border.
  14939. return map(points, function (point) {
  14940. var x = point[0];
  14941. x = mathMax$1(x, rect.x);
  14942. x = mathMin$1(x, rect.x + rect.width);
  14943. var y = point[1];
  14944. y = mathMax$1(y, rect.y);
  14945. y = mathMin$1(y, rect.y + rect.height);
  14946. return [x, y];
  14947. });
  14948. }
  14949. /**
  14950. * Return a new clipped rect. If rect size are negative, return undefined.
  14951. */
  14952. function clipRectByRect(targetRect, rect) {
  14953. var x = mathMax$1(targetRect.x, rect.x);
  14954. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14955. var y = mathMax$1(targetRect.y, rect.y);
  14956. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14957. // If the total rect is cliped, nothing, including the border,
  14958. // should be painted. So return undefined.
  14959. if (x2 >= x && y2 >= y) {
  14960. return {
  14961. x: x,
  14962. y: y,
  14963. width: x2 - x,
  14964. height: y2 - y
  14965. };
  14966. }
  14967. }
  14968. function createIcon(iconStr,
  14969. // Support 'image://' or 'path://' or direct svg path.
  14970. opt, rect) {
  14971. var innerOpts = extend({
  14972. rectHover: true
  14973. }, opt);
  14974. var style = innerOpts.style = {
  14975. strokeNoScale: true
  14976. };
  14977. rect = rect || {
  14978. x: -1,
  14979. y: -1,
  14980. width: 2,
  14981. height: 2
  14982. };
  14983. if (iconStr) {
  14984. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14985. }
  14986. }
  14987. /**
  14988. * Return `true` if the given line (line `a`) and the given polygon
  14989. * are intersect.
  14990. * Note that we do not count colinear as intersect here because no
  14991. * requirement for that. We could do that if required in future.
  14992. */
  14993. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14994. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14995. var p = points[i];
  14996. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14997. return true;
  14998. }
  14999. p2 = p;
  15000. }
  15001. }
  15002. /**
  15003. * Return `true` if the given two lines (line `a` and line `b`)
  15004. * are intersect.
  15005. * Note that we do not count colinear as intersect here because no
  15006. * requirement for that. We could do that if required in future.
  15007. */
  15008. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  15009. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  15010. var mx = a2x - a1x;
  15011. var my = a2y - a1y;
  15012. var nx = b2x - b1x;
  15013. var ny = b2y - b1y;
  15014. // `vec_m` and `vec_n` are parallel iff
  15015. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  15016. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  15017. if (nearZero(nmCrossProduct)) {
  15018. return false;
  15019. }
  15020. // `vec_m` and `vec_n` are intersect iff
  15021. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  15022. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  15023. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  15024. var b1a1x = a1x - b1x;
  15025. var b1a1y = a1y - b1y;
  15026. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  15027. if (q < 0 || q > 1) {
  15028. return false;
  15029. }
  15030. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  15031. if (p < 0 || p > 1) {
  15032. return false;
  15033. }
  15034. return true;
  15035. }
  15036. /**
  15037. * Cross product of 2-dimension vector.
  15038. */
  15039. function crossProduct2d(x1, y1, x2, y2) {
  15040. return x1 * y2 - x2 * y1;
  15041. }
  15042. function nearZero(val) {
  15043. return val <= 1e-6 && val >= -1e-6;
  15044. }
  15045. /**
  15046. * NOTE:
  15047. * A negative-width/height rect (due to negative margins) is not supported;
  15048. * it will be clampped to zero width/height.
  15049. * Although negative-width/height rects can be defined reasonably following the
  15050. * similar sense in CSS, but they are rarely used, hard to understand and complicated.
  15051. *
  15052. * @param rect Assume its width/height >= 0 if existing.
  15053. * x/y/width/height is allowed to be NaN,
  15054. * for the case that only x/width or y/height is intended to be computed.
  15055. * @param delta
  15056. * If be `number[]`, should be `[top, right, bottom, left]`,
  15057. * which can be used in padding or margin case.
  15058. * @see `normalizeCssArray` in `util/format.ts`
  15059. * If be `number`, it means [delta, delta, delta, delta],
  15060. * which can be used in lineWidth (borderWith) case,
  15061. * [NOTICE]: commonly pass lineWidth / 2, following the convention that border is
  15062. * half inside half outside of the rect.
  15063. * @param shrinkOrExpand
  15064. * `true` - shrink if `delta[i]` is positive, commmonly used in `padding` case.
  15065. * `false` - expand if `delta[i]` is positive, commmonly used in `margin` case. (default)
  15066. * @param noNegative
  15067. * `true` - negative `delta[i]` will be clampped to 0.
  15068. * `false` - No clamp to `delta`. (default).
  15069. * @return The input `rect`.
  15070. */
  15071. function expandOrShrinkRect(rect, delta, shrinkOrExpand, noNegative, minSize // by default [0, 0].
  15072. ) {
  15073. if (delta == null) {
  15074. return rect;
  15075. } else if (isNumber(delta)) {
  15076. _tmpExpandRectDelta[0] = _tmpExpandRectDelta[1] = _tmpExpandRectDelta[2] = _tmpExpandRectDelta[3] = delta;
  15077. } else {
  15078. if ("development" !== 'production') {
  15079. assert(delta.length === 4);
  15080. }
  15081. _tmpExpandRectDelta[0] = delta[0];
  15082. _tmpExpandRectDelta[1] = delta[1];
  15083. _tmpExpandRectDelta[2] = delta[2];
  15084. _tmpExpandRectDelta[3] = delta[3];
  15085. }
  15086. if (noNegative) {
  15087. _tmpExpandRectDelta[0] = mathMax$1(0, _tmpExpandRectDelta[0]);
  15088. _tmpExpandRectDelta[1] = mathMax$1(0, _tmpExpandRectDelta[1]);
  15089. _tmpExpandRectDelta[2] = mathMax$1(0, _tmpExpandRectDelta[2]);
  15090. _tmpExpandRectDelta[3] = mathMax$1(0, _tmpExpandRectDelta[3]);
  15091. }
  15092. if (shrinkOrExpand) {
  15093. _tmpExpandRectDelta[0] = -_tmpExpandRectDelta[0];
  15094. _tmpExpandRectDelta[1] = -_tmpExpandRectDelta[1];
  15095. _tmpExpandRectDelta[2] = -_tmpExpandRectDelta[2];
  15096. _tmpExpandRectDelta[3] = -_tmpExpandRectDelta[3];
  15097. }
  15098. expandRectOnOneDimension(rect, _tmpExpandRectDelta, 'x', 'width', 3, 1, minSize && minSize[0] || 0);
  15099. expandRectOnOneDimension(rect, _tmpExpandRectDelta, 'y', 'height', 0, 2, minSize && minSize[1] || 0);
  15100. return rect;
  15101. }
  15102. var _tmpExpandRectDelta = [0, 0, 0, 0];
  15103. function expandRectOnOneDimension(rect, delta, xy, wh, ltIdx, rbIdx, minSize) {
  15104. var deltaSum = delta[rbIdx] + delta[ltIdx];
  15105. var oldSize = rect[wh];
  15106. rect[wh] += deltaSum;
  15107. minSize = mathMax$1(0, mathMin$1(minSize, oldSize));
  15108. if (rect[wh] < minSize) {
  15109. rect[wh] = minSize;
  15110. // Try to make the position of the zero rect reasonable in most visual cases.
  15111. rect[xy] += delta[ltIdx] >= 0 ? -delta[ltIdx] : delta[rbIdx] >= 0 ? oldSize + delta[rbIdx] : mathAbs$1(deltaSum) > 1e-8 ? (oldSize - minSize) * delta[ltIdx] / deltaSum : 0;
  15112. } else {
  15113. rect[xy] -= delta[ltIdx];
  15114. }
  15115. }
  15116. function setTooltipConfig(opt) {
  15117. var itemTooltipOption = opt.itemTooltipOption;
  15118. var componentModel = opt.componentModel;
  15119. var itemName = opt.itemName;
  15120. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  15121. formatter: itemTooltipOption
  15122. } : itemTooltipOption;
  15123. var mainType = componentModel.mainType;
  15124. var componentIndex = componentModel.componentIndex;
  15125. var formatterParams = {
  15126. componentType: mainType,
  15127. name: itemName,
  15128. $vars: ['name']
  15129. };
  15130. formatterParams[mainType + 'Index'] = componentIndex;
  15131. var formatterParamsExtra = opt.formatterParamsExtra;
  15132. if (formatterParamsExtra) {
  15133. each(keys(formatterParamsExtra), function (key) {
  15134. if (!hasOwn(formatterParams, key)) {
  15135. formatterParams[key] = formatterParamsExtra[key];
  15136. formatterParams.$vars.push(key);
  15137. }
  15138. });
  15139. }
  15140. var ecData = getECData(opt.el);
  15141. ecData.componentMainType = mainType;
  15142. ecData.componentIndex = componentIndex;
  15143. ecData.tooltipConfig = {
  15144. name: itemName,
  15145. option: defaults({
  15146. content: itemName,
  15147. encodeHTMLContent: true,
  15148. formatterParams: formatterParams
  15149. }, itemTooltipOptionObj)
  15150. };
  15151. }
  15152. function traverseElement(el, cb) {
  15153. var stopped;
  15154. // TODO
  15155. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  15156. if (el.isGroup) {
  15157. stopped = cb(el);
  15158. }
  15159. if (!stopped) {
  15160. el.traverse(cb);
  15161. }
  15162. }
  15163. function traverseElements(els, cb) {
  15164. if (els) {
  15165. if (isArray(els)) {
  15166. for (var i = 0; i < els.length; i++) {
  15167. traverseElement(els[i], cb);
  15168. }
  15169. } else {
  15170. traverseElement(els, cb);
  15171. }
  15172. }
  15173. }
  15174. /**
  15175. * After a boundingRect applying a `transform`, whether to be still parallel screen X and Y.
  15176. */
  15177. function isBoundingRectAxisAligned(transform) {
  15178. return !transform || mathAbs$1(transform[1]) < AXIS_ALIGN_EPSILON && mathAbs$1(transform[2]) < AXIS_ALIGN_EPSILON || mathAbs$1(transform[0]) < AXIS_ALIGN_EPSILON && mathAbs$1(transform[3]) < AXIS_ALIGN_EPSILON;
  15179. }
  15180. var AXIS_ALIGN_EPSILON = 1e-5;
  15181. /**
  15182. * Create or copy to the existing bounding rect to avoid modifying `source`.
  15183. *
  15184. * @usage
  15185. * out.rect = ensureCopyRect(out.rect, sourceRect);
  15186. */
  15187. function ensureCopyRect(target, source) {
  15188. return target ? BoundingRect.copy(target, source) : source.clone();
  15189. }
  15190. /**
  15191. * Create or copy to the existing transform to avoid modifying `source`.
  15192. *
  15193. * [CAUTION]: transform is `NullUndefined` if no transform, following convention of zrender,
  15194. * and enable to bypass some unnecessary calculation, since in most cases there is no transform.
  15195. *
  15196. * @usage
  15197. * out.transform = ensureCopyTransform(out.transform, sourceTransform);
  15198. */
  15199. function ensureCopyTransform(target, source) {
  15200. return source ? copy$1(target || create$1(), source) : undefined;
  15201. }
  15202. function retrieveZInfo(model) {
  15203. return {
  15204. z: model.get('z') || 0,
  15205. zlevel: model.get('zlevel') || 0
  15206. };
  15207. }
  15208. /**
  15209. * Assume all of the elements has the same `z` and `zlevel`.
  15210. */
  15211. function calcZ2Range(el) {
  15212. var max = -Infinity;
  15213. var min = Infinity;
  15214. traverseElement(el, function (el) {
  15215. visitEl(el);
  15216. visitEl(el.getTextContent());
  15217. visitEl(el.getTextGuideLine());
  15218. });
  15219. function visitEl(el) {
  15220. if (!el || el.isGroup) {
  15221. return;
  15222. }
  15223. var currentStates = el.currentStates;
  15224. if (currentStates.length) {
  15225. for (var idx = 0; idx < currentStates.length; idx++) {
  15226. calcZ2(el.states[currentStates[idx]]);
  15227. }
  15228. }
  15229. calcZ2(el);
  15230. }
  15231. function calcZ2(entity) {
  15232. if (entity) {
  15233. var z2 = entity.z2;
  15234. // Consider z2 may be NullUndefined
  15235. if (z2 > max) {
  15236. max = z2;
  15237. }
  15238. if (z2 < min) {
  15239. min = z2;
  15240. }
  15241. }
  15242. }
  15243. if (min > max) {
  15244. min = max = 0;
  15245. }
  15246. return {
  15247. min: min,
  15248. max: max
  15249. };
  15250. }
  15251. function traverseUpdateZ(el, z, zlevel) {
  15252. doUpdateZ(el, z, zlevel, -Infinity);
  15253. }
  15254. function doUpdateZ(el, z, zlevel,
  15255. // FIXME: Ideally all the labels should be above all the glyphs by default,
  15256. // e.g. in graph, edge labels should be above node elements.
  15257. // Currently impl does not guarantee that.
  15258. maxZ2) {
  15259. // `ignoreModelZ` is used to intentionally lift elements to cover other elements,
  15260. // where maxZ2 (for label.z2) should also not be counted for its parents.
  15261. if (el.ignoreModelZ) {
  15262. return maxZ2;
  15263. }
  15264. // Group may also have textContent
  15265. var label = el.getTextContent();
  15266. var labelLine = el.getTextGuideLine();
  15267. var isGroup = el.isGroup;
  15268. if (isGroup) {
  15269. // set z & zlevel of children elements of Group
  15270. var children = el.childrenRef();
  15271. for (var i = 0; i < children.length; i++) {
  15272. maxZ2 = mathMax$1(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  15273. }
  15274. } else {
  15275. // not Group
  15276. el.z = z;
  15277. el.zlevel = zlevel;
  15278. maxZ2 = mathMax$1(el.z2 || 0, maxZ2);
  15279. }
  15280. // always set z and zlevel if label/labelLine exists
  15281. if (label) {
  15282. label.z = z;
  15283. label.zlevel = zlevel;
  15284. // lift z2 of text content
  15285. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  15286. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  15287. }
  15288. if (labelLine) {
  15289. var textGuideLineConfig = el.textGuideLineConfig;
  15290. labelLine.z = z;
  15291. labelLine.zlevel = zlevel;
  15292. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  15293. }
  15294. return maxZ2;
  15295. }
  15296. // Register built-in shapes. These shapes might be overwritten
  15297. // by users, although we do not recommend that.
  15298. registerShape('circle', Circle);
  15299. registerShape('ellipse', Ellipse);
  15300. registerShape('sector', Sector);
  15301. registerShape('ring', Ring);
  15302. registerShape('polygon', Polygon);
  15303. registerShape('polyline', Polyline);
  15304. registerShape('rect', Rect);
  15305. registerShape('line', Line);
  15306. registerShape('bezierCurve', BezierCurve);
  15307. registerShape('arc', Arc);
  15308. var graphic = /*#__PURE__*/Object.freeze({
  15309. __proto__: null,
  15310. updateProps: updateProps,
  15311. initProps: initProps,
  15312. removeElement: removeElement,
  15313. removeElementWithFadeOut: removeElementWithFadeOut,
  15314. isElementRemoved: isElementRemoved,
  15315. XY: XY$1,
  15316. WH: WH$1,
  15317. extendShape: extendShape,
  15318. extendPath: extendPath,
  15319. registerShape: registerShape,
  15320. getShapeClass: getShapeClass,
  15321. makePath: makePath,
  15322. makeImage: makeImage,
  15323. mergePath: mergePath$1,
  15324. resizePath: resizePath,
  15325. subPixelOptimizeLine: subPixelOptimizeLine$1,
  15326. subPixelOptimizeRect: subPixelOptimizeRect$1,
  15327. subPixelOptimize: subPixelOptimize$1,
  15328. getTransform: getTransform,
  15329. applyTransform: applyTransform$1,
  15330. transformDirection: transformDirection,
  15331. groupTransition: groupTransition,
  15332. clipPointsByRect: clipPointsByRect,
  15333. clipRectByRect: clipRectByRect,
  15334. createIcon: createIcon,
  15335. linePolygonIntersect: linePolygonIntersect,
  15336. lineLineIntersect: lineLineIntersect,
  15337. expandOrShrinkRect: expandOrShrinkRect,
  15338. setTooltipConfig: setTooltipConfig,
  15339. traverseElements: traverseElements,
  15340. isBoundingRectAxisAligned: isBoundingRectAxisAligned,
  15341. ensureCopyRect: ensureCopyRect,
  15342. ensureCopyTransform: ensureCopyTransform,
  15343. retrieveZInfo: retrieveZInfo,
  15344. calcZ2Range: calcZ2Range,
  15345. traverseUpdateZ: traverseUpdateZ,
  15346. Group: Group,
  15347. Image: ZRImage,
  15348. Text: ZRText,
  15349. Circle: Circle,
  15350. Ellipse: Ellipse,
  15351. Sector: Sector,
  15352. Ring: Ring,
  15353. Polygon: Polygon,
  15354. Polyline: Polyline,
  15355. Rect: Rect,
  15356. Line: Line,
  15357. BezierCurve: BezierCurve,
  15358. Arc: Arc,
  15359. IncrementalDisplayable: IncrementalDisplayable,
  15360. CompoundPath: CompoundPath,
  15361. LinearGradient: LinearGradient,
  15362. RadialGradient: RadialGradient,
  15363. BoundingRect: BoundingRect,
  15364. OrientedBoundingRect: OrientedBoundingRect,
  15365. Point: Point,
  15366. Path: Path
  15367. });
  15368. var EMPTY_OBJ = {};
  15369. function setLabelText(label, labelTexts) {
  15370. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  15371. var stateName = SPECIAL_STATES[i];
  15372. var text = labelTexts[stateName];
  15373. var state = label.ensureState(stateName);
  15374. state.style = state.style || {};
  15375. state.style.text = text;
  15376. }
  15377. var oldStates = label.currentStates.slice();
  15378. label.clearStates(true);
  15379. label.setStyle({
  15380. text: labelTexts.normal
  15381. });
  15382. label.useStates(oldStates, true);
  15383. }
  15384. function getLabelText(opt, stateModels, interpolatedValue) {
  15385. var labelFetcher = opt.labelFetcher;
  15386. var labelDataIndex = opt.labelDataIndex;
  15387. var labelDimIndex = opt.labelDimIndex;
  15388. var normalModel = stateModels.normal;
  15389. var baseText;
  15390. if (labelFetcher) {
  15391. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  15392. interpolatedValue: interpolatedValue
  15393. } : null);
  15394. }
  15395. if (baseText == null) {
  15396. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  15397. }
  15398. var statesText = {
  15399. normal: baseText
  15400. };
  15401. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  15402. var stateName = SPECIAL_STATES[i];
  15403. var stateModel = stateModels[stateName];
  15404. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  15405. }
  15406. return statesText;
  15407. }
  15408. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified
  15409. // TODO specified position?
  15410. ) {
  15411. opt = opt || EMPTY_OBJ;
  15412. var isSetOnText = targetEl instanceof ZRText;
  15413. var needsCreateText = false;
  15414. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  15415. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  15416. if (stateModel && stateModel.getShallow('show')) {
  15417. needsCreateText = true;
  15418. break;
  15419. }
  15420. }
  15421. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  15422. if (needsCreateText) {
  15423. if (!isSetOnText) {
  15424. // Reuse the previous
  15425. if (!textContent) {
  15426. textContent = new ZRText();
  15427. targetEl.setTextContent(textContent);
  15428. }
  15429. // Use same state proxy
  15430. if (targetEl.stateProxy) {
  15431. textContent.stateProxy = targetEl.stateProxy;
  15432. }
  15433. }
  15434. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  15435. var normalModel = labelStatesModels.normal;
  15436. var showNormal = !!normalModel.getShallow('show');
  15437. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  15438. normalStyle.text = labelStatesTexts.normal;
  15439. if (!isSetOnText) {
  15440. // Always create new
  15441. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  15442. }
  15443. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  15444. var stateName = SPECIAL_STATES[i];
  15445. var stateModel = labelStatesModels[stateName];
  15446. if (stateModel) {
  15447. var stateObj = textContent.ensureState(stateName);
  15448. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  15449. if (stateShow !== showNormal) {
  15450. stateObj.ignore = !stateShow;
  15451. }
  15452. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  15453. stateObj.style.text = labelStatesTexts[stateName];
  15454. if (!isSetOnText) {
  15455. var targetElEmphasisState = targetEl.ensureState(stateName);
  15456. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  15457. }
  15458. }
  15459. }
  15460. // PENDING: if there is many requirements that emphasis position
  15461. // need to be different from normal position, we might consider
  15462. // auto silent is those cases.
  15463. textContent.silent = !!normalModel.getShallow('silent');
  15464. // Keep x and y
  15465. if (textContent.style.x != null) {
  15466. normalStyle.x = textContent.style.x;
  15467. }
  15468. if (textContent.style.y != null) {
  15469. normalStyle.y = textContent.style.y;
  15470. }
  15471. textContent.ignore = !showNormal;
  15472. // Always create new style.
  15473. textContent.useStyle(normalStyle);
  15474. textContent.dirty();
  15475. if (opt.enableTextSetter) {
  15476. labelInner(textContent).setLabelText = function (interpolatedValue) {
  15477. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  15478. setLabelText(textContent, labelStatesTexts);
  15479. };
  15480. }
  15481. } else if (textContent) {
  15482. // Not display rich text.
  15483. textContent.ignore = true;
  15484. }
  15485. targetEl.dirty();
  15486. }
  15487. function getLabelStatesModels(itemModel, labelName) {
  15488. labelName = labelName || 'label';
  15489. var statesModels = {
  15490. normal: itemModel.getModel(labelName)
  15491. };
  15492. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  15493. var stateName = SPECIAL_STATES[i];
  15494. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  15495. }
  15496. return statesModels;
  15497. }
  15498. /**
  15499. * Set basic textStyle properties.
  15500. */
  15501. function createTextStyle(textStyleModel, specifiedTextStyle,
  15502. // Fixed style in the code. Can't be set by model.
  15503. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  15504. ) {
  15505. var textStyle = {};
  15506. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  15507. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15508. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15509. return textStyle;
  15510. }
  15511. function createTextConfig(textStyleModel, opt, isNotNormal) {
  15512. opt = opt || {};
  15513. var textConfig = {};
  15514. var labelPosition;
  15515. var labelRotate = textStyleModel.getShallow('rotate');
  15516. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  15517. var labelOffset = textStyleModel.getShallow('offset');
  15518. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside');
  15519. // 'outside' is not a valid zr textPostion value, but used
  15520. // in bar series, and magic type should be considered.
  15521. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  15522. if (labelPosition != null) {
  15523. textConfig.position = labelPosition;
  15524. }
  15525. if (labelOffset != null) {
  15526. textConfig.offset = labelOffset;
  15527. }
  15528. if (labelRotate != null) {
  15529. labelRotate *= Math.PI / 180;
  15530. textConfig.rotation = labelRotate;
  15531. }
  15532. if (labelDistance != null) {
  15533. textConfig.distance = labelDistance;
  15534. }
  15535. // fill and auto is determined by the color of path fill if it's not specified by developers.
  15536. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  15537. if (opt.autoOverflowArea != null) {
  15538. textConfig.autoOverflowArea = opt.autoOverflowArea;
  15539. }
  15540. if (opt.layoutRect != null) {
  15541. textConfig.layoutRect = opt.layoutRect;
  15542. }
  15543. return textConfig;
  15544. }
  15545. /**
  15546. * The uniform entry of set text style, that is, retrieve style definitions
  15547. * from `model` and set to `textStyle` object.
  15548. *
  15549. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15550. * properties will be set. (Consider the states of normal and emphasis and
  15551. * default value can be adopted, merge would make the logic too complicated
  15552. * to manage.)
  15553. */
  15554. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  15555. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15556. opt = opt || EMPTY_OBJ;
  15557. var ecModel = textStyleModel.ecModel;
  15558. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15559. // Consider case:
  15560. // {
  15561. // data: [{
  15562. // value: 12,
  15563. // label: {
  15564. // rich: {
  15565. // // no 'a' here but using parent 'a'.
  15566. // }
  15567. // }
  15568. // }],
  15569. // rich: {
  15570. // a: { ... }
  15571. // }
  15572. // }
  15573. var richItemNames = getRichItemNames(textStyleModel);
  15574. var richResult;
  15575. if (richItemNames) {
  15576. richResult = {};
  15577. var richInheritPlainLabelOptionName = 'richInheritPlainLabel';
  15578. var richInheritPlainLabel = retrieve2(textStyleModel.get(richInheritPlainLabelOptionName), ecModel ? ecModel.get(richInheritPlainLabelOptionName) : undefined);
  15579. for (var name_1 in richItemNames) {
  15580. if (richItemNames.hasOwnProperty(name_1)) {
  15581. // Cascade is supported in rich.
  15582. var richTextStyle = textStyleModel.getModel(['rich', name_1]);
  15583. // In rich, never `disableBox`.
  15584. // consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15585. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15586. // That might confuses users. So probably we should put `textStyleModel` as the
  15587. // root ancestor of the `richTextStyle`. But that would be a break change.
  15588. // Since v6, the rich style inherits plain label by default
  15589. // but this behavior can be disabled by setting `richInheritPlainLabel` to `false`.
  15590. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, textStyleModel, richInheritPlainLabel, opt, isNotNormal, isAttached, false, true);
  15591. }
  15592. }
  15593. }
  15594. if (richResult) {
  15595. textStyle.rich = richResult;
  15596. }
  15597. var overflow = textStyleModel.get('overflow');
  15598. if (overflow) {
  15599. textStyle.overflow = overflow;
  15600. }
  15601. var lineOverflow = textStyleModel.get('lineOverflow');
  15602. if (lineOverflow) {
  15603. textStyle.lineOverflow = lineOverflow;
  15604. }
  15605. var labelTextStyle = textStyle;
  15606. // `minMargin` has a higher precedence than `textMargin`, because `textMargin` is allowed
  15607. // to be set in `defaultOption`.
  15608. var minMargin = textStyleModel.get('minMargin');
  15609. if (minMargin != null) {
  15610. // `minMargin` only support number value.
  15611. minMargin = !isNumber(minMargin) ? 0 : minMargin / 2;
  15612. labelTextStyle.margin = [minMargin, minMargin, minMargin, minMargin];
  15613. labelTextStyle.__marginType = LabelMarginType.minMargin;
  15614. } else {
  15615. var textMargin = textStyleModel.get('textMargin');
  15616. if (textMargin != null) {
  15617. labelTextStyle.margin = normalizeCssArray(textMargin);
  15618. labelTextStyle.__marginType = LabelMarginType.textMargin;
  15619. }
  15620. }
  15621. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, null, null, opt, isNotNormal, isAttached, true, false);
  15622. }
  15623. // Consider case:
  15624. // {
  15625. // data: [{
  15626. // value: 12,
  15627. // label: {
  15628. // rich: {
  15629. // // no 'a' here but using parent 'a'.
  15630. // }
  15631. // }
  15632. // }],
  15633. // rich: {
  15634. // a: { ... }
  15635. // }
  15636. // }
  15637. // TODO TextStyleModel
  15638. function getRichItemNames(textStyleModel) {
  15639. // Use object to remove duplicated names.
  15640. var richItemNameMap;
  15641. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15642. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15643. if (rich) {
  15644. richItemNameMap = richItemNameMap || {};
  15645. var richKeys = keys(rich);
  15646. for (var i = 0; i < richKeys.length; i++) {
  15647. var richKey = richKeys[i];
  15648. richItemNameMap[richKey] = 1;
  15649. }
  15650. }
  15651. textStyleModel = textStyleModel.parentModel;
  15652. }
  15653. return richItemNameMap;
  15654. }
  15655. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  15656. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign', 'ellipsis'];
  15657. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  15658. function setTokenTextStyle(textStyle,
  15659. // FIXME: check/refactor for ellipsis handling of rich text.
  15660. textStyleModel, globalTextStyle, plainTextModel, richInheritPlainLabel, opt, isNotNormal, isAttached, isBlock, inRich) {
  15661. // In merge mode, default value should not be given.
  15662. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  15663. var inheritColor = opt && opt.inheritColor;
  15664. var fillColor = textStyleModel.getShallow('color');
  15665. var strokeColor = textStyleModel.getShallow('textBorderColor');
  15666. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  15667. if (fillColor === 'inherit' || fillColor === 'auto') {
  15668. if ("development" !== 'production') {
  15669. if (fillColor === 'auto') {
  15670. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15671. }
  15672. }
  15673. if (inheritColor) {
  15674. fillColor = inheritColor;
  15675. } else {
  15676. fillColor = null;
  15677. }
  15678. }
  15679. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  15680. if ("development" !== 'production') {
  15681. if (strokeColor === 'auto') {
  15682. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15683. }
  15684. }
  15685. if (inheritColor) {
  15686. strokeColor = inheritColor;
  15687. } else {
  15688. strokeColor = null;
  15689. }
  15690. }
  15691. if (!isAttached) {
  15692. // Only use default global textStyle.color if text is individual.
  15693. // Otherwise it will use the strategy of attached text color because text may be on a path.
  15694. fillColor = fillColor || globalTextStyle.color;
  15695. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  15696. }
  15697. if (fillColor != null) {
  15698. // Might not be a string, e.g, it's a function in axisLabel case; but assume that it will
  15699. // be erased by a correct value outside.
  15700. textStyle.fill = fillColor;
  15701. }
  15702. if (strokeColor != null) {
  15703. textStyle.stroke = strokeColor;
  15704. }
  15705. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  15706. if (textBorderWidth != null) {
  15707. textStyle.lineWidth = textBorderWidth;
  15708. }
  15709. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  15710. if (textBorderType != null) {
  15711. textStyle.lineDash = textBorderType;
  15712. }
  15713. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  15714. if (textBorderDashOffset != null) {
  15715. textStyle.lineDashOffset = textBorderDashOffset;
  15716. }
  15717. if (!isNotNormal && opacity == null && !inRich) {
  15718. opacity = opt && opt.defaultOpacity;
  15719. }
  15720. if (opacity != null) {
  15721. textStyle.opacity = opacity;
  15722. }
  15723. // TODO
  15724. if (!isNotNormal && !isAttached) {
  15725. // Set default finally.
  15726. if (textStyle.fill == null && opt.inheritColor) {
  15727. textStyle.fill = opt.inheritColor;
  15728. }
  15729. }
  15730. // Do not use `getFont` here, because merge should be supported, where
  15731. // part of these properties may be changed in emphasis style, and the
  15732. // others should remain their original value got from normal style.
  15733. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  15734. var key = TEXT_PROPS_WITH_GLOBAL[i];
  15735. // props width, height, padding, margin, tag, backgroundColor, borderColor,
  15736. // borderWidth, borderRadius, shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY
  15737. // may inappropriate to inherit from plainTextStyle.
  15738. // And if some props is specified in default options, users may have to reset them one by one.
  15739. // Therefore, we only allow these props to inherit from plainTextStyle.
  15740. // `richInheritPlainLabel` is switch for backward compatibility
  15741. var val = richInheritPlainLabel !== false && plainTextModel ? retrieve3(textStyleModel.getShallow(key), plainTextModel.getShallow(key), globalTextStyle[key]) : retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  15742. if (val != null) {
  15743. textStyle[key] = val;
  15744. }
  15745. }
  15746. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  15747. var key = TEXT_PROPS_SELF[i];
  15748. var val = textStyleModel.getShallow(key);
  15749. if (val != null) {
  15750. textStyle[key] = val;
  15751. }
  15752. }
  15753. if (textStyle.verticalAlign == null) {
  15754. var baseline = textStyleModel.getShallow('baseline');
  15755. if (baseline != null) {
  15756. textStyle.verticalAlign = baseline;
  15757. }
  15758. }
  15759. if (!isBlock || !opt.disableBox) {
  15760. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15761. var key = TEXT_PROPS_BOX[i];
  15762. var val = textStyleModel.getShallow(key);
  15763. if (val != null) {
  15764. textStyle[key] = val;
  15765. }
  15766. }
  15767. var borderType = textStyleModel.getShallow('borderType');
  15768. if (borderType != null) {
  15769. textStyle.borderDash = borderType;
  15770. }
  15771. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15772. if ("development" !== 'production') {
  15773. if (textStyle.backgroundColor === 'auto') {
  15774. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15775. }
  15776. }
  15777. textStyle.backgroundColor = inheritColor;
  15778. }
  15779. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15780. if ("development" !== 'production') {
  15781. if (textStyle.borderColor === 'auto') {
  15782. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15783. }
  15784. }
  15785. textStyle.borderColor = inheritColor;
  15786. }
  15787. }
  15788. }
  15789. function getFont(opt, ecModel) {
  15790. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15791. return trim([
  15792. // FIXME in node-canvas fontWeight is before fontStyle
  15793. 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(' '));
  15794. }
  15795. var labelInner = makeInner();
  15796. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15797. if (!label) {
  15798. return;
  15799. }
  15800. var obj = labelInner(label);
  15801. obj.prevValue = obj.value;
  15802. obj.value = value;
  15803. var normalLabelModel = labelStatesModels.normal;
  15804. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15805. if (obj.valueAnimation) {
  15806. obj.precision = normalLabelModel.get('precision');
  15807. obj.defaultInterpolatedText = getDefaultText;
  15808. obj.statesModels = labelStatesModels;
  15809. }
  15810. }
  15811. /**
  15812. * PENDING: Temporary impl. unify them?
  15813. * @see {LabelCommonOption['textMargin']}
  15814. * @see {LabelCommonOption['minMargin']}
  15815. */
  15816. var LabelMarginType = {
  15817. minMargin: 1,
  15818. textMargin: 2
  15819. };
  15820. var PATH_COLOR = ['textStyle', 'color'];
  15821. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow'];
  15822. // TODO Performance improvement?
  15823. var tmpText = new ZRText();
  15824. var TextStyleMixin = /** @class */function () {
  15825. function TextStyleMixin() {}
  15826. /**
  15827. * Get color property or get color from option.textStyle.color
  15828. */
  15829. // TODO Callback
  15830. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15831. var ecModel = this.ecModel;
  15832. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15833. };
  15834. /**
  15835. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15836. * @return {string}
  15837. */
  15838. TextStyleMixin.prototype.getFont = function () {
  15839. return getFont({
  15840. fontStyle: this.getShallow('fontStyle'),
  15841. fontWeight: this.getShallow('fontWeight'),
  15842. fontSize: this.getShallow('fontSize'),
  15843. fontFamily: this.getShallow('fontFamily')
  15844. }, this.ecModel);
  15845. };
  15846. TextStyleMixin.prototype.getTextRect = function (text) {
  15847. var style = {
  15848. text: text,
  15849. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15850. };
  15851. for (var i = 0; i < textStyleParams.length; i++) {
  15852. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15853. }
  15854. tmpText.useStyle(style);
  15855. tmpText.update();
  15856. return tmpText.getBoundingRect();
  15857. };
  15858. return TextStyleMixin;
  15859. }();
  15860. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit']
  15861. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15862. // So do not transfer decal directly.
  15863. ];
  15864. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15865. var LineStyleMixin = /** @class */function () {
  15866. function LineStyleMixin() {}
  15867. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15868. return getLineStyle(this, excludes);
  15869. };
  15870. return LineStyleMixin;
  15871. }();
  15872. 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']
  15873. // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15874. // So do not transfer decal directly.
  15875. ];
  15876. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15877. var ItemStyleMixin = /** @class */function () {
  15878. function ItemStyleMixin() {}
  15879. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15880. return getItemStyle(this, excludes, includes);
  15881. };
  15882. return ItemStyleMixin;
  15883. }();
  15884. var Model = /** @class */function () {
  15885. function Model(option, parentModel, ecModel) {
  15886. this.parentModel = parentModel;
  15887. this.ecModel = ecModel;
  15888. this.option = option;
  15889. // Simple optimization
  15890. // if (this.init) {
  15891. // if (arguments.length <= 4) {
  15892. // this.init(option, parentModel, ecModel, extraOpt);
  15893. // }
  15894. // else {
  15895. // this.init.apply(this, arguments);
  15896. // }
  15897. // }
  15898. }
  15899. Model.prototype.init = function (option, parentModel, ecModel) {
  15900. var rest = [];
  15901. for (var _i = 3; _i < arguments.length; _i++) {
  15902. rest[_i - 3] = arguments[_i];
  15903. }
  15904. };
  15905. /**
  15906. * Merge the input option to me.
  15907. */
  15908. Model.prototype.mergeOption = function (option, ecModel) {
  15909. merge(this.option, option, true);
  15910. };
  15911. // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15912. // TODO: TYPE strict key check?
  15913. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15914. Model.prototype.get = function (path, ignoreParent) {
  15915. if (path == null) {
  15916. return this.option;
  15917. }
  15918. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15919. };
  15920. Model.prototype.getShallow = function (key, ignoreParent) {
  15921. var option = this.option;
  15922. var val = option == null ? option : option[key];
  15923. if (val == null && !ignoreParent) {
  15924. var parentModel = this.parentModel;
  15925. if (parentModel) {
  15926. // FIXME:TS do not know how to make it works
  15927. val = parentModel.getShallow(key);
  15928. }
  15929. }
  15930. return val;
  15931. };
  15932. // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15933. // getModel(path: string | string[], parentModel?: Model): Model;
  15934. // TODO 'a.b.c' is deprecated
  15935. Model.prototype.getModel = function (path, parentModel) {
  15936. var hasPath = path != null;
  15937. var pathFinal = hasPath ? this.parsePath(path) : null;
  15938. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15939. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15940. return new Model(obj, parentModel, this.ecModel);
  15941. };
  15942. /**
  15943. * If model has option
  15944. */
  15945. Model.prototype.isEmpty = function () {
  15946. return this.option == null;
  15947. };
  15948. Model.prototype.restoreData = function () {};
  15949. // Pending
  15950. Model.prototype.clone = function () {
  15951. var Ctor = this.constructor;
  15952. return new Ctor(clone(this.option));
  15953. };
  15954. // setReadOnly(properties): void {
  15955. // clazzUtil.setReadOnly(this, properties);
  15956. // }
  15957. // If path is null/undefined, return null/undefined.
  15958. Model.prototype.parsePath = function (path) {
  15959. if (typeof path === 'string') {
  15960. return path.split('.');
  15961. }
  15962. return path;
  15963. };
  15964. // Resolve path for parent. Perhaps useful when parent use a different property.
  15965. // Default to be a identity resolver.
  15966. // Can be modified to a different resolver.
  15967. Model.prototype.resolveParentPath = function (path) {
  15968. return path;
  15969. };
  15970. // FIXME:TS check whether put this method here
  15971. Model.prototype.isAnimationEnabled = function () {
  15972. if (!env.node && this.option) {
  15973. if (this.option.animation != null) {
  15974. return !!this.option.animation;
  15975. } else if (this.parentModel) {
  15976. return this.parentModel.isAnimationEnabled();
  15977. }
  15978. }
  15979. };
  15980. Model.prototype._doGet = function (pathArr, parentModel) {
  15981. var obj = this.option;
  15982. if (!pathArr) {
  15983. return obj;
  15984. }
  15985. for (var i = 0; i < pathArr.length; i++) {
  15986. // Ignore empty
  15987. if (!pathArr[i]) {
  15988. continue;
  15989. }
  15990. // obj could be number/string/... (like 0)
  15991. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15992. if (obj == null) {
  15993. break;
  15994. }
  15995. }
  15996. if (obj == null && parentModel) {
  15997. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15998. }
  15999. return obj;
  16000. };
  16001. return Model;
  16002. }();
  16003. // Enable Model.extend.
  16004. enableClassExtend(Model);
  16005. enableClassCheck(Model);
  16006. mixin(Model, LineStyleMixin);
  16007. mixin(Model, ItemStyleMixin);
  16008. mixin(Model, AreaStyleMixin);
  16009. mixin(Model, TextStyleMixin);
  16010. // A random offset
  16011. var base = Math.round(Math.random() * 10);
  16012. /**
  16013. * @public
  16014. * @param {string} type
  16015. * @return {string}
  16016. */
  16017. function getUID(type) {
  16018. // Considering the case of crossing js context,
  16019. // use Math.random to make id as unique as possible.
  16020. return [type || '', base++].join('_');
  16021. }
  16022. /**
  16023. * Implements `SubTypeDefaulterManager` for `target`.
  16024. */
  16025. function enableSubTypeDefaulter(target) {
  16026. var subTypeDefaulters = {};
  16027. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  16028. var componentTypeInfo = parseClassType(componentType);
  16029. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  16030. };
  16031. target.determineSubType = function (componentType, option) {
  16032. var type = option.type;
  16033. if (!type) {
  16034. var componentTypeMain = parseClassType(componentType).main;
  16035. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16036. type = subTypeDefaulters[componentTypeMain](option);
  16037. }
  16038. }
  16039. return type;
  16040. };
  16041. }
  16042. /**
  16043. * Implements `TopologicalTravelable<any>` for `entity`.
  16044. *
  16045. * Topological travel on Activity Network (Activity On Vertices).
  16046. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16047. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16048. * If there is circular dependencey, Error will be thrown.
  16049. */
  16050. function enableTopologicalTravel(entity, dependencyGetter) {
  16051. /**
  16052. * @param targetNameList Target Component type list.
  16053. * Can be ['aa', 'bb', 'aa.xx']
  16054. * @param fullNameList By which we can build dependency graph.
  16055. * @param callback Params: componentType, dependencies.
  16056. * @param context Scope of callback.
  16057. */
  16058. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16059. if (!targetNameList.length) {
  16060. return;
  16061. }
  16062. var result = makeDepndencyGraph(fullNameList);
  16063. var graph = result.graph;
  16064. var noEntryList = result.noEntryList;
  16065. var targetNameSet = {};
  16066. each(targetNameList, function (name) {
  16067. targetNameSet[name] = true;
  16068. });
  16069. while (noEntryList.length) {
  16070. var currComponentType = noEntryList.pop();
  16071. var currVertex = graph[currComponentType];
  16072. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16073. if (isInTargetNameSet) {
  16074. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16075. delete targetNameSet[currComponentType];
  16076. }
  16077. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  16078. }
  16079. each(targetNameSet, function () {
  16080. var errMsg = '';
  16081. if ("development" !== 'production') {
  16082. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  16083. }
  16084. throw new Error(errMsg);
  16085. });
  16086. function removeEdge(succComponentType) {
  16087. graph[succComponentType].entryCount--;
  16088. if (graph[succComponentType].entryCount === 0) {
  16089. noEntryList.push(succComponentType);
  16090. }
  16091. }
  16092. // Consider this case: legend depends on series, and we call
  16093. // chart.setOption({series: [...]}), where only series is in option.
  16094. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16095. // not be called, but only sereis.mergeOption is called. Thus legend
  16096. // have no chance to update its local record about series (like which
  16097. // name of series is available in legend).
  16098. function removeEdgeAndAdd(succComponentType) {
  16099. targetNameSet[succComponentType] = true;
  16100. removeEdge(succComponentType);
  16101. }
  16102. };
  16103. function makeDepndencyGraph(fullNameList) {
  16104. var graph = {};
  16105. var noEntryList = [];
  16106. each(fullNameList, function (name) {
  16107. var thisItem = createDependencyGraphItem(graph, name);
  16108. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16109. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16110. thisItem.entryCount = availableDeps.length;
  16111. if (thisItem.entryCount === 0) {
  16112. noEntryList.push(name);
  16113. }
  16114. each(availableDeps, function (dependentName) {
  16115. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16116. thisItem.predecessor.push(dependentName);
  16117. }
  16118. var thatItem = createDependencyGraphItem(graph, dependentName);
  16119. if (indexOf(thatItem.successor, dependentName) < 0) {
  16120. thatItem.successor.push(name);
  16121. }
  16122. });
  16123. });
  16124. return {
  16125. graph: graph,
  16126. noEntryList: noEntryList
  16127. };
  16128. }
  16129. function createDependencyGraphItem(graph, name) {
  16130. if (!graph[name]) {
  16131. graph[name] = {
  16132. predecessor: [],
  16133. successor: []
  16134. };
  16135. }
  16136. return graph[name];
  16137. }
  16138. function getAvailableDependencies(originalDeps, fullNameList) {
  16139. var availableDeps = [];
  16140. each(originalDeps, function (dep) {
  16141. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16142. });
  16143. return availableDeps;
  16144. }
  16145. }
  16146. function inheritDefaultOption(superOption, subOption) {
  16147. // See also `model/Component.ts#getDefaultOption`
  16148. return merge(merge({}, superOption, true), subOption, true);
  16149. }
  16150. /*
  16151. * Licensed to the Apache Software Foundation (ASF) under one
  16152. * or more contributor license agreements. See the NOTICE file
  16153. * distributed with this work for additional information
  16154. * regarding copyright ownership. The ASF licenses this file
  16155. * to you under the Apache License, Version 2.0 (the
  16156. * "License"); you may not use this file except in compliance
  16157. * with the License. You may obtain a copy of the License at
  16158. *
  16159. * http://www.apache.org/licenses/LICENSE-2.0
  16160. *
  16161. * Unless required by applicable law or agreed to in writing,
  16162. * software distributed under the License is distributed on an
  16163. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16164. * KIND, either express or implied. See the License for the
  16165. * specific language governing permissions and limitations
  16166. * under the License.
  16167. */
  16168. /**
  16169. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16170. */
  16171. /*
  16172. * Licensed to the Apache Software Foundation (ASF) under one
  16173. * or more contributor license agreements. See the NOTICE file
  16174. * distributed with this work for additional information
  16175. * regarding copyright ownership. The ASF licenses this file
  16176. * to you under the Apache License, Version 2.0 (the
  16177. * "License"); you may not use this file except in compliance
  16178. * with the License. You may obtain a copy of the License at
  16179. *
  16180. * http://www.apache.org/licenses/LICENSE-2.0
  16181. *
  16182. * Unless required by applicable law or agreed to in writing,
  16183. * software distributed under the License is distributed on an
  16184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16185. * KIND, either express or implied. See the License for the
  16186. * specific language governing permissions and limitations
  16187. * under the License.
  16188. */
  16189. /**
  16190. * Language: English.
  16191. */
  16192. var langEN = {
  16193. time: {
  16194. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  16195. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  16196. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  16197. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  16198. },
  16199. legend: {
  16200. selector: {
  16201. all: 'All',
  16202. inverse: 'Inv'
  16203. }
  16204. },
  16205. toolbox: {
  16206. brush: {
  16207. title: {
  16208. rect: 'Box Select',
  16209. polygon: 'Lasso Select',
  16210. lineX: 'Horizontally Select',
  16211. lineY: 'Vertically Select',
  16212. keep: 'Keep Selections',
  16213. clear: 'Clear Selections'
  16214. }
  16215. },
  16216. dataView: {
  16217. title: 'Data View',
  16218. lang: ['Data View', 'Close', 'Refresh']
  16219. },
  16220. dataZoom: {
  16221. title: {
  16222. zoom: 'Zoom',
  16223. back: 'Zoom Reset'
  16224. }
  16225. },
  16226. magicType: {
  16227. title: {
  16228. line: 'Switch to Line Chart',
  16229. bar: 'Switch to Bar Chart',
  16230. stack: 'Stack',
  16231. tiled: 'Tile'
  16232. }
  16233. },
  16234. restore: {
  16235. title: 'Restore'
  16236. },
  16237. saveAsImage: {
  16238. title: 'Save as Image',
  16239. lang: ['Right Click to Save Image']
  16240. }
  16241. },
  16242. series: {
  16243. typeNames: {
  16244. pie: 'Pie chart',
  16245. bar: 'Bar chart',
  16246. line: 'Line chart',
  16247. scatter: 'Scatter plot',
  16248. effectScatter: 'Ripple scatter plot',
  16249. radar: 'Radar chart',
  16250. tree: 'Tree',
  16251. treemap: 'Treemap',
  16252. boxplot: 'Boxplot',
  16253. candlestick: 'Candlestick',
  16254. k: 'K line chart',
  16255. heatmap: 'Heat map',
  16256. map: 'Map',
  16257. parallel: 'Parallel coordinate map',
  16258. lines: 'Line graph',
  16259. graph: 'Relationship graph',
  16260. sankey: 'Sankey diagram',
  16261. funnel: 'Funnel chart',
  16262. gauge: 'Gauge',
  16263. pictorialBar: 'Pictorial bar',
  16264. themeRiver: 'Theme River Map',
  16265. sunburst: 'Sunburst',
  16266. custom: 'Custom chart',
  16267. chart: 'Chart'
  16268. }
  16269. },
  16270. aria: {
  16271. general: {
  16272. withTitle: 'This is a chart about "{title}"',
  16273. withoutTitle: 'This is a chart'
  16274. },
  16275. series: {
  16276. single: {
  16277. prefix: '',
  16278. withName: ' with type {seriesType} named {seriesName}.',
  16279. withoutName: ' with type {seriesType}.'
  16280. },
  16281. multiple: {
  16282. prefix: '. It consists of {seriesCount} series count.',
  16283. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  16284. withoutName: ' The {seriesId} series is a {seriesType}.',
  16285. separator: {
  16286. middle: '',
  16287. end: ''
  16288. }
  16289. }
  16290. },
  16291. data: {
  16292. allData: 'The data is as follows: ',
  16293. partialData: 'The first {displayCnt} items are: ',
  16294. withName: 'the data for {name} is {value}',
  16295. withoutName: '{value}',
  16296. separator: {
  16297. middle: ', ',
  16298. end: '. '
  16299. }
  16300. }
  16301. }
  16302. };
  16303. /*
  16304. * Licensed to the Apache Software Foundation (ASF) under one
  16305. * or more contributor license agreements. See the NOTICE file
  16306. * distributed with this work for additional information
  16307. * regarding copyright ownership. The ASF licenses this file
  16308. * to you under the Apache License, Version 2.0 (the
  16309. * "License"); you may not use this file except in compliance
  16310. * with the License. You may obtain a copy of the License at
  16311. *
  16312. * http://www.apache.org/licenses/LICENSE-2.0
  16313. *
  16314. * Unless required by applicable law or agreed to in writing,
  16315. * software distributed under the License is distributed on an
  16316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16317. * KIND, either express or implied. See the License for the
  16318. * specific language governing permissions and limitations
  16319. * under the License.
  16320. */
  16321. /**
  16322. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16323. */
  16324. /*
  16325. * Licensed to the Apache Software Foundation (ASF) under one
  16326. * or more contributor license agreements. See the NOTICE file
  16327. * distributed with this work for additional information
  16328. * regarding copyright ownership. The ASF licenses this file
  16329. * to you under the Apache License, Version 2.0 (the
  16330. * "License"); you may not use this file except in compliance
  16331. * with the License. You may obtain a copy of the License at
  16332. *
  16333. * http://www.apache.org/licenses/LICENSE-2.0
  16334. *
  16335. * Unless required by applicable law or agreed to in writing,
  16336. * software distributed under the License is distributed on an
  16337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16338. * KIND, either express or implied. See the License for the
  16339. * specific language governing permissions and limitations
  16340. * under the License.
  16341. */
  16342. var langZH = {
  16343. time: {
  16344. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  16345. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  16346. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  16347. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  16348. },
  16349. legend: {
  16350. selector: {
  16351. all: '全选',
  16352. inverse: '反选'
  16353. }
  16354. },
  16355. toolbox: {
  16356. brush: {
  16357. title: {
  16358. rect: '矩形选择',
  16359. polygon: '圈选',
  16360. lineX: '横向选择',
  16361. lineY: '纵向选择',
  16362. keep: '保持选择',
  16363. clear: '清除选择'
  16364. }
  16365. },
  16366. dataView: {
  16367. title: '数据视图',
  16368. lang: ['数据视图', '关闭', '刷新']
  16369. },
  16370. dataZoom: {
  16371. title: {
  16372. zoom: '区域缩放',
  16373. back: '区域缩放还原'
  16374. }
  16375. },
  16376. magicType: {
  16377. title: {
  16378. line: '切换为折线图',
  16379. bar: '切换为柱状图',
  16380. stack: '切换为堆叠',
  16381. tiled: '切换为平铺'
  16382. }
  16383. },
  16384. restore: {
  16385. title: '还原'
  16386. },
  16387. saveAsImage: {
  16388. title: '保存为图片',
  16389. lang: ['右键另存为图片']
  16390. }
  16391. },
  16392. series: {
  16393. typeNames: {
  16394. pie: '饼图',
  16395. bar: '柱状图',
  16396. line: '折线图',
  16397. scatter: '散点图',
  16398. effectScatter: '涟漪散点图',
  16399. radar: '雷达图',
  16400. tree: '树图',
  16401. treemap: '矩形树图',
  16402. boxplot: '箱型图',
  16403. candlestick: 'K线图',
  16404. k: 'K线图',
  16405. heatmap: '热力图',
  16406. map: '地图',
  16407. parallel: '平行坐标图',
  16408. lines: '线图',
  16409. graph: '关系图',
  16410. sankey: '桑基图',
  16411. funnel: '漏斗图',
  16412. gauge: '仪表盘图',
  16413. pictorialBar: '象形柱图',
  16414. themeRiver: '主题河流图',
  16415. sunburst: '旭日图',
  16416. custom: '自定义图表',
  16417. chart: '图表'
  16418. }
  16419. },
  16420. aria: {
  16421. general: {
  16422. withTitle: '这是一个关于“{title}”的图表。',
  16423. withoutTitle: '这是一个图表,'
  16424. },
  16425. series: {
  16426. single: {
  16427. prefix: '',
  16428. withName: '图表类型是{seriesType},表示{seriesName}。',
  16429. withoutName: '图表类型是{seriesType}。'
  16430. },
  16431. multiple: {
  16432. prefix: '它由{seriesCount}个图表系列组成。',
  16433. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  16434. withoutName: '第{seriesId}个系列是一个{seriesType},',
  16435. separator: {
  16436. middle: ';',
  16437. end: '。'
  16438. }
  16439. }
  16440. },
  16441. data: {
  16442. allData: '其数据是——',
  16443. partialData: '其中,前{displayCnt}项是——',
  16444. withName: '{name}的数据是{value}',
  16445. withoutName: '{value}',
  16446. separator: {
  16447. middle: ',',
  16448. end: ''
  16449. }
  16450. }
  16451. }
  16452. };
  16453. var LOCALE_ZH = 'ZH';
  16454. var LOCALE_EN = 'EN';
  16455. var DEFAULT_LOCALE = LOCALE_EN;
  16456. var localeStorage = {};
  16457. var localeModels = {};
  16458. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  16459. var langStr = (/* eslint-disable-next-line */
  16460. document.documentElement.lang || navigator.language || navigator.browserLanguage || DEFAULT_LOCALE).toUpperCase();
  16461. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  16462. }();
  16463. function registerLocale(locale, localeObj) {
  16464. locale = locale.toUpperCase();
  16465. localeModels[locale] = new Model(localeObj);
  16466. localeStorage[locale] = localeObj;
  16467. }
  16468. // export function getLocale(locale: string) {
  16469. // return localeStorage[locale];
  16470. // }
  16471. function createLocaleObject(locale) {
  16472. if (isString(locale)) {
  16473. var localeObj = localeStorage[locale.toUpperCase()] || {};
  16474. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  16475. return clone(localeObj);
  16476. } else {
  16477. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  16478. }
  16479. } else {
  16480. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  16481. }
  16482. }
  16483. function getLocaleModel(lang) {
  16484. return localeModels[lang];
  16485. }
  16486. function getDefaultLocaleModel() {
  16487. return localeModels[DEFAULT_LOCALE];
  16488. }
  16489. // Default locale
  16490. registerLocale(LOCALE_EN, langEN);
  16491. registerLocale(LOCALE_ZH, langZH);
  16492. var _impl = null;
  16493. function registerScaleBreakHelperImpl(impl) {
  16494. if (!_impl) {
  16495. _impl = impl;
  16496. }
  16497. }
  16498. function getScaleBreakHelper() {
  16499. return _impl;
  16500. }
  16501. var ONE_SECOND = 1000;
  16502. var ONE_MINUTE = ONE_SECOND * 60;
  16503. var ONE_HOUR = ONE_MINUTE * 60;
  16504. var ONE_DAY = ONE_HOUR * 24;
  16505. var ONE_YEAR = ONE_DAY * 365;
  16506. var primaryTimeUnitFormatterMatchers = {
  16507. year: /({yyyy}|{yy})/,
  16508. month: /({MMMM}|{MMM}|{MM}|{M})/,
  16509. day: /({dd}|{d})/,
  16510. hour: /({HH}|{H}|{hh}|{h})/,
  16511. minute: /({mm}|{m})/,
  16512. second: /({ss}|{s})/,
  16513. millisecond: /({SSS}|{S})/
  16514. };
  16515. var defaultFormatterSeed = {
  16516. year: '{yyyy}',
  16517. month: '{MMM}',
  16518. day: '{d}',
  16519. hour: '{HH}:{mm}',
  16520. minute: '{HH}:{mm}',
  16521. second: '{HH}:{mm}:{ss}',
  16522. millisecond: '{HH}:{mm}:{ss} {SSS}'
  16523. };
  16524. var defaultFullFormatter = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}';
  16525. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  16526. var fullLeveledFormatter = {
  16527. year: '{yyyy}',
  16528. month: '{yyyy}-{MM}',
  16529. day: fullDayFormatter,
  16530. hour: fullDayFormatter + ' ' + defaultFormatterSeed.hour,
  16531. minute: fullDayFormatter + ' ' + defaultFormatterSeed.minute,
  16532. second: fullDayFormatter + ' ' + defaultFormatterSeed.second,
  16533. millisecond: defaultFullFormatter
  16534. };
  16535. // Order must be ensured from big to small.
  16536. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  16537. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  16538. function parseTimeAxisLabelFormatter(formatter) {
  16539. // Keep the logic the same with function `leveledFormat`.
  16540. return !isString(formatter) && !isFunction(formatter) ? parseTimeAxisLabelFormatterDictionary(formatter) : formatter;
  16541. }
  16542. /**
  16543. * The final generated dictionary is like:
  16544. * generated_dict = {
  16545. * year: {
  16546. * year: ['{yyyy}', ...<higher_levels_if_any>]
  16547. * },
  16548. * month: {
  16549. * year: ['{yyyy} {MMM}', ...<higher_levels_if_any>],
  16550. * month: ['{MMM}', ...<higher_levels_if_any>]
  16551. * },
  16552. * day: {
  16553. * year: ['{yyyy} {MMM} {d}', ...<higher_levels_if_any>],
  16554. * month: ['{MMM} {d}', ...<higher_levels_if_any>],
  16555. * day: ['{d}', ...<higher_levels_if_any>]
  16556. * },
  16557. * ...
  16558. * }
  16559. *
  16560. * In echarts option, users can specify the entire dictionary or typically just:
  16561. * {formatter: {
  16562. * year: '{yyyy}', // Or an array of leveled templates: `['{yyyy}', '{bold1|{yyyy}}', ...]`,
  16563. * // corresponding to `[level0, level1, level2, ...]`.
  16564. * month: '{MMM}',
  16565. * day: '{d}',
  16566. * hour: '{HH}:{mm}',
  16567. * second: '{HH}:{mm}',
  16568. * ...
  16569. * }}
  16570. * If any time unit is not specified in echarts option, the default template is used,
  16571. * such as `['{yyyy}', {primary|{yyyy}']`.
  16572. *
  16573. * The `tick.level` is only used to read string from each array, meaning the style type.
  16574. *
  16575. * Let `lowerUnit = getUnitFromValue(tick.value)`.
  16576. * The non-break axis ticks only use `generated_dict[lowerUnit][lowerUnit][level]`.
  16577. * The break axis ticks may use `generated_dict[lowerUnit][upperUnit][level]`, because:
  16578. * Consider the case: the non-break ticks are `16th, 23th, Feb, 7th, ...`, where `Feb` is in the break
  16579. * range and pruned by breaks, and the break ends might be in lower time unit than day. e.g., break start
  16580. * is `Jan 25th 18:00`(in unit `hour`) and break end is `Feb 6th 18:30` (in unit `minute`). Thus the break
  16581. * label prefers `Jan 25th 18:00` and `Feb 6th 18:30` rather than only `18:00` and `18:30`, otherwise it
  16582. * causes misleading.
  16583. * In this case, the tick of the break start and end will both be:
  16584. * `{level: 1, lowerTimeUnit: 'minute', upperTimeUnit: 'month'}`
  16585. * And get the final template by `generated_dict[lowerTimeUnit][upperTimeUnit][level]`.
  16586. * Note that the time unit can not be calculated directly by a single tick value, since the two breaks have
  16587. * to be at the same time unit to avoid awkward appearance. i.e., `Jan 25th 18:00` is in the time unit "hour"
  16588. * but we need it to be "minute", following `Feb 6th 18:30`.
  16589. */
  16590. function parseTimeAxisLabelFormatterDictionary(dictOption) {
  16591. dictOption = dictOption || {};
  16592. var dict = {};
  16593. // Currently if any template is specified by user, it may contain rich text tag,
  16594. // such as `'{my_bold|{YYYY}}'`, thus we do add highlight style to it.
  16595. // (Note that nested tag (`'{some|{some2|xxx}}'`) in rich text is not supported yet.)
  16596. var canAddHighlight = true;
  16597. each(primaryTimeUnits, function (lowestUnit) {
  16598. canAddHighlight && (canAddHighlight = dictOption[lowestUnit] == null);
  16599. });
  16600. each(primaryTimeUnits, function (lowestUnit, lowestUnitIdx) {
  16601. var upperDictOption = dictOption[lowestUnit];
  16602. dict[lowestUnit] = {};
  16603. var lowerTpl = null;
  16604. for (var upperUnitIdx = lowestUnitIdx; upperUnitIdx >= 0; upperUnitIdx--) {
  16605. var upperUnit = primaryTimeUnits[upperUnitIdx];
  16606. var upperDictItemOption = isObject(upperDictOption) && !isArray(upperDictOption) ? upperDictOption[upperUnit] : upperDictOption;
  16607. var tplArr = void 0;
  16608. if (isArray(upperDictItemOption)) {
  16609. tplArr = upperDictItemOption.slice();
  16610. lowerTpl = tplArr[0] || '';
  16611. } else if (isString(upperDictItemOption)) {
  16612. lowerTpl = upperDictItemOption;
  16613. tplArr = [lowerTpl];
  16614. } else {
  16615. if (lowerTpl == null) {
  16616. lowerTpl = defaultFormatterSeed[lowestUnit];
  16617. }
  16618. // Generate the dict by the rule as follows:
  16619. // If the user specify (or by default):
  16620. // {formatter: {
  16621. // year: '{yyyy}',
  16622. // month: '{MMM}',
  16623. // day: '{d}',
  16624. // ...
  16625. // }}
  16626. // Concat them to make the final dictionary:
  16627. // {formatter: {
  16628. // year: {year: ['{yyyy}']},
  16629. // month: {year: ['{yyyy} {MMM}'], month: ['{MMM}']},
  16630. // day: {year: ['{yyyy} {MMM} {d}'], month: ['{MMM} {d}'], day: ['{d}']}
  16631. // ...
  16632. // }}
  16633. // And then add `{primary|...}` to each array if from default template.
  16634. // This strategy is convinient for user configurating and works for most cases.
  16635. // If bad cases encountered, users can specify the entire dictionary themselves
  16636. // instead of going through this logic.
  16637. else if (!primaryTimeUnitFormatterMatchers[upperUnit].test(lowerTpl)) {
  16638. lowerTpl = dict[upperUnit][upperUnit][0] + " " + lowerTpl;
  16639. }
  16640. tplArr = [lowerTpl];
  16641. if (canAddHighlight) {
  16642. tplArr[1] = "{primary|" + lowerTpl + "}";
  16643. }
  16644. }
  16645. dict[lowestUnit][upperUnit] = tplArr;
  16646. }
  16647. });
  16648. return dict;
  16649. }
  16650. function pad(str, len) {
  16651. str += '';
  16652. return '0000'.substr(0, len - str.length) + str;
  16653. }
  16654. function getPrimaryTimeUnit(timeUnit) {
  16655. switch (timeUnit) {
  16656. case 'half-year':
  16657. case 'quarter':
  16658. return 'month';
  16659. case 'week':
  16660. case 'half-week':
  16661. return 'day';
  16662. case 'half-day':
  16663. case 'quarter-day':
  16664. return 'hour';
  16665. default:
  16666. // year, minutes, second, milliseconds
  16667. return timeUnit;
  16668. }
  16669. }
  16670. function isPrimaryTimeUnit(timeUnit) {
  16671. return timeUnit === getPrimaryTimeUnit(timeUnit);
  16672. }
  16673. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  16674. switch (timeUnit) {
  16675. case 'year':
  16676. case 'month':
  16677. return 'day';
  16678. case 'millisecond':
  16679. return 'millisecond';
  16680. default:
  16681. // Also for day, hour, minute, second
  16682. return 'second';
  16683. }
  16684. }
  16685. function format(
  16686. // Note: The result based on `isUTC` are totally different, which can not be just simply
  16687. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  16688. time, template, isUTC, lang) {
  16689. var date = parseDate(time);
  16690. var y = date[fullYearGetterName(isUTC)]();
  16691. var M = date[monthGetterName(isUTC)]() + 1;
  16692. var q = Math.floor((M - 1) / 3) + 1;
  16693. var d = date[dateGetterName(isUTC)]();
  16694. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  16695. var H = date[hoursGetterName(isUTC)]();
  16696. var h = (H - 1) % 12 + 1;
  16697. var m = date[minutesGetterName(isUTC)]();
  16698. var s = date[secondsGetterName(isUTC)]();
  16699. var S = date[millisecondsGetterName(isUTC)]();
  16700. var a = H >= 12 ? 'pm' : 'am';
  16701. var A = a.toUpperCase();
  16702. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  16703. var timeModel = localeModel.getModel('time');
  16704. var month = timeModel.get('month');
  16705. var monthAbbr = timeModel.get('monthAbbr');
  16706. var dayOfWeek = timeModel.get('dayOfWeek');
  16707. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  16708. 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 + '');
  16709. }
  16710. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  16711. var template = null;
  16712. if (isString(formatter)) {
  16713. // Single formatter for all units at all levels
  16714. template = formatter;
  16715. } else if (isFunction(formatter)) {
  16716. var extra = {
  16717. time: tick.time,
  16718. level: tick.time.level
  16719. };
  16720. var scaleBreakHelper = getScaleBreakHelper();
  16721. if (scaleBreakHelper) {
  16722. scaleBreakHelper.makeAxisLabelFormatterParamBreak(extra, tick["break"]);
  16723. }
  16724. template = formatter(tick.value, idx, extra);
  16725. } else {
  16726. var tickTime = tick.time;
  16727. if (tickTime) {
  16728. var leveledTplArr = formatter[tickTime.lowerTimeUnit][tickTime.upperTimeUnit];
  16729. template = leveledTplArr[Math.min(tickTime.level, leveledTplArr.length - 1)] || '';
  16730. } else {
  16731. // tick may be from customTicks or timeline therefore no tick.time.
  16732. var unit = getUnitFromValue(tick.value, isUTC);
  16733. template = formatter[unit][unit][0];
  16734. }
  16735. }
  16736. return format(new Date(tick.value), template, isUTC, lang);
  16737. }
  16738. function getUnitFromValue(value, isUTC) {
  16739. var date = parseDate(value);
  16740. var M = date[monthGetterName(isUTC)]() + 1;
  16741. var d = date[dateGetterName(isUTC)]();
  16742. var h = date[hoursGetterName(isUTC)]();
  16743. var m = date[minutesGetterName(isUTC)]();
  16744. var s = date[secondsGetterName(isUTC)]();
  16745. var S = date[millisecondsGetterName(isUTC)]();
  16746. var isSecond = S === 0;
  16747. var isMinute = isSecond && s === 0;
  16748. var isHour = isMinute && m === 0;
  16749. var isDay = isHour && h === 0;
  16750. var isMonth = isDay && d === 1;
  16751. var isYear = isMonth && M === 1;
  16752. if (isYear) {
  16753. return 'year';
  16754. } else if (isMonth) {
  16755. return 'month';
  16756. } else if (isDay) {
  16757. return 'day';
  16758. } else if (isHour) {
  16759. return 'hour';
  16760. } else if (isMinute) {
  16761. return 'minute';
  16762. } else if (isSecond) {
  16763. return 'second';
  16764. } else {
  16765. return 'millisecond';
  16766. }
  16767. }
  16768. // export function getUnitValue(
  16769. // value: number | Date,
  16770. // unit: TimeUnit,
  16771. // isUTC: boolean
  16772. // ) : number {
  16773. // const date = zrUtil.isNumber(value)
  16774. // ? numberUtil.parseDate(value)
  16775. // : value;
  16776. // unit = unit || getUnitFromValue(value, isUTC);
  16777. // switch (unit) {
  16778. // case 'year':
  16779. // return date[fullYearGetterName(isUTC)]();
  16780. // case 'half-year':
  16781. // return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  16782. // case 'quarter':
  16783. // return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  16784. // case 'month':
  16785. // return date[monthGetterName(isUTC)]();
  16786. // case 'day':
  16787. // return date[dateGetterName(isUTC)]();
  16788. // case 'half-day':
  16789. // return date[hoursGetterName(isUTC)]() / 24;
  16790. // case 'hour':
  16791. // return date[hoursGetterName(isUTC)]();
  16792. // case 'minute':
  16793. // return date[minutesGetterName(isUTC)]();
  16794. // case 'second':
  16795. // return date[secondsGetterName(isUTC)]();
  16796. // case 'millisecond':
  16797. // return date[millisecondsGetterName(isUTC)]();
  16798. // }
  16799. // }
  16800. /**
  16801. * e.g.,
  16802. * If timeUnit is 'year', return the Jan 1st 00:00:00 000 of that year.
  16803. * If timeUnit is 'day', return the 00:00:00 000 of that day.
  16804. *
  16805. * @return The input date.
  16806. */
  16807. function roundTime(date, timeUnit, isUTC) {
  16808. switch (timeUnit) {
  16809. case 'year':
  16810. date[monthSetterName(isUTC)](0);
  16811. case 'month':
  16812. date[dateSetterName(isUTC)](1);
  16813. case 'day':
  16814. date[hoursSetterName(isUTC)](0);
  16815. case 'hour':
  16816. date[minutesSetterName(isUTC)](0);
  16817. case 'minute':
  16818. date[secondsSetterName(isUTC)](0);
  16819. case 'second':
  16820. date[millisecondsSetterName(isUTC)](0);
  16821. }
  16822. return date;
  16823. }
  16824. function fullYearGetterName(isUTC) {
  16825. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  16826. }
  16827. function monthGetterName(isUTC) {
  16828. return isUTC ? 'getUTCMonth' : 'getMonth';
  16829. }
  16830. function dateGetterName(isUTC) {
  16831. return isUTC ? 'getUTCDate' : 'getDate';
  16832. }
  16833. function hoursGetterName(isUTC) {
  16834. return isUTC ? 'getUTCHours' : 'getHours';
  16835. }
  16836. function minutesGetterName(isUTC) {
  16837. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  16838. }
  16839. function secondsGetterName(isUTC) {
  16840. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  16841. }
  16842. function millisecondsGetterName(isUTC) {
  16843. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  16844. }
  16845. function fullYearSetterName(isUTC) {
  16846. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  16847. }
  16848. function monthSetterName(isUTC) {
  16849. return isUTC ? 'setUTCMonth' : 'setMonth';
  16850. }
  16851. function dateSetterName(isUTC) {
  16852. return isUTC ? 'setUTCDate' : 'setDate';
  16853. }
  16854. function hoursSetterName(isUTC) {
  16855. return isUTC ? 'setUTCHours' : 'setHours';
  16856. }
  16857. function minutesSetterName(isUTC) {
  16858. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  16859. }
  16860. function secondsSetterName(isUTC) {
  16861. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  16862. }
  16863. function millisecondsSetterName(isUTC) {
  16864. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  16865. }
  16866. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  16867. var textEl = new ZRText({
  16868. style: {
  16869. text: text,
  16870. font: font,
  16871. align: align,
  16872. verticalAlign: verticalAlign,
  16873. padding: padding,
  16874. rich: rich,
  16875. overflow: truncate ? 'truncate' : null,
  16876. lineHeight: lineHeight
  16877. }
  16878. });
  16879. return textEl.getBoundingRect();
  16880. }
  16881. /**
  16882. * Add a comma each three digit.
  16883. */
  16884. function addCommas(x) {
  16885. if (!isNumeric(x)) {
  16886. return isString(x) ? x : '-';
  16887. }
  16888. var parts = (x + '').split('.');
  16889. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  16890. }
  16891. function toCamelCase(str, upperCaseFirst) {
  16892. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16893. return group1.toUpperCase();
  16894. });
  16895. if (upperCaseFirst && str) {
  16896. str = str.charAt(0).toUpperCase() + str.slice(1);
  16897. }
  16898. return str;
  16899. }
  16900. var normalizeCssArray$1 = normalizeCssArray;
  16901. /**
  16902. * Make value user readable for tooltip and label.
  16903. * "User readable":
  16904. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  16905. * Avoid to display an empty string, which users can not recognize there is
  16906. * a value and it might look like a bug.
  16907. */
  16908. function makeValueReadable(value, valueType, useUTC) {
  16909. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  16910. function stringToUserReadable(str) {
  16911. return str && trim(str) ? str : '-';
  16912. }
  16913. function isNumberUserReadable(num) {
  16914. return !!(num != null && !isNaN(num) && isFinite(num));
  16915. }
  16916. var isTypeTime = valueType === 'time';
  16917. var isValueDate = value instanceof Date;
  16918. if (isTypeTime || isValueDate) {
  16919. var date = isTypeTime ? parseDate(value) : value;
  16920. if (!isNaN(+date)) {
  16921. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  16922. } else if (isValueDate) {
  16923. return '-';
  16924. }
  16925. // In other cases, continue to try to display the value in the following code.
  16926. }
  16927. if (valueType === 'ordinal') {
  16928. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  16929. }
  16930. // By default.
  16931. var numericResult = numericToNumber(value);
  16932. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16933. }
  16934. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16935. var wrapVar = function (varName, seriesIdx) {
  16936. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16937. };
  16938. /**
  16939. * Template formatter
  16940. * @param {Array.<Object>|Object} paramsList
  16941. */
  16942. function formatTpl(tpl, paramsList, encode) {
  16943. if (!isArray(paramsList)) {
  16944. paramsList = [paramsList];
  16945. }
  16946. var seriesLen = paramsList.length;
  16947. if (!seriesLen) {
  16948. return '';
  16949. }
  16950. var $vars = paramsList[0].$vars || [];
  16951. for (var i = 0; i < $vars.length; i++) {
  16952. var alias = TPL_VAR_ALIAS[i];
  16953. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16954. }
  16955. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16956. for (var k = 0; k < $vars.length; k++) {
  16957. var val = paramsList[seriesIdx][$vars[k]];
  16958. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16959. }
  16960. }
  16961. return tpl;
  16962. }
  16963. function getTooltipMarker(inOpt, extraCssText) {
  16964. var opt = isString(inOpt) ? {
  16965. color: inOpt,
  16966. extraCssText: extraCssText
  16967. } : inOpt || {};
  16968. var color = opt.color;
  16969. var type = opt.type;
  16970. extraCssText = opt.extraCssText;
  16971. var renderMode = opt.renderMode || 'html';
  16972. if (!color) {
  16973. return '';
  16974. }
  16975. if (renderMode === 'html') {
  16976. 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:'
  16977. // Only support string
  16978. + 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>';
  16979. } else {
  16980. // Should better not to auto generate style name by auto-increment number here.
  16981. // Because this util is usually called in tooltip formatter, which is probably
  16982. // called repeatedly when mouse move and the auto-increment number increases fast.
  16983. // Users can make their own style name by theirselves, make it unique and readable.
  16984. var markerId = opt.markerId || 'markerX';
  16985. return {
  16986. renderMode: renderMode,
  16987. content: '{' + markerId + '|} ',
  16988. style: type === 'subItem' ? {
  16989. width: 4,
  16990. height: 4,
  16991. borderRadius: 2,
  16992. backgroundColor: color
  16993. } : {
  16994. width: 10,
  16995. height: 10,
  16996. borderRadius: 5,
  16997. backgroundColor: color
  16998. }
  16999. };
  17000. }
  17001. }
  17002. /**
  17003. * @deprecated Use `time/format` instead.
  17004. * ISO Date format
  17005. * @param {string} tpl
  17006. * @param {number} value
  17007. * @param {boolean} [isUTC=false] Default in local time.
  17008. * see `module:echarts/scale/Time`
  17009. * and `module:echarts/util/number#parseDate`.
  17010. * @inner
  17011. */
  17012. function formatTime(tpl, value, isUTC) {
  17013. if ("development" !== 'production') {
  17014. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  17015. }
  17016. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  17017. tpl = 'MM-dd\nyyyy';
  17018. }
  17019. var date = parseDate(value);
  17020. var getUTC = isUTC ? 'getUTC' : 'get';
  17021. var y = date[getUTC + 'FullYear']();
  17022. var M = date[getUTC + 'Month']() + 1;
  17023. var d = date[getUTC + 'Date']();
  17024. var h = date[getUTC + 'Hours']();
  17025. var m = date[getUTC + 'Minutes']();
  17026. var s = date[getUTC + 'Seconds']();
  17027. var S = date[getUTC + 'Milliseconds']();
  17028. 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));
  17029. return tpl;
  17030. }
  17031. /**
  17032. * Capital first
  17033. * @param {string} str
  17034. * @return {string}
  17035. */
  17036. function capitalFirst(str) {
  17037. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17038. }
  17039. /**
  17040. * @return Never be null/undefined.
  17041. */
  17042. function convertToColorString(color, defaultColor) {
  17043. defaultColor = defaultColor || 'transparent';
  17044. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  17045. }
  17046. /**
  17047. * open new tab
  17048. * @param link url
  17049. * @param target blank or self
  17050. */
  17051. function windowOpen(link, target) {
  17052. /* global window */
  17053. if (target === '_blank' || target === 'blank') {
  17054. var blank = window.open();
  17055. blank.opener = null;
  17056. blank.location.href = link;
  17057. } else {
  17058. window.open(link, target);
  17059. }
  17060. }
  17061. /**
  17062. * FIXME:
  17063. * `nonSeriesBoxCoordSysCreators` and `_nonSeriesBoxMasterList` are hardcoded implementations.
  17064. * Regarding "coord sys layout based on another coord sys", currently we only exprimentally support one level
  17065. * dpendency, such as, "grid(cartesian)s can be laid out based on matrix/calendar coord sys."
  17066. * But a comprehensive implementation may need to support:
  17067. * - Recursive dependencies. e.g., a matrix coord sys lays out based on another matrix coord sys.
  17068. * That requires in the implementation `create` and `update` of coord sys are called by a dependency graph.
  17069. * (@see enableTopologicalTravel in `util/component.ts`)
  17070. */
  17071. var nonSeriesBoxCoordSysCreators = {};
  17072. var normalCoordSysCreators = {};
  17073. var CoordinateSystemManager = /** @class */function () {
  17074. function CoordinateSystemManager() {
  17075. this._normalMasterList = [];
  17076. this._nonSeriesBoxMasterList = [];
  17077. }
  17078. /**
  17079. * Typically,
  17080. * - in `create`, a coord sys lays out based on a given rect;
  17081. * - in `update`, update the pixel and data extent of there axes (if any) based on processed `series.data`.
  17082. * After that, a coord sys can serve (typically by `dataToPoint`/`dataToLayout`/`pointToData`).
  17083. * If the coordinate system do not lay out based on `series.data`, `update` is not needed.
  17084. */
  17085. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17086. this._nonSeriesBoxMasterList = dealCreate(nonSeriesBoxCoordSysCreators, true);
  17087. this._normalMasterList = dealCreate(normalCoordSysCreators, false);
  17088. function dealCreate(creatorMap, canBeNonSeriesBox) {
  17089. var coordinateSystems = [];
  17090. each(creatorMap, function (creator, type) {
  17091. var list = creator.create(ecModel, api);
  17092. coordinateSystems = coordinateSystems.concat(list || []);
  17093. if ("development" !== 'production') {
  17094. if (canBeNonSeriesBox) {
  17095. // Disallow `update` is a brutal way to ensure `_nonSeriesBoxMasterList`s are ready to
  17096. // serve after `create`. But if `update` has to be involved in `_nonSeriesBoxMasterList`
  17097. // for some future case, more complicated mechanisms need to be introduced.
  17098. each(list, function (master) {
  17099. return assert(!master.update);
  17100. });
  17101. }
  17102. }
  17103. });
  17104. return coordinateSystems;
  17105. }
  17106. };
  17107. /**
  17108. * @see CoordinateSystem['create']
  17109. */
  17110. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17111. each(this._normalMasterList, function (coordSys) {
  17112. coordSys.update && coordSys.update(ecModel, api);
  17113. });
  17114. };
  17115. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17116. return this._normalMasterList.concat(this._nonSeriesBoxMasterList);
  17117. };
  17118. CoordinateSystemManager.register = function (type, creator) {
  17119. if (type === 'matrix' || type === 'calendar') {
  17120. // FIXME: hardcode, @see nonSeriesBoxCoordSysCreators
  17121. nonSeriesBoxCoordSysCreators[type] = creator;
  17122. return;
  17123. }
  17124. normalCoordSysCreators[type] = creator;
  17125. };
  17126. CoordinateSystemManager.get = function (type) {
  17127. return normalCoordSysCreators[type] || nonSeriesBoxCoordSysCreators[type];
  17128. };
  17129. return CoordinateSystemManager;
  17130. }();
  17131. function canBeNonSeriesBoxCoordSys(coordSysType) {
  17132. return !!nonSeriesBoxCoordSysCreators[coordSysType];
  17133. }
  17134. var BoxCoordinateSystemCoordFrom = {
  17135. // By default fetch coord from `model.get('coord')`.
  17136. coord: 1,
  17137. // Some model/series, such as pie, is allowed to also get coord from `model.get('center')`,
  17138. // if cannot get from `model.get('coord')`. But historically pie use `center` option, but
  17139. // geo use `layoutCenter` option to specify layout center; they are not able to be unified.
  17140. // Therefor it is not recommended.
  17141. coord2: 2
  17142. };
  17143. /**
  17144. * @see_also `createBoxLayoutReference`
  17145. * @see_also `injectCoordSysByOption`
  17146. */
  17147. function registerLayOutOnCoordSysUsage(opt) {
  17148. if ("development" !== 'production') {
  17149. assert(!coordSysUseMap.get(opt.fullType));
  17150. }
  17151. coordSysUseMap.set(opt.fullType, {
  17152. getCoord2: undefined
  17153. }).getCoord2 = opt.getCoord2;
  17154. }
  17155. var coordSysUseMap = createHashMap();
  17156. /**
  17157. * @return Be an object, but never be NullUndefined.
  17158. */
  17159. function getCoordForBoxCoordSys(model) {
  17160. var coord = model.getShallow('coord', true);
  17161. var from = BoxCoordinateSystemCoordFrom.coord;
  17162. if (coord == null) {
  17163. var store = coordSysUseMap.get(model.type);
  17164. if (store && store.getCoord2) {
  17165. from = BoxCoordinateSystemCoordFrom.coord2;
  17166. coord = store.getCoord2(model);
  17167. }
  17168. }
  17169. return {
  17170. coord: coord,
  17171. from: from
  17172. };
  17173. }
  17174. /**
  17175. * - "dataCoordSys": each data item is laid out based on a coord sys.
  17176. * - "boxCoordSys": the overall bounding rect or anchor point is calculated based on a coord sys.
  17177. * e.g.,
  17178. * grid rect (cartesian rect) is calculate based on matrix/calendar coord sys;
  17179. * pie center is calculated based on calendar/cartesian;
  17180. *
  17181. * The default value (if not declared in option `coordinateSystemUsage`):
  17182. * For series, use `dataCoordSys`, since this is the most case and backward compatible.
  17183. * For non-series components, use `boxCoordSys`, since `dataCoordSys` is not applicable.
  17184. */
  17185. var CoordinateSystemUsageKind = {
  17186. none: 0,
  17187. dataCoordSys: 1,
  17188. boxCoordSys: 2
  17189. };
  17190. function decideCoordSysUsageKind(
  17191. // Component or series
  17192. model, printError) {
  17193. // For backward compat, still not use `true` in model.get.
  17194. var coordSysType = model.getShallow('coordinateSystem');
  17195. var coordSysUsageOption = model.getShallow('coordinateSystemUsage', true);
  17196. var isDeclaredExplicitly = coordSysUsageOption != null;
  17197. var kind = CoordinateSystemUsageKind.none;
  17198. if (coordSysType) {
  17199. var isSeries = model.mainType === 'series';
  17200. if (coordSysUsageOption == null) {
  17201. coordSysUsageOption = isSeries ? 'data' : 'box';
  17202. }
  17203. if (coordSysUsageOption === 'data') {
  17204. kind = CoordinateSystemUsageKind.dataCoordSys;
  17205. if (!isSeries) {
  17206. if ("development" !== 'production') {
  17207. if (isDeclaredExplicitly && printError) {
  17208. error('coordinateSystemUsage "data" is not supported in non-series components.');
  17209. }
  17210. }
  17211. kind = CoordinateSystemUsageKind.none;
  17212. }
  17213. } else if (coordSysUsageOption === 'box') {
  17214. kind = CoordinateSystemUsageKind.boxCoordSys;
  17215. if (!isSeries && !canBeNonSeriesBoxCoordSys(coordSysType)) {
  17216. if ("development" !== 'production') {
  17217. if (isDeclaredExplicitly && printError) {
  17218. error("coordinateSystem \"" + coordSysType + "\" cannot be used" + (" as coordinateSystemUsage \"box\" for \"" + model.type + "\" yet."));
  17219. }
  17220. }
  17221. kind = CoordinateSystemUsageKind.none;
  17222. }
  17223. }
  17224. }
  17225. return {
  17226. coordSysType: coordSysType,
  17227. kind: kind
  17228. };
  17229. }
  17230. /**
  17231. * These cases are considered:
  17232. * (A) Most series can use only "dataCoordSys", but "boxCoordSys" is not applicable:
  17233. * - e.g., series.heatmap, series.line, series.bar, series.scatter, ...
  17234. * (B) Some series and most components can use only "boxCoordSys", but "dataCoordSys" is not applicable:
  17235. * - e.g., series.pie, series.funnel, ...
  17236. * - e.g., grid, polar, geo, title, ...
  17237. * (C) Several series can use both "boxCoordSys" and "dataCoordSys", even at the same time:
  17238. * - e.g., series.graph, series.map
  17239. * - If graph or map series use a "boxCoordSys", it creates a internal "dataCoordSys" to lay out its data.
  17240. * - Graph series can use matrix coord sys as either the "dataCoordSys" (each item layout on one cell)
  17241. * or "boxCoordSys" (the entire series are layout within one cell).
  17242. * - To achieve this effect,
  17243. * `series.coordinateSystemUsage: 'box'` needs to be specified explicitly.
  17244. *
  17245. * Check these echarts option settings:
  17246. * - If `series: {type: 'bar'}`:
  17247. * dataCoordSys: "cartesian2d", boxCoordSys: "none".
  17248. * (since `coordinateSystem: 'cartesian2d'` is the default option in bar.)
  17249. * - If `grid: {coordinateSystem: 'matrix'}`
  17250. * dataCoordSys: "none", boxCoordSys: "matrix".
  17251. * - If `series: {type: 'pie', coordinateSystem: 'matrix'}`:
  17252. * dataCoordSys: "none", boxCoordSys: "matrix".
  17253. * (since `coordinateSystemUsage: 'box'` is the default option in pie.)
  17254. * - If `series: {type: 'graph', coordinateSystem: 'matrix'}`:
  17255. * dataCoordSys: "matrix", boxCoordSys: "none"
  17256. * - If `series: {type: 'graph', coordinateSystem: 'matrix', coordinateSystemUsage: 'box'}`:
  17257. * dataCoordSys: "an internal view", boxCoordSys: "the internal view is laid out on a matrix"
  17258. * - If `series: {type: 'map'}`:
  17259. * dataCoordSys: "a internal geo", boxCoordSys: "none"
  17260. * - If `series: {type: 'map', coordinateSystem: 'geo', geoIndex: 0}`:
  17261. * dataCoordSys: "a geo", boxCoordSys: "none"
  17262. * - If `series: {type: 'map', coordinateSystem: 'matrix'}`:
  17263. * not_applicable
  17264. * - If `series: {type: 'map', coordinateSystem: 'matrix', coordinateSystemUsage: 'box'}`:
  17265. * dataCoordSys: "an internal geo", boxCoordSys: "the internal geo is laid out on a matrix"
  17266. *
  17267. * @usage
  17268. * For case (A) & (B),
  17269. * call `injectCoordSysByOption({coordSysType: 'aaa', ...})` once for each series/components.
  17270. * For case (C),
  17271. * call `injectCoordSysByOption({coordSysType: 'aaa', ...})` once for each series/components,
  17272. * and then call `injectCoordSysByOption({coordSysType: 'bbb', ..., isDefaultDataCoordSys: true})`
  17273. * once for each series/components.
  17274. *
  17275. * @return Whether injected.
  17276. */
  17277. function injectCoordSysByOption(opt) {
  17278. var targetModel = opt.targetModel,
  17279. coordSysType = opt.coordSysType,
  17280. coordSysProvider = opt.coordSysProvider,
  17281. isDefaultDataCoordSys = opt.isDefaultDataCoordSys,
  17282. allowNotFound = opt.allowNotFound;
  17283. if ("development" !== 'production') {
  17284. assert(!!coordSysType);
  17285. }
  17286. var _a = decideCoordSysUsageKind(targetModel, true),
  17287. kind = _a.kind,
  17288. declaredType = _a.coordSysType;
  17289. if (isDefaultDataCoordSys && kind !== CoordinateSystemUsageKind.dataCoordSys) {
  17290. // If both dataCoordSys and boxCoordSys declared in one model.
  17291. // There is the only case in series-graph, and no other cases yet.
  17292. kind = CoordinateSystemUsageKind.dataCoordSys;
  17293. declaredType = coordSysType;
  17294. }
  17295. if (kind === CoordinateSystemUsageKind.none || declaredType !== coordSysType) {
  17296. return false;
  17297. }
  17298. var coordSys = coordSysProvider(coordSysType, targetModel);
  17299. if (!coordSys) {
  17300. if ("development" !== 'production') {
  17301. if (!allowNotFound) {
  17302. error(coordSysType + " cannot be found for" + (" " + targetModel.type + " (index: " + targetModel.componentIndex + ")."));
  17303. }
  17304. }
  17305. return false;
  17306. }
  17307. if (kind === CoordinateSystemUsageKind.dataCoordSys) {
  17308. if ("development" !== 'production') {
  17309. assert(targetModel.mainType === 'series');
  17310. }
  17311. targetModel.coordinateSystem = coordSys;
  17312. } else {
  17313. // kind === 'boxCoordSys'
  17314. targetModel.boxCoordinateSystem = coordSys;
  17315. }
  17316. return true;
  17317. }
  17318. var each$1 = each;
  17319. /**
  17320. * @public
  17321. */
  17322. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  17323. /**
  17324. * @public
  17325. */
  17326. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  17327. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17328. var x = 0;
  17329. var y = 0;
  17330. if (maxWidth == null) {
  17331. maxWidth = Infinity;
  17332. }
  17333. if (maxHeight == null) {
  17334. maxHeight = Infinity;
  17335. }
  17336. var currentLineMaxSize = 0;
  17337. group.eachChild(function (child, idx) {
  17338. var rect = child.getBoundingRect();
  17339. var nextChild = group.childAt(idx + 1);
  17340. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17341. var nextX;
  17342. var nextY;
  17343. if (orient === 'horizontal') {
  17344. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  17345. nextX = x + moveX;
  17346. // Wrap when width exceeds maxWidth or meet a `newline` group
  17347. // FIXME compare before adding gap?
  17348. if (nextX > maxWidth || child.newline) {
  17349. x = 0;
  17350. nextX = moveX;
  17351. y += currentLineMaxSize + gap;
  17352. currentLineMaxSize = rect.height;
  17353. } else {
  17354. // FIXME: consider rect.y is not `0`?
  17355. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17356. }
  17357. } else {
  17358. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  17359. nextY = y + moveY;
  17360. // Wrap when width exceeds maxHeight or meet a `newline` group
  17361. if (nextY > maxHeight || child.newline) {
  17362. x += currentLineMaxSize + gap;
  17363. y = 0;
  17364. nextY = moveY;
  17365. currentLineMaxSize = rect.width;
  17366. } else {
  17367. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17368. }
  17369. }
  17370. if (child.newline) {
  17371. return;
  17372. }
  17373. child.x = x;
  17374. child.y = y;
  17375. child.markRedraw();
  17376. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  17377. });
  17378. }
  17379. /**
  17380. * VBox or HBox layouting
  17381. * @param {string} orient
  17382. * @param {module:zrender/graphic/Group} group
  17383. * @param {number} gap
  17384. * @param {number} [width=Infinity]
  17385. * @param {number} [height=Infinity]
  17386. */
  17387. var box = boxLayout;
  17388. /**
  17389. * VBox layouting
  17390. * @param {module:zrender/graphic/Group} group
  17391. * @param {number} gap
  17392. * @param {number} [width=Infinity]
  17393. * @param {number} [height=Infinity]
  17394. */
  17395. var vbox = curry(boxLayout, 'vertical');
  17396. /**
  17397. * HBox layouting
  17398. * @param {module:zrender/graphic/Group} group
  17399. * @param {number} gap
  17400. * @param {number} [width=Infinity]
  17401. * @param {number} [height=Infinity]
  17402. */
  17403. var hbox = curry(boxLayout, 'horizontal');
  17404. function getBoxLayoutParams(boxLayoutModel, ignoreParent) {
  17405. return {
  17406. left: boxLayoutModel.getShallow('left', ignoreParent),
  17407. top: boxLayoutModel.getShallow('top', ignoreParent),
  17408. right: boxLayoutModel.getShallow('right', ignoreParent),
  17409. bottom: boxLayoutModel.getShallow('bottom', ignoreParent),
  17410. width: boxLayoutModel.getShallow('width', ignoreParent),
  17411. height: boxLayoutModel.getShallow('height', ignoreParent)
  17412. };
  17413. }
  17414. function getViewRectAndCenterForCircleLayout(seriesModel, api) {
  17415. var layoutRef = createBoxLayoutReference(seriesModel, api, {
  17416. enableLayoutOnlyByCenter: true
  17417. });
  17418. var boxLayoutParams = seriesModel.getBoxLayoutParams();
  17419. var viewRect;
  17420. var center;
  17421. if (layoutRef.type === BoxLayoutReferenceType.point) {
  17422. center = layoutRef.refPoint;
  17423. // `viewRect` is required in `pie/labelLayout.ts`.
  17424. viewRect = getLayoutRect(boxLayoutParams, {
  17425. width: api.getWidth(),
  17426. height: api.getHeight()
  17427. });
  17428. } else {
  17429. // layoutRef.type === layout.BoxLayoutReferenceType.rect
  17430. var centerOption = seriesModel.get('center');
  17431. var centerOptionArr = isArray(centerOption) ? centerOption : [centerOption, centerOption];
  17432. viewRect = getLayoutRect(boxLayoutParams, layoutRef.refContainer);
  17433. center = layoutRef.boxCoordFrom === BoxCoordinateSystemCoordFrom.coord2 ? layoutRef.refPoint // option `series.center` has been used as coord.
  17434. : [parsePercent$1(centerOptionArr[0], viewRect.width) + viewRect.x, parsePercent$1(centerOptionArr[1], viewRect.height) + viewRect.y];
  17435. }
  17436. return {
  17437. viewRect: viewRect,
  17438. center: center
  17439. };
  17440. }
  17441. function getCircleLayout(seriesModel, api) {
  17442. // center can be string or number when coordinateSystem is specified
  17443. var _a = getViewRectAndCenterForCircleLayout(seriesModel, api),
  17444. viewRect = _a.viewRect,
  17445. center = _a.center;
  17446. var radius = seriesModel.get('radius');
  17447. if (!isArray(radius)) {
  17448. radius = [0, radius];
  17449. }
  17450. var width = parsePercent$1(viewRect.width, api.getWidth());
  17451. var height = parsePercent$1(viewRect.height, api.getHeight());
  17452. var size = Math.min(width, height);
  17453. var r0 = parsePercent$1(radius[0], size / 2);
  17454. var r = parsePercent$1(radius[1], size / 2);
  17455. return {
  17456. cx: center[0],
  17457. cy: center[1],
  17458. r0: r0,
  17459. r: r,
  17460. viewRect: viewRect
  17461. };
  17462. }
  17463. /**
  17464. * Parse position info.
  17465. */
  17466. function getLayoutRect(positionInfo, containerRect,
  17467. // This is the space from the `containerRect` to the returned bounding rect.
  17468. // Commonly used in option `legend.padding`, `timeline.padding`, `title.padding`,
  17469. // `visualMap.padding`, ...
  17470. // [NOTICE]:
  17471. // It's named `margin`, because it's the space that outside the bounding rect. But from
  17472. // the perspective of the the caller, it's commonly used as the `padding` of a component,
  17473. // because conventionally background color covers this space.
  17474. // [BEHAVIOR]:
  17475. // - If width/height is specified, `margin` does not effect them.
  17476. // - Otherwise, they are calculated based on the rect that `containerRect` shrinked by `margin`.
  17477. // - left/right/top/bottom are based on the rect that `containerRect` shrinked by `margin`.
  17478. margin) {
  17479. margin = normalizeCssArray$1(margin || 0);
  17480. var containerWidth = containerRect.width;
  17481. var containerHeight = containerRect.height;
  17482. var left = parsePercent$1(positionInfo.left, containerWidth);
  17483. var top = parsePercent$1(positionInfo.top, containerHeight);
  17484. var right = parsePercent$1(positionInfo.right, containerWidth);
  17485. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17486. var width = parsePercent$1(positionInfo.width, containerWidth);
  17487. var height = parsePercent$1(positionInfo.height, containerHeight);
  17488. var verticalMargin = margin[2] + margin[0];
  17489. var horizontalMargin = margin[1] + margin[3];
  17490. var aspect = positionInfo.aspect;
  17491. // If width is not specified, calculate width from left and right
  17492. if (isNaN(width)) {
  17493. width = containerWidth - right - horizontalMargin - left;
  17494. }
  17495. if (isNaN(height)) {
  17496. height = containerHeight - bottom - verticalMargin - top;
  17497. }
  17498. if (aspect != null) {
  17499. // If width and height are not given
  17500. // 1. Graph should not exceeds the container
  17501. // 2. Aspect must be keeped
  17502. // 3. Graph should take the space as more as possible
  17503. // FIXME
  17504. // Margin is not considered, because there is no case that both
  17505. // using margin and aspect so far.
  17506. if (isNaN(width) && isNaN(height)) {
  17507. // PENDING: if only `left` or `right` is defined, perhaps it's more preferable to
  17508. // calculate size based on `containerWidth - left` or `containerWidth - left` here,
  17509. // but for backward compatibility we do not change it.
  17510. if (aspect > containerWidth / containerHeight) {
  17511. width = containerWidth * 0.8;
  17512. } else {
  17513. height = containerHeight * 0.8;
  17514. }
  17515. }
  17516. // Calculate width or height with given aspect
  17517. if (isNaN(width)) {
  17518. width = aspect * height;
  17519. }
  17520. if (isNaN(height)) {
  17521. height = width / aspect;
  17522. }
  17523. }
  17524. // If left is not specified, calculate left from right and width
  17525. if (isNaN(left)) {
  17526. left = containerWidth - right - width - horizontalMargin;
  17527. }
  17528. if (isNaN(top)) {
  17529. top = containerHeight - bottom - height - verticalMargin;
  17530. }
  17531. // Align left and top
  17532. switch (positionInfo.left || positionInfo.right) {
  17533. case 'center':
  17534. left = containerWidth / 2 - width / 2 - margin[3];
  17535. break;
  17536. case 'right':
  17537. left = containerWidth - width - horizontalMargin;
  17538. break;
  17539. }
  17540. switch (positionInfo.top || positionInfo.bottom) {
  17541. case 'middle':
  17542. case 'center':
  17543. top = containerHeight / 2 - height / 2 - margin[0];
  17544. break;
  17545. case 'bottom':
  17546. top = containerHeight - height - verticalMargin;
  17547. break;
  17548. }
  17549. // If something is wrong and left, top, width, height are calculated as NaN
  17550. left = left || 0;
  17551. top = top || 0;
  17552. if (isNaN(width)) {
  17553. // Width may be NaN if only one value is given except width
  17554. width = containerWidth - horizontalMargin - left - (right || 0);
  17555. }
  17556. if (isNaN(height)) {
  17557. // Height may be NaN if only one value is given except height
  17558. height = containerHeight - verticalMargin - top - (bottom || 0);
  17559. }
  17560. var rect = new BoundingRect((containerRect.x || 0) + left + margin[3], (containerRect.y || 0) + top + margin[0], width, height);
  17561. rect.margin = margin;
  17562. return rect;
  17563. }
  17564. var BoxLayoutReferenceType = {
  17565. rect: 1,
  17566. point: 2
  17567. };
  17568. /**
  17569. * Uniformly calculate layout reference (rect or center) based on either:
  17570. * - viewport:
  17571. * - Get `refContainer` as `{x: 0, y: 0, width: api.getWidth(), height: api.getHeight()}`
  17572. * - coordinate system, which can serve in several ways:
  17573. * - Use `dataToPoint` to get the `refPoint`, such as, in cartesian2d coord sys.
  17574. * - Use `dataToLayout` to get the `refContainer`, such as, in matrix coord sys.
  17575. */
  17576. function createBoxLayoutReference(model, api, opt) {
  17577. var refContainer;
  17578. var refPoint;
  17579. var layoutRefType;
  17580. var boxCoordSys = model.boxCoordinateSystem;
  17581. var boxCoordFrom;
  17582. if (boxCoordSys) {
  17583. var _a = getCoordForBoxCoordSys(model),
  17584. coord = _a.coord,
  17585. from = _a.from;
  17586. // Do not use `clamp` in `dataToLayout` and `dataToPoint`, because:
  17587. // 1. Should support overflow (such as, by dataZoom), where NaN should be in the result.
  17588. // 2. Be consistent with the way used in `series.data`
  17589. if (boxCoordSys.dataToLayout) {
  17590. layoutRefType = BoxLayoutReferenceType.rect;
  17591. boxCoordFrom = from;
  17592. var result = boxCoordSys.dataToLayout(coord);
  17593. refContainer = result.contentRect || result.rect;
  17594. } else if (opt && opt.enableLayoutOnlyByCenter && boxCoordSys.dataToPoint) {
  17595. layoutRefType = BoxLayoutReferenceType.point;
  17596. boxCoordFrom = from;
  17597. refPoint = boxCoordSys.dataToPoint(coord);
  17598. } else {
  17599. if ("development" !== 'production') {
  17600. error(model.type + "[" + model.componentIndex + "]" + (" layout based on " + boxCoordSys.type + " is not supported."));
  17601. }
  17602. }
  17603. }
  17604. if (layoutRefType == null) {
  17605. layoutRefType = BoxLayoutReferenceType.rect;
  17606. }
  17607. if (layoutRefType === BoxLayoutReferenceType.rect) {
  17608. if (!refContainer) {
  17609. refContainer = {
  17610. x: 0,
  17611. y: 0,
  17612. width: api.getWidth(),
  17613. height: api.getHeight()
  17614. };
  17615. }
  17616. refPoint = [refContainer.x + refContainer.width / 2, refContainer.y + refContainer.height / 2];
  17617. }
  17618. return {
  17619. type: layoutRefType,
  17620. refContainer: refContainer,
  17621. refPoint: refPoint,
  17622. boxCoordFrom: boxCoordFrom
  17623. };
  17624. }
  17625. /**
  17626. * Position a zr element in viewport
  17627. * Group position is specified by either
  17628. * {left, top}, {right, bottom}
  17629. * If all properties exists, right and bottom will be igonred.
  17630. *
  17631. * Logic:
  17632. * 1. Scale (against origin point in parent coord)
  17633. * 2. Rotate (against origin point in parent coord)
  17634. * 3. Translate (with el.position by this method)
  17635. * So this method only fixes the last step 'Translate', which does not affect
  17636. * scaling and rotating.
  17637. *
  17638. * If be called repeatedly with the same input el, the same result will be gotten.
  17639. *
  17640. * Return true if the layout happened.
  17641. *
  17642. * @param el Should have `getBoundingRect` method.
  17643. * @param positionInfo
  17644. * @param positionInfo.left
  17645. * @param positionInfo.top
  17646. * @param positionInfo.right
  17647. * @param positionInfo.bottom
  17648. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  17649. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  17650. * @param containerRect
  17651. * @param margin
  17652. * @param opt
  17653. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  17654. * @param opt.boundingMode
  17655. * Specify how to calculate boundingRect when locating.
  17656. * 'all': Position the boundingRect that is transformed and uioned
  17657. * both itself and its descendants.
  17658. * This mode simplies confine the elements in the bounding
  17659. * of their container (e.g., using 'right: 0').
  17660. * 'raw': Position the boundingRect that is not transformed and only itself.
  17661. * This mode is useful when you want a element can overflow its
  17662. * container. (Consider a rotated circle needs to be located in a corner.)
  17663. * In this mode positionInfo.width/height can only be number.
  17664. */
  17665. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  17666. var h = !opt || !opt.hv || opt.hv[0];
  17667. var v = !opt || !opt.hv || opt.hv[1];
  17668. var boundingMode = opt && opt.boundingMode || 'all';
  17669. out = out || el;
  17670. out.x = el.x;
  17671. out.y = el.y;
  17672. if (!h && !v) {
  17673. return false;
  17674. }
  17675. var rect;
  17676. if (boundingMode === 'raw') {
  17677. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  17678. } else {
  17679. rect = el.getBoundingRect();
  17680. if (el.needLocalTransform()) {
  17681. var transform = el.getLocalTransform();
  17682. // Notice: raw rect may be inner object of el,
  17683. // which should not be modified.
  17684. rect = rect.clone();
  17685. rect.applyTransform(transform);
  17686. }
  17687. }
  17688. // The real width and height can not be specified but calculated by the given el.
  17689. var layoutRect = getLayoutRect(defaults({
  17690. width: rect.width,
  17691. height: rect.height
  17692. }, positionInfo), containerRect, margin);
  17693. // Because 'tranlate' is the last step in transform
  17694. // (see zrender/core/Transformable#getLocalTransform),
  17695. // we can just only modify el.position to get final result.
  17696. var dx = h ? layoutRect.x - rect.x : 0;
  17697. var dy = v ? layoutRect.y - rect.y : 0;
  17698. if (boundingMode === 'raw') {
  17699. out.x = dx;
  17700. out.y = dy;
  17701. } else {
  17702. out.x += dx;
  17703. out.y += dy;
  17704. }
  17705. if (out === el) {
  17706. el.markRedraw();
  17707. }
  17708. return true;
  17709. }
  17710. function fetchLayoutMode(ins) {
  17711. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  17712. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  17713. type: layoutMode
  17714. } : null;
  17715. }
  17716. /**
  17717. * Consider Case:
  17718. * When default option has {left: 0, width: 100}, and we set {right: 0}
  17719. * through setOption or media query, using normal zrUtil.merge will cause
  17720. * {right: 0} does not take effect.
  17721. *
  17722. * @example
  17723. * ComponentModel.extend({
  17724. * init: function () {
  17725. * ...
  17726. * let inputPositionParams = layout.getLayoutParams(option);
  17727. * this.mergeOption(inputPositionParams);
  17728. * },
  17729. * mergeOption: function (newOption) {
  17730. * newOption && zrUtil.merge(thisOption, newOption, true);
  17731. * layout.mergeLayoutParam(thisOption, newOption);
  17732. * }
  17733. * });
  17734. *
  17735. * @param targetOption
  17736. * @param newOption
  17737. * @param opt
  17738. */
  17739. function mergeLayoutParam(targetOption, newOption, opt) {
  17740. var ignoreSize = opt && opt.ignoreSize;
  17741. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17742. var hResult = merge(HV_NAMES[0], 0);
  17743. var vResult = merge(HV_NAMES[1], 1);
  17744. copy(HV_NAMES[0], targetOption, hResult);
  17745. copy(HV_NAMES[1], targetOption, vResult);
  17746. function merge(names, hvIdx) {
  17747. var newParams = {};
  17748. var newValueCount = 0;
  17749. var merged = {};
  17750. var mergedValueCount = 0;
  17751. var enoughParamNumber = 2;
  17752. each$1(names, function (name) {
  17753. merged[name] = targetOption[name];
  17754. });
  17755. each$1(names, function (name) {
  17756. // Consider case: newOption.width is null, which is
  17757. // set by user for removing width setting.
  17758. hasOwn(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17759. hasValue(newParams, name) && newValueCount++;
  17760. hasValue(merged, name) && mergedValueCount++;
  17761. });
  17762. if (ignoreSize[hvIdx]) {
  17763. // Only one of left/right is premitted to exist.
  17764. if (hasValue(newOption, names[1])) {
  17765. merged[names[2]] = null;
  17766. } else if (hasValue(newOption, names[2])) {
  17767. merged[names[1]] = null;
  17768. }
  17769. return merged;
  17770. }
  17771. // Case: newOption: {width: ..., right: ...},
  17772. // or targetOption: {right: ...} and newOption: {width: ...},
  17773. // There is no conflict when merged only has params count
  17774. // little than enoughParamNumber.
  17775. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17776. return merged;
  17777. }
  17778. // Case: newOption: {width: ..., right: ...},
  17779. // Than we can make sure user only want those two, and ignore
  17780. // all origin params in targetOption.
  17781. else if (newValueCount >= enoughParamNumber) {
  17782. return newParams;
  17783. } else {
  17784. // Chose another param from targetOption by priority.
  17785. for (var i = 0; i < names.length; i++) {
  17786. var name_1 = names[i];
  17787. if (!hasOwn(newParams, name_1) && hasOwn(targetOption, name_1)) {
  17788. newParams[name_1] = targetOption[name_1];
  17789. break;
  17790. }
  17791. }
  17792. return newParams;
  17793. }
  17794. }
  17795. function hasValue(obj, name) {
  17796. return obj[name] != null && obj[name] !== 'auto';
  17797. }
  17798. function copy(names, target, source) {
  17799. each$1(names, function (name) {
  17800. target[name] = source[name];
  17801. });
  17802. }
  17803. }
  17804. /**
  17805. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17806. */
  17807. function getLayoutParams(source) {
  17808. return copyLayoutParams({}, source);
  17809. }
  17810. /**
  17811. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17812. * @param {Object} source
  17813. * @return {Object} Result contains those props.
  17814. */
  17815. function copyLayoutParams(target, source) {
  17816. source && target && each$1(LOCATION_PARAMS, function (name) {
  17817. hasOwn(source, name) && (target[name] = source[name]);
  17818. });
  17819. return target;
  17820. }
  17821. var inner = makeInner();
  17822. var ComponentModel = /** @class */function (_super) {
  17823. __extends(ComponentModel, _super);
  17824. function ComponentModel(option, parentModel, ecModel) {
  17825. var _this = _super.call(this, option, parentModel, ecModel) || this;
  17826. _this.uid = getUID('ec_cpt_model');
  17827. return _this;
  17828. }
  17829. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  17830. this.mergeDefaultAndTheme(option, ecModel);
  17831. };
  17832. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  17833. var layoutMode = fetchLayoutMode(this);
  17834. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  17835. var themeModel = ecModel.getTheme();
  17836. merge(option, themeModel.get(this.mainType));
  17837. merge(option, this.getDefaultOption());
  17838. if (layoutMode) {
  17839. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17840. }
  17841. };
  17842. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  17843. merge(this.option, option, true);
  17844. var layoutMode = fetchLayoutMode(this);
  17845. if (layoutMode) {
  17846. mergeLayoutParam(this.option, option, layoutMode);
  17847. }
  17848. };
  17849. /**
  17850. * Called immediately after `init` or `mergeOption` of this instance called.
  17851. */
  17852. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  17853. /**
  17854. * [How to declare defaultOption]:
  17855. *
  17856. * (A) If using class declaration in typescript (since echarts 5):
  17857. * ```ts
  17858. * import {ComponentOption} from '../model/option.js';
  17859. * export interface XxxOption extends ComponentOption {
  17860. * aaa: number
  17861. * }
  17862. * export class XxxModel extends Component {
  17863. * static type = 'xxx';
  17864. * static defaultOption: XxxOption = {
  17865. * aaa: 123
  17866. * }
  17867. * }
  17868. * Component.registerClass(XxxModel);
  17869. * ```
  17870. * ```ts
  17871. * import {inheritDefaultOption} from '../util/component.js';
  17872. * import {XxxModel, XxxOption} from './XxxModel.js';
  17873. * export interface XxxSubOption extends XxxOption {
  17874. * bbb: number
  17875. * }
  17876. * class XxxSubModel extends XxxModel {
  17877. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  17878. * bbb: 456
  17879. * })
  17880. * fn() {
  17881. * let opt = this.getDefaultOption();
  17882. * // opt is {aaa: 123, bbb: 456}
  17883. * }
  17884. * }
  17885. * ```
  17886. *
  17887. * (B) If using class extend (previous approach in echarts 3 & 4):
  17888. * ```js
  17889. * let XxxComponent = Component.extend({
  17890. * defaultOption: {
  17891. * xx: 123
  17892. * }
  17893. * })
  17894. * ```
  17895. * ```js
  17896. * let XxxSubComponent = XxxComponent.extend({
  17897. * defaultOption: {
  17898. * yy: 456
  17899. * },
  17900. * fn: function () {
  17901. * let opt = this.getDefaultOption();
  17902. * // opt is {xx: 123, yy: 456}
  17903. * }
  17904. * })
  17905. * ```
  17906. */
  17907. ComponentModel.prototype.getDefaultOption = function () {
  17908. var ctor = this.constructor;
  17909. if (!isExtendedClass(ctor)) {
  17910. // When using ES class declaration, defaultOption must be declared as static.
  17911. // And manually inherit the defaultOption from its parent class if needed, such as,
  17912. // ```ts
  17913. // static defaultOption = inheritDefaultOption(ParentModel.defaultOption, {...});
  17914. // ```
  17915. return ctor.defaultOption;
  17916. }
  17917. // FIXME: remove this approach?
  17918. // Legacy: auto merge defaultOption from ancestor classes if using ParentClass.extend(subProto)
  17919. var fields = inner(this);
  17920. if (!fields.defaultOption) {
  17921. var optList = [];
  17922. var clz = ctor;
  17923. while (clz) {
  17924. var opt = clz.prototype.defaultOption;
  17925. opt && optList.push(opt);
  17926. clz = clz.superClass;
  17927. }
  17928. var defaultOption = {};
  17929. for (var i = optList.length - 1; i >= 0; i--) {
  17930. defaultOption = merge(defaultOption, optList[i], true);
  17931. }
  17932. fields.defaultOption = defaultOption;
  17933. }
  17934. return fields.defaultOption;
  17935. };
  17936. /**
  17937. * Notice: always force to input param `useDefault` in case that forget to consider it.
  17938. * The same behavior as `modelUtil.parseFinder`.
  17939. *
  17940. * @param useDefault In many cases like series refer axis and axis refer grid,
  17941. * If axis index / axis id not specified, use the first target as default.
  17942. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  17943. */
  17944. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  17945. var indexKey = mainType + 'Index';
  17946. var idKey = mainType + 'Id';
  17947. return queryReferringComponents(this.ecModel, mainType, {
  17948. index: this.get(indexKey, true),
  17949. id: this.get(idKey, true)
  17950. }, opt);
  17951. };
  17952. ComponentModel.prototype.getBoxLayoutParams = function () {
  17953. // Consider itself having box layout configs.
  17954. // For backward compatibility, by default do not `ignoreParent`.
  17955. return getBoxLayoutParams(this, false);
  17956. };
  17957. /**
  17958. * Get key for zlevel.
  17959. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  17960. * For example, lines with trail effect and progressive series will in an individual zlevel.
  17961. */
  17962. ComponentModel.prototype.getZLevelKey = function () {
  17963. return '';
  17964. };
  17965. ComponentModel.prototype.setZLevel = function (zlevel) {
  17966. this.option.zlevel = zlevel;
  17967. };
  17968. ComponentModel.protoInitialize = function () {
  17969. var proto = ComponentModel.prototype;
  17970. proto.type = 'component';
  17971. proto.id = '';
  17972. proto.name = '';
  17973. proto.mainType = '';
  17974. proto.subType = '';
  17975. proto.componentIndex = 0;
  17976. }();
  17977. return ComponentModel;
  17978. }(Model);
  17979. mountExtend(ComponentModel, Model);
  17980. enableClassManagement(ComponentModel);
  17981. enableSubTypeDefaulter(ComponentModel);
  17982. enableTopologicalTravel(ComponentModel, getDependencies);
  17983. function getDependencies(componentType) {
  17984. var deps = [];
  17985. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  17986. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  17987. });
  17988. // Ensure main type.
  17989. deps = map(deps, function (type) {
  17990. return parseClassType(type).main;
  17991. });
  17992. // Hack dataset for convenience.
  17993. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17994. deps.unshift('dataset');
  17995. }
  17996. return deps;
  17997. }
  17998. var tokens = {
  17999. color: {},
  18000. darkColor: {},
  18001. size: {}
  18002. };
  18003. var color$1 = tokens.color = {
  18004. theme: ['#5070dd', '#b6d634', '#505372', '#ff994d', '#0ca8df', '#ffd10a', '#fb628b', '#785db0', '#3fbe95'],
  18005. neutral00: '#fff',
  18006. neutral05: '#f4f7fd',
  18007. neutral10: '#e8ebf0',
  18008. neutral15: '#dbdee4',
  18009. neutral20: '#cfd2d7',
  18010. neutral25: '#c3c5cb',
  18011. neutral30: '#b7b9be',
  18012. neutral35: '#aaacb2',
  18013. neutral40: '#9ea0a5',
  18014. neutral45: '#929399',
  18015. neutral50: '#86878c',
  18016. neutral55: '#797b7f',
  18017. neutral60: '#6d6e73',
  18018. neutral65: '#616266',
  18019. neutral70: '#54555a',
  18020. neutral75: '#48494d',
  18021. neutral80: '#3c3c41',
  18022. neutral85: '#303034',
  18023. neutral90: '#232328',
  18024. neutral95: '#17171b',
  18025. neutral99: '#000',
  18026. accent05: '#eff1f9',
  18027. accent10: '#e0e4f2',
  18028. accent15: '#d0d6ec',
  18029. accent20: '#c0c9e6',
  18030. accent25: '#b1bbdf',
  18031. accent30: '#a1aed9',
  18032. accent35: '#91a0d3',
  18033. accent40: '#8292cc',
  18034. accent45: '#7285c6',
  18035. accent50: '#6578ba',
  18036. accent55: '#5c6da9',
  18037. accent60: '#536298',
  18038. accent65: '#4a5787',
  18039. accent70: '#404c76',
  18040. accent75: '#374165',
  18041. accent80: '#2e3654',
  18042. accent85: '#252b43',
  18043. accent90: '#1b2032',
  18044. accent95: '#121521',
  18045. transparent: 'rgba(0,0,0,0)',
  18046. highlight: 'rgba(255,231,130,0.8)'
  18047. };
  18048. extend(color$1, {
  18049. primary: color$1.neutral80,
  18050. secondary: color$1.neutral70,
  18051. tertiary: color$1.neutral60,
  18052. quaternary: color$1.neutral50,
  18053. disabled: color$1.neutral20,
  18054. border: color$1.neutral30,
  18055. borderTint: color$1.neutral20,
  18056. borderShade: color$1.neutral40,
  18057. background: color$1.neutral05,
  18058. backgroundTint: 'rgba(234,237,245,0.5)',
  18059. backgroundTransparent: 'rgba(255,255,255,0)',
  18060. backgroundShade: color$1.neutral10,
  18061. shadow: 'rgba(0,0,0,0.2)',
  18062. shadowTint: 'rgba(129,130,136,0.2)',
  18063. axisLine: color$1.neutral70,
  18064. axisLineTint: color$1.neutral40,
  18065. axisTick: color$1.neutral70,
  18066. axisTickMinor: color$1.neutral60,
  18067. axisLabel: color$1.neutral70,
  18068. axisSplitLine: color$1.neutral15,
  18069. axisMinorSplitLine: color$1.neutral05
  18070. });
  18071. for (var key in color$1) {
  18072. if (color$1.hasOwnProperty(key)) {
  18073. var hex = color$1[key];
  18074. if (key === 'theme') {
  18075. // Don't modify theme colors.
  18076. tokens.darkColor.theme = color$1.theme.slice();
  18077. } else if (key === 'highlight') {
  18078. tokens.darkColor.highlight = 'rgba(255,231,130,0.4)';
  18079. } else if (key.indexOf('accent') === 0) {
  18080. // Desaturate and lighten accent colors.
  18081. tokens.darkColor[key] = modifyHSL(hex, null, function (s) {
  18082. return s * 0.5;
  18083. }, function (l) {
  18084. return Math.min(1, 1.3 - l);
  18085. });
  18086. } else {
  18087. tokens.darkColor[key] = modifyHSL(hex, null, function (s) {
  18088. return s * 0.9;
  18089. }, function (l) {
  18090. return 1 - Math.pow(l, 1.5);
  18091. });
  18092. }
  18093. }
  18094. }
  18095. tokens.size = {
  18096. xxs: 2,
  18097. xs: 5,
  18098. s: 10,
  18099. m: 15,
  18100. l: 20,
  18101. xl: 30,
  18102. xxl: 40,
  18103. xxxl: 50
  18104. };
  18105. var platform = '';
  18106. // Navigator not exists in node
  18107. if (typeof navigator !== 'undefined') {
  18108. /* global navigator */
  18109. platform = navigator.platform || '';
  18110. }
  18111. var decalColor = 'rgba(0, 0, 0, 0.2)';
  18112. var themeColor = tokens.color.theme[0];
  18113. var lightThemeColor = modifyHSL(themeColor, null, null, 0.9);
  18114. var globalDefault = {
  18115. darkMode: 'auto',
  18116. // backgroundColor: 'rgba(0,0,0,0)',
  18117. colorBy: 'series',
  18118. color: tokens.color.theme,
  18119. gradientColor: [lightThemeColor, themeColor],
  18120. aria: {
  18121. decal: {
  18122. decals: [{
  18123. color: decalColor,
  18124. dashArrayX: [1, 0],
  18125. dashArrayY: [2, 5],
  18126. symbolSize: 1,
  18127. rotation: Math.PI / 6
  18128. }, {
  18129. color: decalColor,
  18130. symbol: 'circle',
  18131. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  18132. dashArrayY: [6, 0],
  18133. symbolSize: 0.8
  18134. }, {
  18135. color: decalColor,
  18136. dashArrayX: [1, 0],
  18137. dashArrayY: [4, 3],
  18138. rotation: -Math.PI / 4
  18139. }, {
  18140. color: decalColor,
  18141. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  18142. dashArrayY: [6, 0]
  18143. }, {
  18144. color: decalColor,
  18145. dashArrayX: [[1, 0], [1, 6]],
  18146. dashArrayY: [1, 0, 6, 0],
  18147. rotation: Math.PI / 4
  18148. }, {
  18149. color: decalColor,
  18150. symbol: 'triangle',
  18151. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  18152. dashArrayY: [7, 2],
  18153. symbolSize: 0.75
  18154. }]
  18155. }
  18156. },
  18157. // If xAxis and yAxis declared, grid is created by default.
  18158. // grid: {},
  18159. textStyle: {
  18160. // color: '#000',
  18161. // decoration: 'none',
  18162. // PENDING
  18163. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18164. // fontFamily: 'Arial, Verdana, sans-serif',
  18165. fontSize: 12,
  18166. fontStyle: 'normal',
  18167. fontWeight: 'normal'
  18168. },
  18169. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18170. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18171. // Default is source-over
  18172. blendMode: null,
  18173. stateAnimation: {
  18174. duration: 300,
  18175. easing: 'cubicOut'
  18176. },
  18177. animation: 'auto',
  18178. animationDuration: 1000,
  18179. animationDurationUpdate: 500,
  18180. animationEasing: 'cubicInOut',
  18181. animationEasingUpdate: 'cubicInOut',
  18182. animationThreshold: 2000,
  18183. // Configuration for progressive/incremental rendering
  18184. progressiveThreshold: 3000,
  18185. progressive: 400,
  18186. // Threshold of if use single hover layer to optimize.
  18187. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18188. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18189. // which is unexpected.
  18190. // see example <echarts/test/heatmap-large.html>.
  18191. hoverLayerThreshold: 3000,
  18192. // See: module:echarts/scale/Time
  18193. useUTC: false
  18194. };
  18195. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'itemChildGroupId', 'seriesName']);
  18196. var SOURCE_FORMAT_ORIGINAL = 'original';
  18197. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18198. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18199. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18200. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18201. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18202. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18203. var SERIES_LAYOUT_BY_ROW = 'row';
  18204. // The result of `guessOrdinal`.
  18205. var BE_ORDINAL = {
  18206. Must: 1,
  18207. Might: 2,
  18208. Not: 3 // Other cases
  18209. };
  18210. var innerGlobalModel = makeInner();
  18211. /**
  18212. * MUST be called before mergeOption of all series.
  18213. */
  18214. function resetSourceDefaulter(ecModel) {
  18215. // `datasetMap` is used to make default encode.
  18216. innerGlobalModel(ecModel).datasetMap = createHashMap();
  18217. }
  18218. /**
  18219. * [The strategy of the arrengment of data dimensions for dataset]:
  18220. * "value way": all axes are non-category axes. So series one by one take
  18221. * several (the number is coordSysDims.length) dimensions from dataset.
  18222. * The result of data arrengment of data dimensions like:
  18223. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18224. * "category way": at least one axis is category axis. So the the first data
  18225. * dimension is always mapped to the first category axis and shared by
  18226. * all of the series. The other data dimensions are taken by series like
  18227. * "value way" does.
  18228. * The result of data arrengment of data dimensions like:
  18229. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18230. *
  18231. * @return encode Never be `null/undefined`.
  18232. */
  18233. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18234. var encode = {};
  18235. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  18236. // Currently only make default when using dataset, util more reqirements occur.
  18237. if (!datasetModel || !coordDimensions) {
  18238. return encode;
  18239. }
  18240. var encodeItemName = [];
  18241. var encodeSeriesName = [];
  18242. var ecModel = seriesModel.ecModel;
  18243. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  18244. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18245. var baseCategoryDimIndex;
  18246. var categoryWayValueDimStart;
  18247. coordDimensions = coordDimensions.slice();
  18248. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  18249. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  18250. name: coordDimInfoLoose
  18251. };
  18252. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18253. baseCategoryDimIndex = coordDimIdx;
  18254. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  18255. }
  18256. encode[coordDimInfo.name] = [];
  18257. });
  18258. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  18259. categoryWayDim: categoryWayValueDimStart,
  18260. valueWayDim: 0
  18261. });
  18262. // TODO
  18263. // Auto detect first time axis and do arrangement.
  18264. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18265. var coordDimName = coordDimInfo.name;
  18266. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18267. // In value way.
  18268. if (baseCategoryDimIndex == null) {
  18269. var start = datasetRecord.valueWayDim;
  18270. pushDim(encode[coordDimName], start, count);
  18271. pushDim(encodeSeriesName, start, count);
  18272. datasetRecord.valueWayDim += count;
  18273. // ??? TODO give a better default series name rule?
  18274. // especially when encode x y specified.
  18275. // consider: when multiple series share one dimension
  18276. // category axis, series name should better use
  18277. // the other dimension name. On the other hand, use
  18278. // both dimensions name.
  18279. }
  18280. // In category way, the first category axis.
  18281. else if (baseCategoryDimIndex === coordDimIdx) {
  18282. pushDim(encode[coordDimName], 0, count);
  18283. pushDim(encodeItemName, 0, count);
  18284. }
  18285. // In category way, the other axis.
  18286. else {
  18287. var start = datasetRecord.categoryWayDim;
  18288. pushDim(encode[coordDimName], start, count);
  18289. pushDim(encodeSeriesName, start, count);
  18290. datasetRecord.categoryWayDim += count;
  18291. }
  18292. });
  18293. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18294. for (var i = 0; i < idxCount; i++) {
  18295. dimIdxArr.push(idxFrom + i);
  18296. }
  18297. }
  18298. function getDataDimCountOnCoordDim(coordDimInfo) {
  18299. var dimsDef = coordDimInfo.dimsDef;
  18300. return dimsDef ? dimsDef.length : 1;
  18301. }
  18302. encodeItemName.length && (encode.itemName = encodeItemName);
  18303. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18304. return encode;
  18305. }
  18306. /**
  18307. * Work for data like [{name: ..., value: ...}, ...].
  18308. *
  18309. * @return encode Never be `null/undefined`.
  18310. */
  18311. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18312. var encode = {};
  18313. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel);
  18314. // Currently only make default when using dataset, util more reqirements occur.
  18315. if (!datasetModel) {
  18316. return encode;
  18317. }
  18318. var sourceFormat = source.sourceFormat;
  18319. var dimensionsDefine = source.dimensionsDefine;
  18320. var potentialNameDimIndex;
  18321. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18322. each(dimensionsDefine, function (dim, idx) {
  18323. if ((isObject(dim) ? dim.name : dim) === 'name') {
  18324. potentialNameDimIndex = idx;
  18325. }
  18326. });
  18327. }
  18328. var idxResult = function () {
  18329. var idxRes0 = {};
  18330. var idxRes1 = {};
  18331. var guessRecords = [];
  18332. // 5 is an experience value.
  18333. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18334. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  18335. guessRecords.push(guessResult);
  18336. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18337. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18338. // and then find a name dim with the priority:
  18339. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18340. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18341. idxRes0.v = i;
  18342. }
  18343. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  18344. idxRes0.n = i;
  18345. }
  18346. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18347. return idxRes0;
  18348. }
  18349. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18350. // find the first BE_ORDINAL.Might as the value dim,
  18351. // and then find a name dim with the priority:
  18352. // "other dim" > "the value dim itself".
  18353. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18354. // treated as number.
  18355. if (!isPureNumber) {
  18356. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18357. idxRes1.v = i;
  18358. }
  18359. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  18360. idxRes1.n = i;
  18361. }
  18362. }
  18363. }
  18364. function fulfilled(idxResult) {
  18365. return idxResult.v != null && idxResult.n != null;
  18366. }
  18367. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18368. }();
  18369. if (idxResult) {
  18370. encode.value = [idxResult.v];
  18371. // `potentialNameDimIndex` has highest priority.
  18372. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18373. // By default, label uses itemName in charts.
  18374. // So we don't set encodeLabel here.
  18375. encode.itemName = [nameDimIndex];
  18376. encode.seriesName = [nameDimIndex];
  18377. }
  18378. return encode;
  18379. }
  18380. /**
  18381. * @return If return null/undefined, indicate that should not use datasetModel.
  18382. */
  18383. function querySeriesUpstreamDatasetModel(seriesModel) {
  18384. // Caution: consider the scenario:
  18385. // A dataset is declared and a series is not expected to use the dataset,
  18386. // and at the beginning `setOption({series: { noData })` (just prepare other
  18387. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18388. // the user should set an empty array to avoid that dataset is used by default.
  18389. var thisData = seriesModel.get('data', true);
  18390. if (!thisData) {
  18391. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  18392. index: seriesModel.get('datasetIndex', true),
  18393. id: seriesModel.get('datasetId', true)
  18394. }, SINGLE_REFERRING).models[0];
  18395. }
  18396. }
  18397. /**
  18398. * @return Always return an array event empty.
  18399. */
  18400. function queryDatasetUpstreamDatasetModels(datasetModel) {
  18401. // Only these attributes declared, we by default reference to `datasetIndex: 0`.
  18402. // Otherwise, no reference.
  18403. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  18404. return [];
  18405. }
  18406. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  18407. index: datasetModel.get('fromDatasetIndex', true),
  18408. id: datasetModel.get('fromDatasetId', true)
  18409. }, SINGLE_REFERRING).models;
  18410. }
  18411. /**
  18412. * The rule should not be complex, otherwise user might not
  18413. * be able to known where the data is wrong.
  18414. * The code is ugly, but how to make it neat?
  18415. */
  18416. function guessOrdinal(source, dimIndex) {
  18417. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  18418. }
  18419. // dimIndex may be overflow source data.
  18420. // return {BE_ORDINAL}
  18421. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  18422. var result;
  18423. // Experience value.
  18424. var maxLoop = 5;
  18425. if (isTypedArray(data)) {
  18426. return BE_ORDINAL.Not;
  18427. }
  18428. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18429. // always exists in source.
  18430. var dimName;
  18431. var dimType;
  18432. if (dimensionsDefine) {
  18433. var dimDefItem = dimensionsDefine[dimIndex];
  18434. if (isObject(dimDefItem)) {
  18435. dimName = dimDefItem.name;
  18436. dimType = dimDefItem.type;
  18437. } else if (isString(dimDefItem)) {
  18438. dimName = dimDefItem;
  18439. }
  18440. }
  18441. if (dimType != null) {
  18442. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18443. }
  18444. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18445. var dataArrayRows = data;
  18446. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18447. var sample = dataArrayRows[dimIndex];
  18448. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18449. if ((result = detectValue(sample[startIndex + i])) != null) {
  18450. return result;
  18451. }
  18452. }
  18453. } else {
  18454. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  18455. var row = dataArrayRows[startIndex + i];
  18456. if (row && (result = detectValue(row[dimIndex])) != null) {
  18457. return result;
  18458. }
  18459. }
  18460. }
  18461. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18462. var dataObjectRows = data;
  18463. if (!dimName) {
  18464. return BE_ORDINAL.Not;
  18465. }
  18466. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  18467. var item = dataObjectRows[i];
  18468. if (item && (result = detectValue(item[dimName])) != null) {
  18469. return result;
  18470. }
  18471. }
  18472. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18473. var dataKeyedColumns = data;
  18474. if (!dimName) {
  18475. return BE_ORDINAL.Not;
  18476. }
  18477. var sample = dataKeyedColumns[dimName];
  18478. if (!sample || isTypedArray(sample)) {
  18479. return BE_ORDINAL.Not;
  18480. }
  18481. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18482. if ((result = detectValue(sample[i])) != null) {
  18483. return result;
  18484. }
  18485. }
  18486. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18487. var dataOriginal = data;
  18488. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  18489. var item = dataOriginal[i];
  18490. var val = getDataItemValue(item);
  18491. if (!isArray(val)) {
  18492. return BE_ORDINAL.Not;
  18493. }
  18494. if ((result = detectValue(val[dimIndex])) != null) {
  18495. return result;
  18496. }
  18497. }
  18498. }
  18499. function detectValue(val) {
  18500. var beStr = isString(val);
  18501. // Consider usage convenience, '1', '2' will be treated as "number".
  18502. // `Number('')` (or any whitespace) is `0`.
  18503. if (val != null && Number.isFinite(Number(val)) && val !== '') {
  18504. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18505. } else if (beStr && val !== '-') {
  18506. return BE_ORDINAL.Must;
  18507. }
  18508. }
  18509. return BE_ORDINAL.Not;
  18510. }
  18511. var internalOptionCreatorMap = createHashMap();
  18512. function registerInternalOptionCreator(mainType, creator) {
  18513. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  18514. internalOptionCreatorMap.set(mainType, creator);
  18515. }
  18516. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  18517. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  18518. if (!internalOptionCreator) {
  18519. return newCmptOptionList;
  18520. }
  18521. var internalOptions = internalOptionCreator(ecModel);
  18522. if (!internalOptions) {
  18523. return newCmptOptionList;
  18524. }
  18525. if ("development" !== 'production') {
  18526. for (var i = 0; i < internalOptions.length; i++) {
  18527. assert(isComponentIdInternal(internalOptions[i]));
  18528. }
  18529. }
  18530. return newCmptOptionList.concat(internalOptions);
  18531. }
  18532. var innerColor = makeInner();
  18533. var innerDecal = makeInner();
  18534. var PaletteMixin = /** @class */function () {
  18535. function PaletteMixin() {}
  18536. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  18537. var defaultPalette = normalizeToArray(this.get('color', true));
  18538. var layeredPalette = this.get('colorLayer', true);
  18539. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  18540. };
  18541. PaletteMixin.prototype.clearColorPalette = function () {
  18542. clearPalette(this, innerColor);
  18543. };
  18544. return PaletteMixin;
  18545. }();
  18546. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  18547. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  18548. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  18549. }
  18550. function getNearestPalette(palettes, requestColorNum) {
  18551. var paletteNum = palettes.length;
  18552. // TODO palettes must be in order
  18553. for (var i = 0; i < paletteNum; i++) {
  18554. if (palettes[i].length > requestColorNum) {
  18555. return palettes[i];
  18556. }
  18557. }
  18558. return palettes[paletteNum - 1];
  18559. }
  18560. /**
  18561. * @param name MUST NOT be null/undefined. Otherwise call this function
  18562. * twise with the same parameters will get different result.
  18563. * @param scope default this.
  18564. * @return Can be null/undefined
  18565. */
  18566. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  18567. scope = scope || that;
  18568. var scopeFields = inner(scope);
  18569. var paletteIdx = scopeFields.paletteIdx || 0;
  18570. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {};
  18571. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18572. if (paletteNameMap.hasOwnProperty(name)) {
  18573. return paletteNameMap[name];
  18574. }
  18575. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum);
  18576. // In case can't find in layered color palette.
  18577. palette = palette || defaultPalette;
  18578. if (!palette || !palette.length) {
  18579. return;
  18580. }
  18581. var pickedPaletteItem = palette[paletteIdx];
  18582. if (name) {
  18583. paletteNameMap[name] = pickedPaletteItem;
  18584. }
  18585. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  18586. return pickedPaletteItem;
  18587. }
  18588. function clearPalette(that, inner) {
  18589. inner(that).paletteIdx = 0;
  18590. inner(that).paletteNameMap = {};
  18591. }
  18592. // -----------------------
  18593. // Internal method names:
  18594. // -----------------------
  18595. var reCreateSeriesIndices;
  18596. var assertSeriesInitialized;
  18597. var initBase;
  18598. var OPTION_INNER_KEY = '\0_ec_inner';
  18599. var OPTION_INNER_VALUE = 1;
  18600. var BUITIN_COMPONENTS_MAP = {
  18601. grid: 'GridComponent',
  18602. polar: 'PolarComponent',
  18603. geo: 'GeoComponent',
  18604. singleAxis: 'SingleAxisComponent',
  18605. parallel: 'ParallelComponent',
  18606. calendar: 'CalendarComponent',
  18607. matrix: 'MatrixComponent',
  18608. graphic: 'GraphicComponent',
  18609. toolbox: 'ToolboxComponent',
  18610. tooltip: 'TooltipComponent',
  18611. axisPointer: 'AxisPointerComponent',
  18612. brush: 'BrushComponent',
  18613. title: 'TitleComponent',
  18614. timeline: 'TimelineComponent',
  18615. markPoint: 'MarkPointComponent',
  18616. markLine: 'MarkLineComponent',
  18617. markArea: 'MarkAreaComponent',
  18618. legend: 'LegendComponent',
  18619. dataZoom: 'DataZoomComponent',
  18620. visualMap: 'VisualMapComponent',
  18621. // aria: 'AriaComponent',
  18622. // dataset: 'DatasetComponent',
  18623. // Dependencies
  18624. xAxis: 'GridComponent',
  18625. yAxis: 'GridComponent',
  18626. angleAxis: 'PolarComponent',
  18627. radiusAxis: 'PolarComponent'
  18628. };
  18629. var BUILTIN_CHARTS_MAP = {
  18630. line: 'LineChart',
  18631. bar: 'BarChart',
  18632. pie: 'PieChart',
  18633. scatter: 'ScatterChart',
  18634. radar: 'RadarChart',
  18635. map: 'MapChart',
  18636. tree: 'TreeChart',
  18637. treemap: 'TreemapChart',
  18638. graph: 'GraphChart',
  18639. chord: 'ChordChart',
  18640. gauge: 'GaugeChart',
  18641. funnel: 'FunnelChart',
  18642. parallel: 'ParallelChart',
  18643. sankey: 'SankeyChart',
  18644. boxplot: 'BoxplotChart',
  18645. candlestick: 'CandlestickChart',
  18646. effectScatter: 'EffectScatterChart',
  18647. lines: 'LinesChart',
  18648. heatmap: 'HeatmapChart',
  18649. pictorialBar: 'PictorialBarChart',
  18650. themeRiver: 'ThemeRiverChart',
  18651. sunburst: 'SunburstChart',
  18652. custom: 'CustomChart'
  18653. };
  18654. var componetsMissingLogPrinted = {};
  18655. function checkMissingComponents(option) {
  18656. each(option, function (componentOption, mainType) {
  18657. if (!ComponentModel.hasClass(mainType)) {
  18658. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  18659. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  18660. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  18661. componetsMissingLogPrinted[componentImportName] = true;
  18662. }
  18663. }
  18664. });
  18665. }
  18666. var GlobalModel = /** @class */function (_super) {
  18667. __extends(GlobalModel, _super);
  18668. function GlobalModel() {
  18669. return _super !== null && _super.apply(this, arguments) || this;
  18670. }
  18671. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  18672. theme = theme || {};
  18673. this.option = null; // Mark as not initialized.
  18674. this._theme = new Model(theme);
  18675. this._locale = new Model(locale);
  18676. this._optionManager = optionManager;
  18677. };
  18678. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  18679. if ("development" !== 'production') {
  18680. assert(option != null, 'option is null/undefined');
  18681. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  18682. }
  18683. var innerOpt = normalizeSetOptionInput(opts);
  18684. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  18685. this._resetOption(null, innerOpt);
  18686. };
  18687. /**
  18688. * @param type null/undefined: reset all.
  18689. * 'recreate': force recreate all.
  18690. * 'timeline': only reset timeline option
  18691. * 'media': only reset media query option
  18692. * @return Whether option changed.
  18693. */
  18694. GlobalModel.prototype.resetOption = function (type, opt) {
  18695. return this._resetOption(type, normalizeSetOptionInput(opt));
  18696. };
  18697. GlobalModel.prototype._resetOption = function (type, opt) {
  18698. var optionChanged = false;
  18699. var optionManager = this._optionManager;
  18700. if (!type || type === 'recreate') {
  18701. var baseOption = optionManager.mountOption(type === 'recreate');
  18702. if ("development" !== 'production') {
  18703. checkMissingComponents(baseOption);
  18704. }
  18705. if (!this.option || type === 'recreate') {
  18706. initBase(this, baseOption);
  18707. } else {
  18708. this.restoreData();
  18709. this._mergeOption(baseOption, opt);
  18710. }
  18711. optionChanged = true;
  18712. }
  18713. if (type === 'timeline' || type === 'media') {
  18714. this.restoreData();
  18715. }
  18716. // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  18717. // it should better not have the same props with `MediaUnit['option']`.
  18718. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  18719. // rather than original "baseOption". If they both override a prop, the result might be
  18720. // unexpected when media state changed after `setOption` called.
  18721. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  18722. // (`{baseOption, media}`) in `setOption`.
  18723. // For `timeline`, the case is the same.
  18724. if (!type || type === 'recreate' || type === 'timeline') {
  18725. var timelineOption = optionManager.getTimelineOption(this);
  18726. if (timelineOption) {
  18727. optionChanged = true;
  18728. this._mergeOption(timelineOption, opt);
  18729. }
  18730. }
  18731. if (!type || type === 'recreate' || type === 'media') {
  18732. var mediaOptions = optionManager.getMediaOption(this);
  18733. if (mediaOptions.length) {
  18734. each(mediaOptions, function (mediaOption) {
  18735. optionChanged = true;
  18736. this._mergeOption(mediaOption, opt);
  18737. }, this);
  18738. }
  18739. }
  18740. return optionChanged;
  18741. };
  18742. GlobalModel.prototype.mergeOption = function (option) {
  18743. this._mergeOption(option, null);
  18744. };
  18745. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  18746. var option = this.option;
  18747. var componentsMap = this._componentsMap;
  18748. var componentsCount = this._componentsCount;
  18749. var newCmptTypes = [];
  18750. var newCmptTypeMap = createHashMap();
  18751. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  18752. resetSourceDefaulter(this);
  18753. // If no component class, merge directly.
  18754. // For example: color, animaiton options, etc.
  18755. each(newOption, function (componentOption, mainType) {
  18756. if (componentOption == null) {
  18757. return;
  18758. }
  18759. if (!ComponentModel.hasClass(mainType)) {
  18760. // globalSettingTask.dirty();
  18761. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  18762. } else if (mainType) {
  18763. newCmptTypes.push(mainType);
  18764. newCmptTypeMap.set(mainType, true);
  18765. }
  18766. });
  18767. if (replaceMergeMainTypeMap) {
  18768. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  18769. // we trade it as it is declared in option as `{xxx: []}`. Because:
  18770. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  18771. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  18772. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  18773. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  18774. newCmptTypes.push(mainTypeInReplaceMerge);
  18775. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  18776. }
  18777. });
  18778. }
  18779. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  18780. function visitComponent(mainType) {
  18781. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  18782. var oldCmptList = componentsMap.get(mainType);
  18783. var mergeMode =
  18784. // `!oldCmptList` means init. See the comment in `mappingToExists`
  18785. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  18786. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode);
  18787. // Set mainType and complete subType.
  18788. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel);
  18789. // Empty it before the travel, in order to prevent `this._componentsMap`
  18790. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  18791. // components, which is probably incorrect logic.
  18792. option[mainType] = null;
  18793. componentsMap.set(mainType, null);
  18794. componentsCount.set(mainType, 0);
  18795. var optionsByMainType = [];
  18796. var cmptsByMainType = [];
  18797. var cmptsCountByMainType = 0;
  18798. var tooltipExists;
  18799. var tooltipWarningLogged;
  18800. each(mappingResult, function (resultItem, index) {
  18801. var componentModel = resultItem.existing;
  18802. var newCmptOption = resultItem.newOption;
  18803. if (!newCmptOption) {
  18804. if (componentModel) {
  18805. // Consider where is no new option and should be merged using {},
  18806. // see removeEdgeAndAdd in topologicalTravel and
  18807. // ComponentModel.getAllClassMainTypes.
  18808. componentModel.mergeOption({}, this);
  18809. componentModel.optionUpdated({}, false);
  18810. }
  18811. // If no both `resultItem.exist` and `resultItem.option`,
  18812. // either it is in `replaceMerge` and not matched by any id,
  18813. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  18814. } else {
  18815. var isSeriesType = mainType === 'series';
  18816. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  18817. );
  18818. if (!ComponentModelClass) {
  18819. if ("development" !== 'production') {
  18820. var subType = resultItem.keyInfo.subType;
  18821. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  18822. if (!componetsMissingLogPrinted[subType]) {
  18823. componetsMissingLogPrinted[subType] = true;
  18824. if (seriesImportName) {
  18825. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  18826. } else {
  18827. error("Unknown series " + subType);
  18828. }
  18829. }
  18830. }
  18831. return;
  18832. }
  18833. // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  18834. if (mainType === 'tooltip') {
  18835. if (tooltipExists) {
  18836. if ("development" !== 'production') {
  18837. if (!tooltipWarningLogged) {
  18838. warn('Currently only one tooltip component is allowed.');
  18839. tooltipWarningLogged = true;
  18840. }
  18841. }
  18842. return;
  18843. }
  18844. tooltipExists = true;
  18845. }
  18846. if (componentModel && componentModel.constructor === ComponentModelClass) {
  18847. componentModel.name = resultItem.keyInfo.name;
  18848. // componentModel.settingTask && componentModel.settingTask.dirty();
  18849. componentModel.mergeOption(newCmptOption, this);
  18850. componentModel.optionUpdated(newCmptOption, false);
  18851. } else {
  18852. // PENDING Global as parent ?
  18853. var extraOpt = extend({
  18854. componentIndex: index
  18855. }, resultItem.keyInfo);
  18856. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt);
  18857. // Assign `keyInfo`
  18858. extend(componentModel, extraOpt);
  18859. if (resultItem.brandNew) {
  18860. componentModel.__requireNewView = true;
  18861. }
  18862. componentModel.init(newCmptOption, this, this);
  18863. // Call optionUpdated after init.
  18864. // newCmptOption has been used as componentModel.option
  18865. // and may be merged with theme and default, so pass null
  18866. // to avoid confusion.
  18867. componentModel.optionUpdated(null, true);
  18868. }
  18869. }
  18870. if (componentModel) {
  18871. optionsByMainType.push(componentModel.option);
  18872. cmptsByMainType.push(componentModel);
  18873. cmptsCountByMainType++;
  18874. } else {
  18875. // Always do assign to avoid elided item in array.
  18876. optionsByMainType.push(void 0);
  18877. cmptsByMainType.push(void 0);
  18878. }
  18879. }, this);
  18880. option[mainType] = optionsByMainType;
  18881. componentsMap.set(mainType, cmptsByMainType);
  18882. componentsCount.set(mainType, cmptsCountByMainType);
  18883. // Backup series for filtering.
  18884. if (mainType === 'series') {
  18885. reCreateSeriesIndices(this);
  18886. }
  18887. }
  18888. // If no series declared, ensure `_seriesIndices` initialized.
  18889. if (!this._seriesIndices) {
  18890. reCreateSeriesIndices(this);
  18891. }
  18892. };
  18893. /**
  18894. * Get option for output (cloned option and inner info removed)
  18895. */
  18896. GlobalModel.prototype.getOption = function () {
  18897. var option = clone(this.option);
  18898. each(option, function (optInMainType, mainType) {
  18899. if (ComponentModel.hasClass(mainType)) {
  18900. var opts = normalizeToArray(optInMainType);
  18901. // Inner cmpts need to be removed.
  18902. // Inner cmpts might not be at last since ec5.0, but still
  18903. // compatible for users: if inner cmpt at last, splice the returned array.
  18904. var realLen = opts.length;
  18905. var metNonInner = false;
  18906. for (var i = realLen - 1; i >= 0; i--) {
  18907. // Remove options with inner id.
  18908. if (opts[i] && !isComponentIdInternal(opts[i])) {
  18909. metNonInner = true;
  18910. } else {
  18911. opts[i] = null;
  18912. !metNonInner && realLen--;
  18913. }
  18914. }
  18915. opts.length = realLen;
  18916. option[mainType] = opts;
  18917. }
  18918. });
  18919. delete option[OPTION_INNER_KEY];
  18920. return option;
  18921. };
  18922. GlobalModel.prototype.setTheme = function (theme) {
  18923. this._theme = new Model(theme);
  18924. this._resetOption('recreate', null);
  18925. };
  18926. GlobalModel.prototype.getTheme = function () {
  18927. return this._theme;
  18928. };
  18929. GlobalModel.prototype.getLocaleModel = function () {
  18930. return this._locale;
  18931. };
  18932. GlobalModel.prototype.setUpdatePayload = function (payload) {
  18933. this._payload = payload;
  18934. };
  18935. GlobalModel.prototype.getUpdatePayload = function () {
  18936. return this._payload;
  18937. };
  18938. /**
  18939. * @param idx If not specified, return the first one.
  18940. */
  18941. GlobalModel.prototype.getComponent = function (mainType, idx) {
  18942. var list = this._componentsMap.get(mainType);
  18943. if (list) {
  18944. var cmpt = list[idx || 0];
  18945. if (cmpt) {
  18946. return cmpt;
  18947. } else if (idx == null) {
  18948. for (var i = 0; i < list.length; i++) {
  18949. if (list[i]) {
  18950. return list[i];
  18951. }
  18952. }
  18953. }
  18954. }
  18955. };
  18956. /**
  18957. * @return Never be null/undefined.
  18958. */
  18959. GlobalModel.prototype.queryComponents = function (condition) {
  18960. var mainType = condition.mainType;
  18961. if (!mainType) {
  18962. return [];
  18963. }
  18964. var index = condition.index;
  18965. var id = condition.id;
  18966. var name = condition.name;
  18967. var cmpts = this._componentsMap.get(mainType);
  18968. if (!cmpts || !cmpts.length) {
  18969. return [];
  18970. }
  18971. var result;
  18972. if (index != null) {
  18973. result = [];
  18974. each(normalizeToArray(index), function (idx) {
  18975. cmpts[idx] && result.push(cmpts[idx]);
  18976. });
  18977. } else if (id != null) {
  18978. result = queryByIdOrName('id', id, cmpts);
  18979. } else if (name != null) {
  18980. result = queryByIdOrName('name', name, cmpts);
  18981. } else {
  18982. // Return all non-empty components in that mainType
  18983. result = filter(cmpts, function (cmpt) {
  18984. return !!cmpt;
  18985. });
  18986. }
  18987. return filterBySubType(result, condition);
  18988. };
  18989. /**
  18990. * The interface is different from queryComponents,
  18991. * which is convenient for inner usage.
  18992. *
  18993. * @usage
  18994. * let result = findComponents(
  18995. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18996. * );
  18997. * let result = findComponents(
  18998. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18999. * );
  19000. * let result = findComponents(
  19001. * {mainType: 'series',
  19002. * filter: function (model, index) {...}}
  19003. * );
  19004. * // result like [component0, componnet1, ...]
  19005. */
  19006. GlobalModel.prototype.findComponents = function (condition) {
  19007. var query = condition.query;
  19008. var mainType = condition.mainType;
  19009. var queryCond = getQueryCond(query);
  19010. var result = queryCond ? this.queryComponents(queryCond)
  19011. // Retrieve all non-empty components.
  19012. : filter(this._componentsMap.get(mainType), function (cmpt) {
  19013. return !!cmpt;
  19014. });
  19015. return doFilter(filterBySubType(result, condition));
  19016. function getQueryCond(q) {
  19017. var indexAttr = mainType + 'Index';
  19018. var idAttr = mainType + 'Id';
  19019. var nameAttr = mainType + 'Name';
  19020. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  19021. mainType: mainType,
  19022. // subType will be filtered finally.
  19023. index: q[indexAttr],
  19024. id: q[idAttr],
  19025. name: q[nameAttr]
  19026. } : null;
  19027. }
  19028. function doFilter(res) {
  19029. return condition.filter ? filter(res, condition.filter) : res;
  19030. }
  19031. };
  19032. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  19033. var componentsMap = this._componentsMap;
  19034. if (isFunction(mainType)) {
  19035. var ctxForAll_1 = cb;
  19036. var cbForAll_1 = mainType;
  19037. componentsMap.each(function (cmpts, componentType) {
  19038. for (var i = 0; cmpts && i < cmpts.length; i++) {
  19039. var cmpt = cmpts[i];
  19040. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  19041. }
  19042. });
  19043. } else {
  19044. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  19045. for (var i = 0; cmpts && i < cmpts.length; i++) {
  19046. var cmpt = cmpts[i];
  19047. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  19048. }
  19049. }
  19050. };
  19051. /**
  19052. * Get series list before filtered by name.
  19053. */
  19054. GlobalModel.prototype.getSeriesByName = function (name) {
  19055. var nameStr = convertOptionIdName(name, null);
  19056. return filter(this._componentsMap.get('series'), function (oneSeries) {
  19057. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  19058. });
  19059. };
  19060. /**
  19061. * Get series list before filtered by index.
  19062. */
  19063. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  19064. return this._componentsMap.get('series')[seriesIndex];
  19065. };
  19066. /**
  19067. * Get series list before filtered by type.
  19068. * FIXME: rename to getRawSeriesByType?
  19069. */
  19070. GlobalModel.prototype.getSeriesByType = function (subType) {
  19071. return filter(this._componentsMap.get('series'), function (oneSeries) {
  19072. return !!oneSeries && oneSeries.subType === subType;
  19073. });
  19074. };
  19075. /**
  19076. * Get all series before filtered.
  19077. */
  19078. GlobalModel.prototype.getSeries = function () {
  19079. return filter(this._componentsMap.get('series'), function (oneSeries) {
  19080. return !!oneSeries;
  19081. });
  19082. };
  19083. /**
  19084. * Count series before filtered.
  19085. */
  19086. GlobalModel.prototype.getSeriesCount = function () {
  19087. return this._componentsCount.get('series');
  19088. };
  19089. /**
  19090. * After filtering, series may be different
  19091. * from raw series.
  19092. */
  19093. GlobalModel.prototype.eachSeries = function (cb, context) {
  19094. assertSeriesInitialized(this);
  19095. each(this._seriesIndices, function (rawSeriesIndex) {
  19096. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19097. cb.call(context, series, rawSeriesIndex);
  19098. }, this);
  19099. };
  19100. /**
  19101. * Iterate raw series before filtered.
  19102. *
  19103. * @param {Function} cb
  19104. * @param {*} context
  19105. */
  19106. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  19107. each(this._componentsMap.get('series'), function (series) {
  19108. series && cb.call(context, series, series.componentIndex);
  19109. });
  19110. };
  19111. /**
  19112. * After filtering, series may be different.
  19113. * from raw series.
  19114. */
  19115. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  19116. assertSeriesInitialized(this);
  19117. each(this._seriesIndices, function (rawSeriesIndex) {
  19118. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19119. if (series.subType === subType) {
  19120. cb.call(context, series, rawSeriesIndex);
  19121. }
  19122. }, this);
  19123. };
  19124. /**
  19125. * Iterate raw series before filtered of given type.
  19126. */
  19127. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  19128. return each(this.getSeriesByType(subType), cb, context);
  19129. };
  19130. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  19131. assertSeriesInitialized(this);
  19132. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19133. };
  19134. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  19135. return (this._seriesIndices || []).slice();
  19136. };
  19137. GlobalModel.prototype.filterSeries = function (cb, context) {
  19138. assertSeriesInitialized(this);
  19139. var newSeriesIndices = [];
  19140. each(this._seriesIndices, function (seriesRawIdx) {
  19141. var series = this._componentsMap.get('series')[seriesRawIdx];
  19142. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  19143. }, this);
  19144. this._seriesIndices = newSeriesIndices;
  19145. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  19146. };
  19147. GlobalModel.prototype.restoreData = function (payload) {
  19148. reCreateSeriesIndices(this);
  19149. var componentsMap = this._componentsMap;
  19150. var componentTypes = [];
  19151. componentsMap.each(function (components, componentType) {
  19152. if (ComponentModel.hasClass(componentType)) {
  19153. componentTypes.push(componentType);
  19154. }
  19155. });
  19156. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  19157. each(componentsMap.get(componentType), function (component) {
  19158. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  19159. component.restoreData();
  19160. }
  19161. });
  19162. });
  19163. };
  19164. GlobalModel.internalField = function () {
  19165. reCreateSeriesIndices = function (ecModel) {
  19166. var seriesIndices = ecModel._seriesIndices = [];
  19167. each(ecModel._componentsMap.get('series'), function (series) {
  19168. // series may have been removed by `replaceMerge`.
  19169. series && seriesIndices.push(series.componentIndex);
  19170. });
  19171. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  19172. };
  19173. assertSeriesInitialized = function (ecModel) {
  19174. // Components that use _seriesIndices should depends on series component,
  19175. // which make sure that their initialization is after series.
  19176. if ("development" !== 'production') {
  19177. if (!ecModel._seriesIndices) {
  19178. throw new Error('Option should contains series.');
  19179. }
  19180. }
  19181. };
  19182. initBase = function (ecModel, baseOption) {
  19183. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  19184. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  19185. ecModel.option = {};
  19186. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE;
  19187. // Init with series: [], in case of calling findSeries method
  19188. // before series initialized.
  19189. ecModel._componentsMap = createHashMap({
  19190. series: []
  19191. });
  19192. ecModel._componentsCount = createHashMap();
  19193. // If user spefied `option.aria`, aria will be enable. This detection should be
  19194. // performed before theme and globalDefault merge.
  19195. var airaOption = baseOption.aria;
  19196. if (isObject(airaOption) && airaOption.enabled == null) {
  19197. airaOption.enabled = true;
  19198. }
  19199. mergeTheme(baseOption, ecModel._theme.option);
  19200. // TODO Needs clone when merging to the unexisted property
  19201. merge(baseOption, globalDefault, false);
  19202. ecModel._mergeOption(baseOption, null);
  19203. };
  19204. }();
  19205. return GlobalModel;
  19206. }(Model);
  19207. function isNotTargetSeries(seriesModel, payload) {
  19208. if (payload) {
  19209. var index = payload.seriesIndex;
  19210. var id = payload.seriesId;
  19211. var name_1 = payload.seriesName;
  19212. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  19213. }
  19214. }
  19215. function mergeTheme(option, theme) {
  19216. // PENDING
  19217. // NOT use `colorLayer` in theme if option has `color`
  19218. var notMergeColorLayer = option.color && !option.colorLayer;
  19219. each(theme, function (themeItem, name) {
  19220. if (name === 'colorLayer' && notMergeColorLayer || name === 'color' && option.color) {
  19221. return;
  19222. }
  19223. // If it is component model mainType, the model handles that merge later.
  19224. // otherwise, merge them here.
  19225. if (!ComponentModel.hasClass(name)) {
  19226. if (typeof themeItem === 'object') {
  19227. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  19228. } else {
  19229. if (option[name] == null) {
  19230. option[name] = themeItem;
  19231. }
  19232. }
  19233. }
  19234. });
  19235. }
  19236. function queryByIdOrName(attr, idOrName, cmpts) {
  19237. // Here is a break from echarts4: string and number are
  19238. // treated as equal.
  19239. if (isArray(idOrName)) {
  19240. var keyMap_1 = createHashMap();
  19241. each(idOrName, function (idOrNameItem) {
  19242. if (idOrNameItem != null) {
  19243. var idName = convertOptionIdName(idOrNameItem, null);
  19244. idName != null && keyMap_1.set(idOrNameItem, true);
  19245. }
  19246. });
  19247. return filter(cmpts, function (cmpt) {
  19248. return cmpt && keyMap_1.get(cmpt[attr]);
  19249. });
  19250. } else {
  19251. var idName_1 = convertOptionIdName(idOrName, null);
  19252. return filter(cmpts, function (cmpt) {
  19253. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  19254. });
  19255. }
  19256. }
  19257. function filterBySubType(components, condition) {
  19258. // Using hasOwnProperty for restrict. Consider
  19259. // subType is undefined in user payload.
  19260. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  19261. return cmpt && cmpt.subType === condition.subType;
  19262. }) : components;
  19263. }
  19264. function normalizeSetOptionInput(opts) {
  19265. var replaceMergeMainTypeMap = createHashMap();
  19266. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  19267. if ("development" !== 'production') {
  19268. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  19269. }
  19270. replaceMergeMainTypeMap.set(mainType, true);
  19271. });
  19272. return {
  19273. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  19274. };
  19275. }
  19276. mixin(GlobalModel, PaletteMixin);
  19277. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL',
  19278. // 'getModel',
  19279. 'getOption',
  19280. // 'getViewOfComponentModel',
  19281. // 'getViewOfSeriesModel',
  19282. 'getId', 'updateLabelLayout'];
  19283. var ExtensionAPI = /** @class */function () {
  19284. function ExtensionAPI(ecInstance) {
  19285. each(availableMethods, function (methodName) {
  19286. this[methodName] = bind(ecInstance[methodName], ecInstance);
  19287. }, this);
  19288. }
  19289. return ExtensionAPI;
  19290. }();
  19291. var QUERY_REG = /^(min|max)?(.+)$/;
  19292. // Key: mainType
  19293. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  19294. /**
  19295. * TERM EXPLANATIONS:
  19296. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  19297. */
  19298. var OptionManager = /** @class */function () {
  19299. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19300. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19301. // rawOption cloned and backuped when timeline changed, which does no
  19302. // good to performance. What's more, that both timeline and setOption
  19303. // method supply 'notMerge' brings complex and some problems.
  19304. // Consider this case:
  19305. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19306. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19307. function OptionManager(api) {
  19308. this._timelineOptions = [];
  19309. this._mediaList = [];
  19310. /**
  19311. * -1, means default.
  19312. * empty means no media.
  19313. */
  19314. this._currentMediaIndices = [];
  19315. this._api = api;
  19316. }
  19317. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  19318. if (rawOption) {
  19319. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19320. each(normalizeToArray(rawOption.series), function (series) {
  19321. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19322. });
  19323. each(normalizeToArray(rawOption.dataset), function (dataset) {
  19324. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  19325. });
  19326. }
  19327. // Caution: some series modify option data, if do not clone,
  19328. // it should ensure that the repeat modify correctly
  19329. // (create a new object when modify itself).
  19330. rawOption = clone(rawOption);
  19331. // FIXME
  19332. // If some property is set in timeline options or media option but
  19333. // not set in baseOption, a warning should be given.
  19334. var optionBackup = this._optionBackup;
  19335. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  19336. this._newBaseOption = newParsedOption.baseOption;
  19337. // For setOption at second time (using merge mode);
  19338. if (optionBackup) {
  19339. // FIXME
  19340. // the restore merge solution is essentially incorrect.
  19341. // the mapping can not be 100% consistent with ecModel, which probably brings
  19342. // potential bug!
  19343. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  19344. // let fakeCmptsMap = this._fakeCmptsMap;
  19345. // if (!fakeCmptsMap) {
  19346. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  19347. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  19348. // }
  19349. // mergeToBackupOption(
  19350. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  19351. // );
  19352. // For simplicity, timeline options and media options do not support merge,
  19353. // that is, if you `setOption` twice and both has timeline options, the latter
  19354. // timeline options will not be merged to the former, but just substitute them.
  19355. if (newParsedOption.timelineOptions.length) {
  19356. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  19357. }
  19358. if (newParsedOption.mediaList.length) {
  19359. optionBackup.mediaList = newParsedOption.mediaList;
  19360. }
  19361. if (newParsedOption.mediaDefault) {
  19362. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  19363. }
  19364. } else {
  19365. this._optionBackup = newParsedOption;
  19366. }
  19367. };
  19368. OptionManager.prototype.mountOption = function (isRecreate) {
  19369. var optionBackup = this._optionBackup;
  19370. this._timelineOptions = optionBackup.timelineOptions;
  19371. this._mediaList = optionBackup.mediaList;
  19372. this._mediaDefault = optionBackup.mediaDefault;
  19373. this._currentMediaIndices = [];
  19374. return clone(isRecreate
  19375. // this._optionBackup.baseOption, which is created at the first `setOption`
  19376. // called, and is merged into every new option by inner method `mergeToBackupOption`
  19377. // each time `setOption` called, can be only used in `isRecreate`, because
  19378. // its reliability is under suspicion. In other cases option merge is
  19379. // performed by `model.mergeOption`.
  19380. ? optionBackup.baseOption : this._newBaseOption);
  19381. };
  19382. OptionManager.prototype.getTimelineOption = function (ecModel) {
  19383. var option;
  19384. var timelineOptions = this._timelineOptions;
  19385. if (timelineOptions.length) {
  19386. // getTimelineOption can only be called after ecModel inited,
  19387. // so we can get currentIndex from timelineModel.
  19388. var timelineModel = ecModel.getComponent('timeline');
  19389. if (timelineModel) {
  19390. option = clone(
  19391. // FIXME:TS as TimelineModel or quivlant interface
  19392. timelineOptions[timelineModel.getCurrentIndex()]);
  19393. }
  19394. }
  19395. return option;
  19396. };
  19397. OptionManager.prototype.getMediaOption = function (ecModel) {
  19398. var ecWidth = this._api.getWidth();
  19399. var ecHeight = this._api.getHeight();
  19400. var mediaList = this._mediaList;
  19401. var mediaDefault = this._mediaDefault;
  19402. var indices = [];
  19403. var result = [];
  19404. // No media defined.
  19405. if (!mediaList.length && !mediaDefault) {
  19406. return result;
  19407. }
  19408. // Multi media may be applied, the latter defined media has higher priority.
  19409. for (var i = 0, len = mediaList.length; i < len; i++) {
  19410. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19411. indices.push(i);
  19412. }
  19413. }
  19414. // FIXME
  19415. // Whether mediaDefault should force users to provide? Otherwise
  19416. // the change by media query can not be recorvered.
  19417. if (!indices.length && mediaDefault) {
  19418. indices = [-1];
  19419. }
  19420. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19421. result = map(indices, function (index) {
  19422. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  19423. });
  19424. }
  19425. // Otherwise return nothing.
  19426. this._currentMediaIndices = indices;
  19427. return result;
  19428. };
  19429. return OptionManager;
  19430. }();
  19431. /**
  19432. * [RAW_OPTION_PATTERNS]
  19433. * (Note: "series: []" represents all other props in `ECUnitOption`)
  19434. *
  19435. * (1) No prop "baseOption" declared:
  19436. * Root option is used as "baseOption" (except prop "options" and "media").
  19437. * ```js
  19438. * option = {
  19439. * series: [],
  19440. * timeline: {},
  19441. * options: [],
  19442. * };
  19443. * option = {
  19444. * series: [],
  19445. * media: {},
  19446. * };
  19447. * option = {
  19448. * series: [],
  19449. * timeline: {},
  19450. * options: [],
  19451. * media: {},
  19452. * }
  19453. * ```
  19454. *
  19455. * (2) Prop "baseOption" declared:
  19456. * If "baseOption" declared, `ECUnitOption` props can only be declared
  19457. * inside "baseOption" except prop "timeline" (compat ec2).
  19458. * ```js
  19459. * option = {
  19460. * baseOption: {
  19461. * timeline: {},
  19462. * series: [],
  19463. * },
  19464. * options: []
  19465. * };
  19466. * option = {
  19467. * baseOption: {
  19468. * series: [],
  19469. * },
  19470. * media: []
  19471. * };
  19472. * option = {
  19473. * baseOption: {
  19474. * timeline: {},
  19475. * series: [],
  19476. * },
  19477. * options: []
  19478. * media: []
  19479. * };
  19480. * option = {
  19481. * // ec3 compat ec2: allow (only) `timeline` declared
  19482. * // outside baseOption. Keep this setting for compat.
  19483. * timeline: {},
  19484. * baseOption: {
  19485. * series: [],
  19486. * },
  19487. * options: [],
  19488. * media: []
  19489. * };
  19490. * ```
  19491. */
  19492. function parseRawOption(
  19493. // `rawOption` May be modified
  19494. rawOption, optionPreprocessorFuncs, isNew) {
  19495. var mediaList = [];
  19496. var mediaDefault;
  19497. var baseOption;
  19498. var declaredBaseOption = rawOption.baseOption;
  19499. // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  19500. var timelineOnRoot = rawOption.timeline;
  19501. var timelineOptionsOnRoot = rawOption.options;
  19502. var mediaOnRoot = rawOption.media;
  19503. var hasMedia = !!rawOption.media;
  19504. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  19505. if (declaredBaseOption) {
  19506. baseOption = declaredBaseOption;
  19507. // For merge option.
  19508. if (!baseOption.timeline) {
  19509. baseOption.timeline = timelineOnRoot;
  19510. }
  19511. }
  19512. // For convenience, enable to use the root option as the `baseOption`:
  19513. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  19514. else {
  19515. if (hasTimeline || hasMedia) {
  19516. rawOption.options = rawOption.media = null;
  19517. }
  19518. baseOption = rawOption;
  19519. }
  19520. if (hasMedia) {
  19521. if (isArray(mediaOnRoot)) {
  19522. each(mediaOnRoot, function (singleMedia) {
  19523. if ("development" !== 'production') {
  19524. // Real case of wrong config.
  19525. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  19526. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  19527. }
  19528. }
  19529. if (singleMedia && singleMedia.option) {
  19530. if (singleMedia.query) {
  19531. mediaList.push(singleMedia);
  19532. } else if (!mediaDefault) {
  19533. // Use the first media default.
  19534. mediaDefault = singleMedia;
  19535. }
  19536. }
  19537. });
  19538. } else {
  19539. if ("development" !== 'production') {
  19540. // Real case of wrong config.
  19541. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  19542. }
  19543. }
  19544. }
  19545. doPreprocess(baseOption);
  19546. each(timelineOptionsOnRoot, function (option) {
  19547. return doPreprocess(option);
  19548. });
  19549. each(mediaList, function (media) {
  19550. return doPreprocess(media.option);
  19551. });
  19552. function doPreprocess(option) {
  19553. each(optionPreprocessorFuncs, function (preProcess) {
  19554. preProcess(option, isNew);
  19555. });
  19556. }
  19557. return {
  19558. baseOption: baseOption,
  19559. timelineOptions: timelineOptionsOnRoot || [],
  19560. mediaDefault: mediaDefault,
  19561. mediaList: mediaList
  19562. };
  19563. }
  19564. /**
  19565. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19566. * Support: width, height, aspectRatio
  19567. * Can use max or min as prefix.
  19568. */
  19569. function applyMediaQuery(query, ecWidth, ecHeight) {
  19570. var realMap = {
  19571. width: ecWidth,
  19572. height: ecHeight,
  19573. aspectratio: ecWidth / ecHeight // lower case for convenience.
  19574. };
  19575. var applicable = true;
  19576. each(query, function (value, attr) {
  19577. var matched = attr.match(QUERY_REG);
  19578. if (!matched || !matched[1] || !matched[2]) {
  19579. return;
  19580. }
  19581. var operator = matched[1];
  19582. var realAttr = matched[2].toLowerCase();
  19583. if (!compare(realMap[realAttr], value, operator)) {
  19584. applicable = false;
  19585. }
  19586. });
  19587. return applicable;
  19588. }
  19589. function compare(real, expect, operator) {
  19590. if (operator === 'min') {
  19591. return real >= expect;
  19592. } else if (operator === 'max') {
  19593. return real <= expect;
  19594. } else {
  19595. // Equals
  19596. return real === expect;
  19597. }
  19598. }
  19599. function indicesEquals(indices1, indices2) {
  19600. // indices is always order by asc and has only finite number.
  19601. return indices1.join(',') === indices2.join(',');
  19602. }
  19603. var each$2 = each;
  19604. var isObject$1 = isObject;
  19605. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  19606. function compatEC2ItemStyle(opt) {
  19607. var itemStyleOpt = opt && opt.itemStyle;
  19608. if (!itemStyleOpt) {
  19609. return;
  19610. }
  19611. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19612. var styleName = POSSIBLE_STYLES[i];
  19613. var normalItemStyleOpt = itemStyleOpt.normal;
  19614. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19615. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19616. if ("development" !== 'production') {
  19617. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  19618. }
  19619. opt[styleName] = opt[styleName] || {};
  19620. if (!opt[styleName].normal) {
  19621. opt[styleName].normal = normalItemStyleOpt[styleName];
  19622. } else {
  19623. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19624. }
  19625. normalItemStyleOpt[styleName] = null;
  19626. }
  19627. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19628. if ("development" !== 'production') {
  19629. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  19630. }
  19631. opt[styleName] = opt[styleName] || {};
  19632. if (!opt[styleName].emphasis) {
  19633. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19634. } else {
  19635. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19636. }
  19637. emphasisItemStyleOpt[styleName] = null;
  19638. }
  19639. }
  19640. }
  19641. function convertNormalEmphasis(opt, optType, useExtend) {
  19642. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19643. var normalOpt = opt[optType].normal;
  19644. var emphasisOpt = opt[optType].emphasis;
  19645. if (normalOpt) {
  19646. if ("development" !== 'production') {
  19647. // eslint-disable-next-line max-len
  19648. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  19649. }
  19650. // Timeline controlStyle has other properties besides normal and emphasis
  19651. if (useExtend) {
  19652. opt[optType].normal = opt[optType].emphasis = null;
  19653. defaults(opt[optType], normalOpt);
  19654. } else {
  19655. opt[optType] = normalOpt;
  19656. }
  19657. }
  19658. if (emphasisOpt) {
  19659. if ("development" !== 'production') {
  19660. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  19661. }
  19662. opt.emphasis = opt.emphasis || {};
  19663. opt.emphasis[optType] = emphasisOpt;
  19664. // Also compat the case user mix the style and focus together in ec3 style
  19665. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  19666. if (emphasisOpt.focus) {
  19667. opt.emphasis.focus = emphasisOpt.focus;
  19668. }
  19669. if (emphasisOpt.blurScope) {
  19670. opt.emphasis.blurScope = emphasisOpt.blurScope;
  19671. }
  19672. }
  19673. }
  19674. }
  19675. function removeEC3NormalStatus(opt) {
  19676. convertNormalEmphasis(opt, 'itemStyle');
  19677. convertNormalEmphasis(opt, 'lineStyle');
  19678. convertNormalEmphasis(opt, 'areaStyle');
  19679. convertNormalEmphasis(opt, 'label');
  19680. convertNormalEmphasis(opt, 'labelLine');
  19681. // treemap
  19682. convertNormalEmphasis(opt, 'upperLabel');
  19683. // graph
  19684. convertNormalEmphasis(opt, 'edgeLabel');
  19685. }
  19686. function compatTextStyle(opt, propName) {
  19687. // Check whether is not object (string\null\undefined ...)
  19688. var labelOptSingle = isObject$1(opt) && opt[propName];
  19689. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  19690. if (textStyle) {
  19691. if ("development" !== 'production') {
  19692. // eslint-disable-next-line max-len
  19693. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  19694. }
  19695. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19696. var textPropName = TEXT_STYLE_OPTIONS[i];
  19697. if (textStyle.hasOwnProperty(textPropName)) {
  19698. labelOptSingle[textPropName] = textStyle[textPropName];
  19699. }
  19700. }
  19701. }
  19702. }
  19703. function compatEC3CommonStyles(opt) {
  19704. if (opt) {
  19705. removeEC3NormalStatus(opt);
  19706. compatTextStyle(opt, 'label');
  19707. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19708. }
  19709. }
  19710. function processSeries(seriesOpt) {
  19711. if (!isObject$1(seriesOpt)) {
  19712. return;
  19713. }
  19714. compatEC2ItemStyle(seriesOpt);
  19715. removeEC3NormalStatus(seriesOpt);
  19716. compatTextStyle(seriesOpt, 'label');
  19717. // treemap
  19718. compatTextStyle(seriesOpt, 'upperLabel');
  19719. // graph
  19720. compatTextStyle(seriesOpt, 'edgeLabel');
  19721. if (seriesOpt.emphasis) {
  19722. compatTextStyle(seriesOpt.emphasis, 'label');
  19723. // treemap
  19724. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19725. // graph
  19726. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19727. }
  19728. var markPoint = seriesOpt.markPoint;
  19729. if (markPoint) {
  19730. compatEC2ItemStyle(markPoint);
  19731. compatEC3CommonStyles(markPoint);
  19732. }
  19733. var markLine = seriesOpt.markLine;
  19734. if (markLine) {
  19735. compatEC2ItemStyle(markLine);
  19736. compatEC3CommonStyles(markLine);
  19737. }
  19738. var markArea = seriesOpt.markArea;
  19739. if (markArea) {
  19740. compatEC3CommonStyles(markArea);
  19741. }
  19742. var data = seriesOpt.data;
  19743. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19744. // then the backward compat based on option type will not be performed.
  19745. if (seriesOpt.type === 'graph') {
  19746. data = data || seriesOpt.nodes;
  19747. var edgeData = seriesOpt.links || seriesOpt.edges;
  19748. if (edgeData && !isTypedArray(edgeData)) {
  19749. for (var i = 0; i < edgeData.length; i++) {
  19750. compatEC3CommonStyles(edgeData[i]);
  19751. }
  19752. }
  19753. each(seriesOpt.categories, function (opt) {
  19754. removeEC3NormalStatus(opt);
  19755. });
  19756. }
  19757. if (data && !isTypedArray(data)) {
  19758. for (var i = 0; i < data.length; i++) {
  19759. compatEC3CommonStyles(data[i]);
  19760. }
  19761. }
  19762. // mark point data
  19763. markPoint = seriesOpt.markPoint;
  19764. if (markPoint && markPoint.data) {
  19765. var mpData = markPoint.data;
  19766. for (var i = 0; i < mpData.length; i++) {
  19767. compatEC3CommonStyles(mpData[i]);
  19768. }
  19769. }
  19770. // mark line data
  19771. markLine = seriesOpt.markLine;
  19772. if (markLine && markLine.data) {
  19773. var mlData = markLine.data;
  19774. for (var i = 0; i < mlData.length; i++) {
  19775. if (isArray(mlData[i])) {
  19776. compatEC3CommonStyles(mlData[i][0]);
  19777. compatEC3CommonStyles(mlData[i][1]);
  19778. } else {
  19779. compatEC3CommonStyles(mlData[i]);
  19780. }
  19781. }
  19782. }
  19783. // Series
  19784. if (seriesOpt.type === 'gauge') {
  19785. compatTextStyle(seriesOpt, 'axisLabel');
  19786. compatTextStyle(seriesOpt, 'title');
  19787. compatTextStyle(seriesOpt, 'detail');
  19788. } else if (seriesOpt.type === 'treemap') {
  19789. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19790. each(seriesOpt.levels, function (opt) {
  19791. removeEC3NormalStatus(opt);
  19792. });
  19793. } else if (seriesOpt.type === 'tree') {
  19794. removeEC3NormalStatus(seriesOpt.leaves);
  19795. }
  19796. // sunburst starts from ec4, so it does not need to compat levels.
  19797. }
  19798. function toArr(o) {
  19799. return isArray(o) ? o : o ? [o] : [];
  19800. }
  19801. function toObj(o) {
  19802. return (isArray(o) ? o[0] : o) || {};
  19803. }
  19804. function globalCompatStyle(option, isTheme) {
  19805. each$2(toArr(option.series), function (seriesOpt) {
  19806. isObject$1(seriesOpt) && processSeries(seriesOpt);
  19807. });
  19808. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19809. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19810. each$2(axes, function (axisName) {
  19811. each$2(toArr(option[axisName]), function (axisOpt) {
  19812. if (axisOpt) {
  19813. compatTextStyle(axisOpt, 'axisLabel');
  19814. compatTextStyle(axisOpt.axisPointer, 'label');
  19815. }
  19816. });
  19817. });
  19818. each$2(toArr(option.parallel), function (parallelOpt) {
  19819. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19820. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19821. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19822. });
  19823. each$2(toArr(option.calendar), function (calendarOpt) {
  19824. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19825. compatTextStyle(calendarOpt, 'dayLabel');
  19826. compatTextStyle(calendarOpt, 'monthLabel');
  19827. compatTextStyle(calendarOpt, 'yearLabel');
  19828. });
  19829. // radar.name.textStyle
  19830. each$2(toArr(option.radar), function (radarOpt) {
  19831. compatTextStyle(radarOpt, 'name');
  19832. // Use axisName instead of name because component has name property
  19833. if (radarOpt.name && radarOpt.axisName == null) {
  19834. radarOpt.axisName = radarOpt.name;
  19835. delete radarOpt.name;
  19836. if ("development" !== 'production') {
  19837. deprecateLog('name property in radar component has been changed to axisName');
  19838. }
  19839. }
  19840. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  19841. radarOpt.axisNameGap = radarOpt.nameGap;
  19842. delete radarOpt.nameGap;
  19843. if ("development" !== 'production') {
  19844. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  19845. }
  19846. }
  19847. if ("development" !== 'production') {
  19848. each$2(radarOpt.indicator, function (indicatorOpt) {
  19849. if (indicatorOpt.text) {
  19850. deprecateReplaceLog('text', 'name', 'radar.indicator');
  19851. }
  19852. });
  19853. }
  19854. });
  19855. each$2(toArr(option.geo), function (geoOpt) {
  19856. if (isObject$1(geoOpt)) {
  19857. compatEC3CommonStyles(geoOpt);
  19858. each$2(toArr(geoOpt.regions), function (regionObj) {
  19859. compatEC3CommonStyles(regionObj);
  19860. });
  19861. }
  19862. });
  19863. each$2(toArr(option.timeline), function (timelineOpt) {
  19864. compatEC3CommonStyles(timelineOpt);
  19865. convertNormalEmphasis(timelineOpt, 'label');
  19866. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19867. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19868. var data = timelineOpt.data;
  19869. isArray(data) && each(data, function (item) {
  19870. if (isObject(item)) {
  19871. convertNormalEmphasis(item, 'label');
  19872. convertNormalEmphasis(item, 'itemStyle');
  19873. }
  19874. });
  19875. });
  19876. each$2(toArr(option.toolbox), function (toolboxOpt) {
  19877. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19878. each$2(toolboxOpt.feature, function (featureOpt) {
  19879. convertNormalEmphasis(featureOpt, 'iconStyle');
  19880. });
  19881. });
  19882. compatTextStyle(toObj(option.axisPointer), 'label');
  19883. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19884. // Clean logs
  19885. // storedLogs = {};
  19886. }
  19887. function get(opt, path) {
  19888. var pathArr = path.split(',');
  19889. var obj = opt;
  19890. for (var i = 0; i < pathArr.length; i++) {
  19891. obj = obj && obj[pathArr[i]];
  19892. if (obj == null) {
  19893. break;
  19894. }
  19895. }
  19896. return obj;
  19897. }
  19898. function set$1(opt, path, val, overwrite) {
  19899. var pathArr = path.split(',');
  19900. var obj = opt;
  19901. var key;
  19902. var i = 0;
  19903. for (; i < pathArr.length - 1; i++) {
  19904. key = pathArr[i];
  19905. if (obj[key] == null) {
  19906. obj[key] = {};
  19907. }
  19908. obj = obj[key];
  19909. }
  19910. if (overwrite || obj[pathArr[i]] == null) {
  19911. obj[pathArr[i]] = val;
  19912. }
  19913. }
  19914. function compatLayoutProperties(option) {
  19915. option && each(LAYOUT_PROPERTIES, function (prop) {
  19916. if (prop[0] in option && !(prop[1] in option)) {
  19917. option[prop[1]] = option[prop[0]];
  19918. }
  19919. });
  19920. }
  19921. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  19922. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  19923. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  19924. function compatBarItemStyle(option) {
  19925. var itemStyle = option && option.itemStyle;
  19926. if (itemStyle) {
  19927. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  19928. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  19929. var newName = BAR_ITEM_STYLE_MAP[i][0];
  19930. if (itemStyle[oldName] != null) {
  19931. itemStyle[newName] = itemStyle[oldName];
  19932. if ("development" !== 'production') {
  19933. deprecateReplaceLog(oldName, newName);
  19934. }
  19935. }
  19936. }
  19937. }
  19938. }
  19939. function compatPieLabel(option) {
  19940. if (!option) {
  19941. return;
  19942. }
  19943. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  19944. if ("development" !== 'production') {
  19945. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  19946. }
  19947. option.edgeDistance = option.margin;
  19948. }
  19949. }
  19950. function compatSunburstState(option) {
  19951. if (!option) {
  19952. return;
  19953. }
  19954. if (option.downplay && !option.blur) {
  19955. option.blur = option.downplay;
  19956. if ("development" !== 'production') {
  19957. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  19958. }
  19959. }
  19960. }
  19961. function compatGraphFocus(option) {
  19962. if (!option) {
  19963. return;
  19964. }
  19965. if (option.focusNodeAdjacency != null) {
  19966. option.emphasis = option.emphasis || {};
  19967. if (option.emphasis.focus == null) {
  19968. if ("development" !== 'production') {
  19969. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  19970. }
  19971. option.emphasis.focus = 'adjacency';
  19972. }
  19973. }
  19974. }
  19975. function traverseTree(data, cb) {
  19976. if (data) {
  19977. for (var i = 0; i < data.length; i++) {
  19978. cb(data[i]);
  19979. data[i] && traverseTree(data[i].children, cb);
  19980. }
  19981. }
  19982. }
  19983. function globalBackwardCompat(option, isTheme) {
  19984. globalCompatStyle(option, isTheme);
  19985. // Make sure series array for model initialization.
  19986. option.series = normalizeToArray(option.series);
  19987. each(option.series, function (seriesOpt) {
  19988. if (!isObject(seriesOpt)) {
  19989. return;
  19990. }
  19991. var seriesType = seriesOpt.type;
  19992. if (seriesType === 'line') {
  19993. if (seriesOpt.clipOverflow != null) {
  19994. seriesOpt.clip = seriesOpt.clipOverflow;
  19995. if ("development" !== 'production') {
  19996. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  19997. }
  19998. }
  19999. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  20000. if (seriesOpt.clockWise != null) {
  20001. seriesOpt.clockwise = seriesOpt.clockWise;
  20002. if ("development" !== 'production') {
  20003. deprecateReplaceLog('clockWise', 'clockwise');
  20004. }
  20005. }
  20006. compatPieLabel(seriesOpt.label);
  20007. var data = seriesOpt.data;
  20008. if (data && !isTypedArray(data)) {
  20009. for (var i = 0; i < data.length; i++) {
  20010. compatPieLabel(data[i]);
  20011. }
  20012. }
  20013. if (seriesOpt.hoverOffset != null) {
  20014. seriesOpt.emphasis = seriesOpt.emphasis || {};
  20015. if (seriesOpt.emphasis.scaleSize = null) {
  20016. if ("development" !== 'production') {
  20017. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  20018. }
  20019. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  20020. }
  20021. }
  20022. } else if (seriesType === 'gauge') {
  20023. var pointerColor = get(seriesOpt, 'pointer.color');
  20024. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20025. } else if (seriesType === 'bar') {
  20026. compatBarItemStyle(seriesOpt);
  20027. compatBarItemStyle(seriesOpt.backgroundStyle);
  20028. compatBarItemStyle(seriesOpt.emphasis);
  20029. var data = seriesOpt.data;
  20030. if (data && !isTypedArray(data)) {
  20031. for (var i = 0; i < data.length; i++) {
  20032. if (typeof data[i] === 'object') {
  20033. compatBarItemStyle(data[i]);
  20034. compatBarItemStyle(data[i] && data[i].emphasis);
  20035. }
  20036. }
  20037. }
  20038. } else if (seriesType === 'sunburst') {
  20039. var highlightPolicy = seriesOpt.highlightPolicy;
  20040. if (highlightPolicy) {
  20041. seriesOpt.emphasis = seriesOpt.emphasis || {};
  20042. if (!seriesOpt.emphasis.focus) {
  20043. seriesOpt.emphasis.focus = highlightPolicy;
  20044. if ("development" !== 'production') {
  20045. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  20046. }
  20047. }
  20048. }
  20049. compatSunburstState(seriesOpt);
  20050. traverseTree(seriesOpt.data, compatSunburstState);
  20051. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  20052. compatGraphFocus(seriesOpt);
  20053. // TODO nodes, edges?
  20054. } else if (seriesType === 'map') {
  20055. if (seriesOpt.mapType && !seriesOpt.map) {
  20056. if ("development" !== 'production') {
  20057. deprecateReplaceLog('mapType', 'map', 'map');
  20058. }
  20059. seriesOpt.map = seriesOpt.mapType;
  20060. }
  20061. if (seriesOpt.mapLocation) {
  20062. if ("development" !== 'production') {
  20063. deprecateLog('`mapLocation` is not used anymore.');
  20064. }
  20065. defaults(seriesOpt, seriesOpt.mapLocation);
  20066. }
  20067. }
  20068. if (seriesOpt.hoverAnimation != null) {
  20069. seriesOpt.emphasis = seriesOpt.emphasis || {};
  20070. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  20071. if ("development" !== 'production') {
  20072. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  20073. }
  20074. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  20075. }
  20076. }
  20077. compatLayoutProperties(seriesOpt);
  20078. });
  20079. // dataRange has changed to visualMap
  20080. if (option.dataRange) {
  20081. option.visualMap = option.dataRange;
  20082. }
  20083. each(COMPATITABLE_COMPONENTS, function (componentName) {
  20084. var options = option[componentName];
  20085. if (options) {
  20086. if (!isArray(options)) {
  20087. options = [options];
  20088. }
  20089. each(options, function (option) {
  20090. compatLayoutProperties(option);
  20091. });
  20092. }
  20093. });
  20094. }
  20095. // (1) [Caution]: the logic is correct based on the premises:
  20096. // data processing stage is blocked in stream.
  20097. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20098. // (2) Only register once when import repeatedly.
  20099. // Should be executed after series is filtered and before stack calculation.
  20100. function dataStack(ecModel) {
  20101. var stackInfoMap = createHashMap();
  20102. ecModel.eachSeries(function (seriesModel) {
  20103. var stack = seriesModel.get('stack');
  20104. // Compatible: when `stack` is set as '', do not stack.
  20105. if (stack) {
  20106. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20107. var data = seriesModel.getData();
  20108. var stackInfo = {
  20109. // Used for calculate axis extent automatically.
  20110. // TODO: Type getCalculationInfo return more specific type?
  20111. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20112. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20113. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20114. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20115. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20116. data: data,
  20117. seriesModel: seriesModel
  20118. };
  20119. // If stacked on axis that do not support data stack.
  20120. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  20121. return;
  20122. }
  20123. stackInfoList.push(stackInfo);
  20124. }
  20125. });
  20126. // Process each stack group
  20127. stackInfoMap.each(function (stackInfoList) {
  20128. if (stackInfoList.length === 0) {
  20129. return;
  20130. }
  20131. // Check if stack order needs to be reversed
  20132. var firstSeries = stackInfoList[0].seriesModel;
  20133. var stackOrder = firstSeries.get('stackOrder') || 'seriesAsc';
  20134. if (stackOrder === 'seriesDesc') {
  20135. stackInfoList.reverse();
  20136. }
  20137. // Set stackedOnSeries for each series in the final order
  20138. each(stackInfoList, function (stackInfo, index) {
  20139. stackInfo.data.setCalculationInfo('stackedOnSeries', index > 0 ? stackInfoList[index - 1].seriesModel : null);
  20140. });
  20141. // Calculate stack values
  20142. calculateStack(stackInfoList);
  20143. });
  20144. }
  20145. function calculateStack(stackInfoList) {
  20146. each(stackInfoList, function (targetStackInfo, idxInStack) {
  20147. var resultVal = [];
  20148. var resultNaN = [NaN, NaN];
  20149. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20150. var targetData = targetStackInfo.data;
  20151. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20152. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign';
  20153. // Should not write on raw data, because stack series model list changes
  20154. // depending on legend selection.
  20155. targetData.modify(dims, function (v0, v1, dataIndex) {
  20156. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20157. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20158. // should also be NaN, to draw a appropriate belt area.
  20159. if (isNaN(sum)) {
  20160. return resultNaN;
  20161. }
  20162. var byValue;
  20163. var stackedDataRawIndex;
  20164. if (isStackedByIndex) {
  20165. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20166. } else {
  20167. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20168. }
  20169. // If stackOver is NaN, chart view will render point on value start.
  20170. var stackedOver = NaN;
  20171. for (var j = idxInStack - 1; j >= 0; j--) {
  20172. var stackInfo = stackInfoList[j];
  20173. // Has been optimized by inverted indices on `stackedByDimension`.
  20174. if (!isStackedByIndex) {
  20175. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20176. }
  20177. if (stackedDataRawIndex >= 0) {
  20178. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20179. // Considering positive stack, negative stack and empty data
  20180. if (stackStrategy === 'all' // single stack group
  20181. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  20182. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  20183. ) {
  20184. // The sum has to be very small to be affected by the
  20185. // floating arithmetic problem. An incorrect result will probably
  20186. // cause axis min/max to be filtered incorrectly.
  20187. sum = addSafe(sum, val);
  20188. stackedOver = val;
  20189. break;
  20190. }
  20191. }
  20192. }
  20193. resultVal[0] = sum;
  20194. resultVal[1] = stackedOver;
  20195. return resultVal;
  20196. });
  20197. });
  20198. }
  20199. // @inner
  20200. var SourceImpl = /** @class */function () {
  20201. function SourceImpl(fields) {
  20202. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  20203. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  20204. // Visit config
  20205. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  20206. this.startIndex = fields.startIndex || 0;
  20207. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  20208. this.metaRawOption = fields.metaRawOption;
  20209. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  20210. if (dimensionsDefine) {
  20211. for (var i = 0; i < dimensionsDefine.length; i++) {
  20212. var dim = dimensionsDefine[i];
  20213. if (dim.type == null) {
  20214. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  20215. dim.type = 'ordinal';
  20216. }
  20217. }
  20218. }
  20219. }
  20220. }
  20221. return SourceImpl;
  20222. }();
  20223. function isSourceInstance(val) {
  20224. return val instanceof SourceImpl;
  20225. }
  20226. /**
  20227. * Create a source from option.
  20228. * NOTE: Created source is immutable. Don't change any properties in it.
  20229. */
  20230. function createSource(sourceData, thisMetaRawOption,
  20231. // can be null. If not provided, auto detect it from `sourceData`.
  20232. sourceFormat) {
  20233. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  20234. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  20235. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  20236. var source = new SourceImpl({
  20237. data: sourceData,
  20238. sourceFormat: sourceFormat,
  20239. seriesLayoutBy: seriesLayoutBy,
  20240. dimensionsDefine: determined.dimensionsDefine,
  20241. startIndex: determined.startIndex,
  20242. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  20243. metaRawOption: clone(thisMetaRawOption)
  20244. });
  20245. return source;
  20246. }
  20247. /**
  20248. * Wrap original series data for some compatibility cases.
  20249. */
  20250. function createSourceFromSeriesDataOption(data) {
  20251. return new SourceImpl({
  20252. data: data,
  20253. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  20254. });
  20255. }
  20256. /**
  20257. * Clone source but excludes source data.
  20258. */
  20259. function cloneSourceShallow(source) {
  20260. return new SourceImpl({
  20261. data: source.data,
  20262. sourceFormat: source.sourceFormat,
  20263. seriesLayoutBy: source.seriesLayoutBy,
  20264. dimensionsDefine: clone(source.dimensionsDefine),
  20265. startIndex: source.startIndex,
  20266. dimensionsDetectedCount: source.dimensionsDetectedCount
  20267. });
  20268. }
  20269. /**
  20270. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  20271. */
  20272. function detectSourceFormat(data) {
  20273. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  20274. if (isTypedArray(data)) {
  20275. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  20276. } else if (isArray(data)) {
  20277. // FIXME Whether tolerate null in top level array?
  20278. if (data.length === 0) {
  20279. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  20280. }
  20281. for (var i = 0, len = data.length; i < len; i++) {
  20282. var item = data[i];
  20283. if (item == null) {
  20284. continue;
  20285. } else if (isArray(item) || isTypedArray(item)) {
  20286. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  20287. break;
  20288. } else if (isObject(item)) {
  20289. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  20290. break;
  20291. }
  20292. }
  20293. } else if (isObject(data)) {
  20294. for (var key in data) {
  20295. if (hasOwn(data, key) && isArrayLike(data[key])) {
  20296. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  20297. break;
  20298. }
  20299. }
  20300. }
  20301. return sourceFormat;
  20302. }
  20303. /**
  20304. * Determine the source definitions from data standalone dimensions definitions
  20305. * are not specified.
  20306. */
  20307. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader,
  20308. // standalone raw dimensions definition, like:
  20309. // {
  20310. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  20311. // }
  20312. // in `dataset` or `series`
  20313. dimensionsDefine) {
  20314. var dimensionsDetectedCount;
  20315. var startIndex;
  20316. // PENDING: Could data be null/undefined here?
  20317. // currently, if `dataset.source` not specified, error thrown.
  20318. // if `series.data` not specified, nothing rendered without error thrown.
  20319. // Should test these cases.
  20320. if (!data) {
  20321. return {
  20322. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  20323. startIndex: startIndex,
  20324. dimensionsDetectedCount: dimensionsDetectedCount
  20325. };
  20326. }
  20327. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  20328. var dataArrayRows = data;
  20329. // Rule: Most of the first line are string: it is header.
  20330. // Caution: consider a line with 5 string and 1 number,
  20331. // it still can not be sure it is a head, because the
  20332. // 5 string may be 5 values of category columns.
  20333. if (sourceHeader === 'auto' || sourceHeader == null) {
  20334. arrayRowsTravelFirst(function (val) {
  20335. // '-' is regarded as null/undefined.
  20336. if (val != null && val !== '-') {
  20337. if (isString(val)) {
  20338. startIndex == null && (startIndex = 1);
  20339. } else {
  20340. startIndex = 0;
  20341. }
  20342. }
  20343. // 10 is an experience number, avoid long loop.
  20344. }, seriesLayoutBy, dataArrayRows, 10);
  20345. } else {
  20346. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  20347. }
  20348. if (!dimensionsDefine && startIndex === 1) {
  20349. dimensionsDefine = [];
  20350. arrayRowsTravelFirst(function (val, index) {
  20351. dimensionsDefine[index] = val != null ? val + '' : '';
  20352. }, seriesLayoutBy, dataArrayRows, Infinity);
  20353. }
  20354. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  20355. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  20356. if (!dimensionsDefine) {
  20357. dimensionsDefine = objectRowsCollectDimensions(data);
  20358. }
  20359. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  20360. if (!dimensionsDefine) {
  20361. dimensionsDefine = [];
  20362. each(data, function (colArr, key) {
  20363. dimensionsDefine.push(key);
  20364. });
  20365. }
  20366. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  20367. var value0 = getDataItemValue(data[0]);
  20368. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  20369. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20370. if ("development" !== 'production') {
  20371. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  20372. }
  20373. }
  20374. return {
  20375. startIndex: startIndex,
  20376. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  20377. dimensionsDetectedCount: dimensionsDetectedCount
  20378. };
  20379. }
  20380. function objectRowsCollectDimensions(data) {
  20381. var firstIndex = 0;
  20382. var obj;
  20383. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  20384. if (obj) {
  20385. return keys(obj);
  20386. }
  20387. }
  20388. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  20389. // which is reasonable. But dimension name is duplicated.
  20390. // Returns undefined or an array contains only object without null/undefined or string.
  20391. function normalizeDimensionsOption(dimensionsDefine) {
  20392. if (!dimensionsDefine) {
  20393. // The meaning of null/undefined is different from empty array.
  20394. return;
  20395. }
  20396. var nameMap = createHashMap();
  20397. return map(dimensionsDefine, function (rawItem, index) {
  20398. rawItem = isObject(rawItem) ? rawItem : {
  20399. name: rawItem
  20400. };
  20401. // Other fields will be discarded.
  20402. var item = {
  20403. name: rawItem.name,
  20404. displayName: rawItem.displayName,
  20405. type: rawItem.type
  20406. };
  20407. // User can set null in dimensions.
  20408. // We don't auto specify name, otherwise a given name may
  20409. // cause it to be referred unexpectedly.
  20410. if (item.name == null) {
  20411. return item;
  20412. }
  20413. // Also consider number form like 2012.
  20414. item.name += '';
  20415. // User may also specify displayName.
  20416. // displayName will always exists except user not
  20417. // specified or dim name is not specified or detected.
  20418. // (A auto generated dim name will not be used as
  20419. // displayName).
  20420. if (item.displayName == null) {
  20421. item.displayName = item.name;
  20422. }
  20423. var exist = nameMap.get(item.name);
  20424. if (!exist) {
  20425. nameMap.set(item.name, {
  20426. count: 1
  20427. });
  20428. } else {
  20429. item.name += '-' + exist.count++;
  20430. }
  20431. return item;
  20432. });
  20433. }
  20434. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  20435. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  20436. for (var i = 0; i < data.length && i < maxLoop; i++) {
  20437. cb(data[i] ? data[i][0] : null, i);
  20438. }
  20439. } else {
  20440. var value0 = data[0] || [];
  20441. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  20442. cb(value0[i], i);
  20443. }
  20444. }
  20445. }
  20446. function shouldRetrieveDataByName(source) {
  20447. var sourceFormat = source.sourceFormat;
  20448. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  20449. }
  20450. /*
  20451. * Licensed to the Apache Software Foundation (ASF) under one
  20452. * or more contributor license agreements. See the NOTICE file
  20453. * distributed with this work for additional information
  20454. * regarding copyright ownership. The ASF licenses this file
  20455. * to you under the Apache License, Version 2.0 (the
  20456. * "License"); you may not use this file except in compliance
  20457. * with the License. You may obtain a copy of the License at
  20458. *
  20459. * http://www.apache.org/licenses/LICENSE-2.0
  20460. *
  20461. * Unless required by applicable law or agreed to in writing,
  20462. * software distributed under the License is distributed on an
  20463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20464. * KIND, either express or implied. See the License for the
  20465. * specific language governing permissions and limitations
  20466. * under the License.
  20467. */
  20468. /**
  20469. * AUTO-GENERATED FILE. DO NOT MODIFY.
  20470. */
  20471. /*
  20472. * Licensed to the Apache Software Foundation (ASF) under one
  20473. * or more contributor license agreements. See the NOTICE file
  20474. * distributed with this work for additional information
  20475. * regarding copyright ownership. The ASF licenses this file
  20476. * to you under the Apache License, Version 2.0 (the
  20477. * "License"); you may not use this file except in compliance
  20478. * with the License. You may obtain a copy of the License at
  20479. *
  20480. * http://www.apache.org/licenses/LICENSE-2.0
  20481. *
  20482. * Unless required by applicable law or agreed to in writing,
  20483. * software distributed under the License is distributed on an
  20484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20485. * KIND, either express or implied. See the License for the
  20486. * specific language governing permissions and limitations
  20487. * under the License.
  20488. */
  20489. var _a, _b, _c, _d;
  20490. var providerMethods;
  20491. var mountMethods;
  20492. /**
  20493. * If normal array used, mutable chunk size is supported.
  20494. * If typed array used, chunk size must be fixed.
  20495. */
  20496. var DefaultDataProvider = /** @class */function () {
  20497. function DefaultDataProvider(sourceParam, dimSize) {
  20498. // let source: Source;
  20499. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam;
  20500. // declare source is Source;
  20501. this._source = source;
  20502. var data = this._data = source.data;
  20503. var sourceFormat = source.sourceFormat;
  20504. var seriesLayoutBy = source.seriesLayoutBy;
  20505. // Typed array. TODO IE10+?
  20506. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20507. if ("development" !== 'production') {
  20508. if (dimSize == null) {
  20509. throw new Error('Typed array data must specify dimension size');
  20510. }
  20511. }
  20512. this._offset = 0;
  20513. this._dimSize = dimSize;
  20514. this._data = data;
  20515. }
  20516. if ("development" !== 'production') {
  20517. var validator = rawSourceDataValidatorMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  20518. validator && validator(data, source.dimensionsDefine);
  20519. }
  20520. mountMethods(this, data, source);
  20521. }
  20522. DefaultDataProvider.prototype.getSource = function () {
  20523. return this._source;
  20524. };
  20525. DefaultDataProvider.prototype.count = function () {
  20526. return 0;
  20527. };
  20528. DefaultDataProvider.prototype.getItem = function (idx, out) {
  20529. return;
  20530. };
  20531. DefaultDataProvider.prototype.appendData = function (newData) {};
  20532. DefaultDataProvider.prototype.clean = function () {};
  20533. DefaultDataProvider.protoInitialize = function () {
  20534. // PENDING: To avoid potential incompat (e.g., prototype
  20535. // is visited somewhere), still init them on prototype.
  20536. var proto = DefaultDataProvider.prototype;
  20537. proto.pure = false;
  20538. proto.persistent = true;
  20539. }();
  20540. DefaultDataProvider.internalField = function () {
  20541. var _a;
  20542. mountMethods = function (provider, data, source) {
  20543. var sourceFormat = source.sourceFormat;
  20544. var seriesLayoutBy = source.seriesLayoutBy;
  20545. var startIndex = source.startIndex;
  20546. var dimsDef = source.dimensionsDefine;
  20547. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  20548. if ("development" !== 'production') {
  20549. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20550. }
  20551. extend(provider, methods);
  20552. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20553. provider.getItem = getItemForTypedArray;
  20554. provider.count = countForTypedArray;
  20555. provider.fillStorage = fillStorageForTypedArray;
  20556. } else {
  20557. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  20558. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  20559. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  20560. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  20561. }
  20562. };
  20563. var getItemForTypedArray = function (idx, out) {
  20564. idx = idx - this._offset;
  20565. out = out || [];
  20566. var data = this._data;
  20567. var dimSize = this._dimSize;
  20568. var offset = dimSize * idx;
  20569. for (var i = 0; i < dimSize; i++) {
  20570. out[i] = data[offset + i];
  20571. }
  20572. return out;
  20573. };
  20574. var fillStorageForTypedArray = function (start, end, storage, extent) {
  20575. var data = this._data;
  20576. var dimSize = this._dimSize;
  20577. for (var dim = 0; dim < dimSize; dim++) {
  20578. var dimExtent = extent[dim];
  20579. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  20580. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  20581. var count = end - start;
  20582. var arr = storage[dim];
  20583. for (var i = 0; i < count; i++) {
  20584. // appendData with TypedArray will always do replace in provider.
  20585. var val = data[i * dimSize + dim];
  20586. arr[start + i] = val;
  20587. val < min && (min = val);
  20588. val > max && (max = val);
  20589. }
  20590. dimExtent[0] = min;
  20591. dimExtent[1] = max;
  20592. }
  20593. };
  20594. var countForTypedArray = function () {
  20595. return this._data ? this._data.length / this._dimSize : 0;
  20596. };
  20597. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  20598. pure: true,
  20599. appendData: appendDataSimply
  20600. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  20601. pure: true,
  20602. appendData: function () {
  20603. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20604. }
  20605. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  20606. pure: true,
  20607. appendData: appendDataSimply
  20608. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  20609. pure: true,
  20610. appendData: function (newData) {
  20611. var data = this._data;
  20612. each(newData, function (newCol, key) {
  20613. var oldCol = data[key] || (data[key] = []);
  20614. for (var i = 0; i < (newCol || []).length; i++) {
  20615. oldCol.push(newCol[i]);
  20616. }
  20617. });
  20618. }
  20619. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  20620. appendData: appendDataSimply
  20621. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  20622. persistent: false,
  20623. pure: true,
  20624. appendData: function (newData) {
  20625. if ("development" !== 'production') {
  20626. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  20627. }
  20628. this._data = newData;
  20629. },
  20630. // Clean self if data is already used.
  20631. clean: function () {
  20632. // PENDING
  20633. this._offset += this.count();
  20634. this._data = null;
  20635. }
  20636. }, _a);
  20637. function appendDataSimply(newData) {
  20638. for (var i = 0; i < newData.length; i++) {
  20639. this._data.push(newData[i]);
  20640. }
  20641. }
  20642. }();
  20643. return DefaultDataProvider;
  20644. }();
  20645. var validateSimply = function (rawData) {
  20646. if (!isArray(rawData)) {
  20647. error('series.data or dataset.source must be an array.');
  20648. }
  20649. };
  20650. /**
  20651. * Only run in dev mode - hint users for debug.
  20652. */
  20653. var rawSourceDataValidatorMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = validateSimply, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = validateSimply, _a[SOURCE_FORMAT_OBJECT_ROWS] = validateSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, dimsDef) {
  20654. for (var i = 0; i < dimsDef.length; i++) {
  20655. var dimName = dimsDef[i].name;
  20656. if (dimName == null) {
  20657. error('dimension name must not be null/undefined.');
  20658. }
  20659. }
  20660. }, _a[SOURCE_FORMAT_ORIGINAL] = validateSimply, _a);
  20661. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  20662. return rawData[idx];
  20663. };
  20664. var rawSourceItemGetterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  20665. return rawData[idx + startIndex];
  20666. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  20667. idx += startIndex;
  20668. var item = out || [];
  20669. var data = rawData;
  20670. for (var i = 0; i < data.length; i++) {
  20671. var row = data[i];
  20672. item[i] = row ? row[idx] : null;
  20673. }
  20674. return item;
  20675. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  20676. var item = out || [];
  20677. for (var i = 0; i < dimsDef.length; i++) {
  20678. var dimName = dimsDef[i].name;
  20679. var col = dimName != null ? rawData[dimName] : null;
  20680. item[i] = col ? col[idx] : null;
  20681. }
  20682. return item;
  20683. }, _b[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _b);
  20684. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  20685. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  20686. if ("development" !== 'production') {
  20687. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  20688. }
  20689. return method;
  20690. }
  20691. var countSimply = function (rawData, startIndex, dimsDef) {
  20692. return rawData.length;
  20693. };
  20694. var rawSourceDataCounterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  20695. return Math.max(0, rawData.length - startIndex);
  20696. }, _c[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  20697. var row = rawData[0];
  20698. return row ? Math.max(0, row.length - startIndex) : 0;
  20699. }, _c[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _c[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  20700. var dimName = dimsDef[0].name;
  20701. var col = dimName != null ? rawData[dimName] : null;
  20702. return col ? col.length : 0;
  20703. }, _c[SOURCE_FORMAT_ORIGINAL] = countSimply, _c);
  20704. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  20705. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  20706. if ("development" !== 'production') {
  20707. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  20708. }
  20709. return method;
  20710. }
  20711. var getRawValueSimply = function (dataItem, dimIndex, property) {
  20712. return dataItem[dimIndex];
  20713. };
  20714. var rawSourceValueGetterMap = (_d = {}, _d[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _d[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  20715. return dataItem[property];
  20716. }, _d[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _d[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  20717. // FIXME: In some case (markpoint in geo (geo-map.html)),
  20718. // dataItem is {coord: [...]}
  20719. var value = getDataItemValue(dataItem);
  20720. return !(value instanceof Array) ? value : value[dimIndex];
  20721. }, _d[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _d);
  20722. function getRawSourceValueGetter(sourceFormat) {
  20723. var method = rawSourceValueGetterMap[sourceFormat];
  20724. if ("development" !== 'production') {
  20725. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  20726. }
  20727. return method;
  20728. }
  20729. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  20730. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  20731. }
  20732. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20733. // Consider persistent.
  20734. // Caution: why use raw value to display on label or tooltip?
  20735. // A reason is to avoid format. For example time value we do not know
  20736. // how to format is expected. More over, if stack is used, calculated
  20737. // value may be 0.91000000001, which have brings trouble to display.
  20738. // TODO: consider how to treat null/undefined/NaN when display?
  20739. function retrieveRawValue(data, dataIndex,
  20740. // If dimIndex is null/undefined, return OptionDataItem.
  20741. // Otherwise, return OptionDataValue.
  20742. dim) {
  20743. if (!data) {
  20744. return;
  20745. }
  20746. // Consider data may be not persistent.
  20747. var dataItem = data.getRawDataItem(dataIndex);
  20748. if (dataItem == null) {
  20749. return;
  20750. }
  20751. var store = data.getStore();
  20752. var sourceFormat = store.getSource().sourceFormat;
  20753. if (dim != null) {
  20754. var dimIndex = data.getDimensionIndex(dim);
  20755. var property = store.getDimensionProperty(dimIndex);
  20756. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  20757. } else {
  20758. var result = dataItem;
  20759. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  20760. result = getDataItemValue(dataItem);
  20761. }
  20762. return result;
  20763. }
  20764. }
  20765. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20766. var DataFormatMixin = /** @class */function () {
  20767. function DataFormatMixin() {}
  20768. /**
  20769. * Get params for formatter
  20770. */
  20771. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  20772. var data = this.getData(dataType);
  20773. var rawValue = this.getRawValue(dataIndex, dataType);
  20774. var rawDataIndex = data.getRawIndex(dataIndex);
  20775. var name = data.getName(dataIndex);
  20776. var itemOpt = data.getRawDataItem(dataIndex);
  20777. var style = data.getItemVisual(dataIndex, 'style');
  20778. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  20779. var borderColor = style && style.stroke;
  20780. var mainType = this.mainType;
  20781. var isSeries = mainType === 'series';
  20782. var userOutput = data.userOutput && data.userOutput.get();
  20783. return {
  20784. componentType: mainType,
  20785. componentSubType: this.subType,
  20786. componentIndex: this.componentIndex,
  20787. seriesType: isSeries ? this.subType : null,
  20788. seriesIndex: this.seriesIndex,
  20789. seriesId: isSeries ? this.id : null,
  20790. seriesName: isSeries ? this.name : null,
  20791. name: name,
  20792. dataIndex: rawDataIndex,
  20793. data: itemOpt,
  20794. dataType: dataType,
  20795. value: rawValue,
  20796. color: color,
  20797. borderColor: borderColor,
  20798. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  20799. encode: userOutput ? userOutput.encode : null,
  20800. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20801. $vars: ['seriesName', 'name', 'value']
  20802. };
  20803. };
  20804. /**
  20805. * Format label
  20806. * @param dataIndex
  20807. * @param status 'normal' by default
  20808. * @param dataType
  20809. * @param labelDimIndex Only used in some chart that
  20810. * use formatter in different dimensions, like radar.
  20811. * @param formatter Formatter given outside.
  20812. * @return return null/undefined if no formatter
  20813. */
  20814. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  20815. status = status || 'normal';
  20816. var data = this.getData(dataType);
  20817. var params = this.getDataParams(dataIndex, dataType);
  20818. if (extendParams) {
  20819. params.value = extendParams.interpolatedValue;
  20820. }
  20821. if (labelDimIndex != null && isArray(params.value)) {
  20822. params.value = params.value[labelDimIndex];
  20823. }
  20824. if (!formatter) {
  20825. var itemModel = data.getItemModel(dataIndex);
  20826. // @ts-ignore
  20827. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  20828. }
  20829. if (isFunction(formatter)) {
  20830. params.status = status;
  20831. params.dimensionIndex = labelDimIndex;
  20832. return formatter(params);
  20833. } else if (isString(formatter)) {
  20834. var str = formatTpl(formatter, params);
  20835. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20836. // Do not support '}' in dim name util have to.
  20837. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  20838. var len = dimStr.length;
  20839. var dimLoose = dimStr;
  20840. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  20841. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  20842. if ("development" !== 'production') {
  20843. if (isNaN(dimLoose)) {
  20844. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  20845. }
  20846. }
  20847. }
  20848. var val = retrieveRawValue(data, dataIndex, dimLoose);
  20849. if (extendParams && isArray(extendParams.interpolatedValue)) {
  20850. var dimIndex = data.getDimensionIndex(dimLoose);
  20851. if (dimIndex >= 0) {
  20852. val = extendParams.interpolatedValue[dimIndex];
  20853. }
  20854. }
  20855. return val != null ? val + '' : '';
  20856. });
  20857. }
  20858. };
  20859. /**
  20860. * Get raw value in option
  20861. */
  20862. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  20863. return retrieveRawValue(this.getData(dataType), idx);
  20864. };
  20865. /**
  20866. * Should be implemented.
  20867. * @param {number} dataIndex
  20868. * @param {boolean} [multipleSeries=false]
  20869. * @param {string} [dataType]
  20870. */
  20871. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  20872. // Empty function
  20873. return;
  20874. };
  20875. return DataFormatMixin;
  20876. }();
  20877. // PENDING: previously we accept this type when calling `formatTooltip`,
  20878. // but guess little chance has been used outside. Do we need to backward
  20879. // compat it?
  20880. // type TooltipFormatResultLegacyObject = {
  20881. // // `html` means the markup language text, either in 'html' or 'richText'.
  20882. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  20883. // // string. But still support it for backward compatibility.
  20884. // html: string;
  20885. // markers: Dictionary<ColorString>;
  20886. // };
  20887. /**
  20888. * For backward compat, normalize the return from `formatTooltip`.
  20889. */
  20890. function normalizeTooltipFormatResult(result) {
  20891. var markupText;
  20892. // let markers: Dictionary<ColorString>;
  20893. var markupFragment;
  20894. if (isObject(result)) {
  20895. if (result.type) {
  20896. markupFragment = result;
  20897. } else {
  20898. if ("development" !== 'production') {
  20899. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  20900. }
  20901. }
  20902. // else {
  20903. // markupText = (result as TooltipFormatResultLegacyObject).html;
  20904. // markers = (result as TooltipFormatResultLegacyObject).markers;
  20905. // if (markersExisting) {
  20906. // markers = zrUtil.merge(markersExisting, markers);
  20907. // }
  20908. // }
  20909. } else {
  20910. markupText = result;
  20911. }
  20912. return {
  20913. text: markupText,
  20914. // markers: markers || markersExisting,
  20915. frag: markupFragment
  20916. };
  20917. }
  20918. /**
  20919. * @param {Object} define
  20920. * @return See the return of `createTask`.
  20921. */
  20922. function createTask(define) {
  20923. return new Task(define);
  20924. }
  20925. var Task = /** @class */function () {
  20926. function Task(define) {
  20927. define = define || {};
  20928. this._reset = define.reset;
  20929. this._plan = define.plan;
  20930. this._count = define.count;
  20931. this._onDirty = define.onDirty;
  20932. this._dirty = true;
  20933. }
  20934. /**
  20935. * @param step Specified step.
  20936. * @param skip Skip customer perform call.
  20937. * @param modBy Sampling window size.
  20938. * @param modDataCount Sampling count.
  20939. * @return whether unfinished.
  20940. */
  20941. Task.prototype.perform = function (performArgs) {
  20942. var upTask = this._upstream;
  20943. var skip = performArgs && performArgs.skip;
  20944. // TODO some refactor.
  20945. // Pull data. Must pull data each time, because context.data
  20946. // may be updated by Series.setData.
  20947. if (this._dirty && upTask) {
  20948. var context = this.context;
  20949. context.data = context.outputData = upTask.context.outputData;
  20950. }
  20951. if (this.__pipeline) {
  20952. this.__pipeline.currentTask = this;
  20953. }
  20954. var planResult;
  20955. if (this._plan && !skip) {
  20956. planResult = this._plan(this.context);
  20957. }
  20958. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20959. // elements uniformed distributed when progress, especially when moving or zooming.
  20960. var lastModBy = normalizeModBy(this._modBy);
  20961. var lastModDataCount = this._modDataCount || 0;
  20962. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20963. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20964. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20965. planResult = 'reset';
  20966. }
  20967. function normalizeModBy(val) {
  20968. !(val >= 1) && (val = 1); // jshint ignore:line
  20969. return val;
  20970. }
  20971. var forceFirstProgress;
  20972. if (this._dirty || planResult === 'reset') {
  20973. this._dirty = false;
  20974. forceFirstProgress = this._doReset(skip);
  20975. }
  20976. this._modBy = modBy;
  20977. this._modDataCount = modDataCount;
  20978. var step = performArgs && performArgs.step;
  20979. if (upTask) {
  20980. if ("development" !== 'production') {
  20981. assert(upTask._outputDueEnd != null);
  20982. }
  20983. this._dueEnd = upTask._outputDueEnd;
  20984. }
  20985. // DataTask or overallTask
  20986. else {
  20987. if ("development" !== 'production') {
  20988. assert(!this._progress || this._count);
  20989. }
  20990. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20991. }
  20992. // Note: Stubs, that its host overall task let it has progress, has progress.
  20993. // If no progress, pass index from upstream to downstream each time plan called.
  20994. if (this._progress) {
  20995. var start = this._dueIndex;
  20996. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  20997. if (!skip && (forceFirstProgress || start < end)) {
  20998. var progress = this._progress;
  20999. if (isArray(progress)) {
  21000. for (var i = 0; i < progress.length; i++) {
  21001. this._doProgress(progress[i], start, end, modBy, modDataCount);
  21002. }
  21003. } else {
  21004. this._doProgress(progress, start, end, modBy, modDataCount);
  21005. }
  21006. }
  21007. this._dueIndex = end;
  21008. // If no `outputDueEnd`, assume that output data and
  21009. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21010. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  21011. if ("development" !== 'production') {
  21012. // ??? Can not rollback.
  21013. assert(outputDueEnd >= this._outputDueEnd);
  21014. }
  21015. this._outputDueEnd = outputDueEnd;
  21016. } else {
  21017. // (1) Some overall task has no progress.
  21018. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21019. // This should always be performed so it can be passed to downstream.
  21020. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  21021. }
  21022. return this.unfinished();
  21023. };
  21024. Task.prototype.dirty = function () {
  21025. this._dirty = true;
  21026. this._onDirty && this._onDirty(this.context);
  21027. };
  21028. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  21029. iterator.reset(start, end, modBy, modDataCount);
  21030. this._callingProgress = progress;
  21031. this._callingProgress({
  21032. start: start,
  21033. end: end,
  21034. count: end - start,
  21035. next: iterator.next
  21036. }, this.context);
  21037. };
  21038. Task.prototype._doReset = function (skip) {
  21039. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  21040. this._settedOutputEnd = null;
  21041. var progress;
  21042. var forceFirstProgress;
  21043. if (!skip && this._reset) {
  21044. progress = this._reset(this.context);
  21045. if (progress && progress.progress) {
  21046. forceFirstProgress = progress.forceFirstProgress;
  21047. progress = progress.progress;
  21048. }
  21049. // To simplify no progress checking, array must has item.
  21050. if (isArray(progress) && !progress.length) {
  21051. progress = null;
  21052. }
  21053. }
  21054. this._progress = progress;
  21055. this._modBy = this._modDataCount = null;
  21056. var downstream = this._downstream;
  21057. downstream && downstream.dirty();
  21058. return forceFirstProgress;
  21059. };
  21060. Task.prototype.unfinished = function () {
  21061. return this._progress && this._dueIndex < this._dueEnd;
  21062. };
  21063. /**
  21064. * @param downTask The downstream task.
  21065. * @return The downstream task.
  21066. */
  21067. Task.prototype.pipe = function (downTask) {
  21068. if ("development" !== 'production') {
  21069. assert(downTask && !downTask._disposed && downTask !== this);
  21070. }
  21071. // If already downstream, do not dirty downTask.
  21072. if (this._downstream !== downTask || this._dirty) {
  21073. this._downstream = downTask;
  21074. downTask._upstream = this;
  21075. downTask.dirty();
  21076. }
  21077. };
  21078. Task.prototype.dispose = function () {
  21079. if (this._disposed) {
  21080. return;
  21081. }
  21082. this._upstream && (this._upstream._downstream = null);
  21083. this._downstream && (this._downstream._upstream = null);
  21084. this._dirty = false;
  21085. this._disposed = true;
  21086. };
  21087. Task.prototype.getUpstream = function () {
  21088. return this._upstream;
  21089. };
  21090. Task.prototype.getDownstream = function () {
  21091. return this._downstream;
  21092. };
  21093. Task.prototype.setOutputEnd = function (end) {
  21094. // This only happens in dataTask, dataZoom, map, currently.
  21095. // where dataZoom do not set end each time, but only set
  21096. // when reset. So we should record the set end, in case
  21097. // that the stub of dataZoom perform again and earse the
  21098. // set end by upstream.
  21099. this._outputDueEnd = this._settedOutputEnd = end;
  21100. };
  21101. return Task;
  21102. }();
  21103. var iterator = function () {
  21104. var end;
  21105. var current;
  21106. var modBy;
  21107. var modDataCount;
  21108. var winCount;
  21109. var it = {
  21110. reset: function (s, e, sStep, sCount) {
  21111. current = s;
  21112. end = e;
  21113. modBy = sStep;
  21114. modDataCount = sCount;
  21115. winCount = Math.ceil(modDataCount / modBy);
  21116. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  21117. }
  21118. };
  21119. return it;
  21120. function sequentialNext() {
  21121. return current < end ? current++ : null;
  21122. }
  21123. function modNext() {
  21124. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  21125. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex
  21126. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21127. // Use normal linear rendering mode.
  21128. : current;
  21129. current++;
  21130. return result;
  21131. }
  21132. }();
  21133. // -----------------------------------------------------------------------------
  21134. // For stream debug (Should be commented out after used!)
  21135. // @usage: printTask(this, 'begin');
  21136. // @usage: printTask(this, null, {someExtraProp});
  21137. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  21138. //
  21139. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  21140. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21141. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21142. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21143. // let props = [];
  21144. // if (task.__pipeline) {
  21145. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21146. // props.push({text: '__idxInPipeline/total', value: val});
  21147. // } else {
  21148. // let stubCount = 0;
  21149. // task.agentStubMap.each(() => stubCount++);
  21150. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21151. // }
  21152. // props.push({text: 'uid', value: task.uidDebug});
  21153. // if (task.__pipeline) {
  21154. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  21155. // task.agent && props.push(
  21156. // {text: 'stubFor', value: task.agent.uidDebug}
  21157. // );
  21158. // }
  21159. // props.push(
  21160. // {text: 'dirty', value: task._dirty},
  21161. // {text: 'dueIndex', value: task._dueIndex},
  21162. // {text: 'dueEnd', value: task._dueEnd},
  21163. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21164. // );
  21165. // if (extra) {
  21166. // Object.keys(extra).forEach(key => {
  21167. // props.push({text: key, value: extra[key]});
  21168. // });
  21169. // }
  21170. // let args = ['color: blue'];
  21171. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21172. // args.push('color: green', 'color: red'),
  21173. // `${item.text}: %c${item.value}`
  21174. // )).join('%c, ');
  21175. // console.log.apply(console, [msg].concat(args));
  21176. // // console.log(this);
  21177. // };
  21178. // window.printPipeline = function (task: any, prefix: string) {
  21179. // const pipeline = task.__pipeline;
  21180. // let currTask = pipeline.head;
  21181. // while (currTask) {
  21182. // window.printTask(currTask, prefix);
  21183. // currTask = currTask._downstream;
  21184. // }
  21185. // };
  21186. // window.showChain = function (chainHeadTask) {
  21187. // var chain = [];
  21188. // var task = chainHeadTask;
  21189. // while (task) {
  21190. // chain.push({
  21191. // task: task,
  21192. // up: task._upstream,
  21193. // down: task._downstream,
  21194. // idxInPipeline: task.__idxInPipeline
  21195. // });
  21196. // task = task._downstream;
  21197. // }
  21198. // return chain;
  21199. // };
  21200. // window.findTaskInChain = function (task, chainHeadTask) {
  21201. // let chain = window.showChain(chainHeadTask);
  21202. // let result = [];
  21203. // for (let i = 0; i < chain.length; i++) {
  21204. // let chainItem = chain[i];
  21205. // if (chainItem.task === task) {
  21206. // result.push(i);
  21207. // }
  21208. // }
  21209. // return result;
  21210. // };
  21211. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  21212. // let chainA = window.showChain(chainHeadTaskA);
  21213. // for (let i = 0; i < chainA.length; i++) {
  21214. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  21215. // }
  21216. // };
  21217. /**
  21218. * Convert raw the value in to inner value in List.
  21219. *
  21220. * [Performance sensitive]
  21221. *
  21222. * [Caution]: this is the key logic of user value parser.
  21223. * For backward compatibility, do not modify it until you have to!
  21224. */
  21225. function parseDataValue(value,
  21226. // For high performance, do not omit the second param.
  21227. opt) {
  21228. // Performance sensitive.
  21229. var dimType = opt && opt.type;
  21230. if (dimType === 'ordinal') {
  21231. // If given value is a category string
  21232. return value;
  21233. }
  21234. if (dimType === 'time'
  21235. // spead up when using timestamp
  21236. && !isNumber(value) && value != null && value !== '-') {
  21237. value = +parseDate(value);
  21238. }
  21239. // dimType defaults 'number'.
  21240. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  21241. // parse to NaN.
  21242. // number-like string (like ' 123 ') can be converted to a number.
  21243. // where null/undefined or other string will be converted to NaN.
  21244. return value == null || value === '' ? NaN
  21245. // If string (like '-'), using '+' parse to NaN
  21246. // If object, also parse to NaN
  21247. : Number(value);
  21248. }
  21249. var valueParserMap = createHashMap({
  21250. 'number': function (val) {
  21251. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  21252. // Here the number parser can have loose rule:
  21253. // enable to cut suffix: "120px" => 120, "14%" => 14.
  21254. return parseFloat(val);
  21255. },
  21256. 'time': function (val) {
  21257. // return timestamp.
  21258. return +parseDate(val);
  21259. },
  21260. 'trim': function (val) {
  21261. return isString(val) ? trim(val) : val;
  21262. }
  21263. });
  21264. var SortOrderComparator = /** @class */function () {
  21265. /**
  21266. * @param order by default: 'asc'
  21267. * @param incomparable by default: Always on the tail.
  21268. * That is, if 'asc' => 'max', if 'desc' => 'min'
  21269. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  21270. */
  21271. function SortOrderComparator(order, incomparable) {
  21272. var isDesc = order === 'desc';
  21273. this._resultLT = isDesc ? 1 : -1;
  21274. if (incomparable == null) {
  21275. incomparable = isDesc ? 'min' : 'max';
  21276. }
  21277. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  21278. }
  21279. // See [SORT_COMPARISON_RULE].
  21280. // Performance sensitive.
  21281. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  21282. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  21283. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  21284. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  21285. var lvalNotNumeric = isNaN(lvalFloat);
  21286. var rvalNotNumeric = isNaN(rvalFloat);
  21287. if (lvalNotNumeric) {
  21288. lvalFloat = this._incomparable;
  21289. }
  21290. if (rvalNotNumeric) {
  21291. rvalFloat = this._incomparable;
  21292. }
  21293. if (lvalNotNumeric && rvalNotNumeric) {
  21294. var lvalIsStr = isString(lval);
  21295. var rvalIsStr = isString(rval);
  21296. if (lvalIsStr) {
  21297. lvalFloat = rvalIsStr ? lval : 0;
  21298. }
  21299. if (rvalIsStr) {
  21300. rvalFloat = lvalIsStr ? rval : 0;
  21301. }
  21302. }
  21303. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  21304. };
  21305. return SortOrderComparator;
  21306. }();
  21307. /**
  21308. * TODO: disable writable.
  21309. * This structure will be exposed to users.
  21310. */
  21311. var ExternalSource = /** @class */function () {
  21312. function ExternalSource() {}
  21313. ExternalSource.prototype.getRawData = function () {
  21314. // Only built-in transform available.
  21315. throw new Error('not supported');
  21316. };
  21317. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  21318. // Only built-in transform available.
  21319. throw new Error('not supported');
  21320. };
  21321. ExternalSource.prototype.cloneRawData = function () {
  21322. return;
  21323. };
  21324. /**
  21325. * @return If dimension not found, return null/undefined.
  21326. */
  21327. ExternalSource.prototype.getDimensionInfo = function (dim) {
  21328. return;
  21329. };
  21330. /**
  21331. * dimensions defined if and only if either:
  21332. * (a) dataset.dimensions are declared.
  21333. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  21334. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  21335. * the defined dimensions.
  21336. * Otherwise, `dimensionInfoAll` is determined by data columns.
  21337. * @return Always return an array (even empty array).
  21338. */
  21339. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  21340. return;
  21341. };
  21342. ExternalSource.prototype.count = function () {
  21343. return;
  21344. };
  21345. /**
  21346. * Only support by dimension index.
  21347. * No need to support by dimension name in transform function,
  21348. * because transform function is not case-specific, no need to use name literally.
  21349. */
  21350. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  21351. return;
  21352. };
  21353. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  21354. return;
  21355. };
  21356. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  21357. return parseDataValue(rawVal, dimInfo);
  21358. };
  21359. return ExternalSource;
  21360. }();
  21361. function createExternalSource(internalSource, externalTransform) {
  21362. var extSource = new ExternalSource();
  21363. var data = internalSource.data;
  21364. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  21365. var sourceHeaderCount = internalSource.startIndex;
  21366. var errMsg = '';
  21367. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  21368. // For the logic simplicity in transformer, only 'culumn' is
  21369. // supported in data transform. Otherwise, the `dimensionsDefine`
  21370. // might be detected by 'row', which probably confuses users.
  21371. if ("development" !== 'production') {
  21372. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  21373. }
  21374. throwError(errMsg);
  21375. }
  21376. // [MEMO]
  21377. // Create a new dimensions structure for exposing.
  21378. // Do not expose all dimension info to users directly.
  21379. // Because the dimension is probably auto detected from data and not might reliable.
  21380. // Should not lead the transformers to think that is reliable and return it.
  21381. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  21382. var dimensions = [];
  21383. var dimsByName = {};
  21384. var dimsDef = internalSource.dimensionsDefine;
  21385. if (dimsDef) {
  21386. each(dimsDef, function (dimDef, idx) {
  21387. var name = dimDef.name;
  21388. var dimDefExt = {
  21389. index: idx,
  21390. name: name,
  21391. displayName: dimDef.displayName
  21392. };
  21393. dimensions.push(dimDefExt);
  21394. // Users probably do not specify dimension name. For simplicity, data transform
  21395. // does not generate dimension name.
  21396. if (name != null) {
  21397. // Dimension name should not be duplicated.
  21398. // For simplicity, data transform forbids name duplication, do not generate
  21399. // new name like module `completeDimensions.ts` did, but just tell users.
  21400. var errMsg_1 = '';
  21401. if (hasOwn(dimsByName, name)) {
  21402. if ("development" !== 'production') {
  21403. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  21404. }
  21405. throwError(errMsg_1);
  21406. }
  21407. dimsByName[name] = dimDefExt;
  21408. }
  21409. });
  21410. }
  21411. // If dimension definitions are not defined and can not be detected.
  21412. // e.g., pure data `[[11, 22], ...]`.
  21413. else {
  21414. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  21415. // Do not generete name or anything others. The consequence process in
  21416. // `transform` or `series` probably have there own name generation strategry.
  21417. dimensions.push({
  21418. index: i
  21419. });
  21420. }
  21421. }
  21422. // Implement public methods:
  21423. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  21424. if (externalTransform.__isBuiltIn) {
  21425. extSource.getRawDataItem = function (dataIndex) {
  21426. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  21427. };
  21428. extSource.getRawData = bind(getRawData, null, internalSource);
  21429. }
  21430. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  21431. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  21432. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  21433. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  21434. extSource.retrieveValue = function (dataIndex, dimIndex) {
  21435. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  21436. return retrieveValueFromItem(rawItem, dimIndex);
  21437. };
  21438. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  21439. if (dataItem == null) {
  21440. return;
  21441. }
  21442. var dimDef = dimensions[dimIndex];
  21443. // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  21444. if (dimDef) {
  21445. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  21446. }
  21447. };
  21448. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  21449. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  21450. return extSource;
  21451. }
  21452. function getRawData(upstream) {
  21453. var sourceFormat = upstream.sourceFormat;
  21454. if (!isSupportedSourceFormat(sourceFormat)) {
  21455. var errMsg = '';
  21456. if ("development" !== 'production') {
  21457. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  21458. }
  21459. throwError(errMsg);
  21460. }
  21461. return upstream.data;
  21462. }
  21463. function cloneRawData(upstream) {
  21464. var sourceFormat = upstream.sourceFormat;
  21465. var data = upstream.data;
  21466. if (!isSupportedSourceFormat(sourceFormat)) {
  21467. var errMsg = '';
  21468. if ("development" !== 'production') {
  21469. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  21470. }
  21471. throwError(errMsg);
  21472. }
  21473. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  21474. var result = [];
  21475. for (var i = 0, len = data.length; i < len; i++) {
  21476. // Not strictly clone for performance
  21477. result.push(data[i].slice());
  21478. }
  21479. return result;
  21480. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  21481. var result = [];
  21482. for (var i = 0, len = data.length; i < len; i++) {
  21483. // Not strictly clone for performance
  21484. result.push(extend({}, data[i]));
  21485. }
  21486. return result;
  21487. }
  21488. }
  21489. function getDimensionInfo(dimensions, dimsByName, dim) {
  21490. if (dim == null) {
  21491. return;
  21492. }
  21493. // Keep the same logic as `List::getDimension` did.
  21494. if (isNumber(dim)
  21495. // If being a number-like string but not being defined a dimension name.
  21496. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  21497. return dimensions[dim];
  21498. } else if (hasOwn(dimsByName, dim)) {
  21499. return dimsByName[dim];
  21500. }
  21501. }
  21502. function cloneAllDimensionInfo(dimensions) {
  21503. return clone(dimensions);
  21504. }
  21505. var externalTransformMap = createHashMap();
  21506. function registerExternalTransform(externalTransform) {
  21507. externalTransform = clone(externalTransform);
  21508. var type = externalTransform.type;
  21509. var errMsg = '';
  21510. if (!type) {
  21511. if ("development" !== 'production') {
  21512. errMsg = 'Must have a `type` when `registerTransform`.';
  21513. }
  21514. throwError(errMsg);
  21515. }
  21516. var typeParsed = type.split(':');
  21517. if (typeParsed.length !== 2) {
  21518. if ("development" !== 'production') {
  21519. errMsg = 'Name must include namespace like "ns:regression".';
  21520. }
  21521. throwError(errMsg);
  21522. }
  21523. // Namespace 'echarts:xxx' is official namespace, where the transforms should
  21524. // be called directly via 'xxx' rather than 'echarts:xxx'.
  21525. var isBuiltIn = false;
  21526. if (typeParsed[0] === 'echarts') {
  21527. type = typeParsed[1];
  21528. isBuiltIn = true;
  21529. }
  21530. externalTransform.__isBuiltIn = isBuiltIn;
  21531. externalTransformMap.set(type, externalTransform);
  21532. }
  21533. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  21534. var pipedTransOption = normalizeToArray(rawTransOption);
  21535. var pipeLen = pipedTransOption.length;
  21536. var errMsg = '';
  21537. if (!pipeLen) {
  21538. if ("development" !== 'production') {
  21539. errMsg = 'If `transform` declared, it should at least contain one transform.';
  21540. }
  21541. throwError(errMsg);
  21542. }
  21543. for (var i = 0, len = pipeLen; i < len; i++) {
  21544. var transOption = pipedTransOption[i];
  21545. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i);
  21546. // piped transform only support single input, except the fist one.
  21547. // piped transform only support single output, except the last one.
  21548. if (i !== len - 1) {
  21549. sourceList.length = Math.max(sourceList.length, 1);
  21550. }
  21551. }
  21552. return sourceList;
  21553. }
  21554. function applySingleDataTransform(transOption, upSourceList, infoForPrint,
  21555. // If `pipeIndex` is null/undefined, no piped transform.
  21556. pipeIndex) {
  21557. var errMsg = '';
  21558. if (!upSourceList.length) {
  21559. if ("development" !== 'production') {
  21560. errMsg = 'Must have at least one upstream dataset.';
  21561. }
  21562. throwError(errMsg);
  21563. }
  21564. if (!isObject(transOption)) {
  21565. if ("development" !== 'production') {
  21566. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  21567. }
  21568. throwError(errMsg);
  21569. }
  21570. var transType = transOption.type;
  21571. var externalTransform = externalTransformMap.get(transType);
  21572. if (!externalTransform) {
  21573. if ("development" !== 'production') {
  21574. errMsg = 'Can not find transform on type "' + transType + '".';
  21575. }
  21576. throwError(errMsg);
  21577. }
  21578. // Prepare source
  21579. var extUpSourceList = map(upSourceList, function (upSource) {
  21580. return createExternalSource(upSource, externalTransform);
  21581. });
  21582. var resultList = normalizeToArray(externalTransform.transform({
  21583. upstream: extUpSourceList[0],
  21584. upstreamList: extUpSourceList,
  21585. config: clone(transOption.config)
  21586. }));
  21587. if ("development" !== 'production') {
  21588. if (transOption.print) {
  21589. var printStrArr = map(resultList, function (extSource) {
  21590. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  21591. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  21592. }).join('\n');
  21593. log(printStrArr);
  21594. }
  21595. }
  21596. return map(resultList, function (result, resultIndex) {
  21597. var errMsg = '';
  21598. if (!isObject(result)) {
  21599. if ("development" !== 'production') {
  21600. errMsg = 'A transform should not return some empty results.';
  21601. }
  21602. throwError(errMsg);
  21603. }
  21604. if (!result.data) {
  21605. if ("development" !== 'production') {
  21606. errMsg = 'Transform result data should be not be null or undefined';
  21607. }
  21608. throwError(errMsg);
  21609. }
  21610. var sourceFormat = detectSourceFormat(result.data);
  21611. if (!isSupportedSourceFormat(sourceFormat)) {
  21612. if ("development" !== 'production') {
  21613. errMsg = 'Transform result data should be array rows or object rows.';
  21614. }
  21615. throwError(errMsg);
  21616. }
  21617. var resultMetaRawOption;
  21618. var firstUpSource = upSourceList[0];
  21619. /**
  21620. * Intuitively, the end users known the content of the original `dataset.source`,
  21621. * calucating the transform result in mind.
  21622. * Suppose the original `dataset.source` is:
  21623. * ```js
  21624. * [
  21625. * ['product', '2012', '2013', '2014', '2015'],
  21626. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  21627. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  21628. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  21629. * ]
  21630. * ```
  21631. * The dimension info have to be detected from the source data.
  21632. * Some of the transformers (like filter, sort) will follow the dimension info
  21633. * of upstream, while others use new dimensions (like aggregate).
  21634. * Transformer can output a field `dimensions` to define the its own output dimensions.
  21635. * We also allow transformers to ignore the output `dimensions` field, and
  21636. * inherit the upstream dimensions definition. It can reduce the burden of handling
  21637. * dimensions in transformers.
  21638. *
  21639. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  21640. */
  21641. if (firstUpSource && resultIndex === 0
  21642. // If transformer returns `dimensions`, it means that the transformer has different
  21643. // dimensions definitions. We do not inherit anything from upstream.
  21644. && !result.dimensions) {
  21645. var startIndex = firstUpSource.startIndex;
  21646. // We copy the header of upstream to the result, because:
  21647. // (1) The returned data always does not contain header line and can not be used
  21648. // as dimension-detection. In this case we can not use "detected dimensions" of
  21649. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  21650. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  21651. // So the original detected header should be add to the result, otherwise they can not be read.
  21652. if (startIndex) {
  21653. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  21654. }
  21655. resultMetaRawOption = {
  21656. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21657. sourceHeader: startIndex,
  21658. dimensions: firstUpSource.metaRawOption.dimensions
  21659. };
  21660. } else {
  21661. resultMetaRawOption = {
  21662. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21663. sourceHeader: 0,
  21664. dimensions: result.dimensions
  21665. };
  21666. }
  21667. return createSource(result.data, resultMetaRawOption, null);
  21668. });
  21669. }
  21670. function isSupportedSourceFormat(sourceFormat) {
  21671. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  21672. }
  21673. var UNDEFINED = 'undefined';
  21674. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  21675. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  21676. // different from the Ctor of typed array.
  21677. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  21678. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  21679. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  21680. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  21681. /**
  21682. * Multi dimensional data store
  21683. */
  21684. var dataCtors = {
  21685. 'float': CtorFloat64Array,
  21686. 'int': CtorInt32Array,
  21687. // Ordinal data type can be string or int
  21688. 'ordinal': Array,
  21689. 'number': Array,
  21690. 'time': CtorFloat64Array
  21691. };
  21692. var defaultDimValueGetters;
  21693. function getIndicesCtor(rawCount) {
  21694. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  21695. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  21696. }
  21697. function getInitialExtent() {
  21698. return [Infinity, -Infinity];
  21699. }
  21700. function cloneChunk(originalChunk) {
  21701. var Ctor = originalChunk.constructor;
  21702. // Only shallow clone is enough when Array.
  21703. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  21704. }
  21705. function prepareStore(store, dimIdx, dimType, end, append) {
  21706. var DataCtor = dataCtors[dimType || 'float'];
  21707. if (append) {
  21708. var oldStore = store[dimIdx];
  21709. var oldLen = oldStore && oldStore.length;
  21710. if (!(oldLen === end)) {
  21711. var newStore = new DataCtor(end);
  21712. // The cost of the copy is probably inconsiderable
  21713. // within the initial chunkSize.
  21714. for (var j = 0; j < oldLen; j++) {
  21715. newStore[j] = oldStore[j];
  21716. }
  21717. store[dimIdx] = newStore;
  21718. }
  21719. } else {
  21720. store[dimIdx] = new DataCtor(end);
  21721. }
  21722. }
  21723. /**
  21724. * Basically, DataStore API keep immutable.
  21725. */
  21726. var DataStore = /** @class */function () {
  21727. function DataStore() {
  21728. this._chunks = [];
  21729. // It will not be calculated until needed.
  21730. this._rawExtent = [];
  21731. this._extent = [];
  21732. this._count = 0;
  21733. this._rawCount = 0;
  21734. this._calcDimNameToIdx = createHashMap();
  21735. }
  21736. /**
  21737. * Initialize from data
  21738. */
  21739. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  21740. if ("development" !== 'production') {
  21741. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  21742. }
  21743. this._provider = provider;
  21744. // Clear
  21745. this._chunks = [];
  21746. this._indices = null;
  21747. this.getRawIndex = this._getRawIdxIdentity;
  21748. var source = provider.getSource();
  21749. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat];
  21750. // Default dim value getter
  21751. this._dimValueGetter = dimValueGetter || defaultGetter;
  21752. // Reset raw extent.
  21753. this._rawExtent = [];
  21754. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  21755. this._dimensions = map(inputDimensions, function (dim) {
  21756. if ("development" !== 'production') {
  21757. if (willRetrieveDataByName) {
  21758. assert(dim.property != null);
  21759. }
  21760. }
  21761. return {
  21762. // Only pick these two props. Not leak other properties like orderMeta.
  21763. type: dim.type,
  21764. property: dim.property
  21765. };
  21766. });
  21767. this._initDataFromProvider(0, provider.count());
  21768. };
  21769. DataStore.prototype.getProvider = function () {
  21770. return this._provider;
  21771. };
  21772. /**
  21773. * Caution: even when a `source` instance owned by a series, the created data store
  21774. * may still be shared by different sereis (the source hash does not use all `source`
  21775. * props, see `sourceManager`). In this case, the `source` props that are not used in
  21776. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  21777. * thus should not be fetch here.
  21778. */
  21779. DataStore.prototype.getSource = function () {
  21780. return this._provider.getSource();
  21781. };
  21782. /**
  21783. * @caution Only used in dataStack.
  21784. */
  21785. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  21786. var calcDimNameToIdx = this._calcDimNameToIdx;
  21787. var dimensions = this._dimensions;
  21788. var calcDimIdx = calcDimNameToIdx.get(dimName);
  21789. if (calcDimIdx != null) {
  21790. if (dimensions[calcDimIdx].type === type) {
  21791. return calcDimIdx;
  21792. }
  21793. } else {
  21794. calcDimIdx = dimensions.length;
  21795. }
  21796. dimensions[calcDimIdx] = {
  21797. type: type
  21798. };
  21799. calcDimNameToIdx.set(dimName, calcDimIdx);
  21800. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  21801. this._rawExtent[calcDimIdx] = getInitialExtent();
  21802. return calcDimIdx;
  21803. };
  21804. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  21805. var chunk = this._chunks[dimIdx];
  21806. var dim = this._dimensions[dimIdx];
  21807. var rawExtents = this._rawExtent;
  21808. var offset = dim.ordinalOffset || 0;
  21809. var len = chunk.length;
  21810. if (offset === 0) {
  21811. // We need to reset the rawExtent if collect is from start.
  21812. // Because this dimension may be guessed as number and calcuating a wrong extent.
  21813. rawExtents[dimIdx] = getInitialExtent();
  21814. }
  21815. var dimRawExtent = rawExtents[dimIdx];
  21816. // Parse from previous data offset. len may be changed after appendData
  21817. for (var i = offset; i < len; i++) {
  21818. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  21819. if (!isNaN(val)) {
  21820. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  21821. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  21822. }
  21823. }
  21824. dim.ordinalMeta = ordinalMeta;
  21825. dim.ordinalOffset = len;
  21826. dim.type = 'ordinal'; // Force to be ordinal
  21827. };
  21828. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  21829. var dimInfo = this._dimensions[dimIdx];
  21830. var ordinalMeta = dimInfo.ordinalMeta;
  21831. return ordinalMeta;
  21832. };
  21833. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  21834. var item = this._dimensions[dimIndex];
  21835. return item && item.property;
  21836. };
  21837. /**
  21838. * Caution: Can be only called on raw data (before `this._indices` created).
  21839. */
  21840. DataStore.prototype.appendData = function (data) {
  21841. if ("development" !== 'production') {
  21842. assert(!this._indices, 'appendData can only be called on raw data.');
  21843. }
  21844. var provider = this._provider;
  21845. var start = this.count();
  21846. provider.appendData(data);
  21847. var end = provider.count();
  21848. if (!provider.persistent) {
  21849. end += start;
  21850. }
  21851. if (start < end) {
  21852. this._initDataFromProvider(start, end, true);
  21853. }
  21854. return [start, end];
  21855. };
  21856. DataStore.prototype.appendValues = function (values, minFillLen) {
  21857. var chunks = this._chunks;
  21858. var dimensions = this._dimensions;
  21859. var dimLen = dimensions.length;
  21860. var rawExtent = this._rawExtent;
  21861. var start = this.count();
  21862. var end = start + Math.max(values.length, minFillLen || 0);
  21863. for (var i = 0; i < dimLen; i++) {
  21864. var dim = dimensions[i];
  21865. prepareStore(chunks, i, dim.type, end, true);
  21866. }
  21867. var emptyDataItem = [];
  21868. for (var idx = start; idx < end; idx++) {
  21869. var sourceIdx = idx - start;
  21870. // Store the data by dimensions
  21871. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  21872. var dim = dimensions[dimIdx];
  21873. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  21874. chunks[dimIdx][idx] = val;
  21875. var dimRawExtent = rawExtent[dimIdx];
  21876. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  21877. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  21878. }
  21879. }
  21880. this._rawCount = this._count = end;
  21881. return {
  21882. start: start,
  21883. end: end
  21884. };
  21885. };
  21886. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  21887. var provider = this._provider;
  21888. var chunks = this._chunks;
  21889. var dimensions = this._dimensions;
  21890. var dimLen = dimensions.length;
  21891. var rawExtent = this._rawExtent;
  21892. var dimNames = map(dimensions, function (dim) {
  21893. return dim.property;
  21894. });
  21895. for (var i = 0; i < dimLen; i++) {
  21896. var dim = dimensions[i];
  21897. if (!rawExtent[i]) {
  21898. rawExtent[i] = getInitialExtent();
  21899. }
  21900. prepareStore(chunks, i, dim.type, end, append);
  21901. }
  21902. if (provider.fillStorage) {
  21903. provider.fillStorage(start, end, chunks, rawExtent);
  21904. } else {
  21905. var dataItem = [];
  21906. for (var idx = start; idx < end; idx++) {
  21907. // NOTICE: Try not to write things into dataItem
  21908. dataItem = provider.getItem(idx, dataItem);
  21909. // Each data item is value
  21910. // [1, 2]
  21911. // 2
  21912. // Bar chart, line chart which uses category axis
  21913. // only gives the 'y' value. 'x' value is the indices of category
  21914. // Use a tempValue to normalize the value to be a (x, y) value
  21915. // Store the data by dimensions
  21916. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  21917. var dimStorage = chunks[dimIdx];
  21918. // PENDING NULL is empty or zero
  21919. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  21920. dimStorage[idx] = val;
  21921. var dimRawExtent = rawExtent[dimIdx];
  21922. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  21923. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  21924. }
  21925. }
  21926. }
  21927. if (!provider.persistent && provider.clean) {
  21928. // Clean unused data if data source is typed array.
  21929. provider.clean();
  21930. }
  21931. this._rawCount = this._count = end;
  21932. // Reset data extent
  21933. this._extent = [];
  21934. };
  21935. DataStore.prototype.count = function () {
  21936. return this._count;
  21937. };
  21938. /**
  21939. * Get value. Return NaN if idx is out of range.
  21940. */
  21941. DataStore.prototype.get = function (dim, idx) {
  21942. if (!(idx >= 0 && idx < this._count)) {
  21943. return NaN;
  21944. }
  21945. var dimStore = this._chunks[dim];
  21946. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  21947. };
  21948. DataStore.prototype.getValues = function (dimensions, idx) {
  21949. var values = [];
  21950. var dimArr = [];
  21951. if (idx == null) {
  21952. idx = dimensions;
  21953. // TODO get all from store?
  21954. dimensions = [];
  21955. // All dimensions
  21956. for (var i = 0; i < this._dimensions.length; i++) {
  21957. dimArr.push(i);
  21958. }
  21959. } else {
  21960. dimArr = dimensions;
  21961. }
  21962. for (var i = 0, len = dimArr.length; i < len; i++) {
  21963. values.push(this.get(dimArr[i], idx));
  21964. }
  21965. return values;
  21966. };
  21967. /**
  21968. * @param dim concrete dim
  21969. */
  21970. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  21971. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  21972. return NaN;
  21973. }
  21974. var dimStore = this._chunks[dim];
  21975. return dimStore ? dimStore[rawIdx] : NaN;
  21976. };
  21977. /**
  21978. * Get sum of data in one dimension
  21979. */
  21980. DataStore.prototype.getSum = function (dim) {
  21981. var dimData = this._chunks[dim];
  21982. var sum = 0;
  21983. if (dimData) {
  21984. for (var i = 0, len = this.count(); i < len; i++) {
  21985. var value = this.get(dim, i);
  21986. if (!isNaN(value)) {
  21987. sum += value;
  21988. }
  21989. }
  21990. }
  21991. return sum;
  21992. };
  21993. /**
  21994. * Get median of data in one dimension
  21995. */
  21996. DataStore.prototype.getMedian = function (dim) {
  21997. var dimDataArray = [];
  21998. // map all data of one dimension
  21999. this.each([dim], function (val) {
  22000. if (!isNaN(val)) {
  22001. dimDataArray.push(val);
  22002. }
  22003. });
  22004. // TODO
  22005. // Use quick select?
  22006. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  22007. return a - b;
  22008. });
  22009. var len = this.count();
  22010. // calculate median
  22011. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  22012. };
  22013. /**
  22014. * Retrieve the index with given raw data index.
  22015. */
  22016. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  22017. if (rawIndex >= this._rawCount || rawIndex < 0) {
  22018. return -1;
  22019. }
  22020. if (!this._indices) {
  22021. return rawIndex;
  22022. }
  22023. // Indices are ascending
  22024. var indices = this._indices;
  22025. // If rawIndex === dataIndex
  22026. var rawDataIndex = indices[rawIndex];
  22027. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  22028. return rawIndex;
  22029. }
  22030. var left = 0;
  22031. var right = this._count - 1;
  22032. while (left <= right) {
  22033. var mid = (left + right) / 2 | 0;
  22034. if (indices[mid] < rawIndex) {
  22035. left = mid + 1;
  22036. } else if (indices[mid] > rawIndex) {
  22037. right = mid - 1;
  22038. } else {
  22039. return mid;
  22040. }
  22041. }
  22042. return -1;
  22043. };
  22044. DataStore.prototype.getIndices = function () {
  22045. var newIndices;
  22046. var indices = this._indices;
  22047. if (indices) {
  22048. var Ctor = indices.constructor;
  22049. var thisCount = this._count;
  22050. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  22051. if (Ctor === Array) {
  22052. newIndices = new Ctor(thisCount);
  22053. for (var i = 0; i < thisCount; i++) {
  22054. newIndices[i] = indices[i];
  22055. }
  22056. } else {
  22057. newIndices = new Ctor(indices.buffer, 0, thisCount);
  22058. }
  22059. } else {
  22060. var Ctor = getIndicesCtor(this._rawCount);
  22061. newIndices = new Ctor(this.count());
  22062. for (var i = 0; i < newIndices.length; i++) {
  22063. newIndices[i] = i;
  22064. }
  22065. }
  22066. return newIndices;
  22067. };
  22068. /**
  22069. * Data filter.
  22070. */
  22071. DataStore.prototype.filter = function (dims, cb) {
  22072. if (!this._count) {
  22073. return this;
  22074. }
  22075. var newStore = this.clone();
  22076. var count = newStore.count();
  22077. var Ctor = getIndicesCtor(newStore._rawCount);
  22078. var newIndices = new Ctor(count);
  22079. var value = [];
  22080. var dimSize = dims.length;
  22081. var offset = 0;
  22082. var dim0 = dims[0];
  22083. var chunks = newStore._chunks;
  22084. for (var i = 0; i < count; i++) {
  22085. var keep = void 0;
  22086. var rawIdx = newStore.getRawIndex(i);
  22087. // Simple optimization
  22088. if (dimSize === 0) {
  22089. keep = cb(i);
  22090. } else if (dimSize === 1) {
  22091. var val = chunks[dim0][rawIdx];
  22092. keep = cb(val, i);
  22093. } else {
  22094. var k = 0;
  22095. for (; k < dimSize; k++) {
  22096. value[k] = chunks[dims[k]][rawIdx];
  22097. }
  22098. value[k] = i;
  22099. keep = cb.apply(null, value);
  22100. }
  22101. if (keep) {
  22102. newIndices[offset++] = rawIdx;
  22103. }
  22104. }
  22105. // Set indices after filtered.
  22106. if (offset < count) {
  22107. newStore._indices = newIndices;
  22108. }
  22109. newStore._count = offset;
  22110. // Reset data extent
  22111. newStore._extent = [];
  22112. newStore._updateGetRawIdx();
  22113. return newStore;
  22114. };
  22115. /**
  22116. * Select data in range. (For optimization of filter)
  22117. * (Manually inline code, support 5 million data filtering in data zoom.)
  22118. */
  22119. DataStore.prototype.selectRange = function (range) {
  22120. var newStore = this.clone();
  22121. var len = newStore._count;
  22122. if (!len) {
  22123. return this;
  22124. }
  22125. var dims = keys(range);
  22126. var dimSize = dims.length;
  22127. if (!dimSize) {
  22128. return this;
  22129. }
  22130. var originalCount = newStore.count();
  22131. var Ctor = getIndicesCtor(newStore._rawCount);
  22132. var newIndices = new Ctor(originalCount);
  22133. var offset = 0;
  22134. var dim0 = dims[0];
  22135. var min = range[dim0][0];
  22136. var max = range[dim0][1];
  22137. var storeArr = newStore._chunks;
  22138. var quickFinished = false;
  22139. if (!newStore._indices) {
  22140. // Extreme optimization for common case. About 2x faster in chrome.
  22141. var idx = 0;
  22142. if (dimSize === 1) {
  22143. var dimStorage = storeArr[dims[0]];
  22144. for (var i = 0; i < len; i++) {
  22145. var val = dimStorage[i];
  22146. // NaN will not be filtered. Consider the case, in line chart, empty
  22147. // value indicates the line should be broken. But for the case like
  22148. // scatter plot, a data item with empty value will not be rendered,
  22149. // but the axis extent may be effected if some other dim of the data
  22150. // item has value. Fortunately it is not a significant negative effect.
  22151. if (val >= min && val <= max || isNaN(val)) {
  22152. newIndices[offset++] = idx;
  22153. }
  22154. idx++;
  22155. }
  22156. quickFinished = true;
  22157. } else if (dimSize === 2) {
  22158. var dimStorage = storeArr[dims[0]];
  22159. var dimStorage2 = storeArr[dims[1]];
  22160. var min2 = range[dims[1]][0];
  22161. var max2 = range[dims[1]][1];
  22162. for (var i = 0; i < len; i++) {
  22163. var val = dimStorage[i];
  22164. var val2 = dimStorage2[i];
  22165. // Do not filter NaN, see comment above.
  22166. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  22167. newIndices[offset++] = idx;
  22168. }
  22169. idx++;
  22170. }
  22171. quickFinished = true;
  22172. }
  22173. }
  22174. if (!quickFinished) {
  22175. if (dimSize === 1) {
  22176. for (var i = 0; i < originalCount; i++) {
  22177. var rawIndex = newStore.getRawIndex(i);
  22178. var val = storeArr[dims[0]][rawIndex];
  22179. // Do not filter NaN, see comment above.
  22180. if (val >= min && val <= max || isNaN(val)) {
  22181. newIndices[offset++] = rawIndex;
  22182. }
  22183. }
  22184. } else {
  22185. for (var i = 0; i < originalCount; i++) {
  22186. var keep = true;
  22187. var rawIndex = newStore.getRawIndex(i);
  22188. for (var k = 0; k < dimSize; k++) {
  22189. var dimk = dims[k];
  22190. var val = storeArr[dimk][rawIndex];
  22191. // Do not filter NaN, see comment above.
  22192. if (val < range[dimk][0] || val > range[dimk][1]) {
  22193. keep = false;
  22194. }
  22195. }
  22196. if (keep) {
  22197. newIndices[offset++] = newStore.getRawIndex(i);
  22198. }
  22199. }
  22200. }
  22201. }
  22202. // Set indices after filtered.
  22203. if (offset < originalCount) {
  22204. newStore._indices = newIndices;
  22205. }
  22206. newStore._count = offset;
  22207. // Reset data extent
  22208. newStore._extent = [];
  22209. newStore._updateGetRawIdx();
  22210. return newStore;
  22211. };
  22212. // /**
  22213. // * Data mapping to a plain array
  22214. // */
  22215. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  22216. // const result: any[] = [];
  22217. // this.each(dims, function () {
  22218. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  22219. // });
  22220. // return result;
  22221. // }
  22222. /**
  22223. * Data mapping to a new List with given dimensions
  22224. */
  22225. DataStore.prototype.map = function (dims, cb) {
  22226. // TODO only clone picked chunks.
  22227. var target = this.clone(dims);
  22228. this._updateDims(target, dims, cb);
  22229. return target;
  22230. };
  22231. /**
  22232. * @caution Danger!! Only used in dataStack.
  22233. */
  22234. DataStore.prototype.modify = function (dims, cb) {
  22235. this._updateDims(this, dims, cb);
  22236. };
  22237. DataStore.prototype._updateDims = function (target, dims, cb) {
  22238. var targetChunks = target._chunks;
  22239. var tmpRetValue = [];
  22240. var dimSize = dims.length;
  22241. var dataCount = target.count();
  22242. var values = [];
  22243. var rawExtent = target._rawExtent;
  22244. for (var i = 0; i < dims.length; i++) {
  22245. rawExtent[dims[i]] = getInitialExtent();
  22246. }
  22247. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  22248. var rawIndex = target.getRawIndex(dataIndex);
  22249. for (var k = 0; k < dimSize; k++) {
  22250. values[k] = targetChunks[dims[k]][rawIndex];
  22251. }
  22252. values[dimSize] = dataIndex;
  22253. var retValue = cb && cb.apply(null, values);
  22254. if (retValue != null) {
  22255. // a number or string (in oridinal dimension)?
  22256. if (typeof retValue !== 'object') {
  22257. tmpRetValue[0] = retValue;
  22258. retValue = tmpRetValue;
  22259. }
  22260. for (var i = 0; i < retValue.length; i++) {
  22261. var dim = dims[i];
  22262. var val = retValue[i];
  22263. var rawExtentOnDim = rawExtent[dim];
  22264. var dimStore = targetChunks[dim];
  22265. if (dimStore) {
  22266. dimStore[rawIndex] = val;
  22267. }
  22268. if (val < rawExtentOnDim[0]) {
  22269. rawExtentOnDim[0] = val;
  22270. }
  22271. if (val > rawExtentOnDim[1]) {
  22272. rawExtentOnDim[1] = val;
  22273. }
  22274. }
  22275. }
  22276. }
  22277. };
  22278. /**
  22279. * Large data down sampling using largest-triangle-three-buckets
  22280. * @param {string} valueDimension
  22281. * @param {number} targetCount
  22282. */
  22283. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  22284. var target = this.clone([valueDimension], true);
  22285. var targetStorage = target._chunks;
  22286. var dimStore = targetStorage[valueDimension];
  22287. var len = this.count();
  22288. var sampledIndex = 0;
  22289. var frameSize = Math.floor(1 / rate);
  22290. var currentRawIndex = this.getRawIndex(0);
  22291. var maxArea;
  22292. var area;
  22293. var nextRawIndex;
  22294. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len));
  22295. // First frame use the first data.
  22296. newIndices[sampledIndex++] = currentRawIndex;
  22297. for (var i = 1; i < len - 1; i += frameSize) {
  22298. var nextFrameStart = Math.min(i + frameSize, len - 1);
  22299. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  22300. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  22301. var avgY = 0;
  22302. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  22303. var rawIndex = this.getRawIndex(idx);
  22304. var y = dimStore[rawIndex];
  22305. if (isNaN(y)) {
  22306. continue;
  22307. }
  22308. avgY += y;
  22309. }
  22310. avgY /= nextFrameEnd - nextFrameStart;
  22311. var frameStart = i;
  22312. var frameEnd = Math.min(i + frameSize, len);
  22313. var pointAX = i - 1;
  22314. var pointAY = dimStore[currentRawIndex];
  22315. maxArea = -1;
  22316. nextRawIndex = frameStart;
  22317. var firstNaNIndex = -1;
  22318. var countNaN = 0;
  22319. // Find a point from current frame that construct a triangle with largest area with previous selected point
  22320. // And the average of next frame.
  22321. for (var idx = frameStart; idx < frameEnd; idx++) {
  22322. var rawIndex = this.getRawIndex(idx);
  22323. var y = dimStore[rawIndex];
  22324. if (isNaN(y)) {
  22325. countNaN++;
  22326. if (firstNaNIndex < 0) {
  22327. firstNaNIndex = rawIndex;
  22328. }
  22329. continue;
  22330. }
  22331. // Calculate triangle area over three buckets
  22332. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  22333. if (area > maxArea) {
  22334. maxArea = area;
  22335. nextRawIndex = rawIndex; // Next a is this b
  22336. }
  22337. }
  22338. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  22339. // Append first NaN point in every bucket.
  22340. // It is necessary to ensure the correct order of indices.
  22341. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  22342. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  22343. }
  22344. newIndices[sampledIndex++] = nextRawIndex;
  22345. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  22346. }
  22347. // First frame use the last data.
  22348. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  22349. target._count = sampledIndex;
  22350. target._indices = newIndices;
  22351. target.getRawIndex = this._getRawIdx;
  22352. return target;
  22353. };
  22354. /**
  22355. * Large data down sampling using min-max
  22356. * @param {string} valueDimension
  22357. * @param {number} rate
  22358. */
  22359. DataStore.prototype.minmaxDownSample = function (valueDimension, rate) {
  22360. var target = this.clone([valueDimension], true);
  22361. var targetStorage = target._chunks;
  22362. var frameSize = Math.floor(1 / rate);
  22363. var dimStore = targetStorage[valueDimension];
  22364. var len = this.count();
  22365. // Each frame results in 2 data points, one for min and one for max
  22366. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize) * 2);
  22367. var offset = 0;
  22368. for (var i = 0; i < len; i += frameSize) {
  22369. var minIndex = i;
  22370. var minValue = dimStore[this.getRawIndex(minIndex)];
  22371. var maxIndex = i;
  22372. var maxValue = dimStore[this.getRawIndex(maxIndex)];
  22373. var thisFrameSize = frameSize;
  22374. // Handle final smaller frame
  22375. if (i + frameSize > len) {
  22376. thisFrameSize = len - i;
  22377. }
  22378. // Determine min and max within the current frame
  22379. for (var k = 0; k < thisFrameSize; k++) {
  22380. var rawIndex = this.getRawIndex(i + k);
  22381. var value = dimStore[rawIndex];
  22382. if (value < minValue) {
  22383. minValue = value;
  22384. minIndex = i + k;
  22385. }
  22386. if (value > maxValue) {
  22387. maxValue = value;
  22388. maxIndex = i + k;
  22389. }
  22390. }
  22391. var rawMinIndex = this.getRawIndex(minIndex);
  22392. var rawMaxIndex = this.getRawIndex(maxIndex);
  22393. // Set the order of the min and max values, based on their ordering in the frame
  22394. if (minIndex < maxIndex) {
  22395. newIndices[offset++] = rawMinIndex;
  22396. newIndices[offset++] = rawMaxIndex;
  22397. } else {
  22398. newIndices[offset++] = rawMaxIndex;
  22399. newIndices[offset++] = rawMinIndex;
  22400. }
  22401. }
  22402. target._count = offset;
  22403. target._indices = newIndices;
  22404. target._updateGetRawIdx();
  22405. return target;
  22406. };
  22407. /**
  22408. * Large data down sampling on given dimension
  22409. * @param sampleIndex Sample index for name and id
  22410. */
  22411. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  22412. var target = this.clone([dimension], true);
  22413. var targetStorage = target._chunks;
  22414. var frameValues = [];
  22415. var frameSize = Math.floor(1 / rate);
  22416. var dimStore = targetStorage[dimension];
  22417. var len = this.count();
  22418. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  22419. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  22420. var offset = 0;
  22421. for (var i = 0; i < len; i += frameSize) {
  22422. // Last frame
  22423. if (frameSize > len - i) {
  22424. frameSize = len - i;
  22425. frameValues.length = frameSize;
  22426. }
  22427. for (var k = 0; k < frameSize; k++) {
  22428. var dataIdx = this.getRawIndex(i + k);
  22429. frameValues[k] = dimStore[dataIdx];
  22430. }
  22431. var value = sampleValue(frameValues);
  22432. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1));
  22433. // Only write value on the filtered data
  22434. dimStore[sampleFrameIdx] = value;
  22435. if (value < rawExtentOnDim[0]) {
  22436. rawExtentOnDim[0] = value;
  22437. }
  22438. if (value > rawExtentOnDim[1]) {
  22439. rawExtentOnDim[1] = value;
  22440. }
  22441. newIndices[offset++] = sampleFrameIdx;
  22442. }
  22443. target._count = offset;
  22444. target._indices = newIndices;
  22445. target._updateGetRawIdx();
  22446. return target;
  22447. };
  22448. /**
  22449. * Data iteration
  22450. * @param ctx default this
  22451. * @example
  22452. * list.each('x', function (x, idx) {});
  22453. * list.each(['x', 'y'], function (x, y, idx) {});
  22454. * list.each(function (idx) {})
  22455. */
  22456. DataStore.prototype.each = function (dims, cb) {
  22457. if (!this._count) {
  22458. return;
  22459. }
  22460. var dimSize = dims.length;
  22461. var chunks = this._chunks;
  22462. for (var i = 0, len = this.count(); i < len; i++) {
  22463. var rawIdx = this.getRawIndex(i);
  22464. // Simple optimization
  22465. switch (dimSize) {
  22466. case 0:
  22467. cb(i);
  22468. break;
  22469. case 1:
  22470. cb(chunks[dims[0]][rawIdx], i);
  22471. break;
  22472. case 2:
  22473. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  22474. break;
  22475. default:
  22476. var k = 0;
  22477. var value = [];
  22478. for (; k < dimSize; k++) {
  22479. value[k] = chunks[dims[k]][rawIdx];
  22480. }
  22481. // Index
  22482. value[k] = i;
  22483. cb.apply(null, value);
  22484. }
  22485. }
  22486. };
  22487. /**
  22488. * Get extent of data in one dimension
  22489. */
  22490. DataStore.prototype.getDataExtent = function (dim) {
  22491. // Make sure use concrete dim as cache name.
  22492. var dimData = this._chunks[dim];
  22493. var initialExtent = getInitialExtent();
  22494. if (!dimData) {
  22495. return initialExtent;
  22496. }
  22497. // Make more strict checkings to ensure hitting cache.
  22498. var currEnd = this.count();
  22499. // Consider the most cases when using data zoom, `getDataExtent`
  22500. // happened before filtering. We cache raw extent, which is not
  22501. // necessary to be cleared and recalculated when restore data.
  22502. var useRaw = !this._indices;
  22503. var dimExtent;
  22504. if (useRaw) {
  22505. return this._rawExtent[dim].slice();
  22506. }
  22507. dimExtent = this._extent[dim];
  22508. if (dimExtent) {
  22509. return dimExtent.slice();
  22510. }
  22511. dimExtent = initialExtent;
  22512. var min = dimExtent[0];
  22513. var max = dimExtent[1];
  22514. for (var i = 0; i < currEnd; i++) {
  22515. var rawIdx = this.getRawIndex(i);
  22516. var value = dimData[rawIdx];
  22517. value < min && (min = value);
  22518. value > max && (max = value);
  22519. }
  22520. dimExtent = [min, max];
  22521. this._extent[dim] = dimExtent;
  22522. return dimExtent;
  22523. };
  22524. /**
  22525. * Get raw data item
  22526. */
  22527. DataStore.prototype.getRawDataItem = function (idx) {
  22528. var rawIdx = this.getRawIndex(idx);
  22529. if (!this._provider.persistent) {
  22530. var val = [];
  22531. var chunks = this._chunks;
  22532. for (var i = 0; i < chunks.length; i++) {
  22533. val.push(chunks[i][rawIdx]);
  22534. }
  22535. return val;
  22536. } else {
  22537. return this._provider.getItem(rawIdx);
  22538. }
  22539. };
  22540. /**
  22541. * Clone shallow.
  22542. *
  22543. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  22544. */
  22545. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  22546. var target = new DataStore();
  22547. var chunks = this._chunks;
  22548. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  22549. obj[dimIdx] = true;
  22550. return obj;
  22551. }, {});
  22552. if (clonedDimsMap) {
  22553. for (var i = 0; i < chunks.length; i++) {
  22554. // Not clone if dim is not picked.
  22555. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  22556. }
  22557. } else {
  22558. target._chunks = chunks;
  22559. }
  22560. this._copyCommonProps(target);
  22561. if (!ignoreIndices) {
  22562. target._indices = this._cloneIndices();
  22563. }
  22564. target._updateGetRawIdx();
  22565. return target;
  22566. };
  22567. DataStore.prototype._copyCommonProps = function (target) {
  22568. target._count = this._count;
  22569. target._rawCount = this._rawCount;
  22570. target._provider = this._provider;
  22571. target._dimensions = this._dimensions;
  22572. target._extent = clone(this._extent);
  22573. target._rawExtent = clone(this._rawExtent);
  22574. };
  22575. DataStore.prototype._cloneIndices = function () {
  22576. if (this._indices) {
  22577. var Ctor = this._indices.constructor;
  22578. var indices = void 0;
  22579. if (Ctor === Array) {
  22580. var thisCount = this._indices.length;
  22581. indices = new Ctor(thisCount);
  22582. for (var i = 0; i < thisCount; i++) {
  22583. indices[i] = this._indices[i];
  22584. }
  22585. } else {
  22586. indices = new Ctor(this._indices);
  22587. }
  22588. return indices;
  22589. }
  22590. return null;
  22591. };
  22592. DataStore.prototype._getRawIdxIdentity = function (idx) {
  22593. return idx;
  22594. };
  22595. DataStore.prototype._getRawIdx = function (idx) {
  22596. if (idx < this._count && idx >= 0) {
  22597. return this._indices[idx];
  22598. }
  22599. return -1;
  22600. };
  22601. DataStore.prototype._updateGetRawIdx = function () {
  22602. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  22603. };
  22604. DataStore.internalField = function () {
  22605. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  22606. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  22607. }
  22608. defaultDimValueGetters = {
  22609. arrayRows: getDimValueSimply,
  22610. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  22611. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  22612. },
  22613. keyedColumns: getDimValueSimply,
  22614. original: function (dataItem, property, dataIndex, dimIndex) {
  22615. // Performance sensitive, do not use modelUtil.getDataItemValue.
  22616. // If dataItem is an plain object with no value field, the let `value`
  22617. // will be assigned with the object, but it will be tread correctly
  22618. // in the `convertValue`.
  22619. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  22620. return parseDataValue(value instanceof Array ? value[dimIndex]
  22621. // If value is a single number or something else not array.
  22622. : value, this._dimensions[dimIndex]);
  22623. },
  22624. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  22625. return dataItem[dimIndex];
  22626. }
  22627. };
  22628. }();
  22629. return DataStore;
  22630. }();
  22631. /**
  22632. * [REQUIREMENT_MEMO]:
  22633. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  22634. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  22635. * `root-dataset`. Them on `series` has higher priority.
  22636. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  22637. * confuse users: whether those props indicate how to visit the upstream source or visit
  22638. * the transform result source, and some transforms has nothing to do with these props,
  22639. * and some transforms might have multiple upstream.
  22640. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  22641. * declared in `root-dataset`.
  22642. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  22643. * That is for reducing complexity in transforms.
  22644. * PENDING: Whether to provide transposition transform?
  22645. *
  22646. * [IMPLEMENTAION_MEMO]:
  22647. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  22648. * They will not be calculated until `source` is about to be visited (to prevent from
  22649. * duplicate calcuation). `source` is visited only in series and input to transforms.
  22650. *
  22651. * [DIMENSION_INHERIT_RULE]:
  22652. * By default the dimensions are inherited from ancestors, unless a transform return
  22653. * a new dimensions definition.
  22654. * Consider the case:
  22655. * ```js
  22656. * dataset: [{
  22657. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  22658. * }, {
  22659. * transform: { type: 'filter', ... }
  22660. * }]
  22661. * dataset: [{
  22662. * dimension: ['Product', 'Sales', 'Prise'],
  22663. * source: [ ['Cookies', 321, 44.21], ...]
  22664. * }, {
  22665. * transform: { type: 'filter', ... }
  22666. * }]
  22667. * ```
  22668. * The two types of option should have the same behavior after transform.
  22669. *
  22670. *
  22671. * [SCENARIO]:
  22672. * (1) Provide source data directly:
  22673. * ```js
  22674. * series: {
  22675. * encode: {...},
  22676. * dimensions: [...]
  22677. * seriesLayoutBy: 'row',
  22678. * data: [[...]]
  22679. * }
  22680. * ```
  22681. * (2) Series refer to dataset.
  22682. * ```js
  22683. * series: [{
  22684. * encode: {...}
  22685. * // Ignore datasetIndex means `datasetIndex: 0`
  22686. * // and the dimensions defination in dataset is used
  22687. * }, {
  22688. * encode: {...},
  22689. * seriesLayoutBy: 'column',
  22690. * datasetIndex: 1
  22691. * }]
  22692. * ```
  22693. * (3) dataset transform
  22694. * ```js
  22695. * dataset: [{
  22696. * source: [...]
  22697. * }, {
  22698. * source: [...]
  22699. * }, {
  22700. * // By default from 0.
  22701. * transform: { type: 'filter', config: {...} }
  22702. * }, {
  22703. * // Piped.
  22704. * transform: [
  22705. * { type: 'filter', config: {...} },
  22706. * { type: 'sort', config: {...} }
  22707. * ]
  22708. * }, {
  22709. * id: 'regressionData',
  22710. * fromDatasetIndex: 1,
  22711. * // Third-party transform
  22712. * transform: { type: 'ecStat:regression', config: {...} }
  22713. * }, {
  22714. * // retrieve the extra result.
  22715. * id: 'regressionFormula',
  22716. * fromDatasetId: 'regressionData',
  22717. * fromTransformResult: 1
  22718. * }]
  22719. * ```
  22720. */
  22721. var SourceManager = /** @class */function () {
  22722. function SourceManager(sourceHost) {
  22723. // Cached source. Do not repeat calculating if not dirty.
  22724. this._sourceList = [];
  22725. this._storeList = [];
  22726. // version sign of each upstream source manager.
  22727. this._upstreamSignList = [];
  22728. this._versionSignBase = 0;
  22729. this._dirty = true;
  22730. this._sourceHost = sourceHost;
  22731. }
  22732. /**
  22733. * Mark dirty.
  22734. */
  22735. SourceManager.prototype.dirty = function () {
  22736. this._setLocalSource([], []);
  22737. this._storeList = [];
  22738. this._dirty = true;
  22739. };
  22740. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  22741. this._sourceList = sourceList;
  22742. this._upstreamSignList = upstreamSignList;
  22743. this._versionSignBase++;
  22744. if (this._versionSignBase > 9e10) {
  22745. this._versionSignBase = 0;
  22746. }
  22747. };
  22748. /**
  22749. * For detecting whether the upstream source is dirty, so that
  22750. * the local cached source (in `_sourceList`) should be discarded.
  22751. */
  22752. SourceManager.prototype._getVersionSign = function () {
  22753. return this._sourceHost.uid + '_' + this._versionSignBase;
  22754. };
  22755. /**
  22756. * Always return a source instance. Otherwise throw error.
  22757. */
  22758. SourceManager.prototype.prepareSource = function () {
  22759. // For the case that call `setOption` multiple time but no data changed,
  22760. // cache the result source to prevent from repeating transform.
  22761. if (this._isDirty()) {
  22762. this._createSource();
  22763. this._dirty = false;
  22764. }
  22765. };
  22766. SourceManager.prototype._createSource = function () {
  22767. this._setLocalSource([], []);
  22768. var sourceHost = this._sourceHost;
  22769. var upSourceMgrList = this._getUpstreamSourceManagers();
  22770. var hasUpstream = !!upSourceMgrList.length;
  22771. var resultSourceList;
  22772. var upstreamSignList;
  22773. if (isSeries(sourceHost)) {
  22774. var seriesModel = sourceHost;
  22775. var data = void 0;
  22776. var sourceFormat = void 0;
  22777. var upSource = void 0;
  22778. // Has upstream dataset
  22779. if (hasUpstream) {
  22780. var upSourceMgr = upSourceMgrList[0];
  22781. upSourceMgr.prepareSource();
  22782. upSource = upSourceMgr.getSource();
  22783. data = upSource.data;
  22784. sourceFormat = upSource.sourceFormat;
  22785. upstreamSignList = [upSourceMgr._getVersionSign()];
  22786. }
  22787. // Series data is from own.
  22788. else {
  22789. data = seriesModel.get('data', true);
  22790. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  22791. upstreamSignList = [];
  22792. }
  22793. // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  22794. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  22795. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  22796. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  22797. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader);
  22798. // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  22799. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  22800. // but series need `seriesLayoutBy: 'row'`.
  22801. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions);
  22802. // We share source with dataset as much as possible
  22803. // to avoid extra memory cost of high dimensional data.
  22804. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  22805. resultSourceList = needsCreateSource ? [createSource(data, {
  22806. seriesLayoutBy: seriesLayoutBy,
  22807. sourceHeader: sourceHeader,
  22808. dimensions: dimensions
  22809. }, sourceFormat)] : [];
  22810. } else {
  22811. var datasetModel = sourceHost;
  22812. // Has upstream dataset.
  22813. if (hasUpstream) {
  22814. var result = this._applyTransform(upSourceMgrList);
  22815. resultSourceList = result.sourceList;
  22816. upstreamSignList = result.upstreamSignList;
  22817. }
  22818. // Is root dataset.
  22819. else {
  22820. var sourceData = datasetModel.get('source', true);
  22821. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  22822. upstreamSignList = [];
  22823. }
  22824. }
  22825. if ("development" !== 'production') {
  22826. assert(resultSourceList && upstreamSignList);
  22827. }
  22828. this._setLocalSource(resultSourceList, upstreamSignList);
  22829. };
  22830. SourceManager.prototype._applyTransform = function (upMgrList) {
  22831. var datasetModel = this._sourceHost;
  22832. var transformOption = datasetModel.get('transform', true);
  22833. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  22834. if ("development" !== 'production') {
  22835. assert(fromTransformResult != null || transformOption != null);
  22836. }
  22837. if (fromTransformResult != null) {
  22838. var errMsg = '';
  22839. if (upMgrList.length !== 1) {
  22840. if ("development" !== 'production') {
  22841. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  22842. }
  22843. doThrow(errMsg);
  22844. }
  22845. }
  22846. var sourceList;
  22847. var upSourceList = [];
  22848. var upstreamSignList = [];
  22849. each(upMgrList, function (upMgr) {
  22850. upMgr.prepareSource();
  22851. var upSource = upMgr.getSource(fromTransformResult || 0);
  22852. var errMsg = '';
  22853. if (fromTransformResult != null && !upSource) {
  22854. if ("development" !== 'production') {
  22855. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  22856. }
  22857. doThrow(errMsg);
  22858. }
  22859. upSourceList.push(upSource);
  22860. upstreamSignList.push(upMgr._getVersionSign());
  22861. });
  22862. if (transformOption) {
  22863. sourceList = applyDataTransform(transformOption, upSourceList, {
  22864. datasetIndex: datasetModel.componentIndex
  22865. });
  22866. } else if (fromTransformResult != null) {
  22867. sourceList = [cloneSourceShallow(upSourceList[0])];
  22868. }
  22869. return {
  22870. sourceList: sourceList,
  22871. upstreamSignList: upstreamSignList
  22872. };
  22873. };
  22874. SourceManager.prototype._isDirty = function () {
  22875. if (this._dirty) {
  22876. return true;
  22877. }
  22878. // All sourceList is from the some upstream.
  22879. var upSourceMgrList = this._getUpstreamSourceManagers();
  22880. for (var i = 0; i < upSourceMgrList.length; i++) {
  22881. var upSrcMgr = upSourceMgrList[i];
  22882. if (
  22883. // Consider the case that there is ancestor diry, call it recursively.
  22884. // The performance is probably not an issue because usually the chain is not long.
  22885. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  22886. return true;
  22887. }
  22888. }
  22889. };
  22890. /**
  22891. * @param sourceIndex By default 0, means "main source".
  22892. * In most cases there is only one source.
  22893. */
  22894. SourceManager.prototype.getSource = function (sourceIndex) {
  22895. sourceIndex = sourceIndex || 0;
  22896. var source = this._sourceList[sourceIndex];
  22897. if (!source) {
  22898. // Series may share source instance with dataset.
  22899. var upSourceMgrList = this._getUpstreamSourceManagers();
  22900. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  22901. }
  22902. return source;
  22903. };
  22904. /**
  22905. *
  22906. * Get a data store which can be shared across series.
  22907. * Only available for series.
  22908. *
  22909. * @param seriesDimRequest Dimensions that are generated in series.
  22910. * Should have been sorted by `storeDimIndex` asc.
  22911. */
  22912. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  22913. if ("development" !== 'production') {
  22914. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  22915. }
  22916. var schema = seriesDimRequest.makeStoreSchema();
  22917. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  22918. };
  22919. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  22920. // TODO Can use other sourceIndex?
  22921. var sourceIndex = 0;
  22922. var storeList = this._storeList;
  22923. var cachedStoreMap = storeList[sourceIndex];
  22924. if (!cachedStoreMap) {
  22925. cachedStoreMap = storeList[sourceIndex] = {};
  22926. }
  22927. var cachedStore = cachedStoreMap[sourceReadKey];
  22928. if (!cachedStore) {
  22929. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  22930. if (isSeries(this._sourceHost) && upSourceMgr) {
  22931. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  22932. } else {
  22933. cachedStore = new DataStore();
  22934. // Always create store from source of series.
  22935. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  22936. }
  22937. cachedStoreMap[sourceReadKey] = cachedStore;
  22938. }
  22939. return cachedStore;
  22940. };
  22941. /**
  22942. * PENDING: Is it fast enough?
  22943. * If no upstream, return empty array.
  22944. */
  22945. SourceManager.prototype._getUpstreamSourceManagers = function () {
  22946. // Always get the relationship from the raw option.
  22947. // Do not cache the link of the dependency graph, so that
  22948. // there is no need to update them when change happens.
  22949. var sourceHost = this._sourceHost;
  22950. if (isSeries(sourceHost)) {
  22951. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  22952. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  22953. } else {
  22954. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  22955. return datasetModel.getSourceManager();
  22956. });
  22957. }
  22958. };
  22959. SourceManager.prototype._getSourceMetaRawOption = function () {
  22960. var sourceHost = this._sourceHost;
  22961. var seriesLayoutBy;
  22962. var sourceHeader;
  22963. var dimensions;
  22964. if (isSeries(sourceHost)) {
  22965. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  22966. sourceHeader = sourceHost.get('sourceHeader', true);
  22967. dimensions = sourceHost.get('dimensions', true);
  22968. }
  22969. // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  22970. else if (!this._getUpstreamSourceManagers().length) {
  22971. var model = sourceHost;
  22972. seriesLayoutBy = model.get('seriesLayoutBy', true);
  22973. sourceHeader = model.get('sourceHeader', true);
  22974. dimensions = model.get('dimensions', true);
  22975. }
  22976. return {
  22977. seriesLayoutBy: seriesLayoutBy,
  22978. sourceHeader: sourceHeader,
  22979. dimensions: dimensions
  22980. };
  22981. };
  22982. return SourceManager;
  22983. }();
  22984. // Call this method after `super.init` and `super.mergeOption` to
  22985. // disable the transform merge, but do not disable transform clone from rawOption.
  22986. function disableTransformOptionMerge(datasetModel) {
  22987. var transformOption = datasetModel.option.transform;
  22988. transformOption && setAsPrimitive(datasetModel.option.transform);
  22989. }
  22990. function isSeries(sourceHost) {
  22991. // Avoid circular dependency with Series.ts
  22992. return sourceHost.mainType === 'series';
  22993. }
  22994. function doThrow(errMsg) {
  22995. throw new Error(errMsg);
  22996. }
  22997. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1';
  22998. function getTooltipLineHeight(textStyle) {
  22999. var lineHeight = textStyle.lineHeight;
  23000. if (lineHeight == null) {
  23001. return TOOLTIP_LINE_HEIGHT_CSS;
  23002. } else {
  23003. return "line-height:" + encodeHTML(lineHeight + '') + "px";
  23004. }
  23005. }
  23006. // TODO: more textStyle option
  23007. function getTooltipTextStyle(textStyle, renderMode) {
  23008. var nameFontColor = textStyle.color || tokens.color.tertiary;
  23009. var nameFontSize = textStyle.fontSize || 12;
  23010. var nameFontWeight = textStyle.fontWeight || '400';
  23011. var valueFontColor = textStyle.color || tokens.color.secondary;
  23012. var valueFontSize = textStyle.fontSize || 14;
  23013. var valueFontWeight = textStyle.fontWeight || '900';
  23014. if (renderMode === 'html') {
  23015. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  23016. return {
  23017. // eslint-disable-next-line max-len
  23018. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  23019. // eslint-disable-next-line max-len
  23020. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  23021. };
  23022. } else {
  23023. return {
  23024. nameStyle: {
  23025. fontSize: nameFontSize,
  23026. fill: nameFontColor,
  23027. fontWeight: nameFontWeight
  23028. },
  23029. valueStyle: {
  23030. fontSize: valueFontSize,
  23031. fill: valueFontColor,
  23032. fontWeight: valueFontWeight
  23033. }
  23034. };
  23035. }
  23036. }
  23037. // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  23038. // (value from UI design)
  23039. var HTML_GAPS = [0, 10, 20, 30];
  23040. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n'];
  23041. // eslint-disable-next-line max-len
  23042. function createTooltipMarkup(type, option) {
  23043. option.type = type;
  23044. return option;
  23045. }
  23046. function isSectionFragment(frag) {
  23047. return frag.type === 'section';
  23048. }
  23049. function getBuilder(frag) {
  23050. return isSectionFragment(frag) ? buildSection : buildNameValue;
  23051. }
  23052. function getBlockGapLevel(frag) {
  23053. if (isSectionFragment(frag)) {
  23054. var gapLevel_1 = 0;
  23055. var subBlockLen = frag.blocks.length;
  23056. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  23057. each(frag.blocks, function (subBlock) {
  23058. var subGapLevel = getBlockGapLevel(subBlock);
  23059. // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  23060. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  23061. if (subGapLevel >= gapLevel_1) {
  23062. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && (
  23063. // 0 always can not be readable gap level.
  23064. !subGapLevel
  23065. // If no header, always keep the sub gap level. Otherwise
  23066. // look weird in case `multipleSeries`.
  23067. || isSectionFragment(subBlock) && !subBlock.noHeader));
  23068. }
  23069. });
  23070. return gapLevel_1;
  23071. }
  23072. return 0;
  23073. }
  23074. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  23075. var noHeader = fragment.noHeader;
  23076. var gaps = getGap(getBlockGapLevel(fragment));
  23077. var subMarkupTextList = [];
  23078. var subBlocks = fragment.blocks || [];
  23079. assert(!subBlocks || isArray(subBlocks));
  23080. subBlocks = subBlocks || [];
  23081. var orderMode = ctx.orderMode;
  23082. if (fragment.sortBlocks && orderMode) {
  23083. subBlocks = subBlocks.slice();
  23084. var orderMap = {
  23085. valueAsc: 'asc',
  23086. valueDesc: 'desc'
  23087. };
  23088. if (hasOwn(orderMap, orderMode)) {
  23089. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  23090. subBlocks.sort(function (a, b) {
  23091. return comparator_1.evaluate(a.sortParam, b.sortParam);
  23092. });
  23093. }
  23094. // FIXME 'seriesDesc' necessary?
  23095. else if (orderMode === 'seriesDesc') {
  23096. subBlocks.reverse();
  23097. }
  23098. }
  23099. each(subBlocks, function (subBlock, idx) {
  23100. var valueFormatter = fragment.valueFormatter;
  23101. var subMarkupText = getBuilder(subBlock)(
  23102. // Inherit valueFormatter
  23103. valueFormatter ? extend(extend({}, ctx), {
  23104. valueFormatter: valueFormatter
  23105. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  23106. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  23107. });
  23108. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(toolTipTextStyle, subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  23109. if (noHeader) {
  23110. return subMarkupText;
  23111. }
  23112. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  23113. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  23114. var tooltipLineHeight = getTooltipLineHeight(toolTipTextStyle);
  23115. if (ctx.renderMode === 'richText') {
  23116. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  23117. } else {
  23118. return wrapBlockHTML(toolTipTextStyle, "<div style=\"" + nameStyle + ";" + tooltipLineHeight + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  23119. }
  23120. }
  23121. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  23122. var renderMode = ctx.renderMode;
  23123. var noName = fragment.noName;
  23124. var noValue = fragment.noValue;
  23125. var noMarker = !fragment.markerType;
  23126. var name = fragment.name;
  23127. var useUTC = ctx.useUTC;
  23128. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  23129. value = isArray(value) ? value : [value];
  23130. return map(value, function (val, idx) {
  23131. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  23132. });
  23133. };
  23134. if (noName && noValue) {
  23135. return;
  23136. }
  23137. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || tokens.color.secondary, renderMode);
  23138. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  23139. var valueTypeOption = fragment.valueType;
  23140. var readableValueList = noValue ? [] : valueFormatter(fragment.value, fragment.dataIndex);
  23141. var valueAlignRight = !noMarker || !noName;
  23142. // It little weird if only value next to marker but far from marker.
  23143. var valueCloseToMarker = !noMarker && noName;
  23144. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  23145. nameStyle = _a.nameStyle,
  23146. valueStyle = _a.valueStyle;
  23147. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle))
  23148. // Value has commas inside, so use ' ' as delimiter for multiple values.
  23149. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML(toolTipTextStyle, (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  23150. }
  23151. /**
  23152. * @return markupText. null/undefined means no content.
  23153. */
  23154. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  23155. if (!fragment) {
  23156. return;
  23157. }
  23158. var builder = getBuilder(fragment);
  23159. var ctx = {
  23160. useUTC: useUTC,
  23161. renderMode: renderMode,
  23162. orderMode: orderMode,
  23163. markupStyleCreator: markupStyleCreator,
  23164. valueFormatter: fragment.valueFormatter
  23165. };
  23166. return builder(ctx, fragment, 0, toolTipTextStyle);
  23167. }
  23168. function getGap(gapLevel) {
  23169. return {
  23170. html: HTML_GAPS[gapLevel],
  23171. richText: RICH_TEXT_GAPS[gapLevel]
  23172. };
  23173. }
  23174. function wrapBlockHTML(textStyle, encodedContent, topGap) {
  23175. var clearfix = '<div style="clear:both"></div>';
  23176. var marginCSS = "margin: " + topGap + "px 0 0";
  23177. var tooltipLineHeight = getTooltipLineHeight(textStyle);
  23178. return "<div style=\"" + marginCSS + ";" + tooltipLineHeight + ";\">" + encodedContent + clearfix + '</div>';
  23179. }
  23180. function wrapInlineNameHTML(name, leftHasMarker, style) {
  23181. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  23182. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  23183. }
  23184. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  23185. // Do not too close to marker, considering there are multiple values separated by spaces.
  23186. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  23187. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  23188. valueList = isArray(valueList) ? valueList : [valueList];
  23189. return "<span style=\"" + alignCSS + ";" + style + "\">"
  23190. // Value has commas inside, so use ' ' as delimiter for multiple values.
  23191. + map(valueList, function (value) {
  23192. return encodeHTML(value);
  23193. }).join('&nbsp;&nbsp;') + '</span>';
  23194. }
  23195. function wrapInlineNameRichText(ctx, name, style) {
  23196. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  23197. }
  23198. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  23199. var styles = [style];
  23200. var paddingLeft = valueCloseToMarker ? 10 : 20;
  23201. alignRight && styles.push({
  23202. padding: [0, 0, 0, paddingLeft],
  23203. align: 'right'
  23204. });
  23205. // Value has commas inside, so use ' ' as delimiter for multiple values.
  23206. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  23207. }
  23208. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  23209. var style = series.getData().getItemVisual(dataIndex, 'style');
  23210. var color = style[series.visualDrawType];
  23211. return convertToColorString(color);
  23212. }
  23213. function getPaddingFromTooltipModel(model, renderMode) {
  23214. var padding = model.get('padding');
  23215. return padding != null ? padding
  23216. // We give slightly different to look pretty.
  23217. : renderMode === 'richText' ? [8, 10] : 10;
  23218. }
  23219. /**
  23220. * The major feature is generate styles for `renderMode: 'richText'`.
  23221. * But it also serves `renderMode: 'html'` to provide
  23222. * "renderMode-independent" API.
  23223. */
  23224. var TooltipMarkupStyleCreator = /** @class */function () {
  23225. function TooltipMarkupStyleCreator() {
  23226. this.richTextStyles = {};
  23227. // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  23228. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  23229. // rather than static shared by all creators (which will cause it increase to fast).
  23230. this._nextStyleNameId = getRandomIdBase();
  23231. }
  23232. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  23233. return '__EC_aUTo_' + this._nextStyleNameId++;
  23234. };
  23235. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  23236. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  23237. var marker = getTooltipMarker({
  23238. color: colorStr,
  23239. type: markerType,
  23240. renderMode: renderMode,
  23241. markerId: markerId
  23242. });
  23243. if (isString(marker)) {
  23244. return marker;
  23245. } else {
  23246. if ("development" !== 'production') {
  23247. assert(markerId);
  23248. }
  23249. this.richTextStyles[markerId] = marker.style;
  23250. return marker.content;
  23251. }
  23252. };
  23253. /**
  23254. * @usage
  23255. * ```ts
  23256. * const styledText = markupStyleCreator.wrapRichTextStyle([
  23257. * // The styles will be auto merged.
  23258. * {
  23259. * fontSize: 12,
  23260. * color: 'blue'
  23261. * },
  23262. * {
  23263. * padding: 20
  23264. * }
  23265. * ]);
  23266. * ```
  23267. */
  23268. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  23269. var finalStl = {};
  23270. if (isArray(styles)) {
  23271. each(styles, function (stl) {
  23272. return extend(finalStl, stl);
  23273. });
  23274. } else {
  23275. extend(finalStl, styles);
  23276. }
  23277. var styleName = this._generateStyleName();
  23278. this.richTextStyles[styleName] = finalStl;
  23279. return "{" + styleName + "|" + text + "}";
  23280. };
  23281. return TooltipMarkupStyleCreator;
  23282. }();
  23283. function defaultSeriesFormatTooltip(opt) {
  23284. var series = opt.series;
  23285. var dataIndex = opt.dataIndex;
  23286. var multipleSeries = opt.multipleSeries;
  23287. var data = series.getData();
  23288. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  23289. var tooltipDimLen = tooltipDims.length;
  23290. var value = series.getRawValue(dataIndex);
  23291. var isValueArr = isArray(value);
  23292. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex);
  23293. // Complicated rule for pretty tooltip.
  23294. var inlineValue;
  23295. var inlineValueType;
  23296. var subBlocks;
  23297. var sortParam;
  23298. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  23299. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  23300. inlineValue = formatArrResult.inlineValues;
  23301. inlineValueType = formatArrResult.inlineValueTypes;
  23302. subBlocks = formatArrResult.blocks;
  23303. // Only support tooltip sort by the first inline value. It's enough in most cases.
  23304. sortParam = formatArrResult.inlineValues[0];
  23305. } else if (tooltipDimLen) {
  23306. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  23307. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  23308. inlineValueType = dimInfo.type;
  23309. } else {
  23310. sortParam = inlineValue = isValueArr ? value[0] : value;
  23311. }
  23312. // Do not show generated series name. It might not be readable.
  23313. var seriesNameSpecified = isNameSpecified(series);
  23314. var seriesName = seriesNameSpecified && series.name || '';
  23315. var itemName = data.getName(dataIndex);
  23316. var inlineName = multipleSeries ? seriesName : itemName;
  23317. return createTooltipMarkup('section', {
  23318. header: seriesName,
  23319. // When series name is not specified, do not show a header line with only '-'.
  23320. // This case always happens in tooltip.trigger: 'item'.
  23321. noHeader: multipleSeries || !seriesNameSpecified,
  23322. sortParam: sortParam,
  23323. blocks: [createTooltipMarkup('nameValue', {
  23324. markerType: 'item',
  23325. markerColor: markerColor,
  23326. // Do not mix display seriesName and itemName in one tooltip,
  23327. // which might confuses users.
  23328. name: inlineName,
  23329. // name dimension might be auto assigned, where the name might
  23330. // be not readable. So we check trim here.
  23331. noName: !trim(inlineName),
  23332. value: inlineValue,
  23333. valueType: inlineValueType,
  23334. dataIndex: dataIndex
  23335. })].concat(subBlocks || [])
  23336. });
  23337. }
  23338. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  23339. // check: category-no-encode-has-axis-data in dataset.html
  23340. var data = series.getData();
  23341. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  23342. var dimItem = data.getDimensionInfo(idx);
  23343. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  23344. }, false);
  23345. var inlineValues = [];
  23346. var inlineValueTypes = [];
  23347. var blocks = [];
  23348. tooltipDims.length ? each(tooltipDims, function (dim) {
  23349. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  23350. })
  23351. // By default, all dims is used on tooltip.
  23352. : each(value, setEachItem);
  23353. function setEachItem(val, dim) {
  23354. var dimInfo = data.getDimensionInfo(dim);
  23355. // If `dimInfo.tooltip` is not set, show tooltip.
  23356. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  23357. return;
  23358. }
  23359. if (isValueMultipleLine) {
  23360. blocks.push(createTooltipMarkup('nameValue', {
  23361. markerType: 'subItem',
  23362. markerColor: colorStr,
  23363. name: dimInfo.displayName,
  23364. value: val,
  23365. valueType: dimInfo.type
  23366. }));
  23367. } else {
  23368. inlineValues.push(val);
  23369. inlineValueTypes.push(dimInfo.type);
  23370. }
  23371. }
  23372. return {
  23373. inlineValues: inlineValues,
  23374. inlineValueTypes: inlineValueTypes,
  23375. blocks: blocks
  23376. };
  23377. }
  23378. var inner$1 = makeInner();
  23379. function getSelectionKey(data, dataIndex) {
  23380. return data.getName(dataIndex) || data.getId(dataIndex);
  23381. }
  23382. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  23383. var SeriesModel = /** @class */function (_super) {
  23384. __extends(SeriesModel, _super);
  23385. function SeriesModel() {
  23386. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  23387. // the class members must not be initialized in constructor or declaration place.
  23388. // Otherwise there is bad case:
  23389. // class A {xxx = 1;}
  23390. // enableClassExtend(A);
  23391. // class B extends A {}
  23392. // var C = B.extend({xxx: 5});
  23393. // var c = new C();
  23394. // console.log(c.xxx); // expect 5 but always 1.
  23395. var _this = _super !== null && _super.apply(this, arguments) || this;
  23396. // ---------------------------------------
  23397. // Props about data selection
  23398. // ---------------------------------------
  23399. _this._selectedDataIndicesMap = {};
  23400. return _this;
  23401. }
  23402. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  23403. this.seriesIndex = this.componentIndex;
  23404. this.dataTask = createTask({
  23405. count: dataTaskCount,
  23406. reset: dataTaskReset
  23407. });
  23408. this.dataTask.context = {
  23409. model: this
  23410. };
  23411. this.mergeDefaultAndTheme(option, ecModel);
  23412. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  23413. sourceManager.prepareSource();
  23414. var data = this.getInitialData(option, ecModel);
  23415. wrapData(data, this);
  23416. this.dataTask.context.data = data;
  23417. if ("development" !== 'production') {
  23418. assert(data, 'getInitialData returned invalid data.');
  23419. }
  23420. inner$1(this).dataBeforeProcessed = data;
  23421. // If we reverse the order (make data firstly, and then make
  23422. // dataBeforeProcessed by cloneShallow), cloneShallow will
  23423. // cause data.graph.data !== data when using
  23424. // module:echarts/data/Graph or module:echarts/data/Tree.
  23425. // See module:echarts/data/helper/linkSeriesData
  23426. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  23427. // init or merge stage, because the data can be restored. So we do not `restoreData`
  23428. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  23429. // Call `seriesModel.getRawData()` instead.
  23430. // this.restoreData();
  23431. autoSeriesName(this);
  23432. this._initSelectedMapFromData(data);
  23433. };
  23434. /**
  23435. * Util for merge default and theme to option
  23436. */
  23437. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  23438. var layoutMode = fetchLayoutMode(this);
  23439. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  23440. // Backward compat: using subType on theme.
  23441. // But if name duplicate between series subType
  23442. // (for example: parallel) add component mainType,
  23443. // add suffix 'Series'.
  23444. var themeSubType = this.subType;
  23445. if (ComponentModel.hasClass(themeSubType)) {
  23446. themeSubType += 'Series';
  23447. }
  23448. merge(option, ecModel.getTheme().get(this.subType));
  23449. merge(option, this.getDefaultOption());
  23450. // Default label emphasis `show`
  23451. defaultEmphasis(option, 'label', ['show']);
  23452. this.fillDataTextStyle(option.data);
  23453. if (layoutMode) {
  23454. mergeLayoutParam(option, inputPositionParams, layoutMode);
  23455. }
  23456. };
  23457. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  23458. // this.settingTask.dirty();
  23459. newSeriesOption = merge(this.option, newSeriesOption, true);
  23460. this.fillDataTextStyle(newSeriesOption.data);
  23461. var layoutMode = fetchLayoutMode(this);
  23462. if (layoutMode) {
  23463. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  23464. }
  23465. var sourceManager = inner$1(this).sourceManager;
  23466. sourceManager.dirty();
  23467. sourceManager.prepareSource();
  23468. var data = this.getInitialData(newSeriesOption, ecModel);
  23469. wrapData(data, this);
  23470. this.dataTask.dirty();
  23471. this.dataTask.context.data = data;
  23472. inner$1(this).dataBeforeProcessed = data;
  23473. autoSeriesName(this);
  23474. this._initSelectedMapFromData(data);
  23475. };
  23476. SeriesModel.prototype.fillDataTextStyle = function (data) {
  23477. // Default data label emphasis `show`
  23478. // FIXME Tree structure data ?
  23479. // FIXME Performance ?
  23480. if (data && !isTypedArray(data)) {
  23481. var props = ['show'];
  23482. for (var i = 0; i < data.length; i++) {
  23483. if (data[i] && data[i].label) {
  23484. defaultEmphasis(data[i], 'label', props);
  23485. }
  23486. }
  23487. }
  23488. };
  23489. /**
  23490. * Init a data structure from data related option in series
  23491. * Must be overridden.
  23492. */
  23493. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  23494. return;
  23495. };
  23496. /**
  23497. * Append data to list
  23498. */
  23499. SeriesModel.prototype.appendData = function (params) {
  23500. // FIXME ???
  23501. // (1) If data from dataset, forbidden append.
  23502. // (2) support append data of dataset.
  23503. var data = this.getRawData();
  23504. data.appendData(params.data);
  23505. };
  23506. /**
  23507. * Consider some method like `filter`, `map` need make new data,
  23508. * We should make sure that `seriesModel.getData()` get correct
  23509. * data in the stream procedure. So we fetch data from upstream
  23510. * each time `task.perform` called.
  23511. */
  23512. SeriesModel.prototype.getData = function (dataType) {
  23513. var task = getCurrentTask(this);
  23514. if (task) {
  23515. var data = task.context.data;
  23516. return dataType == null || !data.getLinkedData ? data : data.getLinkedData(dataType);
  23517. } else {
  23518. // When series is not alive (that may happen when click toolbox
  23519. // restore or setOption with not merge mode), series data may
  23520. // be still need to judge animation or something when graphic
  23521. // elements want to know whether fade out.
  23522. return inner$1(this).data;
  23523. }
  23524. };
  23525. SeriesModel.prototype.getAllData = function () {
  23526. var mainData = this.getData();
  23527. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  23528. data: mainData
  23529. }];
  23530. };
  23531. SeriesModel.prototype.setData = function (data) {
  23532. var task = getCurrentTask(this);
  23533. if (task) {
  23534. var context = task.context;
  23535. // Consider case: filter, data sample.
  23536. // FIXME:TS never used, so comment it
  23537. // if (context.data !== data && task.modifyOutputEnd) {
  23538. // task.setOutputEnd(data.count());
  23539. // }
  23540. context.outputData = data;
  23541. // Caution: setData should update context.data,
  23542. // Because getData may be called multiply in a
  23543. // single stage and expect to get the data just
  23544. // set. (For example, AxisProxy, x y both call
  23545. // getData and setDate sequentially).
  23546. // So the context.data should be fetched from
  23547. // upstream each time when a stage starts to be
  23548. // performed.
  23549. if (task !== this.dataTask) {
  23550. context.data = data;
  23551. }
  23552. }
  23553. inner$1(this).data = data;
  23554. };
  23555. SeriesModel.prototype.getEncode = function () {
  23556. var encode = this.get('encode', true);
  23557. if (encode) {
  23558. return createHashMap(encode);
  23559. }
  23560. };
  23561. SeriesModel.prototype.getSourceManager = function () {
  23562. return inner$1(this).sourceManager;
  23563. };
  23564. SeriesModel.prototype.getSource = function () {
  23565. return this.getSourceManager().getSource();
  23566. };
  23567. /**
  23568. * Get data before processed
  23569. */
  23570. SeriesModel.prototype.getRawData = function () {
  23571. return inner$1(this).dataBeforeProcessed;
  23572. };
  23573. SeriesModel.prototype.getColorBy = function () {
  23574. var colorBy = this.get('colorBy');
  23575. return colorBy || 'series';
  23576. };
  23577. SeriesModel.prototype.isColorBySeries = function () {
  23578. return this.getColorBy() === 'series';
  23579. };
  23580. /**
  23581. * Get base axis if has coordinate system and has axis.
  23582. * By default use coordSys.getBaseAxis();
  23583. * Can be overridden for some chart.
  23584. * @return {type} description
  23585. */
  23586. SeriesModel.prototype.getBaseAxis = function () {
  23587. var coordSys = this.coordinateSystem;
  23588. // @ts-ignore
  23589. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  23590. };
  23591. /**
  23592. * Retrieve the index of nearest value in the view coordinate.
  23593. * Data position is compared with each axis's dataToCoord.
  23594. *
  23595. * @param axisDim axis dimension
  23596. * @param dim data dimension
  23597. * @param value
  23598. * @param [maxDistance=Infinity] The maximum distance in view coordinate space
  23599. * @return If and only if multiple indices has
  23600. * the same value, they are put to the result.
  23601. */
  23602. SeriesModel.prototype.indicesOfNearest = function (axisDim, dim, value, maxDistance) {
  23603. var data = this.getData();
  23604. var coordSys = this.coordinateSystem;
  23605. var axis = coordSys && coordSys.getAxis(axisDim);
  23606. if (!coordSys || !axis) {
  23607. return [];
  23608. }
  23609. var targetCoord = axis.dataToCoord(value);
  23610. if (maxDistance == null) {
  23611. maxDistance = Infinity;
  23612. }
  23613. var nearestIndices = [];
  23614. var minDist = Infinity;
  23615. var minDiff = -1;
  23616. var nearestIndicesLen = 0;
  23617. data.each(dim, function (dimValue, idx) {
  23618. var dataCoord = axis.dataToCoord(dimValue);
  23619. var diff = targetCoord - dataCoord;
  23620. var dist = Math.abs(diff);
  23621. if (dist <= maxDistance) {
  23622. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  23623. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  23624. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  23625. // So we choose the one that `diff >= 0` in this case.
  23626. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  23627. // should be push to `nearestIndices`.
  23628. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  23629. minDist = dist;
  23630. minDiff = diff;
  23631. nearestIndicesLen = 0;
  23632. }
  23633. if (diff === minDiff) {
  23634. nearestIndices[nearestIndicesLen++] = idx;
  23635. }
  23636. }
  23637. });
  23638. nearestIndices.length = nearestIndicesLen;
  23639. return nearestIndices;
  23640. };
  23641. /**
  23642. * Default tooltip formatter
  23643. *
  23644. * @param dataIndex
  23645. * @param multipleSeries
  23646. * @param dataType
  23647. * @param renderMode valid values: 'html'(by default) and 'richText'.
  23648. * 'html' is used for rendering tooltip in extra DOM form, and the result
  23649. * string is used as DOM HTML content.
  23650. * 'richText' is used for rendering tooltip in rich text form, for those where
  23651. * DOM operation is not supported.
  23652. * @return formatted tooltip with `html` and `markers`
  23653. * Notice: The override method can also return string
  23654. */
  23655. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  23656. return defaultSeriesFormatTooltip({
  23657. series: this,
  23658. dataIndex: dataIndex,
  23659. multipleSeries: multipleSeries
  23660. });
  23661. };
  23662. SeriesModel.prototype.isAnimationEnabled = function () {
  23663. var ecModel = this.ecModel;
  23664. // Disable animation if using echarts in node but not give ssr flag.
  23665. // In ssr mode, renderToString will generate svg with css animation.
  23666. if (env.node && !(ecModel && ecModel.ssr)) {
  23667. return false;
  23668. }
  23669. var animationEnabled = this.getShallow('animation');
  23670. if (animationEnabled) {
  23671. if (this.getData().count() > this.getShallow('animationThreshold')) {
  23672. animationEnabled = false;
  23673. }
  23674. }
  23675. return !!animationEnabled;
  23676. };
  23677. SeriesModel.prototype.restoreData = function () {
  23678. this.dataTask.dirty();
  23679. };
  23680. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  23681. var ecModel = this.ecModel;
  23682. // PENDING
  23683. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  23684. if (!color) {
  23685. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  23686. }
  23687. return color;
  23688. };
  23689. /**
  23690. * Use `data.mapDimensionsAll(coordDim)` instead.
  23691. * @deprecated
  23692. */
  23693. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  23694. return this.getRawData().mapDimensionsAll(coordDim);
  23695. };
  23696. /**
  23697. * Get progressive rendering count each step
  23698. */
  23699. SeriesModel.prototype.getProgressive = function () {
  23700. return this.get('progressive');
  23701. };
  23702. /**
  23703. * Get progressive rendering count each step
  23704. */
  23705. SeriesModel.prototype.getProgressiveThreshold = function () {
  23706. return this.get('progressiveThreshold');
  23707. };
  23708. // PENGING If selectedMode is null ?
  23709. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  23710. this._innerSelect(this.getData(dataType), innerDataIndices);
  23711. };
  23712. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  23713. var selectedMap = this.option.selectedMap;
  23714. if (!selectedMap) {
  23715. return;
  23716. }
  23717. var selectedMode = this.option.selectedMode;
  23718. var data = this.getData(dataType);
  23719. if (selectedMode === 'series' || selectedMap === 'all') {
  23720. this.option.selectedMap = {};
  23721. this._selectedDataIndicesMap = {};
  23722. return;
  23723. }
  23724. for (var i = 0; i < innerDataIndices.length; i++) {
  23725. var dataIndex = innerDataIndices[i];
  23726. var nameOrId = getSelectionKey(data, dataIndex);
  23727. selectedMap[nameOrId] = false;
  23728. this._selectedDataIndicesMap[nameOrId] = -1;
  23729. }
  23730. };
  23731. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  23732. var tmpArr = [];
  23733. for (var i = 0; i < innerDataIndices.length; i++) {
  23734. tmpArr[0] = innerDataIndices[i];
  23735. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  23736. }
  23737. };
  23738. SeriesModel.prototype.getSelectedDataIndices = function () {
  23739. if (this.option.selectedMap === 'all') {
  23740. return [].slice.call(this.getData().getIndices());
  23741. }
  23742. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  23743. var nameOrIds = keys(selectedDataIndicesMap);
  23744. var dataIndices = [];
  23745. for (var i = 0; i < nameOrIds.length; i++) {
  23746. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  23747. if (dataIndex >= 0) {
  23748. dataIndices.push(dataIndex);
  23749. }
  23750. }
  23751. return dataIndices;
  23752. };
  23753. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  23754. var selectedMap = this.option.selectedMap;
  23755. if (!selectedMap) {
  23756. return false;
  23757. }
  23758. var data = this.getData(dataType);
  23759. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  23760. };
  23761. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  23762. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  23763. return true;
  23764. }
  23765. var universalTransitionOpt = this.option.universalTransition;
  23766. // Quick reject
  23767. if (!universalTransitionOpt) {
  23768. return false;
  23769. }
  23770. if (universalTransitionOpt === true) {
  23771. return true;
  23772. }
  23773. // Can be simply 'universalTransition: true'
  23774. return universalTransitionOpt && universalTransitionOpt.enabled;
  23775. };
  23776. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  23777. var _a, _b;
  23778. var option = this.option;
  23779. var selectedMode = option.selectedMode;
  23780. var len = innerDataIndices.length;
  23781. if (!selectedMode || !len) {
  23782. return;
  23783. }
  23784. if (selectedMode === 'series') {
  23785. option.selectedMap = 'all';
  23786. } else if (selectedMode === 'multiple') {
  23787. if (!isObject(option.selectedMap)) {
  23788. option.selectedMap = {};
  23789. }
  23790. var selectedMap = option.selectedMap;
  23791. for (var i = 0; i < len; i++) {
  23792. var dataIndex = innerDataIndices[i];
  23793. // TODO different types of data share same object.
  23794. var nameOrId = getSelectionKey(data, dataIndex);
  23795. selectedMap[nameOrId] = true;
  23796. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  23797. }
  23798. } else if (selectedMode === 'single' || selectedMode === true) {
  23799. var lastDataIndex = innerDataIndices[len - 1];
  23800. var nameOrId = getSelectionKey(data, lastDataIndex);
  23801. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  23802. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  23803. }
  23804. };
  23805. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  23806. // Ignore select info in data if selectedMap exists.
  23807. // NOTE It's only for legacy usage. edge data is not supported.
  23808. if (this.option.selectedMap) {
  23809. return;
  23810. }
  23811. var dataIndices = [];
  23812. if (data.hasItemOption) {
  23813. data.each(function (idx) {
  23814. var rawItem = data.getRawDataItem(idx);
  23815. if (rawItem && rawItem.selected) {
  23816. dataIndices.push(idx);
  23817. }
  23818. });
  23819. }
  23820. if (dataIndices.length > 0) {
  23821. this._innerSelect(data, dataIndices);
  23822. }
  23823. };
  23824. // /**
  23825. // * @see {module:echarts/stream/Scheduler}
  23826. // */
  23827. // abstract pipeTask: null
  23828. SeriesModel.registerClass = function (clz) {
  23829. return ComponentModel.registerClass(clz);
  23830. };
  23831. SeriesModel.protoInitialize = function () {
  23832. var proto = SeriesModel.prototype;
  23833. proto.type = 'series.__base__';
  23834. proto.seriesIndex = 0;
  23835. proto.ignoreStyleOnData = false;
  23836. proto.hasSymbolVisual = false;
  23837. proto.defaultSymbol = 'circle';
  23838. // Make sure the values can be accessed!
  23839. proto.visualStyleAccessPath = 'itemStyle';
  23840. proto.visualDrawType = 'fill';
  23841. }();
  23842. return SeriesModel;
  23843. }(ComponentModel);
  23844. mixin(SeriesModel, DataFormatMixin);
  23845. mixin(SeriesModel, PaletteMixin);
  23846. mountExtend(SeriesModel, ComponentModel);
  23847. /**
  23848. * MUST be called after `prepareSource` called
  23849. * Here we need to make auto series, especially for auto legend. But we
  23850. * do not modify series.name in option to avoid side effects.
  23851. */
  23852. function autoSeriesName(seriesModel) {
  23853. // User specified name has higher priority, otherwise it may cause
  23854. // series can not be queried unexpectedly.
  23855. var name = seriesModel.name;
  23856. if (!isNameSpecified(seriesModel)) {
  23857. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  23858. }
  23859. }
  23860. function getSeriesAutoName(seriesModel) {
  23861. var data = seriesModel.getRawData();
  23862. var dataDims = data.mapDimensionsAll('seriesName');
  23863. var nameArr = [];
  23864. each(dataDims, function (dataDim) {
  23865. var dimInfo = data.getDimensionInfo(dataDim);
  23866. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  23867. });
  23868. return nameArr.join(' ');
  23869. }
  23870. function dataTaskCount(context) {
  23871. return context.model.getRawData().count();
  23872. }
  23873. function dataTaskReset(context) {
  23874. var seriesModel = context.model;
  23875. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  23876. return dataTaskProgress;
  23877. }
  23878. function dataTaskProgress(param, context) {
  23879. // Avoid repeat cloneShallow when data just created in reset.
  23880. if (context.outputData && param.end > context.outputData.count()) {
  23881. context.model.getRawData().cloneShallow(context.outputData);
  23882. }
  23883. }
  23884. // TODO refactor
  23885. function wrapData(data, seriesModel) {
  23886. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  23887. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  23888. });
  23889. }
  23890. function onDataChange(seriesModel, newList) {
  23891. var task = getCurrentTask(seriesModel);
  23892. if (task) {
  23893. // Consider case: filter, selectRange
  23894. task.setOutputEnd((newList || this).count());
  23895. }
  23896. return newList;
  23897. }
  23898. function getCurrentTask(seriesModel) {
  23899. var scheduler = (seriesModel.ecModel || {}).scheduler;
  23900. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  23901. if (pipeline) {
  23902. // When pipline finished, the currrentTask keep the last
  23903. // task (renderTask).
  23904. var task = pipeline.currentTask;
  23905. if (task) {
  23906. var agentStubMap = task.agentStubMap;
  23907. if (agentStubMap) {
  23908. task = agentStubMap.get(seriesModel.uid);
  23909. }
  23910. }
  23911. return task;
  23912. }
  23913. }
  23914. var ComponentView = /** @class */function () {
  23915. function ComponentView() {
  23916. this.group = new Group();
  23917. this.uid = getUID('viewComponent');
  23918. }
  23919. ComponentView.prototype.init = function (ecModel, api) {};
  23920. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  23921. ComponentView.prototype.dispose = function (ecModel, api) {};
  23922. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {
  23923. // Do nothing;
  23924. };
  23925. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {
  23926. // Do nothing;
  23927. };
  23928. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {
  23929. // Do nothing;
  23930. };
  23931. /**
  23932. * Hook for toggle blur target series.
  23933. * Can be used in marker for blur or leave blur the markers
  23934. */
  23935. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {
  23936. // Do nothing;
  23937. };
  23938. /**
  23939. * Traverse the new rendered elements.
  23940. *
  23941. * It will traverse the new added element in progressive rendering.
  23942. * And traverse all in normal rendering.
  23943. */
  23944. ComponentView.prototype.eachRendered = function (cb) {
  23945. var group = this.group;
  23946. if (group) {
  23947. group.traverse(cb);
  23948. }
  23949. };
  23950. return ComponentView;
  23951. }();
  23952. enableClassExtend(ComponentView);
  23953. enableClassManagement(ComponentView);
  23954. /**
  23955. * @return {string} If large mode changed, return string 'reset';
  23956. */
  23957. function createRenderPlanner() {
  23958. var inner = makeInner();
  23959. return function (seriesModel) {
  23960. var fields = inner(seriesModel);
  23961. var pipelineContext = seriesModel.pipelineContext;
  23962. var originalLarge = !!fields.large;
  23963. var originalProgressive = !!fields.progressiveRender;
  23964. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  23965. // exists. See #11611 . Probably we need to modify this structure, see the comment
  23966. // on `performRawSeries` in `Schedular.js`.
  23967. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  23968. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  23969. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  23970. };
  23971. }
  23972. var inner$2 = makeInner();
  23973. var renderPlanner = createRenderPlanner();
  23974. var ChartView = /** @class */function () {
  23975. function ChartView() {
  23976. this.group = new Group();
  23977. this.uid = getUID('viewChart');
  23978. this.renderTask = createTask({
  23979. plan: renderTaskPlan,
  23980. reset: renderTaskReset
  23981. });
  23982. this.renderTask.context = {
  23983. view: this
  23984. };
  23985. }
  23986. ChartView.prototype.init = function (ecModel, api) {};
  23987. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  23988. if ("development" !== 'production') {
  23989. throw new Error('render method must been implemented');
  23990. }
  23991. };
  23992. /**
  23993. * Highlight series or specified data item.
  23994. */
  23995. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  23996. var data = seriesModel.getData(payload && payload.dataType);
  23997. if (!data) {
  23998. if ("development" !== 'production') {
  23999. error("Unknown dataType " + payload.dataType);
  24000. }
  24001. return;
  24002. }
  24003. toggleHighlight(data, payload, 'emphasis');
  24004. };
  24005. /**
  24006. * Downplay series or specified data item.
  24007. */
  24008. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  24009. var data = seriesModel.getData(payload && payload.dataType);
  24010. if (!data) {
  24011. if ("development" !== 'production') {
  24012. error("Unknown dataType " + payload.dataType);
  24013. }
  24014. return;
  24015. }
  24016. toggleHighlight(data, payload, 'normal');
  24017. };
  24018. /**
  24019. * Remove self.
  24020. */
  24021. ChartView.prototype.remove = function (ecModel, api) {
  24022. this.group.removeAll();
  24023. };
  24024. /**
  24025. * Dispose self.
  24026. */
  24027. ChartView.prototype.dispose = function (ecModel, api) {};
  24028. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  24029. this.render(seriesModel, ecModel, api, payload);
  24030. };
  24031. // FIXME never used?
  24032. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  24033. this.render(seriesModel, ecModel, api, payload);
  24034. };
  24035. // FIXME never used?
  24036. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  24037. this.render(seriesModel, ecModel, api, payload);
  24038. };
  24039. /**
  24040. * Traverse the new rendered elements.
  24041. *
  24042. * It will traverse the new added element in progressive rendering.
  24043. * And traverse all in normal rendering.
  24044. */
  24045. ChartView.prototype.eachRendered = function (cb) {
  24046. traverseElements(this.group, cb);
  24047. };
  24048. ChartView.markUpdateMethod = function (payload, methodName) {
  24049. inner$2(payload).updateMethod = methodName;
  24050. };
  24051. ChartView.protoInitialize = function () {
  24052. var proto = ChartView.prototype;
  24053. proto.type = 'chart';
  24054. }();
  24055. return ChartView;
  24056. }();
  24057. /**
  24058. * Set state of single element
  24059. */
  24060. function elSetState(el, state, highlightDigit) {
  24061. if (el && isHighDownDispatcher(el)) {
  24062. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  24063. }
  24064. }
  24065. function toggleHighlight(data, payload, state) {
  24066. var dataIndex = queryDataIndex(data, payload);
  24067. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  24068. if (dataIndex != null) {
  24069. each(normalizeToArray(dataIndex), function (dataIdx) {
  24070. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  24071. });
  24072. } else {
  24073. data.eachItemGraphicEl(function (el) {
  24074. elSetState(el, state, highlightDigit);
  24075. });
  24076. }
  24077. }
  24078. enableClassExtend(ChartView, ['dispose']);
  24079. enableClassManagement(ChartView);
  24080. function renderTaskPlan(context) {
  24081. return renderPlanner(context.model);
  24082. }
  24083. function renderTaskReset(context) {
  24084. var seriesModel = context.model;
  24085. var ecModel = context.ecModel;
  24086. var api = context.api;
  24087. var payload = context.payload;
  24088. // FIXME: remove updateView updateVisual
  24089. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  24090. var view = context.view;
  24091. var updateMethod = payload && inner$2(payload).updateMethod;
  24092. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod
  24093. // `appendData` is also supported when data amount
  24094. // is less than progressive threshold.
  24095. : 'render';
  24096. if (methodName !== 'render') {
  24097. view[methodName](seriesModel, ecModel, api, payload);
  24098. }
  24099. return progressMethodMap[methodName];
  24100. }
  24101. var progressMethodMap = {
  24102. incrementalPrepareRender: {
  24103. progress: function (params, context) {
  24104. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  24105. }
  24106. },
  24107. render: {
  24108. // Put view.render in `progress` to support appendData. But in this case
  24109. // view.render should not be called in reset, otherwise it will be called
  24110. // twise. Use `forceFirstProgress` to make sure that view.render is called
  24111. // in any cases.
  24112. forceFirstProgress: true,
  24113. progress: function (params, context) {
  24114. context.view.render(context.model, context.ecModel, context.api, context.payload);
  24115. }
  24116. }
  24117. };
  24118. /*
  24119. * Licensed to the Apache Software Foundation (ASF) under one
  24120. * or more contributor license agreements. See the NOTICE file
  24121. * distributed with this work for additional information
  24122. * regarding copyright ownership. The ASF licenses this file
  24123. * to you under the Apache License, Version 2.0 (the
  24124. * "License"); you may not use this file except in compliance
  24125. * with the License. You may obtain a copy of the License at
  24126. *
  24127. * http://www.apache.org/licenses/LICENSE-2.0
  24128. *
  24129. * Unless required by applicable law or agreed to in writing,
  24130. * software distributed under the License is distributed on an
  24131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24132. * KIND, either express or implied. See the License for the
  24133. * specific language governing permissions and limitations
  24134. * under the License.
  24135. */
  24136. /**
  24137. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24138. */
  24139. /*
  24140. * Licensed to the Apache Software Foundation (ASF) under one
  24141. * or more contributor license agreements. See the NOTICE file
  24142. * distributed with this work for additional information
  24143. * regarding copyright ownership. The ASF licenses this file
  24144. * to you under the Apache License, Version 2.0 (the
  24145. * "License"); you may not use this file except in compliance
  24146. * with the License. You may obtain a copy of the License at
  24147. *
  24148. * http://www.apache.org/licenses/LICENSE-2.0
  24149. *
  24150. * Unless required by applicable law or agreed to in writing,
  24151. * software distributed under the License is distributed on an
  24152. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24153. * KIND, either express or implied. See the License for the
  24154. * specific language governing permissions and limitations
  24155. * under the License.
  24156. */
  24157. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  24158. var RATE = '\0__throttleRate';
  24159. var THROTTLE_TYPE = '\0__throttleType';
  24160. /**
  24161. * @public
  24162. * @param {(Function)} fn
  24163. * @param {number} [delay=0] Unit: ms.
  24164. * @param {boolean} [debounce=false]
  24165. * true: If call interval less than `delay`, only the last call works.
  24166. * false: If call interval less than `delay, call works on fixed rate.
  24167. * @return {(Function)} throttled fn.
  24168. */
  24169. function throttle(fn, delay, debounce) {
  24170. var currCall;
  24171. var lastCall = 0;
  24172. var lastExec = 0;
  24173. var timer = null;
  24174. var diff;
  24175. var scope;
  24176. var args;
  24177. var debounceNextCall;
  24178. delay = delay || 0;
  24179. function exec() {
  24180. lastExec = new Date().getTime();
  24181. timer = null;
  24182. fn.apply(scope, args || []);
  24183. }
  24184. var cb = function () {
  24185. var cbArgs = [];
  24186. for (var _i = 0; _i < arguments.length; _i++) {
  24187. cbArgs[_i] = arguments[_i];
  24188. }
  24189. currCall = new Date().getTime();
  24190. scope = this;
  24191. args = cbArgs;
  24192. var thisDelay = debounceNextCall || delay;
  24193. var thisDebounce = debounceNextCall || debounce;
  24194. debounceNextCall = null;
  24195. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  24196. clearTimeout(timer);
  24197. // Here we should make sure that: the `exec` SHOULD NOT be called later
  24198. // than a new call of `cb`, that is, preserving the command order. Consider
  24199. // calculating "scale rate" when roaming as an example. When a call of `cb`
  24200. // happens, either the `exec` is called dierectly, or the call is delayed.
  24201. // But the delayed call should never be later than next call of `cb`. Under
  24202. // this assurance, we can simply update view state each time `dispatchAction`
  24203. // triggered by user roaming, but not need to add extra code to avoid the
  24204. // state being "rolled-back".
  24205. if (thisDebounce) {
  24206. timer = setTimeout(exec, thisDelay);
  24207. } else {
  24208. if (diff >= 0) {
  24209. exec();
  24210. } else {
  24211. timer = setTimeout(exec, -diff);
  24212. }
  24213. }
  24214. lastCall = currCall;
  24215. };
  24216. /**
  24217. * Clear throttle.
  24218. * @public
  24219. */
  24220. cb.clear = function () {
  24221. if (timer) {
  24222. clearTimeout(timer);
  24223. timer = null;
  24224. }
  24225. };
  24226. /**
  24227. * Enable debounce once.
  24228. */
  24229. cb.debounceNextCall = function (debounceDelay) {
  24230. debounceNextCall = debounceDelay;
  24231. };
  24232. return cb;
  24233. }
  24234. /**
  24235. * Create throttle method or update throttle rate.
  24236. *
  24237. * @example
  24238. * ComponentView.prototype.render = function () {
  24239. * ...
  24240. * throttle.createOrUpdate(
  24241. * this,
  24242. * '_dispatchAction',
  24243. * this.model.get('throttle'),
  24244. * 'fixRate'
  24245. * );
  24246. * };
  24247. * ComponentView.prototype.remove = function () {
  24248. * throttle.clear(this, '_dispatchAction');
  24249. * };
  24250. * ComponentView.prototype.dispose = function () {
  24251. * throttle.clear(this, '_dispatchAction');
  24252. * };
  24253. *
  24254. */
  24255. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  24256. var fn = obj[fnAttr];
  24257. if (!fn) {
  24258. return;
  24259. }
  24260. var originFn = fn[ORIGIN_METHOD] || fn;
  24261. var lastThrottleType = fn[THROTTLE_TYPE];
  24262. var lastRate = fn[RATE];
  24263. if (lastRate !== rate || lastThrottleType !== throttleType) {
  24264. if (rate == null || !throttleType) {
  24265. return obj[fnAttr] = originFn;
  24266. }
  24267. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  24268. fn[ORIGIN_METHOD] = originFn;
  24269. fn[THROTTLE_TYPE] = throttleType;
  24270. fn[RATE] = rate;
  24271. }
  24272. return fn;
  24273. }
  24274. /**
  24275. * Clear throttle. Example see throttle.createOrUpdate.
  24276. */
  24277. function clear(obj, fnAttr) {
  24278. var fn = obj[fnAttr];
  24279. if (fn && fn[ORIGIN_METHOD]) {
  24280. // Clear throttle
  24281. fn.clear && fn.clear();
  24282. obj[fnAttr] = fn[ORIGIN_METHOD];
  24283. }
  24284. }
  24285. var inner$3 = makeInner();
  24286. var defaultStyleMappers = {
  24287. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  24288. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  24289. };
  24290. var defaultColorKey = {
  24291. lineStyle: 'stroke',
  24292. itemStyle: 'fill'
  24293. };
  24294. function getStyleMapper(seriesModel, stylePath) {
  24295. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  24296. if (!styleMapper) {
  24297. console.warn("Unknown style type '" + stylePath + "'.");
  24298. return defaultStyleMappers.itemStyle;
  24299. }
  24300. return styleMapper;
  24301. }
  24302. function getDefaultColorKey(seriesModel, stylePath) {
  24303. // return defaultColorKey[stylePath] ||
  24304. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  24305. if (!colorKey) {
  24306. console.warn("Unknown style type '" + stylePath + "'.");
  24307. return 'fill';
  24308. }
  24309. return colorKey;
  24310. }
  24311. var seriesStyleTask = {
  24312. createOnAllSeries: true,
  24313. performRawSeries: true,
  24314. reset: function (seriesModel, ecModel) {
  24315. var data = seriesModel.getData();
  24316. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  24317. // Set in itemStyle
  24318. var styleModel = seriesModel.getModel(stylePath);
  24319. var getStyle = getStyleMapper(seriesModel, stylePath);
  24320. var globalStyle = getStyle(styleModel);
  24321. var decalOption = styleModel.getShallow('decal');
  24322. if (decalOption) {
  24323. data.setVisual('decal', decalOption);
  24324. decalOption.dirty = true;
  24325. }
  24326. // TODO
  24327. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  24328. var color = globalStyle[colorKey];
  24329. // TODO style callback
  24330. var colorCallback = isFunction(color) ? color : null;
  24331. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto';
  24332. // Get from color palette by default.
  24333. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  24334. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  24335. // make it effect palette. Because some scenarios users need to make some series
  24336. // transparent or as background, which should better not effect the palette.
  24337. var colorPalette = seriesModel.getColorFromPalette(
  24338. // TODO series count changed.
  24339. seriesModel.name, null, ecModel.getSeriesCount());
  24340. if (!globalStyle[colorKey]) {
  24341. globalStyle[colorKey] = colorPalette;
  24342. data.setVisual('colorFromPalette', true);
  24343. }
  24344. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  24345. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  24346. }
  24347. data.setVisual('style', globalStyle);
  24348. data.setVisual('drawType', colorKey);
  24349. // Only visible series has each data be visual encoded
  24350. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  24351. data.setVisual('colorFromPalette', false);
  24352. return {
  24353. dataEach: function (data, idx) {
  24354. var dataParams = seriesModel.getDataParams(idx);
  24355. var itemStyle = extend({}, globalStyle);
  24356. itemStyle[colorKey] = colorCallback(dataParams);
  24357. data.setItemVisual(idx, 'style', itemStyle);
  24358. }
  24359. };
  24360. }
  24361. }
  24362. };
  24363. var sharedModel = new Model();
  24364. var dataStyleTask = {
  24365. createOnAllSeries: true,
  24366. performRawSeries: true,
  24367. reset: function (seriesModel, ecModel) {
  24368. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  24369. return;
  24370. }
  24371. var data = seriesModel.getData();
  24372. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  24373. // Set in itemStyle
  24374. var getStyle = getStyleMapper(seriesModel, stylePath);
  24375. var colorKey = data.getVisual('drawType');
  24376. return {
  24377. dataEach: data.hasItemOption ? function (data, idx) {
  24378. // Not use getItemModel for performance considuration
  24379. var rawItem = data.getRawDataItem(idx);
  24380. if (rawItem && rawItem[stylePath]) {
  24381. sharedModel.option = rawItem[stylePath];
  24382. var style = getStyle(sharedModel);
  24383. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  24384. extend(existsStyle, style);
  24385. if (sharedModel.option.decal) {
  24386. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  24387. sharedModel.option.decal.dirty = true;
  24388. }
  24389. if (colorKey in style) {
  24390. data.setItemVisual(idx, 'colorFromPalette', false);
  24391. }
  24392. }
  24393. } : null
  24394. };
  24395. }
  24396. };
  24397. // Pick color from palette for the data which has not been set with color yet.
  24398. // Note: do not support stream rendering. No such cases yet.
  24399. var dataColorPaletteTask = {
  24400. performRawSeries: true,
  24401. overallReset: function (ecModel) {
  24402. // Each type of series uses one scope.
  24403. // Pie and funnel are using different scopes.
  24404. var paletteScopeGroupByType = createHashMap();
  24405. ecModel.eachSeries(function (seriesModel) {
  24406. var colorBy = seriesModel.getColorBy();
  24407. if (seriesModel.isColorBySeries()) {
  24408. return;
  24409. }
  24410. var key = seriesModel.type + '-' + colorBy;
  24411. var colorScope = paletteScopeGroupByType.get(key);
  24412. if (!colorScope) {
  24413. colorScope = {};
  24414. paletteScopeGroupByType.set(key, colorScope);
  24415. }
  24416. inner$3(seriesModel).scope = colorScope;
  24417. });
  24418. ecModel.eachSeries(function (seriesModel) {
  24419. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  24420. return;
  24421. }
  24422. var dataAll = seriesModel.getRawData();
  24423. var idxMap = {};
  24424. var data = seriesModel.getData();
  24425. var colorScope = inner$3(seriesModel).scope;
  24426. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  24427. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  24428. data.each(function (idx) {
  24429. var rawIdx = data.getRawIndex(idx);
  24430. idxMap[rawIdx] = idx;
  24431. });
  24432. // Iterate on data before filtered. To make sure color from palette can be
  24433. // Consistent when toggling legend.
  24434. dataAll.each(function (rawIdx) {
  24435. var idx = idxMap[rawIdx];
  24436. var fromPalette = data.getItemVisual(idx, 'colorFromPalette');
  24437. // Get color from palette for each data only when the color is inherited from series color, which is
  24438. // also picked from color palette. So following situation is not in the case:
  24439. // 1. series.itemStyle.color is set
  24440. // 2. color is encoded by visualMap
  24441. if (fromPalette) {
  24442. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  24443. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  24444. var dataCount = dataAll.count();
  24445. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  24446. }
  24447. });
  24448. });
  24449. }
  24450. };
  24451. var PI$3 = Math.PI;
  24452. /**
  24453. * @param {module:echarts/ExtensionAPI} api
  24454. * @param {Object} [opts]
  24455. * @param {string} [opts.text]
  24456. * @param {string} [opts.color]
  24457. * @param {string} [opts.textColor]
  24458. * @return {module:zrender/Element}
  24459. */
  24460. function defaultLoading(api, opts) {
  24461. opts = opts || {};
  24462. defaults(opts, {
  24463. text: 'loading',
  24464. textColor: tokens.color.primary,
  24465. fontSize: 12,
  24466. fontWeight: 'normal',
  24467. fontStyle: 'normal',
  24468. fontFamily: 'sans-serif',
  24469. maskColor: 'rgba(255,255,255,0.8)',
  24470. showSpinner: true,
  24471. color: tokens.color.theme[0],
  24472. spinnerRadius: 10,
  24473. lineWidth: 5,
  24474. zlevel: 0
  24475. });
  24476. var group = new Group();
  24477. var mask = new Rect({
  24478. style: {
  24479. fill: opts.maskColor
  24480. },
  24481. zlevel: opts.zlevel,
  24482. z: 10000
  24483. });
  24484. group.add(mask);
  24485. var textContent = new ZRText({
  24486. style: {
  24487. text: opts.text,
  24488. fill: opts.textColor,
  24489. fontSize: opts.fontSize,
  24490. fontWeight: opts.fontWeight,
  24491. fontStyle: opts.fontStyle,
  24492. fontFamily: opts.fontFamily
  24493. },
  24494. zlevel: opts.zlevel,
  24495. z: 10001
  24496. });
  24497. var labelRect = new Rect({
  24498. style: {
  24499. fill: 'none'
  24500. },
  24501. textContent: textContent,
  24502. textConfig: {
  24503. position: 'right',
  24504. distance: 10
  24505. },
  24506. zlevel: opts.zlevel,
  24507. z: 10001
  24508. });
  24509. group.add(labelRect);
  24510. var arc;
  24511. if (opts.showSpinner) {
  24512. arc = new Arc({
  24513. shape: {
  24514. startAngle: -PI$3 / 2,
  24515. endAngle: -PI$3 / 2 + 0.1,
  24516. r: opts.spinnerRadius
  24517. },
  24518. style: {
  24519. stroke: opts.color,
  24520. lineCap: 'round',
  24521. lineWidth: opts.lineWidth
  24522. },
  24523. zlevel: opts.zlevel,
  24524. z: 10001
  24525. });
  24526. arc.animateShape(true).when(1000, {
  24527. endAngle: PI$3 * 3 / 2
  24528. }).start('circularInOut');
  24529. arc.animateShape(true).when(1000, {
  24530. startAngle: PI$3 * 3 / 2
  24531. }).delay(300).start('circularInOut');
  24532. group.add(arc);
  24533. }
  24534. // Inject resize
  24535. group.resize = function () {
  24536. var textWidth = textContent.getBoundingRect().width;
  24537. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  24538. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  24539. // textDistance needs to be calculated when both animation and text exist
  24540. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2)
  24541. // only show the text
  24542. + (opts.showSpinner ? 0 : textWidth / 2)
  24543. // only show the spinner
  24544. + (textWidth ? 0 : r);
  24545. var cy = api.getHeight() / 2;
  24546. opts.showSpinner && arc.setShape({
  24547. cx: cx,
  24548. cy: cy
  24549. });
  24550. labelRect.setShape({
  24551. x: cx - r,
  24552. y: cy - r,
  24553. width: r * 2,
  24554. height: r * 2
  24555. });
  24556. mask.setShape({
  24557. x: 0,
  24558. y: 0,
  24559. width: api.getWidth(),
  24560. height: api.getHeight()
  24561. });
  24562. };
  24563. group.resize();
  24564. return group;
  24565. }
  24566. var Scheduler = /** @class */function () {
  24567. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  24568. // key: handlerUID
  24569. this._stageTaskMap = createHashMap();
  24570. this.ecInstance = ecInstance;
  24571. this.api = api;
  24572. // Fix current processors in case that in some rear cases that
  24573. // processors might be registered after echarts instance created.
  24574. // Register processors incrementally for a echarts instance is
  24575. // not supported by this stream architecture.
  24576. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  24577. visualHandlers = this._visualHandlers = visualHandlers.slice();
  24578. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  24579. }
  24580. Scheduler.prototype.restoreData = function (ecModel, payload) {
  24581. // TODO: Only restore needed series and components, but not all components.
  24582. // Currently `restoreData` of all of the series and component will be called.
  24583. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  24584. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  24585. // and some components like coordinate system, axes, dataZoom, visualMap only
  24586. // need their target series refresh.
  24587. // (1) If we are implementing this feature some day, we should consider these cases:
  24588. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  24589. // on the settings of `dataZoom`), it should be re-performed if the component
  24590. // is modified by `setOption`.
  24591. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  24592. // it should be re-performed when the result array of `getTargetSeries` changed.
  24593. // We use `dependencies` to cover these issues.
  24594. // (3) How to update target series when coordinate system related components modified.
  24595. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  24596. // and this case all of the tasks will be set as dirty.
  24597. ecModel.restoreData(payload);
  24598. // Theoretically an overall task not only depends on each of its target series, but also
  24599. // depends on all of the series.
  24600. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  24601. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  24602. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  24603. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  24604. // probably cause state chaos (consider `dataZoomProcessor`).
  24605. this._stageTaskMap.each(function (taskRecord) {
  24606. var overallTask = taskRecord.overallTask;
  24607. overallTask && overallTask.dirty();
  24608. });
  24609. };
  24610. // If seriesModel provided, incremental threshold is check by series data.
  24611. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  24612. // For overall task
  24613. if (!task.__pipeline) {
  24614. return;
  24615. }
  24616. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  24617. var pCtx = pipeline.context;
  24618. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  24619. var step = incremental ? pipeline.step : null;
  24620. var modDataCount = pCtx && pCtx.modDataCount;
  24621. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  24622. return {
  24623. step: step,
  24624. modBy: modBy,
  24625. modDataCount: modDataCount
  24626. };
  24627. };
  24628. Scheduler.prototype.getPipeline = function (pipelineId) {
  24629. return this._pipelineMap.get(pipelineId);
  24630. };
  24631. /**
  24632. * Current, progressive rendering starts from visual and layout.
  24633. * Always detect render mode in the same stage, avoiding that incorrect
  24634. * detection caused by data filtering.
  24635. * Caution:
  24636. * `updateStreamModes` use `seriesModel.getData()`.
  24637. */
  24638. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  24639. var pipeline = this._pipelineMap.get(seriesModel.uid);
  24640. var data = seriesModel.getData();
  24641. var dataLen = data.count();
  24642. // `progressiveRender` means that can render progressively in each
  24643. // animation frame. Note that some types of series do not provide
  24644. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  24645. // use the term `incremental` but not `progressive` to describe the
  24646. // case that `chart.appendData`.
  24647. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  24648. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  24649. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  24650. // see `test/candlestick-large3.html`
  24651. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  24652. seriesModel.pipelineContext = pipeline.context = {
  24653. progressiveRender: progressiveRender,
  24654. modDataCount: modDataCount,
  24655. large: large
  24656. };
  24657. };
  24658. Scheduler.prototype.restorePipelines = function (ecModel) {
  24659. var scheduler = this;
  24660. var pipelineMap = scheduler._pipelineMap = createHashMap();
  24661. ecModel.eachSeries(function (seriesModel) {
  24662. var progressive = seriesModel.getProgressive();
  24663. var pipelineId = seriesModel.uid;
  24664. pipelineMap.set(pipelineId, {
  24665. id: pipelineId,
  24666. head: null,
  24667. tail: null,
  24668. threshold: seriesModel.getProgressiveThreshold(),
  24669. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  24670. blockIndex: -1,
  24671. step: Math.round(progressive || 700),
  24672. count: 0
  24673. });
  24674. scheduler._pipe(seriesModel, seriesModel.dataTask);
  24675. });
  24676. };
  24677. Scheduler.prototype.prepareStageTasks = function () {
  24678. var stageTaskMap = this._stageTaskMap;
  24679. var ecModel = this.api.getModel();
  24680. var api = this.api;
  24681. each(this._allHandlers, function (handler) {
  24682. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  24683. var errMsg = '';
  24684. if ("development" !== 'production') {
  24685. // Currently do not need to support to sepecify them both.
  24686. errMsg = '"reset" and "overallReset" must not be both specified.';
  24687. }
  24688. assert(!(handler.reset && handler.overallReset), errMsg);
  24689. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  24690. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  24691. }, this);
  24692. };
  24693. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  24694. var renderTask = view.renderTask;
  24695. var context = renderTask.context;
  24696. context.model = model;
  24697. context.ecModel = ecModel;
  24698. context.api = api;
  24699. renderTask.__block = !view.incrementalPrepareRender;
  24700. this._pipe(model, renderTask);
  24701. };
  24702. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  24703. // If we do not use `block` here, it should be considered when to update modes.
  24704. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  24705. block: true
  24706. });
  24707. };
  24708. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  24709. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  24710. };
  24711. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  24712. opt = opt || {};
  24713. var unfinished = false;
  24714. var scheduler = this;
  24715. each(stageHandlers, function (stageHandler, idx) {
  24716. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  24717. return;
  24718. }
  24719. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  24720. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  24721. var overallTask = stageHandlerRecord.overallTask;
  24722. if (overallTask) {
  24723. var overallNeedDirty_1;
  24724. var agentStubMap = overallTask.agentStubMap;
  24725. agentStubMap.each(function (stub) {
  24726. if (needSetDirty(opt, stub)) {
  24727. stub.dirty();
  24728. overallNeedDirty_1 = true;
  24729. }
  24730. });
  24731. overallNeedDirty_1 && overallTask.dirty();
  24732. scheduler.updatePayload(overallTask, payload);
  24733. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block);
  24734. // Execute stubs firstly, which may set the overall task dirty,
  24735. // then execute the overall task. And stub will call seriesModel.setData,
  24736. // which ensures that in the overallTask seriesModel.getData() will not
  24737. // return incorrect data.
  24738. agentStubMap.each(function (stub) {
  24739. stub.perform(performArgs_1);
  24740. });
  24741. if (overallTask.perform(performArgs_1)) {
  24742. unfinished = true;
  24743. }
  24744. } else if (seriesTaskMap) {
  24745. seriesTaskMap.each(function (task, pipelineId) {
  24746. if (needSetDirty(opt, task)) {
  24747. task.dirty();
  24748. }
  24749. var performArgs = scheduler.getPerformArgs(task, opt.block);
  24750. // FIXME
  24751. // if intending to declare `performRawSeries` in handlers, only
  24752. // stream-independent (specifically, data item independent) operations can be
  24753. // performed. Because if a series is filtered, most of the tasks will not
  24754. // be performed. A stream-dependent operation probably cause wrong biz logic.
  24755. // Perhaps we should not provide a separate callback for this case instead
  24756. // of providing the config `performRawSeries`. The stream-dependent operations
  24757. // and stream-independent operations should better not be mixed.
  24758. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  24759. scheduler.updatePayload(task, payload);
  24760. if (task.perform(performArgs)) {
  24761. unfinished = true;
  24762. }
  24763. });
  24764. }
  24765. });
  24766. function needSetDirty(opt, task) {
  24767. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  24768. }
  24769. this.unfinished = unfinished || this.unfinished;
  24770. };
  24771. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  24772. var unfinished;
  24773. ecModel.eachSeries(function (seriesModel) {
  24774. // Progress to the end for dataInit and dataRestore.
  24775. unfinished = seriesModel.dataTask.perform() || unfinished;
  24776. });
  24777. this.unfinished = unfinished || this.unfinished;
  24778. };
  24779. Scheduler.prototype.plan = function () {
  24780. // Travel pipelines, check block.
  24781. this._pipelineMap.each(function (pipeline) {
  24782. var task = pipeline.tail;
  24783. do {
  24784. if (task.__block) {
  24785. pipeline.blockIndex = task.__idxInPipeline;
  24786. break;
  24787. }
  24788. task = task.getUpstream();
  24789. } while (task);
  24790. });
  24791. };
  24792. Scheduler.prototype.updatePayload = function (task, payload) {
  24793. payload !== 'remain' && (task.context.payload = payload);
  24794. };
  24795. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  24796. var scheduler = this;
  24797. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap;
  24798. // The count of stages are totally about only several dozen, so
  24799. // do not need to reuse the map.
  24800. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  24801. var seriesType = stageHandler.seriesType;
  24802. var getTargetSeries = stageHandler.getTargetSeries;
  24803. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  24804. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  24805. // it works but it may cause other irrelevant charts blocked.
  24806. if (stageHandler.createOnAllSeries) {
  24807. ecModel.eachRawSeries(create);
  24808. } else if (seriesType) {
  24809. ecModel.eachRawSeriesByType(seriesType, create);
  24810. } else if (getTargetSeries) {
  24811. getTargetSeries(ecModel, api).each(create);
  24812. }
  24813. function create(seriesModel) {
  24814. var pipelineId = seriesModel.uid;
  24815. // Init tasks for each seriesModel only once.
  24816. // Reuse original task instance.
  24817. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  24818. plan: seriesTaskPlan,
  24819. reset: seriesTaskReset,
  24820. count: seriesTaskCount
  24821. }));
  24822. task.context = {
  24823. model: seriesModel,
  24824. ecModel: ecModel,
  24825. api: api,
  24826. // PENDING: `useClearVisual` not used?
  24827. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  24828. plan: stageHandler.plan,
  24829. reset: stageHandler.reset,
  24830. scheduler: scheduler
  24831. };
  24832. scheduler._pipe(seriesModel, task);
  24833. }
  24834. };
  24835. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  24836. var scheduler = this;
  24837. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  24838. // For overall task, the function only be called on reset stage.
  24839. || createTask({
  24840. reset: overallTaskReset
  24841. });
  24842. overallTask.context = {
  24843. ecModel: ecModel,
  24844. api: api,
  24845. overallReset: stageHandler.overallReset,
  24846. scheduler: scheduler
  24847. };
  24848. var oldAgentStubMap = overallTask.agentStubMap;
  24849. // The count of stages are totally about only several dozen, so
  24850. // do not need to reuse the map.
  24851. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  24852. var seriesType = stageHandler.seriesType;
  24853. var getTargetSeries = stageHandler.getTargetSeries;
  24854. var overallProgress = true;
  24855. var shouldOverallTaskDirty = false;
  24856. // FIXME:TS never used, so comment it
  24857. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  24858. // An overall task with seriesType detected or has `getTargetSeries`, we add
  24859. // stub in each pipelines, it will set the overall task dirty when the pipeline
  24860. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  24861. // we set the pipeline block.
  24862. var errMsg = '';
  24863. if ("development" !== 'production') {
  24864. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  24865. }
  24866. assert(!stageHandler.createOnAllSeries, errMsg);
  24867. if (seriesType) {
  24868. ecModel.eachRawSeriesByType(seriesType, createStub);
  24869. } else if (getTargetSeries) {
  24870. getTargetSeries(ecModel, api).each(createStub);
  24871. }
  24872. // Otherwise, (usually it is legacy case), the overall task will only be
  24873. // executed when upstream is dirty. Otherwise the progressive rendering of all
  24874. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  24875. // dirty info from upstream.
  24876. else {
  24877. overallProgress = false;
  24878. each(ecModel.getSeries(), createStub);
  24879. }
  24880. function createStub(seriesModel) {
  24881. var pipelineId = seriesModel.uid;
  24882. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || (
  24883. // When the result of `getTargetSeries` changed, the overallTask
  24884. // should be set as dirty and re-performed.
  24885. shouldOverallTaskDirty = true, createTask({
  24886. reset: stubReset,
  24887. onDirty: stubOnDirty
  24888. })));
  24889. stub.context = {
  24890. model: seriesModel,
  24891. overallProgress: overallProgress
  24892. // FIXME:TS never used, so comment it
  24893. // modifyOutputEnd: modifyOutputEnd
  24894. };
  24895. stub.agent = overallTask;
  24896. stub.__block = overallProgress;
  24897. scheduler._pipe(seriesModel, stub);
  24898. }
  24899. if (shouldOverallTaskDirty) {
  24900. overallTask.dirty();
  24901. }
  24902. };
  24903. Scheduler.prototype._pipe = function (seriesModel, task) {
  24904. var pipelineId = seriesModel.uid;
  24905. var pipeline = this._pipelineMap.get(pipelineId);
  24906. !pipeline.head && (pipeline.head = task);
  24907. pipeline.tail && pipeline.tail.pipe(task);
  24908. pipeline.tail = task;
  24909. task.__idxInPipeline = pipeline.count++;
  24910. task.__pipeline = pipeline;
  24911. };
  24912. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  24913. if (isFunction(stageHandler)) {
  24914. stageHandler = {
  24915. overallReset: stageHandler,
  24916. seriesType: detectSeriseType(stageHandler)
  24917. };
  24918. }
  24919. stageHandler.uid = getUID('stageHandler');
  24920. visualType && (stageHandler.visualType = visualType);
  24921. return stageHandler;
  24922. };
  24923. return Scheduler;
  24924. }();
  24925. function overallTaskReset(context) {
  24926. context.overallReset(context.ecModel, context.api, context.payload);
  24927. }
  24928. function stubReset(context) {
  24929. return context.overallProgress && stubProgress;
  24930. }
  24931. function stubProgress() {
  24932. this.agent.dirty();
  24933. this.getDownstream().dirty();
  24934. }
  24935. function stubOnDirty() {
  24936. this.agent && this.agent.dirty();
  24937. }
  24938. function seriesTaskPlan(context) {
  24939. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  24940. }
  24941. function seriesTaskReset(context) {
  24942. if (context.useClearVisual) {
  24943. context.data.clearAllVisual();
  24944. }
  24945. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  24946. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  24947. return makeSeriesTaskProgress(idx);
  24948. }) : singleSeriesTaskProgress;
  24949. }
  24950. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  24951. function makeSeriesTaskProgress(resetDefineIdx) {
  24952. return function (params, context) {
  24953. var data = context.data;
  24954. var resetDefine = context.resetDefines[resetDefineIdx];
  24955. if (resetDefine && resetDefine.dataEach) {
  24956. for (var i = params.start; i < params.end; i++) {
  24957. resetDefine.dataEach(data, i);
  24958. }
  24959. } else if (resetDefine && resetDefine.progress) {
  24960. resetDefine.progress(params, data);
  24961. }
  24962. };
  24963. }
  24964. function seriesTaskCount(context) {
  24965. return context.data.count();
  24966. }
  24967. /**
  24968. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  24969. * To ensure that they can work normally, they should work in block mode, that is,
  24970. * they should not be started util the previous tasks finished. So they cause the
  24971. * progressive rendering disabled. We try to detect the series type, to narrow down
  24972. * the block range to only the series type they concern, but not all series.
  24973. */
  24974. function detectSeriseType(legacyFunc) {
  24975. seriesType = null;
  24976. try {
  24977. // Assume there is no async when calling `eachSeriesByType`.
  24978. legacyFunc(ecModelMock, apiMock);
  24979. } catch (e) {}
  24980. return seriesType;
  24981. }
  24982. var ecModelMock = {};
  24983. var apiMock = {};
  24984. var seriesType;
  24985. mockMethods(ecModelMock, GlobalModel);
  24986. mockMethods(apiMock, ExtensionAPI);
  24987. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  24988. seriesType = type;
  24989. };
  24990. ecModelMock.eachComponent = function (cond) {
  24991. if (cond.mainType === 'series' && cond.subType) {
  24992. seriesType = cond.subType;
  24993. }
  24994. };
  24995. function mockMethods(target, Clz) {
  24996. /* eslint-disable */
  24997. for (var name_1 in Clz.prototype) {
  24998. // Do not use hasOwnProperty
  24999. target[name_1] = noop;
  25000. }
  25001. /* eslint-enable */
  25002. }
  25003. var color$2 = tokens.darkColor;
  25004. var backgroundColor = color$2.background;
  25005. var axisCommon = function () {
  25006. return {
  25007. axisLine: {
  25008. lineStyle: {
  25009. color: color$2.axisLine
  25010. }
  25011. },
  25012. splitLine: {
  25013. lineStyle: {
  25014. color: color$2.axisSplitLine
  25015. }
  25016. },
  25017. splitArea: {
  25018. areaStyle: {
  25019. color: [color$2.backgroundTint, color$2.backgroundTransparent]
  25020. }
  25021. },
  25022. minorSplitLine: {
  25023. lineStyle: {
  25024. color: color$2.axisMinorSplitLine
  25025. }
  25026. },
  25027. axisLabel: {
  25028. color: color$2.axisLabel
  25029. },
  25030. axisName: {}
  25031. };
  25032. };
  25033. var matrixAxis = {
  25034. label: {
  25035. color: color$2.secondary
  25036. },
  25037. itemStyle: {
  25038. borderColor: color$2.borderTint
  25039. },
  25040. dividerLineStyle: {
  25041. color: color$2.border
  25042. }
  25043. };
  25044. var theme = {
  25045. darkMode: true,
  25046. color: color$2.theme,
  25047. backgroundColor: backgroundColor,
  25048. axisPointer: {
  25049. lineStyle: {
  25050. color: color$2.border
  25051. },
  25052. crossStyle: {
  25053. color: color$2.borderShade
  25054. },
  25055. label: {
  25056. color: color$2.tertiary
  25057. }
  25058. },
  25059. legend: {
  25060. textStyle: {
  25061. color: color$2.secondary
  25062. },
  25063. pageTextStyle: {
  25064. color: color$2.tertiary
  25065. }
  25066. },
  25067. textStyle: {
  25068. color: color$2.secondary
  25069. },
  25070. title: {
  25071. textStyle: {
  25072. color: color$2.primary
  25073. },
  25074. subtextStyle: {
  25075. color: color$2.quaternary
  25076. }
  25077. },
  25078. toolbox: {
  25079. iconStyle: {
  25080. borderColor: color$2.accent50
  25081. }
  25082. },
  25083. tooltip: {
  25084. backgroundColor: color$2.neutral20,
  25085. defaultBorderColor: color$2.border,
  25086. textStyle: {
  25087. color: color$2.tertiary
  25088. }
  25089. },
  25090. dataZoom: {
  25091. borderColor: color$2.accent10,
  25092. textStyle: {
  25093. color: color$2.tertiary
  25094. },
  25095. brushStyle: {
  25096. color: color$2.backgroundTint
  25097. },
  25098. handleStyle: {
  25099. color: color$2.neutral00,
  25100. borderColor: color$2.accent20
  25101. },
  25102. moveHandleStyle: {
  25103. color: color$2.accent40
  25104. },
  25105. emphasis: {
  25106. handleStyle: {
  25107. borderColor: color$2.accent50
  25108. }
  25109. },
  25110. dataBackground: {
  25111. lineStyle: {
  25112. color: color$2.accent30
  25113. },
  25114. areaStyle: {
  25115. color: color$2.accent20
  25116. }
  25117. },
  25118. selectedDataBackground: {
  25119. lineStyle: {
  25120. color: color$2.accent50
  25121. },
  25122. areaStyle: {
  25123. color: color$2.accent30
  25124. }
  25125. }
  25126. },
  25127. visualMap: {
  25128. textStyle: {
  25129. color: color$2.secondary
  25130. },
  25131. handleStyle: {
  25132. borderColor: color$2.neutral30
  25133. }
  25134. },
  25135. timeline: {
  25136. lineStyle: {
  25137. color: color$2.accent10
  25138. },
  25139. label: {
  25140. color: color$2.tertiary
  25141. },
  25142. controlStyle: {
  25143. color: color$2.accent30,
  25144. borderColor: color$2.accent30
  25145. }
  25146. },
  25147. calendar: {
  25148. itemStyle: {
  25149. color: color$2.neutral00,
  25150. borderColor: color$2.neutral20
  25151. },
  25152. dayLabel: {
  25153. color: color$2.tertiary
  25154. },
  25155. monthLabel: {
  25156. color: color$2.secondary
  25157. },
  25158. yearLabel: {
  25159. color: color$2.secondary
  25160. }
  25161. },
  25162. matrix: {
  25163. x: matrixAxis,
  25164. y: matrixAxis,
  25165. backgroundColor: {
  25166. borderColor: color$2.axisLine
  25167. },
  25168. body: {
  25169. itemStyle: {
  25170. borderColor: color$2.borderTint
  25171. }
  25172. }
  25173. },
  25174. timeAxis: axisCommon(),
  25175. logAxis: axisCommon(),
  25176. valueAxis: axisCommon(),
  25177. categoryAxis: axisCommon(),
  25178. line: {
  25179. symbol: 'circle'
  25180. },
  25181. graph: {
  25182. color: color$2.theme
  25183. },
  25184. gauge: {
  25185. title: {
  25186. color: color$2.secondary
  25187. },
  25188. axisLine: {
  25189. lineStyle: {
  25190. color: [[1, color$2.neutral05]]
  25191. }
  25192. },
  25193. axisLabel: {
  25194. color: color$2.axisLabel
  25195. },
  25196. detail: {
  25197. color: color$2.primary
  25198. }
  25199. },
  25200. candlestick: {
  25201. itemStyle: {
  25202. color: '#f64e56',
  25203. color0: '#54ea92',
  25204. borderColor: '#f64e56',
  25205. borderColor0: '#54ea92'
  25206. // borderColor: '#ca2824',
  25207. // borderColor0: '#09a443'
  25208. }
  25209. },
  25210. funnel: {
  25211. itemStyle: {
  25212. borderColor: color$2.background
  25213. }
  25214. },
  25215. radar: function () {
  25216. var radar = axisCommon();
  25217. radar.axisName = {
  25218. color: color$2.axisLabel
  25219. };
  25220. radar.axisLine.lineStyle.color = color$2.neutral20;
  25221. return radar;
  25222. }(),
  25223. treemap: {
  25224. breadcrumb: {
  25225. itemStyle: {
  25226. color: color$2.neutral20,
  25227. textStyle: {
  25228. color: color$2.secondary
  25229. }
  25230. },
  25231. emphasis: {
  25232. itemStyle: {
  25233. color: color$2.neutral30
  25234. }
  25235. }
  25236. }
  25237. },
  25238. sunburst: {
  25239. itemStyle: {
  25240. borderColor: color$2.background
  25241. }
  25242. },
  25243. map: {
  25244. itemStyle: {
  25245. borderColor: color$2.border,
  25246. areaColor: color$2.neutral10
  25247. },
  25248. label: {
  25249. color: color$2.tertiary
  25250. },
  25251. emphasis: {
  25252. label: {
  25253. color: color$2.primary
  25254. },
  25255. itemStyle: {
  25256. areaColor: color$2.highlight
  25257. }
  25258. },
  25259. select: {
  25260. label: {
  25261. color: color$2.primary
  25262. },
  25263. itemStyle: {
  25264. areaColor: color$2.highlight
  25265. }
  25266. }
  25267. },
  25268. geo: {
  25269. itemStyle: {
  25270. borderColor: color$2.border,
  25271. areaColor: color$2.neutral10
  25272. },
  25273. emphasis: {
  25274. label: {
  25275. color: color$2.primary
  25276. },
  25277. itemStyle: {
  25278. areaColor: color$2.highlight
  25279. }
  25280. },
  25281. select: {
  25282. label: {
  25283. color: color$2.primary
  25284. },
  25285. itemStyle: {
  25286. color: color$2.highlight
  25287. }
  25288. }
  25289. }
  25290. };
  25291. theme.categoryAxis.splitLine.show = false;
  25292. /**
  25293. * Usage of query:
  25294. * `chart.on('click', query, handler);`
  25295. * The `query` can be:
  25296. * + The component type query string, only `mainType` or `mainType.subType`,
  25297. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25298. * + The component query object, like:
  25299. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25300. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25301. * + The data query object, like:
  25302. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25303. * + The other query object (cmponent customized query), like:
  25304. * `{element: 'some'}` (only available in custom series).
  25305. *
  25306. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25307. * same as there is no such prop in the `query` object.
  25308. */
  25309. var ECEventProcessor = /** @class */function () {
  25310. function ECEventProcessor() {}
  25311. ECEventProcessor.prototype.normalizeQuery = function (query) {
  25312. var cptQuery = {};
  25313. var dataQuery = {};
  25314. var otherQuery = {};
  25315. // `query` is `mainType` or `mainType.subType` of component.
  25316. if (isString(query)) {
  25317. var condCptType = parseClassType(query);
  25318. // `.main` and `.sub` may be ''.
  25319. cptQuery.mainType = condCptType.main || null;
  25320. cptQuery.subType = condCptType.sub || null;
  25321. }
  25322. // `query` is an object, convert to {mainType, index, name, id}.
  25323. else {
  25324. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25325. // can not be used in `compomentModel.filterForExposedEvent`.
  25326. var suffixes_1 = ['Index', 'Name', 'Id'];
  25327. var dataKeys_1 = {
  25328. name: 1,
  25329. dataIndex: 1,
  25330. dataType: 1
  25331. };
  25332. each(query, function (val, key) {
  25333. var reserved = false;
  25334. for (var i = 0; i < suffixes_1.length; i++) {
  25335. var propSuffix = suffixes_1[i];
  25336. var suffixPos = key.lastIndexOf(propSuffix);
  25337. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25338. var mainType = key.slice(0, suffixPos);
  25339. // Consider `dataIndex`.
  25340. if (mainType !== 'data') {
  25341. cptQuery.mainType = mainType;
  25342. cptQuery[propSuffix.toLowerCase()] = val;
  25343. reserved = true;
  25344. }
  25345. }
  25346. }
  25347. if (dataKeys_1.hasOwnProperty(key)) {
  25348. dataQuery[key] = val;
  25349. reserved = true;
  25350. }
  25351. if (!reserved) {
  25352. otherQuery[key] = val;
  25353. }
  25354. });
  25355. }
  25356. return {
  25357. cptQuery: cptQuery,
  25358. dataQuery: dataQuery,
  25359. otherQuery: otherQuery
  25360. };
  25361. };
  25362. ECEventProcessor.prototype.filter = function (eventType, query) {
  25363. // They should be assigned before each trigger call.
  25364. var eventInfo = this.eventInfo;
  25365. if (!eventInfo) {
  25366. return true;
  25367. }
  25368. var targetEl = eventInfo.targetEl;
  25369. var packedEvent = eventInfo.packedEvent;
  25370. var model = eventInfo.model;
  25371. var view = eventInfo.view;
  25372. // For event like 'globalout'.
  25373. if (!model || !view) {
  25374. return true;
  25375. }
  25376. var cptQuery = query.cptQuery;
  25377. var dataQuery = query.dataQuery;
  25378. 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));
  25379. function check(query, host, prop, propOnHost) {
  25380. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25381. }
  25382. };
  25383. ECEventProcessor.prototype.afterTrigger = function () {
  25384. // Make sure the eventInfo won't be used in next trigger.
  25385. this.eventInfo = null;
  25386. };
  25387. return ECEventProcessor;
  25388. }();
  25389. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  25390. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']);
  25391. // Encoding visual for all series include which is filtered for legend drawing
  25392. var seriesSymbolTask = {
  25393. createOnAllSeries: true,
  25394. // For legend.
  25395. performRawSeries: true,
  25396. reset: function (seriesModel, ecModel) {
  25397. var data = seriesModel.getData();
  25398. if (seriesModel.legendIcon) {
  25399. data.setVisual('legendIcon', seriesModel.legendIcon);
  25400. }
  25401. if (!seriesModel.hasSymbolVisual) {
  25402. return;
  25403. }
  25404. var symbolOptions = {};
  25405. var symbolOptionsCb = {};
  25406. var hasCallback = false;
  25407. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  25408. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  25409. var val = seriesModel.get(symbolPropName);
  25410. if (isFunction(val)) {
  25411. hasCallback = true;
  25412. symbolOptionsCb[symbolPropName] = val;
  25413. } else {
  25414. symbolOptions[symbolPropName] = val;
  25415. }
  25416. }
  25417. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  25418. data.setVisual(extend({
  25419. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  25420. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  25421. }, symbolOptions));
  25422. // Only visible series has each data be visual encoded
  25423. if (ecModel.isSeriesFiltered(seriesModel)) {
  25424. return;
  25425. }
  25426. var symbolPropsCb = keys(symbolOptionsCb);
  25427. function dataEach(data, idx) {
  25428. var rawValue = seriesModel.getRawValue(idx);
  25429. var params = seriesModel.getDataParams(idx);
  25430. for (var i = 0; i < symbolPropsCb.length; i++) {
  25431. var symbolPropName = symbolPropsCb[i];
  25432. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  25433. }
  25434. }
  25435. return {
  25436. dataEach: hasCallback ? dataEach : null
  25437. };
  25438. }
  25439. };
  25440. var dataSymbolTask = {
  25441. createOnAllSeries: true,
  25442. // For legend.
  25443. performRawSeries: true,
  25444. reset: function (seriesModel, ecModel) {
  25445. if (!seriesModel.hasSymbolVisual) {
  25446. return;
  25447. }
  25448. // Only visible series has each data be visual encoded
  25449. if (ecModel.isSeriesFiltered(seriesModel)) {
  25450. return;
  25451. }
  25452. var data = seriesModel.getData();
  25453. function dataEach(data, idx) {
  25454. var itemModel = data.getItemModel(idx);
  25455. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  25456. var symbolPropName = SYMBOL_PROPS[i];
  25457. var val = itemModel.getShallow(symbolPropName, true);
  25458. if (val != null) {
  25459. data.setItemVisual(idx, symbolPropName, val);
  25460. }
  25461. }
  25462. }
  25463. return {
  25464. dataEach: data.hasItemOption ? dataEach : null
  25465. };
  25466. }
  25467. };
  25468. /*
  25469. * Licensed to the Apache Software Foundation (ASF) under one
  25470. * or more contributor license agreements. See the NOTICE file
  25471. * distributed with this work for additional information
  25472. * regarding copyright ownership. The ASF licenses this file
  25473. * to you under the Apache License, Version 2.0 (the
  25474. * "License"); you may not use this file except in compliance
  25475. * with the License. You may obtain a copy of the License at
  25476. *
  25477. * http://www.apache.org/licenses/LICENSE-2.0
  25478. *
  25479. * Unless required by applicable law or agreed to in writing,
  25480. * software distributed under the License is distributed on an
  25481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25482. * KIND, either express or implied. See the License for the
  25483. * specific language governing permissions and limitations
  25484. * under the License.
  25485. */
  25486. /**
  25487. * AUTO-GENERATED FILE. DO NOT MODIFY.
  25488. */
  25489. /*
  25490. * Licensed to the Apache Software Foundation (ASF) under one
  25491. * or more contributor license agreements. See the NOTICE file
  25492. * distributed with this work for additional information
  25493. * regarding copyright ownership. The ASF licenses this file
  25494. * to you under the Apache License, Version 2.0 (the
  25495. * "License"); you may not use this file except in compliance
  25496. * with the License. You may obtain a copy of the License at
  25497. *
  25498. * http://www.apache.org/licenses/LICENSE-2.0
  25499. *
  25500. * Unless required by applicable law or agreed to in writing,
  25501. * software distributed under the License is distributed on an
  25502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25503. * KIND, either express or implied. See the License for the
  25504. * specific language governing permissions and limitations
  25505. * under the License.
  25506. */
  25507. function getItemVisualFromData(data, dataIndex, key) {
  25508. switch (key) {
  25509. case 'color':
  25510. var style = data.getItemVisual(dataIndex, 'style');
  25511. return style[data.getVisual('drawType')];
  25512. case 'opacity':
  25513. return data.getItemVisual(dataIndex, 'style').opacity;
  25514. case 'symbol':
  25515. case 'symbolSize':
  25516. case 'liftZ':
  25517. return data.getItemVisual(dataIndex, key);
  25518. default:
  25519. if ("development" !== 'production') {
  25520. console.warn("Unknown visual type " + key);
  25521. }
  25522. }
  25523. }
  25524. function getVisualFromData(data, key) {
  25525. switch (key) {
  25526. case 'color':
  25527. var style = data.getVisual('style');
  25528. return style[data.getVisual('drawType')];
  25529. case 'opacity':
  25530. return data.getVisual('style').opacity;
  25531. case 'symbol':
  25532. case 'symbolSize':
  25533. case 'liftZ':
  25534. return data.getVisual(key);
  25535. default:
  25536. if ("development" !== 'production') {
  25537. console.warn("Unknown visual type " + key);
  25538. }
  25539. }
  25540. }
  25541. // Legacy data selection action.
  25542. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  25543. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  25544. function getSeriesIndices(ecModel, payload) {
  25545. var seriesIndices = [];
  25546. ecModel.eachComponent({
  25547. mainType: 'series',
  25548. subType: seriesType,
  25549. query: payload
  25550. }, function (seriesModel) {
  25551. seriesIndices.push(seriesModel.seriesIndex);
  25552. });
  25553. return seriesIndices;
  25554. }
  25555. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  25556. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  25557. payload = extend({}, payload);
  25558. if ("development" !== 'production') {
  25559. deprecateReplaceLog(payload.type, eventsMap[1]);
  25560. }
  25561. api.dispatchAction(extend(payload, {
  25562. type: eventsMap[1],
  25563. seriesIndex: getSeriesIndices(ecModel, payload)
  25564. }));
  25565. });
  25566. });
  25567. }
  25568. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  25569. var legacyEventName = type + eventPostfix;
  25570. if (!ecIns.isSilent(legacyEventName)) {
  25571. if ("development" !== 'production') {
  25572. deprecateLog("event " + legacyEventName + " is deprecated.");
  25573. }
  25574. ecModel.eachComponent({
  25575. mainType: 'series',
  25576. subType: 'pie'
  25577. }, function (seriesModel) {
  25578. var seriesIndex = seriesModel.seriesIndex;
  25579. var selectedMap = seriesModel.option.selectedMap;
  25580. var selected = payload.selected;
  25581. for (var i = 0; i < selected.length; i++) {
  25582. if (selected[i].seriesIndex === seriesIndex) {
  25583. var data = seriesModel.getData();
  25584. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  25585. ecIns.trigger(legacyEventName, {
  25586. type: legacyEventName,
  25587. seriesId: seriesModel.id,
  25588. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  25589. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  25590. });
  25591. }
  25592. }
  25593. });
  25594. }
  25595. }
  25596. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  25597. messageCenter.on('selectchanged', function (params) {
  25598. var ecModel = api.getModel();
  25599. if (params.isFromClick) {
  25600. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  25601. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  25602. } else if (params.fromAction === 'select') {
  25603. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  25604. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  25605. } else if (params.fromAction === 'unselect') {
  25606. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  25607. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  25608. }
  25609. });
  25610. }
  25611. /*
  25612. * Licensed to the Apache Software Foundation (ASF) under one
  25613. * or more contributor license agreements. See the NOTICE file
  25614. * distributed with this work for additional information
  25615. * regarding copyright ownership. The ASF licenses this file
  25616. * to you under the Apache License, Version 2.0 (the
  25617. * "License"); you may not use this file except in compliance
  25618. * with the License. You may obtain a copy of the License at
  25619. *
  25620. * http://www.apache.org/licenses/LICENSE-2.0
  25621. *
  25622. * Unless required by applicable law or agreed to in writing,
  25623. * software distributed under the License is distributed on an
  25624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25625. * KIND, either express or implied. See the License for the
  25626. * specific language governing permissions and limitations
  25627. * under the License.
  25628. */
  25629. /**
  25630. * AUTO-GENERATED FILE. DO NOT MODIFY.
  25631. */
  25632. /*
  25633. * Licensed to the Apache Software Foundation (ASF) under one
  25634. * or more contributor license agreements. See the NOTICE file
  25635. * distributed with this work for additional information
  25636. * regarding copyright ownership. The ASF licenses this file
  25637. * to you under the Apache License, Version 2.0 (the
  25638. * "License"); you may not use this file except in compliance
  25639. * with the License. You may obtain a copy of the License at
  25640. *
  25641. * http://www.apache.org/licenses/LICENSE-2.0
  25642. *
  25643. * Unless required by applicable law or agreed to in writing,
  25644. * software distributed under the License is distributed on an
  25645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25646. * KIND, either express or implied. See the License for the
  25647. * specific language governing permissions and limitations
  25648. * under the License.
  25649. */
  25650. function findEventDispatcher(target, det, returnFirstMatch) {
  25651. var found;
  25652. while (target) {
  25653. if (det(target)) {
  25654. found = target;
  25655. if (returnFirstMatch) {
  25656. break;
  25657. }
  25658. }
  25659. target = target.__hostTarget || target.parent;
  25660. }
  25661. return found;
  25662. }
  25663. var wmUniqueIndex = Math.round(Math.random() * 9);
  25664. var supportDefineProperty = typeof Object.defineProperty === 'function';
  25665. var WeakMap = (function () {
  25666. function WeakMap() {
  25667. this._id = '__ec_inner_' + wmUniqueIndex++;
  25668. }
  25669. WeakMap.prototype.get = function (key) {
  25670. return this._guard(key)[this._id];
  25671. };
  25672. WeakMap.prototype.set = function (key, value) {
  25673. var target = this._guard(key);
  25674. if (supportDefineProperty) {
  25675. Object.defineProperty(target, this._id, {
  25676. value: value,
  25677. enumerable: false,
  25678. configurable: true
  25679. });
  25680. }
  25681. else {
  25682. target[this._id] = value;
  25683. }
  25684. return this;
  25685. };
  25686. WeakMap.prototype["delete"] = function (key) {
  25687. if (this.has(key)) {
  25688. delete this._guard(key)[this._id];
  25689. return true;
  25690. }
  25691. return false;
  25692. };
  25693. WeakMap.prototype.has = function (key) {
  25694. return !!this._guard(key)[this._id];
  25695. };
  25696. WeakMap.prototype._guard = function (key) {
  25697. if (key !== Object(key)) {
  25698. throw TypeError('Value of WeakMap is not a non-null object.');
  25699. }
  25700. return key;
  25701. };
  25702. return WeakMap;
  25703. }());
  25704. /**
  25705. * Triangle shape
  25706. * @inner
  25707. */
  25708. var Triangle = Path.extend({
  25709. type: 'triangle',
  25710. shape: {
  25711. cx: 0,
  25712. cy: 0,
  25713. width: 0,
  25714. height: 0
  25715. },
  25716. buildPath: function (path, shape) {
  25717. var cx = shape.cx;
  25718. var cy = shape.cy;
  25719. var width = shape.width / 2;
  25720. var height = shape.height / 2;
  25721. path.moveTo(cx, cy - height);
  25722. path.lineTo(cx + width, cy + height);
  25723. path.lineTo(cx - width, cy + height);
  25724. path.closePath();
  25725. }
  25726. });
  25727. /**
  25728. * Diamond shape
  25729. * @inner
  25730. */
  25731. var Diamond = Path.extend({
  25732. type: 'diamond',
  25733. shape: {
  25734. cx: 0,
  25735. cy: 0,
  25736. width: 0,
  25737. height: 0
  25738. },
  25739. buildPath: function (path, shape) {
  25740. var cx = shape.cx;
  25741. var cy = shape.cy;
  25742. var width = shape.width / 2;
  25743. var height = shape.height / 2;
  25744. path.moveTo(cx, cy - height);
  25745. path.lineTo(cx + width, cy);
  25746. path.lineTo(cx, cy + height);
  25747. path.lineTo(cx - width, cy);
  25748. path.closePath();
  25749. }
  25750. });
  25751. /**
  25752. * Pin shape
  25753. * @inner
  25754. */
  25755. var Pin = Path.extend({
  25756. type: 'pin',
  25757. shape: {
  25758. // x, y on the cusp
  25759. x: 0,
  25760. y: 0,
  25761. width: 0,
  25762. height: 0
  25763. },
  25764. buildPath: function (path, shape) {
  25765. var x = shape.x;
  25766. var y = shape.y;
  25767. var w = shape.width / 5 * 3;
  25768. // Height must be larger than width
  25769. var h = Math.max(w, shape.height);
  25770. var r = w / 2;
  25771. // Dist on y with tangent point and circle center
  25772. var dy = r * r / (h - r);
  25773. var cy = y - h + r + dy;
  25774. var angle = Math.asin(dy / r);
  25775. // Dist on x with tangent point and circle center
  25776. var dx = Math.cos(angle) * r;
  25777. var tanX = Math.sin(angle);
  25778. var tanY = Math.cos(angle);
  25779. var cpLen = r * 0.6;
  25780. var cpLen2 = r * 0.7;
  25781. path.moveTo(x - dx, cy + dy);
  25782. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  25783. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  25784. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  25785. path.closePath();
  25786. }
  25787. });
  25788. /**
  25789. * Arrow shape
  25790. * @inner
  25791. */
  25792. var Arrow = Path.extend({
  25793. type: 'arrow',
  25794. shape: {
  25795. x: 0,
  25796. y: 0,
  25797. width: 0,
  25798. height: 0
  25799. },
  25800. buildPath: function (ctx, shape) {
  25801. var height = shape.height;
  25802. var width = shape.width;
  25803. var x = shape.x;
  25804. var y = shape.y;
  25805. var dx = width / 3 * 2;
  25806. ctx.moveTo(x, y);
  25807. ctx.lineTo(x + dx, y + height);
  25808. ctx.lineTo(x, y + height / 4 * 3);
  25809. ctx.lineTo(x - dx, y + height);
  25810. ctx.lineTo(x, y);
  25811. ctx.closePath();
  25812. }
  25813. });
  25814. /**
  25815. * Map of path constructors
  25816. */
  25817. // TODO Use function to build symbol path.
  25818. var symbolCtors = {
  25819. line: Line,
  25820. rect: Rect,
  25821. roundRect: Rect,
  25822. square: Rect,
  25823. circle: Circle,
  25824. diamond: Diamond,
  25825. pin: Pin,
  25826. arrow: Arrow,
  25827. triangle: Triangle
  25828. };
  25829. var symbolShapeMakers = {
  25830. line: function (x, y, w, h, shape) {
  25831. shape.x1 = x;
  25832. shape.y1 = y + h / 2;
  25833. shape.x2 = x + w;
  25834. shape.y2 = y + h / 2;
  25835. },
  25836. rect: function (x, y, w, h, shape) {
  25837. shape.x = x;
  25838. shape.y = y;
  25839. shape.width = w;
  25840. shape.height = h;
  25841. },
  25842. roundRect: function (x, y, w, h, shape) {
  25843. shape.x = x;
  25844. shape.y = y;
  25845. shape.width = w;
  25846. shape.height = h;
  25847. shape.r = Math.min(w, h) / 4;
  25848. },
  25849. square: function (x, y, w, h, shape) {
  25850. var size = Math.min(w, h);
  25851. shape.x = x;
  25852. shape.y = y;
  25853. shape.width = size;
  25854. shape.height = size;
  25855. },
  25856. circle: function (x, y, w, h, shape) {
  25857. // Put circle in the center of square
  25858. shape.cx = x + w / 2;
  25859. shape.cy = y + h / 2;
  25860. shape.r = Math.min(w, h) / 2;
  25861. },
  25862. diamond: function (x, y, w, h, shape) {
  25863. shape.cx = x + w / 2;
  25864. shape.cy = y + h / 2;
  25865. shape.width = w;
  25866. shape.height = h;
  25867. },
  25868. pin: function (x, y, w, h, shape) {
  25869. shape.x = x + w / 2;
  25870. shape.y = y + h / 2;
  25871. shape.width = w;
  25872. shape.height = h;
  25873. },
  25874. arrow: function (x, y, w, h, shape) {
  25875. shape.x = x + w / 2;
  25876. shape.y = y + h / 2;
  25877. shape.width = w;
  25878. shape.height = h;
  25879. },
  25880. triangle: function (x, y, w, h, shape) {
  25881. shape.cx = x + w / 2;
  25882. shape.cy = y + h / 2;
  25883. shape.width = w;
  25884. shape.height = h;
  25885. }
  25886. };
  25887. var symbolBuildProxies = {};
  25888. each(symbolCtors, function (Ctor, name) {
  25889. symbolBuildProxies[name] = new Ctor();
  25890. });
  25891. var SymbolClz = Path.extend({
  25892. type: 'symbol',
  25893. shape: {
  25894. symbolType: '',
  25895. x: 0,
  25896. y: 0,
  25897. width: 0,
  25898. height: 0
  25899. },
  25900. calculateTextPosition: function (out, config, rect) {
  25901. var res = calculateTextPosition(out, config, rect);
  25902. var shape = this.shape;
  25903. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  25904. res.y = rect.y + rect.height * 0.4;
  25905. }
  25906. return res;
  25907. },
  25908. buildPath: function (ctx, shape, inBundle) {
  25909. var symbolType = shape.symbolType;
  25910. if (symbolType !== 'none') {
  25911. var proxySymbol = symbolBuildProxies[symbolType];
  25912. if (!proxySymbol) {
  25913. // Default rect
  25914. symbolType = 'rect';
  25915. proxySymbol = symbolBuildProxies[symbolType];
  25916. }
  25917. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  25918. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  25919. }
  25920. }
  25921. });
  25922. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  25923. function symbolPathSetColor(color, innerColor) {
  25924. if (this.type !== 'image') {
  25925. var symbolStyle = this.style;
  25926. if (this.__isEmptyBrush) {
  25927. symbolStyle.stroke = color;
  25928. symbolStyle.fill = innerColor || tokens.color.neutral00;
  25929. // TODO Same width with lineStyle in LineView
  25930. symbolStyle.lineWidth = 2;
  25931. } else if (this.shape.symbolType === 'line') {
  25932. symbolStyle.stroke = color;
  25933. } else {
  25934. symbolStyle.fill = color;
  25935. }
  25936. this.markRedraw();
  25937. }
  25938. }
  25939. /**
  25940. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  25941. */
  25942. function createSymbol(symbolType, x, y, w, h, color,
  25943. // whether to keep the ratio of w/h,
  25944. keepAspect) {
  25945. // TODO Support image object, DynamicImage.
  25946. var isEmpty = symbolType.indexOf('empty') === 0;
  25947. if (isEmpty) {
  25948. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  25949. }
  25950. var symbolPath;
  25951. if (symbolType.indexOf('image://') === 0) {
  25952. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  25953. } else if (symbolType.indexOf('path://') === 0) {
  25954. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  25955. } else {
  25956. symbolPath = new SymbolClz({
  25957. shape: {
  25958. symbolType: symbolType,
  25959. x: x,
  25960. y: y,
  25961. width: w,
  25962. height: h
  25963. }
  25964. });
  25965. }
  25966. symbolPath.__isEmptyBrush = isEmpty;
  25967. // TODO Should deprecate setColor
  25968. symbolPath.setColor = symbolPathSetColor;
  25969. if (color) {
  25970. symbolPath.setColor(color);
  25971. }
  25972. return symbolPath;
  25973. }
  25974. function normalizeSymbolSize(symbolSize) {
  25975. if (!isArray(symbolSize)) {
  25976. symbolSize = [+symbolSize, +symbolSize];
  25977. }
  25978. return [symbolSize[0] || 0, symbolSize[1] || 0];
  25979. }
  25980. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  25981. if (symbolOffset == null) {
  25982. return;
  25983. }
  25984. if (!isArray(symbolOffset)) {
  25985. symbolOffset = [symbolOffset, symbolOffset];
  25986. }
  25987. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  25988. }
  25989. function isSafeNum(num) {
  25990. return isFinite(num);
  25991. }
  25992. function createLinearGradient(ctx, obj, rect) {
  25993. var x = obj.x == null ? 0 : obj.x;
  25994. var x2 = obj.x2 == null ? 1 : obj.x2;
  25995. var y = obj.y == null ? 0 : obj.y;
  25996. var y2 = obj.y2 == null ? 0 : obj.y2;
  25997. if (!obj.global) {
  25998. x = x * rect.width + rect.x;
  25999. x2 = x2 * rect.width + rect.x;
  26000. y = y * rect.height + rect.y;
  26001. y2 = y2 * rect.height + rect.y;
  26002. }
  26003. x = isSafeNum(x) ? x : 0;
  26004. x2 = isSafeNum(x2) ? x2 : 1;
  26005. y = isSafeNum(y) ? y : 0;
  26006. y2 = isSafeNum(y2) ? y2 : 0;
  26007. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  26008. return canvasGradient;
  26009. }
  26010. function createRadialGradient(ctx, obj, rect) {
  26011. var width = rect.width;
  26012. var height = rect.height;
  26013. var min = Math.min(width, height);
  26014. var x = obj.x == null ? 0.5 : obj.x;
  26015. var y = obj.y == null ? 0.5 : obj.y;
  26016. var r = obj.r == null ? 0.5 : obj.r;
  26017. if (!obj.global) {
  26018. x = x * width + rect.x;
  26019. y = y * height + rect.y;
  26020. r = r * min;
  26021. }
  26022. x = isSafeNum(x) ? x : 0.5;
  26023. y = isSafeNum(y) ? y : 0.5;
  26024. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  26025. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  26026. return canvasGradient;
  26027. }
  26028. function getCanvasGradient(ctx, obj, rect) {
  26029. var canvasGradient = obj.type === 'radial'
  26030. ? createRadialGradient(ctx, obj, rect)
  26031. : createLinearGradient(ctx, obj, rect);
  26032. var colorStops = obj.colorStops;
  26033. for (var i = 0; i < colorStops.length; i++) {
  26034. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  26035. }
  26036. return canvasGradient;
  26037. }
  26038. function isClipPathChanged(clipPaths, prevClipPaths) {
  26039. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  26040. return false;
  26041. }
  26042. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  26043. return true;
  26044. }
  26045. for (var i = 0; i < clipPaths.length; i++) {
  26046. if (clipPaths[i] !== prevClipPaths[i]) {
  26047. return true;
  26048. }
  26049. }
  26050. return false;
  26051. }
  26052. function parseInt10(val) {
  26053. return parseInt(val, 10);
  26054. }
  26055. function getSize(root, whIdx, opts) {
  26056. var wh = ['width', 'height'][whIdx];
  26057. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  26058. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  26059. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  26060. if (opts[wh] != null && opts[wh] !== 'auto') {
  26061. return parseFloat(opts[wh]);
  26062. }
  26063. var stl = document.defaultView.getComputedStyle(root);
  26064. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  26065. - (parseInt10(stl[plt]) || 0)
  26066. - (parseInt10(stl[prb]) || 0)) | 0;
  26067. }
  26068. function normalizeLineDash(lineType, lineWidth) {
  26069. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  26070. return null;
  26071. }
  26072. return lineType === 'dashed'
  26073. ? [4 * lineWidth, 2 * lineWidth]
  26074. : lineType === 'dotted'
  26075. ? [lineWidth]
  26076. : isNumber(lineType)
  26077. ? [lineType] : isArray(lineType) ? lineType : null;
  26078. }
  26079. function getLineDash(el) {
  26080. var style = el.style;
  26081. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  26082. var lineDashOffset = style.lineDashOffset;
  26083. if (lineDash) {
  26084. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  26085. if (lineScale_1 && lineScale_1 !== 1) {
  26086. lineDash = map(lineDash, function (rawVal) {
  26087. return rawVal / lineScale_1;
  26088. });
  26089. lineDashOffset /= lineScale_1;
  26090. }
  26091. }
  26092. return [lineDash, lineDashOffset];
  26093. }
  26094. var pathProxyForDraw = new PathProxy(true);
  26095. function styleHasStroke(style) {
  26096. var stroke = style.stroke;
  26097. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  26098. }
  26099. function isValidStrokeFillStyle(strokeOrFill) {
  26100. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  26101. }
  26102. function styleHasFill(style) {
  26103. var fill = style.fill;
  26104. return fill != null && fill !== 'none';
  26105. }
  26106. function doFillPath(ctx, style) {
  26107. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  26108. var originalGlobalAlpha = ctx.globalAlpha;
  26109. ctx.globalAlpha = style.fillOpacity * style.opacity;
  26110. ctx.fill();
  26111. ctx.globalAlpha = originalGlobalAlpha;
  26112. }
  26113. else {
  26114. ctx.fill();
  26115. }
  26116. }
  26117. function doStrokePath(ctx, style) {
  26118. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  26119. var originalGlobalAlpha = ctx.globalAlpha;
  26120. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  26121. ctx.stroke();
  26122. ctx.globalAlpha = originalGlobalAlpha;
  26123. }
  26124. else {
  26125. ctx.stroke();
  26126. }
  26127. }
  26128. function createCanvasPattern(ctx, pattern, el) {
  26129. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  26130. if (isImageReady(image)) {
  26131. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  26132. if (typeof DOMMatrix === 'function'
  26133. && canvasPattern
  26134. && canvasPattern.setTransform) {
  26135. var matrix = new DOMMatrix();
  26136. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  26137. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  26138. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  26139. canvasPattern.setTransform(matrix);
  26140. }
  26141. return canvasPattern;
  26142. }
  26143. }
  26144. function brushPath(ctx, el, style, inBatch) {
  26145. var _a;
  26146. var hasStroke = styleHasStroke(style);
  26147. var hasFill = styleHasFill(style);
  26148. var strokePercent = style.strokePercent;
  26149. var strokePart = strokePercent < 1;
  26150. var firstDraw = !el.path;
  26151. if ((!el.silent || strokePart) && firstDraw) {
  26152. el.createPathProxy();
  26153. }
  26154. var path = el.path || pathProxyForDraw;
  26155. var dirtyFlag = el.__dirty;
  26156. if (!inBatch) {
  26157. var fill = style.fill;
  26158. var stroke = style.stroke;
  26159. var hasFillGradient = hasFill && !!fill.colorStops;
  26160. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  26161. var hasFillPattern = hasFill && !!fill.image;
  26162. var hasStrokePattern = hasStroke && !!stroke.image;
  26163. var fillGradient = void 0;
  26164. var strokeGradient = void 0;
  26165. var fillPattern = void 0;
  26166. var strokePattern = void 0;
  26167. var rect = void 0;
  26168. if (hasFillGradient || hasStrokeGradient) {
  26169. rect = el.getBoundingRect();
  26170. }
  26171. if (hasFillGradient) {
  26172. fillGradient = dirtyFlag
  26173. ? getCanvasGradient(ctx, fill, rect)
  26174. : el.__canvasFillGradient;
  26175. el.__canvasFillGradient = fillGradient;
  26176. }
  26177. if (hasStrokeGradient) {
  26178. strokeGradient = dirtyFlag
  26179. ? getCanvasGradient(ctx, stroke, rect)
  26180. : el.__canvasStrokeGradient;
  26181. el.__canvasStrokeGradient = strokeGradient;
  26182. }
  26183. if (hasFillPattern) {
  26184. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  26185. ? createCanvasPattern(ctx, fill, el)
  26186. : el.__canvasFillPattern;
  26187. el.__canvasFillPattern = fillPattern;
  26188. }
  26189. if (hasStrokePattern) {
  26190. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  26191. ? createCanvasPattern(ctx, stroke, el)
  26192. : el.__canvasStrokePattern;
  26193. el.__canvasStrokePattern = strokePattern;
  26194. }
  26195. if (hasFillGradient) {
  26196. ctx.fillStyle = fillGradient;
  26197. }
  26198. else if (hasFillPattern) {
  26199. if (fillPattern) {
  26200. ctx.fillStyle = fillPattern;
  26201. }
  26202. else {
  26203. hasFill = false;
  26204. }
  26205. }
  26206. if (hasStrokeGradient) {
  26207. ctx.strokeStyle = strokeGradient;
  26208. }
  26209. else if (hasStrokePattern) {
  26210. if (strokePattern) {
  26211. ctx.strokeStyle = strokePattern;
  26212. }
  26213. else {
  26214. hasStroke = false;
  26215. }
  26216. }
  26217. }
  26218. var scale = el.getGlobalScale();
  26219. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  26220. var lineDash;
  26221. var lineDashOffset;
  26222. if (ctx.setLineDash && style.lineDash) {
  26223. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  26224. }
  26225. var needsRebuild = true;
  26226. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  26227. path.setDPR(ctx.dpr);
  26228. if (strokePart) {
  26229. path.setContext(null);
  26230. }
  26231. else {
  26232. path.setContext(ctx);
  26233. needsRebuild = false;
  26234. }
  26235. path.reset();
  26236. el.buildPath(path, el.shape, inBatch);
  26237. path.toStatic();
  26238. el.pathUpdated();
  26239. }
  26240. if (needsRebuild) {
  26241. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  26242. }
  26243. if (lineDash) {
  26244. ctx.setLineDash(lineDash);
  26245. ctx.lineDashOffset = lineDashOffset;
  26246. }
  26247. if (!inBatch) {
  26248. if (style.strokeFirst) {
  26249. if (hasStroke) {
  26250. doStrokePath(ctx, style);
  26251. }
  26252. if (hasFill) {
  26253. doFillPath(ctx, style);
  26254. }
  26255. }
  26256. else {
  26257. if (hasFill) {
  26258. doFillPath(ctx, style);
  26259. }
  26260. if (hasStroke) {
  26261. doStrokePath(ctx, style);
  26262. }
  26263. }
  26264. }
  26265. if (lineDash) {
  26266. ctx.setLineDash([]);
  26267. }
  26268. }
  26269. function brushImage(ctx, el, style) {
  26270. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  26271. if (!image || !isImageReady(image)) {
  26272. return;
  26273. }
  26274. var x = style.x || 0;
  26275. var y = style.y || 0;
  26276. var width = el.getWidth();
  26277. var height = el.getHeight();
  26278. var aspect = image.width / image.height;
  26279. if (width == null && height != null) {
  26280. width = height * aspect;
  26281. }
  26282. else if (height == null && width != null) {
  26283. height = width / aspect;
  26284. }
  26285. else if (width == null && height == null) {
  26286. width = image.width;
  26287. height = image.height;
  26288. }
  26289. if (style.sWidth && style.sHeight) {
  26290. var sx = style.sx || 0;
  26291. var sy = style.sy || 0;
  26292. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  26293. }
  26294. else if (style.sx && style.sy) {
  26295. var sx = style.sx;
  26296. var sy = style.sy;
  26297. var sWidth = width - sx;
  26298. var sHeight = height - sy;
  26299. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  26300. }
  26301. else {
  26302. ctx.drawImage(image, x, y, width, height);
  26303. }
  26304. }
  26305. function brushText(ctx, el, style) {
  26306. var _a;
  26307. var text = style.text;
  26308. text != null && (text += '');
  26309. if (text) {
  26310. ctx.font = style.font || DEFAULT_FONT;
  26311. ctx.textAlign = style.textAlign;
  26312. ctx.textBaseline = style.textBaseline;
  26313. var lineDash = void 0;
  26314. var lineDashOffset = void 0;
  26315. if (ctx.setLineDash && style.lineDash) {
  26316. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  26317. }
  26318. if (lineDash) {
  26319. ctx.setLineDash(lineDash);
  26320. ctx.lineDashOffset = lineDashOffset;
  26321. }
  26322. if (style.strokeFirst) {
  26323. if (styleHasStroke(style)) {
  26324. ctx.strokeText(text, style.x, style.y);
  26325. }
  26326. if (styleHasFill(style)) {
  26327. ctx.fillText(text, style.x, style.y);
  26328. }
  26329. }
  26330. else {
  26331. if (styleHasFill(style)) {
  26332. ctx.fillText(text, style.x, style.y);
  26333. }
  26334. if (styleHasStroke(style)) {
  26335. ctx.strokeText(text, style.x, style.y);
  26336. }
  26337. }
  26338. if (lineDash) {
  26339. ctx.setLineDash([]);
  26340. }
  26341. }
  26342. }
  26343. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  26344. var STROKE_PROPS = [
  26345. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  26346. ];
  26347. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  26348. var styleChanged = false;
  26349. if (!forceSetAll) {
  26350. prevStyle = prevStyle || {};
  26351. if (style === prevStyle) {
  26352. return false;
  26353. }
  26354. }
  26355. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  26356. flushPathDrawn(ctx, scope);
  26357. styleChanged = true;
  26358. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  26359. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  26360. }
  26361. if (forceSetAll || style.blend !== prevStyle.blend) {
  26362. if (!styleChanged) {
  26363. flushPathDrawn(ctx, scope);
  26364. styleChanged = true;
  26365. }
  26366. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  26367. }
  26368. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  26369. var propName = SHADOW_NUMBER_PROPS[i];
  26370. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  26371. if (!styleChanged) {
  26372. flushPathDrawn(ctx, scope);
  26373. styleChanged = true;
  26374. }
  26375. ctx[propName] = ctx.dpr * (style[propName] || 0);
  26376. }
  26377. }
  26378. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  26379. if (!styleChanged) {
  26380. flushPathDrawn(ctx, scope);
  26381. styleChanged = true;
  26382. }
  26383. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  26384. }
  26385. return styleChanged;
  26386. }
  26387. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  26388. var style = getStyle(el, scope.inHover);
  26389. var prevStyle = forceSetAll
  26390. ? null
  26391. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  26392. if (style === prevStyle) {
  26393. return false;
  26394. }
  26395. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  26396. if (forceSetAll || style.fill !== prevStyle.fill) {
  26397. if (!styleChanged) {
  26398. flushPathDrawn(ctx, scope);
  26399. styleChanged = true;
  26400. }
  26401. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  26402. }
  26403. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  26404. if (!styleChanged) {
  26405. flushPathDrawn(ctx, scope);
  26406. styleChanged = true;
  26407. }
  26408. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  26409. }
  26410. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  26411. if (!styleChanged) {
  26412. flushPathDrawn(ctx, scope);
  26413. styleChanged = true;
  26414. }
  26415. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  26416. }
  26417. if (el.hasStroke()) {
  26418. var lineWidth = style.lineWidth;
  26419. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  26420. if (ctx.lineWidth !== newLineWidth) {
  26421. if (!styleChanged) {
  26422. flushPathDrawn(ctx, scope);
  26423. styleChanged = true;
  26424. }
  26425. ctx.lineWidth = newLineWidth;
  26426. }
  26427. }
  26428. for (var i = 0; i < STROKE_PROPS.length; i++) {
  26429. var prop = STROKE_PROPS[i];
  26430. var propName = prop[0];
  26431. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  26432. if (!styleChanged) {
  26433. flushPathDrawn(ctx, scope);
  26434. styleChanged = true;
  26435. }
  26436. ctx[propName] = style[propName] || prop[1];
  26437. }
  26438. }
  26439. return styleChanged;
  26440. }
  26441. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  26442. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  26443. }
  26444. function setContextTransform(ctx, el) {
  26445. var m = el.transform;
  26446. var dpr = ctx.dpr || 1;
  26447. if (m) {
  26448. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  26449. }
  26450. else {
  26451. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  26452. }
  26453. }
  26454. function updateClipStatus(clipPaths, ctx, scope) {
  26455. var allClipped = false;
  26456. for (var i = 0; i < clipPaths.length; i++) {
  26457. var clipPath = clipPaths[i];
  26458. allClipped = allClipped || clipPath.isZeroArea();
  26459. setContextTransform(ctx, clipPath);
  26460. ctx.beginPath();
  26461. clipPath.buildPath(ctx, clipPath.shape);
  26462. ctx.clip();
  26463. }
  26464. scope.allClipped = allClipped;
  26465. }
  26466. function isTransformChanged(m0, m1) {
  26467. if (m0 && m1) {
  26468. return m0[0] !== m1[0]
  26469. || m0[1] !== m1[1]
  26470. || m0[2] !== m1[2]
  26471. || m0[3] !== m1[3]
  26472. || m0[4] !== m1[4]
  26473. || m0[5] !== m1[5];
  26474. }
  26475. else if (!m0 && !m1) {
  26476. return false;
  26477. }
  26478. return true;
  26479. }
  26480. var DRAW_TYPE_PATH = 1;
  26481. var DRAW_TYPE_IMAGE = 2;
  26482. var DRAW_TYPE_TEXT = 3;
  26483. var DRAW_TYPE_INCREMENTAL = 4;
  26484. function canPathBatch(style) {
  26485. var hasFill = styleHasFill(style);
  26486. var hasStroke = styleHasStroke(style);
  26487. return !(style.lineDash
  26488. || !(+hasFill ^ +hasStroke)
  26489. || (hasFill && typeof style.fill !== 'string')
  26490. || (hasStroke && typeof style.stroke !== 'string')
  26491. || style.strokePercent < 1
  26492. || style.strokeOpacity < 1
  26493. || style.fillOpacity < 1);
  26494. }
  26495. function flushPathDrawn(ctx, scope) {
  26496. scope.batchFill && ctx.fill();
  26497. scope.batchStroke && ctx.stroke();
  26498. scope.batchFill = '';
  26499. scope.batchStroke = '';
  26500. }
  26501. function getStyle(el, inHover) {
  26502. return inHover ? (el.__hoverStyle || el.style) : el.style;
  26503. }
  26504. function brushSingle(ctx, el) {
  26505. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  26506. }
  26507. function brush(ctx, el, scope, isLast) {
  26508. var m = el.transform;
  26509. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  26510. el.__dirty &= ~REDRAW_BIT;
  26511. el.__isRendered = false;
  26512. return;
  26513. }
  26514. var clipPaths = el.__clipPaths;
  26515. var prevElClipPaths = scope.prevElClipPaths;
  26516. var forceSetTransform = false;
  26517. var forceSetStyle = false;
  26518. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  26519. if (prevElClipPaths && prevElClipPaths.length) {
  26520. flushPathDrawn(ctx, scope);
  26521. ctx.restore();
  26522. forceSetStyle = forceSetTransform = true;
  26523. scope.prevElClipPaths = null;
  26524. scope.allClipped = false;
  26525. scope.prevEl = null;
  26526. }
  26527. if (clipPaths && clipPaths.length) {
  26528. flushPathDrawn(ctx, scope);
  26529. ctx.save();
  26530. updateClipStatus(clipPaths, ctx, scope);
  26531. forceSetTransform = true;
  26532. }
  26533. scope.prevElClipPaths = clipPaths;
  26534. }
  26535. if (scope.allClipped) {
  26536. el.__isRendered = false;
  26537. return;
  26538. }
  26539. el.beforeBrush && el.beforeBrush();
  26540. el.innerBeforeBrush();
  26541. var prevEl = scope.prevEl;
  26542. if (!prevEl) {
  26543. forceSetStyle = forceSetTransform = true;
  26544. }
  26545. var canBatchPath = el instanceof Path
  26546. && el.autoBatch
  26547. && canPathBatch(el.style);
  26548. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  26549. flushPathDrawn(ctx, scope);
  26550. setContextTransform(ctx, el);
  26551. }
  26552. else if (!canBatchPath) {
  26553. flushPathDrawn(ctx, scope);
  26554. }
  26555. var style = getStyle(el, scope.inHover);
  26556. if (el instanceof Path) {
  26557. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  26558. forceSetStyle = true;
  26559. scope.lastDrawType = DRAW_TYPE_PATH;
  26560. }
  26561. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  26562. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  26563. ctx.beginPath();
  26564. }
  26565. brushPath(ctx, el, style, canBatchPath);
  26566. if (canBatchPath) {
  26567. scope.batchFill = style.fill || '';
  26568. scope.batchStroke = style.stroke || '';
  26569. }
  26570. }
  26571. else {
  26572. if (el instanceof TSpan) {
  26573. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  26574. forceSetStyle = true;
  26575. scope.lastDrawType = DRAW_TYPE_TEXT;
  26576. }
  26577. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  26578. brushText(ctx, el, style);
  26579. }
  26580. else if (el instanceof ZRImage) {
  26581. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  26582. forceSetStyle = true;
  26583. scope.lastDrawType = DRAW_TYPE_IMAGE;
  26584. }
  26585. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  26586. brushImage(ctx, el, style);
  26587. }
  26588. else if (el.getTemporalDisplayables) {
  26589. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  26590. forceSetStyle = true;
  26591. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  26592. }
  26593. brushIncremental(ctx, el, scope);
  26594. }
  26595. }
  26596. if (canBatchPath && isLast) {
  26597. flushPathDrawn(ctx, scope);
  26598. }
  26599. el.innerAfterBrush();
  26600. el.afterBrush && el.afterBrush();
  26601. scope.prevEl = el;
  26602. el.__dirty = 0;
  26603. el.__isRendered = true;
  26604. }
  26605. function brushIncremental(ctx, el, scope) {
  26606. var displayables = el.getDisplayables();
  26607. var temporalDisplayables = el.getTemporalDisplayables();
  26608. ctx.save();
  26609. var innerScope = {
  26610. prevElClipPaths: null,
  26611. prevEl: null,
  26612. allClipped: false,
  26613. viewWidth: scope.viewWidth,
  26614. viewHeight: scope.viewHeight,
  26615. inHover: scope.inHover
  26616. };
  26617. var i;
  26618. var len;
  26619. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  26620. var displayable = displayables[i];
  26621. displayable.beforeBrush && displayable.beforeBrush();
  26622. displayable.innerBeforeBrush();
  26623. brush(ctx, displayable, innerScope, i === len - 1);
  26624. displayable.innerAfterBrush();
  26625. displayable.afterBrush && displayable.afterBrush();
  26626. innerScope.prevEl = displayable;
  26627. }
  26628. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  26629. var displayable = temporalDisplayables[i_1];
  26630. displayable.beforeBrush && displayable.beforeBrush();
  26631. displayable.innerBeforeBrush();
  26632. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  26633. displayable.innerAfterBrush();
  26634. displayable.afterBrush && displayable.afterBrush();
  26635. innerScope.prevEl = displayable;
  26636. }
  26637. el.clearTemporalDisplayables();
  26638. el.notClear = true;
  26639. ctx.restore();
  26640. }
  26641. var decalMap = new WeakMap();
  26642. var decalCache = new LRU(100);
  26643. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  26644. /**
  26645. * Create or update pattern image from decal options
  26646. *
  26647. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  26648. * @return {Pattern} pattern with generated image, null if no decal
  26649. */
  26650. function createOrUpdatePatternFromDecal(decalObject, api) {
  26651. if (decalObject === 'none') {
  26652. return null;
  26653. }
  26654. var dpr = api.getDevicePixelRatio();
  26655. var zr = api.getZr();
  26656. var isSVG = zr.painter.type === 'svg';
  26657. if (decalObject.dirty) {
  26658. decalMap["delete"](decalObject);
  26659. }
  26660. var oldPattern = decalMap.get(decalObject);
  26661. if (oldPattern) {
  26662. return oldPattern;
  26663. }
  26664. var decalOpt = defaults(decalObject, {
  26665. symbol: 'rect',
  26666. symbolSize: 1,
  26667. symbolKeepAspect: true,
  26668. color: 'rgba(0, 0, 0, 0.2)',
  26669. backgroundColor: null,
  26670. dashArrayX: 5,
  26671. dashArrayY: 5,
  26672. rotation: 0,
  26673. maxTileWidth: 512,
  26674. maxTileHeight: 512
  26675. });
  26676. if (decalOpt.backgroundColor === 'none') {
  26677. decalOpt.backgroundColor = null;
  26678. }
  26679. var pattern = {
  26680. repeat: 'repeat'
  26681. };
  26682. setPatternnSource(pattern);
  26683. pattern.rotation = decalOpt.rotation;
  26684. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  26685. decalMap.set(decalObject, pattern);
  26686. decalObject.dirty = false;
  26687. return pattern;
  26688. function setPatternnSource(pattern) {
  26689. var keys = [dpr];
  26690. var isValidKey = true;
  26691. for (var i = 0; i < decalKeys.length; ++i) {
  26692. var value = decalOpt[decalKeys[i]];
  26693. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  26694. isValidKey = false;
  26695. break;
  26696. }
  26697. keys.push(value);
  26698. }
  26699. var cacheKey;
  26700. if (isValidKey) {
  26701. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  26702. var cache = decalCache.get(cacheKey);
  26703. if (cache) {
  26704. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  26705. }
  26706. }
  26707. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  26708. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  26709. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  26710. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  26711. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  26712. var canvas = !isSVG && platformApi.createCanvas();
  26713. var svgRoot = isSVG && {
  26714. tag: 'g',
  26715. attrs: {},
  26716. key: 'dcl',
  26717. children: []
  26718. };
  26719. var pSize = getPatternSize();
  26720. var ctx;
  26721. if (canvas) {
  26722. canvas.width = pSize.width * dpr;
  26723. canvas.height = pSize.height * dpr;
  26724. ctx = canvas.getContext('2d');
  26725. }
  26726. brushDecal();
  26727. if (isValidKey) {
  26728. decalCache.put(cacheKey, canvas || svgRoot);
  26729. }
  26730. pattern.image = canvas;
  26731. pattern.svgElement = svgRoot;
  26732. pattern.svgWidth = pSize.width;
  26733. pattern.svgHeight = pSize.height;
  26734. /**
  26735. * Get minimum length that can make a repeatable pattern.
  26736. *
  26737. * @return {Object} pattern width and height
  26738. */
  26739. function getPatternSize() {
  26740. /**
  26741. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  26742. * |--- --- --- --- --- ...
  26743. * |-- -- -- -- -- -- -- -- ...
  26744. * |--- --- --- --- --- ...
  26745. * |-- -- -- -- -- -- -- -- ...
  26746. * So the minimum length of X is 15,
  26747. * which is the least common multiple of `3 + 2` and `2 + 1`
  26748. * |--- --- --- |--- --- ...
  26749. * |-- -- -- -- -- |-- -- -- ...
  26750. */
  26751. var width = 1;
  26752. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  26753. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  26754. }
  26755. var symbolRepeats = 1;
  26756. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  26757. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  26758. }
  26759. width *= symbolRepeats;
  26760. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  26761. if ("development" !== 'production') {
  26762. var warn = function (attrName) {
  26763. /* eslint-disable-next-line */
  26764. 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.");
  26765. };
  26766. if (width > decalOpt.maxTileWidth) {
  26767. warn('maxTileWidth');
  26768. }
  26769. if (height > decalOpt.maxTileHeight) {
  26770. warn('maxTileHeight');
  26771. }
  26772. }
  26773. return {
  26774. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  26775. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  26776. };
  26777. }
  26778. function brushDecal() {
  26779. if (ctx) {
  26780. ctx.clearRect(0, 0, canvas.width, canvas.height);
  26781. if (decalOpt.backgroundColor) {
  26782. ctx.fillStyle = decalOpt.backgroundColor;
  26783. ctx.fillRect(0, 0, canvas.width, canvas.height);
  26784. }
  26785. }
  26786. var ySum = 0;
  26787. for (var i = 0; i < dashArrayY.length; ++i) {
  26788. ySum += dashArrayY[i];
  26789. }
  26790. if (ySum <= 0) {
  26791. // dashArrayY is 0, draw nothing
  26792. return;
  26793. }
  26794. var y = -lineBlockLengthY;
  26795. var yId = 0;
  26796. var yIdTotal = 0;
  26797. var xId0 = 0;
  26798. while (y < pSize.height) {
  26799. if (yId % 2 === 0) {
  26800. var symbolYId = yIdTotal / 2 % symbolArray.length;
  26801. var x = 0;
  26802. var xId1 = 0;
  26803. var xId1Total = 0;
  26804. while (x < pSize.width * 2) {
  26805. var xSum = 0;
  26806. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  26807. xSum += dashArrayX[xId0][i];
  26808. }
  26809. if (xSum <= 0) {
  26810. // Skip empty line
  26811. break;
  26812. }
  26813. // E.g., [15, 5, 20, 5] draws only for 15 and 20
  26814. if (xId1 % 2 === 0) {
  26815. var size = (1 - decalOpt.symbolSize) * 0.5;
  26816. var left = x + dashArrayX[xId0][xId1] * size;
  26817. var top_1 = y + dashArrayY[yId] * size;
  26818. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  26819. var height = dashArrayY[yId] * decalOpt.symbolSize;
  26820. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  26821. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  26822. }
  26823. x += dashArrayX[xId0][xId1];
  26824. ++xId1Total;
  26825. ++xId1;
  26826. if (xId1 === dashArrayX[xId0].length) {
  26827. xId1 = 0;
  26828. }
  26829. }
  26830. ++xId0;
  26831. if (xId0 === dashArrayX.length) {
  26832. xId0 = 0;
  26833. }
  26834. }
  26835. y += dashArrayY[yId];
  26836. ++yIdTotal;
  26837. ++yId;
  26838. if (yId === dashArrayY.length) {
  26839. yId = 0;
  26840. }
  26841. }
  26842. function brushSymbol(x, y, width, height, symbolType) {
  26843. var scale = isSVG ? 1 : dpr;
  26844. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  26845. if (isSVG) {
  26846. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  26847. if (symbolVNode) {
  26848. svgRoot.children.push(symbolVNode);
  26849. }
  26850. } else {
  26851. // Paint to canvas for all other renderers.
  26852. brushSingle(ctx, symbol);
  26853. }
  26854. }
  26855. }
  26856. }
  26857. }
  26858. /**
  26859. * Convert symbol array into normalized array
  26860. *
  26861. * @param {string | (string | string[])[]} symbol symbol input
  26862. * @return {string[][]} normolized symbol array
  26863. */
  26864. function normalizeSymbolArray(symbol) {
  26865. if (!symbol || symbol.length === 0) {
  26866. return [['rect']];
  26867. }
  26868. if (isString(symbol)) {
  26869. return [[symbol]];
  26870. }
  26871. var isAllString = true;
  26872. for (var i = 0; i < symbol.length; ++i) {
  26873. if (!isString(symbol[i])) {
  26874. isAllString = false;
  26875. break;
  26876. }
  26877. }
  26878. if (isAllString) {
  26879. return normalizeSymbolArray([symbol]);
  26880. }
  26881. var result = [];
  26882. for (var i = 0; i < symbol.length; ++i) {
  26883. if (isString(symbol[i])) {
  26884. result.push([symbol[i]]);
  26885. } else {
  26886. result.push(symbol[i]);
  26887. }
  26888. }
  26889. return result;
  26890. }
  26891. /**
  26892. * Convert dash input into dashArray
  26893. *
  26894. * @param {DecalDashArrayX} dash dash input
  26895. * @return {number[][]} normolized dash array
  26896. */
  26897. function normalizeDashArrayX(dash) {
  26898. if (!dash || dash.length === 0) {
  26899. return [[0, 0]];
  26900. }
  26901. if (isNumber(dash)) {
  26902. var dashValue = Math.ceil(dash);
  26903. return [[dashValue, dashValue]];
  26904. }
  26905. /**
  26906. * [20, 5] should be normalized into [[20, 5]],
  26907. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  26908. */
  26909. var isAllNumber = true;
  26910. for (var i = 0; i < dash.length; ++i) {
  26911. if (!isNumber(dash[i])) {
  26912. isAllNumber = false;
  26913. break;
  26914. }
  26915. }
  26916. if (isAllNumber) {
  26917. return normalizeDashArrayX([dash]);
  26918. }
  26919. var result = [];
  26920. for (var i = 0; i < dash.length; ++i) {
  26921. if (isNumber(dash[i])) {
  26922. var dashValue = Math.ceil(dash[i]);
  26923. result.push([dashValue, dashValue]);
  26924. } else {
  26925. var dashValue = map(dash[i], function (n) {
  26926. return Math.ceil(n);
  26927. });
  26928. if (dashValue.length % 2 === 1) {
  26929. // [4, 2, 1] means |---- - -- |---- - -- |
  26930. // so normalize it to be [4, 2, 1, 4, 2, 1]
  26931. result.push(dashValue.concat(dashValue));
  26932. } else {
  26933. result.push(dashValue);
  26934. }
  26935. }
  26936. }
  26937. return result;
  26938. }
  26939. /**
  26940. * Convert dash input into dashArray
  26941. *
  26942. * @param {DecalDashArrayY} dash dash input
  26943. * @return {number[]} normolized dash array
  26944. */
  26945. function normalizeDashArrayY(dash) {
  26946. if (!dash || typeof dash === 'object' && dash.length === 0) {
  26947. return [0, 0];
  26948. }
  26949. if (isNumber(dash)) {
  26950. var dashValue_1 = Math.ceil(dash);
  26951. return [dashValue_1, dashValue_1];
  26952. }
  26953. var dashValue = map(dash, function (n) {
  26954. return Math.ceil(n);
  26955. });
  26956. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  26957. }
  26958. /**
  26959. * Get block length of each line. A block is the length of dash line and space.
  26960. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  26961. * that, so the block length of this line is 5.
  26962. *
  26963. * @param {number[][]} dash dash array of X or Y
  26964. * @return {number[]} block length of each line
  26965. */
  26966. function getLineBlockLengthX(dash) {
  26967. return map(dash, function (line) {
  26968. return getLineBlockLengthY(line);
  26969. });
  26970. }
  26971. function getLineBlockLengthY(dash) {
  26972. var blockLength = 0;
  26973. for (var i = 0; i < dash.length; ++i) {
  26974. blockLength += dash[i];
  26975. }
  26976. if (dash.length % 2 === 1) {
  26977. // [4, 2, 1] means |---- - -- |---- - -- |
  26978. // So total length is (4 + 2 + 1) * 2
  26979. return blockLength * 2;
  26980. }
  26981. return blockLength;
  26982. }
  26983. function decalVisual(ecModel, api) {
  26984. ecModel.eachRawSeries(function (seriesModel) {
  26985. if (ecModel.isSeriesFiltered(seriesModel)) {
  26986. return;
  26987. }
  26988. var data = seriesModel.getData();
  26989. if (data.hasItemVisual()) {
  26990. data.each(function (idx) {
  26991. var decal = data.getItemVisual(idx, 'decal');
  26992. if (decal) {
  26993. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  26994. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  26995. }
  26996. });
  26997. }
  26998. var decal = data.getVisual('decal');
  26999. if (decal) {
  27000. var style = data.getVisual('style');
  27001. style.decal = createOrUpdatePatternFromDecal(decal, api);
  27002. }
  27003. });
  27004. }
  27005. var lifecycle = new Eventful();
  27006. // Implementation of exported APIs. For example registerMap, getMap.
  27007. // The implementations will be registered when installing the component.
  27008. // Avoid these code being bundled to the core module.
  27009. var implsStore = {};
  27010. // TODO Type
  27011. function registerImpl(name, impl) {
  27012. if ("development" !== 'production') {
  27013. if (implsStore[name]) {
  27014. error("Already has an implementation of " + name + ".");
  27015. }
  27016. }
  27017. implsStore[name] = impl;
  27018. }
  27019. function getImpl(name) {
  27020. if ("development" !== 'production') {
  27021. if (!implsStore[name]) {
  27022. error("Implementation of " + name + " doesn't exists.");
  27023. }
  27024. }
  27025. return implsStore[name];
  27026. }
  27027. var version$1 = '6.0.0';
  27028. var dependencies = {
  27029. zrender: '6.0.0'
  27030. };
  27031. var TEST_FRAME_REMAIN_TIME = 1;
  27032. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  27033. // Some data processors depends on the stack result dimension (to calculate data extent).
  27034. // So data stack stage should be in front of data processing stage.
  27035. var PRIORITY_PROCESSOR_DATASTACK = 900;
  27036. // "Data filter" will block the stream, so it should be
  27037. // put at the beginning of data processing.
  27038. var PRIORITY_PROCESSOR_FILTER = 1000;
  27039. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  27040. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  27041. var PRIORITY_VISUAL_LAYOUT = 1000;
  27042. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  27043. var PRIORITY_VISUAL_GLOBAL = 2000;
  27044. var PRIORITY_VISUAL_CHART = 3000;
  27045. var PRIORITY_VISUAL_COMPONENT = 4000;
  27046. // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  27047. // overwrite the viusal result of component (like `visualMap`)
  27048. // using data item specific setting (like itemStyle.xxx on data item)
  27049. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500;
  27050. // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  27051. // visual result like `symbolSize`.
  27052. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  27053. var PRIORITY_VISUAL_BRUSH = 5000;
  27054. var PRIORITY_VISUAL_ARIA = 6000;
  27055. var PRIORITY_VISUAL_DECAL = 7000;
  27056. var PRIORITY = {
  27057. PROCESSOR: {
  27058. FILTER: PRIORITY_PROCESSOR_FILTER,
  27059. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  27060. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  27061. },
  27062. VISUAL: {
  27063. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  27064. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  27065. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  27066. CHART: PRIORITY_VISUAL_CHART,
  27067. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  27068. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  27069. BRUSH: PRIORITY_VISUAL_BRUSH,
  27070. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  27071. ARIA: PRIORITY_VISUAL_ARIA,
  27072. DECAL: PRIORITY_VISUAL_DECAL
  27073. }
  27074. };
  27075. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  27076. // where they must not be invoked nestedly, except the only case: invoke
  27077. // dispatchAction with updateMethod "none" in main process.
  27078. // This flag is used to carry out this rule.
  27079. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  27080. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  27081. // Useful for detecting outdated rendering results in scenarios that these issues are involved:
  27082. // - Use shortcut (such as, updateTransform, or no update) to start a main process.
  27083. // - Asynchronously update rendered view (e.g., graph force layout).
  27084. // - Multiple ChartView/ComponentView render to one group cooperatively.
  27085. var MAIN_PROCESS_VERSION_KEY = '__mainProcessVersion';
  27086. var PENDING_UPDATE = '__pendingUpdate';
  27087. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  27088. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  27089. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  27090. var CONNECT_STATUS_PENDING = 0;
  27091. var CONNECT_STATUS_UPDATING = 1;
  27092. var CONNECT_STATUS_UPDATED = 2;
  27093. function createRegisterEventWithLowercaseECharts(method) {
  27094. return function () {
  27095. var args = [];
  27096. for (var _i = 0; _i < arguments.length; _i++) {
  27097. args[_i] = arguments[_i];
  27098. }
  27099. if (this.isDisposed()) {
  27100. disposedWarning(this.id);
  27101. return;
  27102. }
  27103. return toLowercaseNameAndCallEventful(this, method, args);
  27104. };
  27105. }
  27106. function createRegisterEventWithLowercaseMessageCenter(method) {
  27107. return function () {
  27108. var args = [];
  27109. for (var _i = 0; _i < arguments.length; _i++) {
  27110. args[_i] = arguments[_i];
  27111. }
  27112. return toLowercaseNameAndCallEventful(this, method, args);
  27113. };
  27114. }
  27115. function toLowercaseNameAndCallEventful(host, method, args) {
  27116. // `args[0]` is event name. Event name is all lowercase.
  27117. args[0] = args[0] && args[0].toLowerCase();
  27118. return Eventful.prototype[method].apply(host, args);
  27119. }
  27120. var MessageCenter = /** @class */function (_super) {
  27121. __extends(MessageCenter, _super);
  27122. function MessageCenter() {
  27123. return _super !== null && _super.apply(this, arguments) || this;
  27124. }
  27125. return MessageCenter;
  27126. }(Eventful);
  27127. var messageCenterProto = MessageCenter.prototype;
  27128. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  27129. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off');
  27130. // ---------------------------------------
  27131. // Internal method names for class ECharts
  27132. // ---------------------------------------
  27133. var prepare;
  27134. var prepareView;
  27135. var updateDirectly;
  27136. var updateMethods;
  27137. var doConvertPixel;
  27138. var updateStreamModes;
  27139. var doDispatchAction;
  27140. var flushPendingActions;
  27141. var triggerUpdatedEvent;
  27142. var bindRenderedEvent;
  27143. var bindMouseEvent;
  27144. var render;
  27145. var renderComponents;
  27146. var renderSeries;
  27147. var createExtensionAPI;
  27148. var enableConnect;
  27149. var markStatusToUpdate;
  27150. var applyChangedStates;
  27151. var updateMainProcessVersion;
  27152. var ECharts = /** @class */function (_super) {
  27153. __extends(ECharts, _super);
  27154. function ECharts(dom,
  27155. // Theme name or themeOption.
  27156. theme, opts) {
  27157. var _this = _super.call(this, new ECEventProcessor()) || this;
  27158. _this._chartsViews = [];
  27159. _this._chartsMap = {};
  27160. _this._componentsViews = [];
  27161. _this._componentsMap = {};
  27162. // Can't dispatch action during rendering procedure
  27163. _this._pendingActions = [];
  27164. opts = opts || {};
  27165. _this._dom = dom;
  27166. var defaultRenderer = 'canvas';
  27167. var defaultCoarsePointer = 'auto';
  27168. var defaultUseDirtyRect = false;
  27169. _this[MAIN_PROCESS_VERSION_KEY] = 1;
  27170. if ("development" !== 'production') {
  27171. var root = /* eslint-disable-next-line */
  27172. env.hasGlobalWindow ? window : global;
  27173. if (root) {
  27174. defaultRenderer = retrieve2(root.__ECHARTS__DEFAULT__RENDERER__, defaultRenderer);
  27175. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  27176. defaultUseDirtyRect = retrieve2(root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__, defaultUseDirtyRect);
  27177. }
  27178. }
  27179. if (opts.ssr) {
  27180. registerSSRDataGetter(function (el) {
  27181. var ecData = getECData(el);
  27182. var dataIndex = ecData.dataIndex;
  27183. if (dataIndex == null) {
  27184. return;
  27185. }
  27186. var hashMap = createHashMap();
  27187. hashMap.set('series_index', ecData.seriesIndex);
  27188. hashMap.set('data_index', dataIndex);
  27189. ecData.ssrType && hashMap.set('ssr_type', ecData.ssrType);
  27190. return hashMap;
  27191. });
  27192. }
  27193. var zr = _this._zr = init(dom, {
  27194. renderer: opts.renderer || defaultRenderer,
  27195. devicePixelRatio: opts.devicePixelRatio,
  27196. width: opts.width,
  27197. height: opts.height,
  27198. ssr: opts.ssr,
  27199. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  27200. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  27201. pointerSize: opts.pointerSize
  27202. });
  27203. _this._ssr = opts.ssr;
  27204. // Expect 60 fps.
  27205. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  27206. _this._updateTheme(theme);
  27207. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  27208. _this._coordSysMgr = new CoordinateSystemManager();
  27209. var api = _this._api = createExtensionAPI(_this);
  27210. // Sort on demand
  27211. function prioritySortFunc(a, b) {
  27212. return a.__prio - b.__prio;
  27213. }
  27214. sort(visualFuncs, prioritySortFunc);
  27215. sort(dataProcessorFuncs, prioritySortFunc);
  27216. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  27217. _this._messageCenter = new MessageCenter();
  27218. // Init mouse events
  27219. _this._initEvents();
  27220. // In case some people write `window.onresize = chart.resize`
  27221. _this.resize = bind(_this.resize, _this);
  27222. zr.animation.on('frame', _this._onframe, _this);
  27223. bindRenderedEvent(zr, _this);
  27224. bindMouseEvent(zr, _this);
  27225. // ECharts instance can be used as value.
  27226. setAsPrimitive(_this);
  27227. return _this;
  27228. }
  27229. ECharts.prototype._onframe = function () {
  27230. if (this._disposed) {
  27231. return;
  27232. }
  27233. applyChangedStates(this);
  27234. var scheduler = this._scheduler;
  27235. // Lazy update
  27236. if (this[PENDING_UPDATE]) {
  27237. var silent = this[PENDING_UPDATE].silent;
  27238. this[IN_MAIN_PROCESS_KEY] = true;
  27239. updateMainProcessVersion(this);
  27240. try {
  27241. prepare(this);
  27242. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  27243. } catch (e) {
  27244. this[IN_MAIN_PROCESS_KEY] = false;
  27245. this[PENDING_UPDATE] = null;
  27246. throw e;
  27247. }
  27248. // At present, in each frame, zrender performs:
  27249. // (1) animation step forward.
  27250. // (2) trigger('frame') (where this `_onframe` is called)
  27251. // (3) zrender flush (render).
  27252. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  27253. // will render the final state of the elements before the real animation started.
  27254. this._zr.flush();
  27255. this[IN_MAIN_PROCESS_KEY] = false;
  27256. this[PENDING_UPDATE] = null;
  27257. flushPendingActions.call(this, silent);
  27258. triggerUpdatedEvent.call(this, silent);
  27259. }
  27260. // Avoid do both lazy update and progress in one frame.
  27261. else if (scheduler.unfinished) {
  27262. // Stream progress.
  27263. var remainTime = TEST_FRAME_REMAIN_TIME;
  27264. var ecModel = this._model;
  27265. var api = this._api;
  27266. scheduler.unfinished = false;
  27267. do {
  27268. var startTime = +new Date();
  27269. scheduler.performSeriesTasks(ecModel);
  27270. // Currently dataProcessorFuncs do not check threshold.
  27271. scheduler.performDataProcessorTasks(ecModel);
  27272. updateStreamModes(this, ecModel);
  27273. // Do not update coordinate system here. Because that coord system update in
  27274. // each frame is not a good user experience. So we follow the rule that
  27275. // the extent of the coordinate system is determined in the first frame (the
  27276. // frame is executed immediately after task reset.
  27277. // this._coordSysMgr.update(ecModel, api);
  27278. // console.log('--- ec frame visual ---', remainTime);
  27279. scheduler.performVisualTasks(ecModel);
  27280. renderSeries(this, this._model, api, 'remain', {});
  27281. remainTime -= +new Date() - startTime;
  27282. } while (remainTime > 0 && scheduler.unfinished);
  27283. // Call flush explicitly for trigger finished event.
  27284. if (!scheduler.unfinished) {
  27285. this._zr.flush();
  27286. }
  27287. // Else, zr flushing be ensue within the same frame,
  27288. // because zr flushing is after onframe event.
  27289. }
  27290. };
  27291. ECharts.prototype.getDom = function () {
  27292. return this._dom;
  27293. };
  27294. ECharts.prototype.getId = function () {
  27295. return this.id;
  27296. };
  27297. ECharts.prototype.getZr = function () {
  27298. return this._zr;
  27299. };
  27300. ECharts.prototype.isSSR = function () {
  27301. return this._ssr;
  27302. };
  27303. /* eslint-disable-next-line */
  27304. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  27305. if (this[IN_MAIN_PROCESS_KEY]) {
  27306. if ("development" !== 'production') {
  27307. error('`setOption` should not be called during main process.');
  27308. }
  27309. return;
  27310. }
  27311. if (this._disposed) {
  27312. disposedWarning(this.id);
  27313. return;
  27314. }
  27315. var silent;
  27316. var replaceMerge;
  27317. var transitionOpt;
  27318. if (isObject(notMerge)) {
  27319. lazyUpdate = notMerge.lazyUpdate;
  27320. silent = notMerge.silent;
  27321. replaceMerge = notMerge.replaceMerge;
  27322. transitionOpt = notMerge.transition;
  27323. notMerge = notMerge.notMerge;
  27324. }
  27325. this[IN_MAIN_PROCESS_KEY] = true;
  27326. updateMainProcessVersion(this);
  27327. if (!this._model || notMerge) {
  27328. var optionManager = new OptionManager(this._api);
  27329. var theme = this._theme;
  27330. var ecModel = this._model = new GlobalModel();
  27331. ecModel.scheduler = this._scheduler;
  27332. ecModel.ssr = this._ssr;
  27333. ecModel.init(null, null, null, theme, this._locale, optionManager);
  27334. }
  27335. this._model.setOption(option, {
  27336. replaceMerge: replaceMerge
  27337. }, optionPreprocessorFuncs);
  27338. var updateParams = {
  27339. seriesTransition: transitionOpt,
  27340. optionChanged: true
  27341. };
  27342. if (lazyUpdate) {
  27343. this[PENDING_UPDATE] = {
  27344. silent: silent,
  27345. updateParams: updateParams
  27346. };
  27347. this[IN_MAIN_PROCESS_KEY] = false;
  27348. // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  27349. // It should wake it up to make sure zrender start to render at the next frame.
  27350. this.getZr().wakeUp();
  27351. } else {
  27352. try {
  27353. prepare(this);
  27354. updateMethods.update.call(this, null, updateParams);
  27355. } catch (e) {
  27356. this[PENDING_UPDATE] = null;
  27357. this[IN_MAIN_PROCESS_KEY] = false;
  27358. throw e;
  27359. }
  27360. // Ensure zr refresh sychronously, and then pixel in canvas can be
  27361. // fetched after `setOption`.
  27362. if (!this._ssr) {
  27363. // not use flush when using ssr mode.
  27364. this._zr.flush();
  27365. }
  27366. this[PENDING_UPDATE] = null;
  27367. this[IN_MAIN_PROCESS_KEY] = false;
  27368. flushPendingActions.call(this, silent);
  27369. triggerUpdatedEvent.call(this, silent);
  27370. }
  27371. };
  27372. /**
  27373. * Update theme with name or theme option and repaint the chart.
  27374. * @param theme Theme name or theme option.
  27375. * @param opts Optional settings
  27376. */
  27377. ECharts.prototype.setTheme = function (theme, opts) {
  27378. if (this[IN_MAIN_PROCESS_KEY]) {
  27379. if ("development" !== 'production') {
  27380. error('`setTheme` should not be called during main process.');
  27381. }
  27382. return;
  27383. }
  27384. if (this._disposed) {
  27385. disposedWarning(this.id);
  27386. return;
  27387. }
  27388. var ecModel = this._model;
  27389. if (!ecModel) {
  27390. return;
  27391. }
  27392. var silent = opts && opts.silent;
  27393. var updateParams = null;
  27394. if (this[PENDING_UPDATE]) {
  27395. if (silent == null) {
  27396. silent = this[PENDING_UPDATE].silent;
  27397. }
  27398. updateParams = this[PENDING_UPDATE].updateParams;
  27399. this[PENDING_UPDATE] = null;
  27400. }
  27401. this[IN_MAIN_PROCESS_KEY] = true;
  27402. updateMainProcessVersion(this);
  27403. try {
  27404. this._updateTheme(theme);
  27405. ecModel.setTheme(this._theme);
  27406. prepare(this);
  27407. updateMethods.update.call(this, {
  27408. type: 'setTheme'
  27409. }, updateParams);
  27410. } catch (e) {
  27411. this[IN_MAIN_PROCESS_KEY] = false;
  27412. throw e;
  27413. }
  27414. this[IN_MAIN_PROCESS_KEY] = false;
  27415. flushPendingActions.call(this, silent);
  27416. triggerUpdatedEvent.call(this, silent);
  27417. };
  27418. ECharts.prototype._updateTheme = function (theme) {
  27419. if (isString(theme)) {
  27420. theme = themeStorage[theme];
  27421. }
  27422. if (theme) {
  27423. theme = clone(theme);
  27424. theme && globalBackwardCompat(theme, true);
  27425. this._theme = theme;
  27426. }
  27427. };
  27428. // We don't want developers to use getModel directly.
  27429. ECharts.prototype.getModel = function () {
  27430. return this._model;
  27431. };
  27432. ECharts.prototype.getOption = function () {
  27433. return this._model && this._model.getOption();
  27434. };
  27435. ECharts.prototype.getWidth = function () {
  27436. return this._zr.getWidth();
  27437. };
  27438. ECharts.prototype.getHeight = function () {
  27439. return this._zr.getHeight();
  27440. };
  27441. ECharts.prototype.getDevicePixelRatio = function () {
  27442. return this._zr.painter.dpr
  27443. /* eslint-disable-next-line */ || env.hasGlobalWindow && window.devicePixelRatio || 1;
  27444. };
  27445. /**
  27446. * Get canvas which has all thing rendered
  27447. * @deprecated Use renderToCanvas instead.
  27448. */
  27449. ECharts.prototype.getRenderedCanvas = function (opts) {
  27450. if ("development" !== 'production') {
  27451. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  27452. }
  27453. return this.renderToCanvas(opts);
  27454. };
  27455. ECharts.prototype.renderToCanvas = function (opts) {
  27456. opts = opts || {};
  27457. var painter = this._zr.painter;
  27458. if ("development" !== 'production') {
  27459. if (painter.type !== 'canvas') {
  27460. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  27461. }
  27462. }
  27463. return painter.getRenderedCanvas({
  27464. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  27465. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  27466. });
  27467. };
  27468. ECharts.prototype.renderToSVGString = function (opts) {
  27469. opts = opts || {};
  27470. var painter = this._zr.painter;
  27471. if ("development" !== 'production') {
  27472. if (painter.type !== 'svg') {
  27473. throw new Error('renderToSVGString can only be used in the svg renderer.');
  27474. }
  27475. }
  27476. return painter.renderToString({
  27477. useViewBox: opts.useViewBox
  27478. });
  27479. };
  27480. /**
  27481. * Get svg data url
  27482. */
  27483. ECharts.prototype.getSvgDataURL = function () {
  27484. var zr = this._zr;
  27485. var list = zr.storage.getDisplayList();
  27486. // Stop animations
  27487. each(list, function (el) {
  27488. el.stopAnimation(null, true);
  27489. });
  27490. return zr.painter.toDataURL();
  27491. };
  27492. ECharts.prototype.getDataURL = function (opts) {
  27493. if (this._disposed) {
  27494. disposedWarning(this.id);
  27495. return;
  27496. }
  27497. opts = opts || {};
  27498. var excludeComponents = opts.excludeComponents;
  27499. var ecModel = this._model;
  27500. var excludesComponentViews = [];
  27501. var self = this;
  27502. each(excludeComponents, function (componentType) {
  27503. ecModel.eachComponent({
  27504. mainType: componentType
  27505. }, function (component) {
  27506. var view = self._componentsMap[component.__viewId];
  27507. if (!view.group.ignore) {
  27508. excludesComponentViews.push(view);
  27509. view.group.ignore = true;
  27510. }
  27511. });
  27512. });
  27513. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  27514. each(excludesComponentViews, function (view) {
  27515. view.group.ignore = false;
  27516. });
  27517. return url;
  27518. };
  27519. ECharts.prototype.getConnectedDataURL = function (opts) {
  27520. if (this._disposed) {
  27521. disposedWarning(this.id);
  27522. return;
  27523. }
  27524. var isSvg = opts.type === 'svg';
  27525. var groupId = this.group;
  27526. var mathMin = Math.min;
  27527. var mathMax = Math.max;
  27528. var MAX_NUMBER = Infinity;
  27529. if (connectedGroups[groupId]) {
  27530. var left_1 = MAX_NUMBER;
  27531. var top_1 = MAX_NUMBER;
  27532. var right_1 = -MAX_NUMBER;
  27533. var bottom_1 = -MAX_NUMBER;
  27534. var canvasList_1 = [];
  27535. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  27536. each(instances$1, function (chart, id) {
  27537. if (chart.group === groupId) {
  27538. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  27539. var boundingRect = chart.getDom().getBoundingClientRect();
  27540. left_1 = mathMin(boundingRect.left, left_1);
  27541. top_1 = mathMin(boundingRect.top, top_1);
  27542. right_1 = mathMax(boundingRect.right, right_1);
  27543. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  27544. canvasList_1.push({
  27545. dom: canvas,
  27546. left: boundingRect.left,
  27547. top: boundingRect.top
  27548. });
  27549. }
  27550. });
  27551. left_1 *= dpr_1;
  27552. top_1 *= dpr_1;
  27553. right_1 *= dpr_1;
  27554. bottom_1 *= dpr_1;
  27555. var width = right_1 - left_1;
  27556. var height = bottom_1 - top_1;
  27557. var targetCanvas = platformApi.createCanvas();
  27558. var zr_1 = init(targetCanvas, {
  27559. renderer: isSvg ? 'svg' : 'canvas'
  27560. });
  27561. zr_1.resize({
  27562. width: width,
  27563. height: height
  27564. });
  27565. if (isSvg) {
  27566. var content_1 = '';
  27567. each(canvasList_1, function (item) {
  27568. var x = item.left - left_1;
  27569. var y = item.top - top_1;
  27570. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  27571. });
  27572. zr_1.painter.getSvgRoot().innerHTML = content_1;
  27573. if (opts.connectedBackgroundColor) {
  27574. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  27575. }
  27576. zr_1.refreshImmediately();
  27577. return zr_1.painter.toDataURL();
  27578. } else {
  27579. // Background between the charts
  27580. if (opts.connectedBackgroundColor) {
  27581. zr_1.add(new Rect({
  27582. shape: {
  27583. x: 0,
  27584. y: 0,
  27585. width: width,
  27586. height: height
  27587. },
  27588. style: {
  27589. fill: opts.connectedBackgroundColor
  27590. }
  27591. }));
  27592. }
  27593. each(canvasList_1, function (item) {
  27594. var img = new ZRImage({
  27595. style: {
  27596. x: item.left * dpr_1 - left_1,
  27597. y: item.top * dpr_1 - top_1,
  27598. image: item.dom
  27599. }
  27600. });
  27601. zr_1.add(img);
  27602. });
  27603. zr_1.refreshImmediately();
  27604. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  27605. }
  27606. } else {
  27607. return this.getDataURL(opts);
  27608. }
  27609. };
  27610. ECharts.prototype.convertToPixel = function (finder, value, opt) {
  27611. return doConvertPixel(this, 'convertToPixel', finder, value, opt);
  27612. };
  27613. /**
  27614. * Convert from logical coordinate system to pixel coordinate system.
  27615. * See CoordinateSystem#convertToPixel.
  27616. *
  27617. * @see CoordinateSystem['dataToLayout'] for parameters and return.
  27618. * @see CoordinateSystemDataCoord
  27619. */
  27620. ECharts.prototype.convertToLayout = function (finder, value, opt) {
  27621. return doConvertPixel(this, 'convertToLayout', finder, value, opt);
  27622. };
  27623. // The above are signatures from before v6, thus they should be preserved for backward compat.
  27624. ECharts.prototype.convertFromPixel = function (finder, value, opt) {
  27625. return doConvertPixel(this, 'convertFromPixel', finder, value, opt);
  27626. };
  27627. /**
  27628. * Is the specified coordinate systems or components contain the given pixel point.
  27629. * @param {Array|number} value
  27630. * @return {boolean} result
  27631. */
  27632. ECharts.prototype.containPixel = function (finder, value) {
  27633. if (this._disposed) {
  27634. disposedWarning(this.id);
  27635. return;
  27636. }
  27637. var ecModel = this._model;
  27638. var result;
  27639. var findResult = parseFinder(ecModel, finder);
  27640. each(findResult, function (models, key) {
  27641. key.indexOf('Models') >= 0 && each(models, function (model) {
  27642. var coordSys = model.coordinateSystem;
  27643. if (coordSys && coordSys.containPoint) {
  27644. result = result || !!coordSys.containPoint(value);
  27645. } else if (key === 'seriesModels') {
  27646. var view = this._chartsMap[model.__viewId];
  27647. if (view && view.containPoint) {
  27648. result = result || view.containPoint(value, model);
  27649. } else {
  27650. if ("development" !== 'production') {
  27651. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  27652. }
  27653. }
  27654. } else {
  27655. if ("development" !== 'production') {
  27656. warn(key + ': containPoint is not supported');
  27657. }
  27658. }
  27659. }, this);
  27660. }, this);
  27661. return !!result;
  27662. };
  27663. /**
  27664. * Get visual from series or data.
  27665. * @param finder
  27666. * If string, e.g., 'series', means {seriesIndex: 0}.
  27667. * If Object, could contain some of these properties below:
  27668. * {
  27669. * seriesIndex / seriesId / seriesName,
  27670. * dataIndex / dataIndexInside
  27671. * }
  27672. * If dataIndex is not specified, series visual will be fetched,
  27673. * but not data item visual.
  27674. * If all of seriesIndex, seriesId, seriesName are not specified,
  27675. * visual will be fetched from first series.
  27676. * @param visualType 'color', 'symbol', 'symbolSize'
  27677. */
  27678. ECharts.prototype.getVisual = function (finder, visualType) {
  27679. var ecModel = this._model;
  27680. var parsedFinder = parseFinder(ecModel, finder, {
  27681. defaultMainType: 'series'
  27682. });
  27683. var seriesModel = parsedFinder.seriesModel;
  27684. if ("development" !== 'production') {
  27685. if (!seriesModel) {
  27686. warn('There is no specified series model');
  27687. }
  27688. }
  27689. var data = seriesModel.getData();
  27690. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  27691. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  27692. };
  27693. /**
  27694. * Get view of corresponding component model
  27695. */
  27696. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  27697. return this._componentsMap[componentModel.__viewId];
  27698. };
  27699. /**
  27700. * Get view of corresponding series model
  27701. */
  27702. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  27703. return this._chartsMap[seriesModel.__viewId];
  27704. };
  27705. ECharts.prototype._initEvents = function () {
  27706. var _this = this;
  27707. each(MOUSE_EVENT_NAMES, function (eveName) {
  27708. var handler = function (e) {
  27709. var ecModel = _this.getModel();
  27710. var el = e.target;
  27711. var params;
  27712. var isGlobalOut = eveName === 'globalout';
  27713. // no e.target when 'globalout'.
  27714. if (isGlobalOut) {
  27715. params = {};
  27716. } else {
  27717. el && findEventDispatcher(el, function (parent) {
  27718. var ecData = getECData(parent);
  27719. if (ecData && ecData.dataIndex != null) {
  27720. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  27721. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType, el) || {};
  27722. return true;
  27723. }
  27724. // If element has custom eventData of components
  27725. else if (ecData.eventData) {
  27726. params = extend({}, ecData.eventData);
  27727. return true;
  27728. }
  27729. }, true);
  27730. }
  27731. // Contract: if params prepared in mouse event,
  27732. // these properties must be specified:
  27733. // {
  27734. // componentType: string (component main type)
  27735. // componentIndex: number
  27736. // }
  27737. // Otherwise event query can not work.
  27738. if (params) {
  27739. var componentType = params.componentType;
  27740. var componentIndex = params.componentIndex;
  27741. // Special handling for historic reason: when trigger by
  27742. // markLine/markPoint/markArea, the componentType is
  27743. // 'markLine'/'markPoint'/'markArea', but we should better
  27744. // enable them to be queried by seriesIndex, since their
  27745. // option is set in each series.
  27746. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  27747. componentType = 'series';
  27748. componentIndex = params.seriesIndex;
  27749. }
  27750. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  27751. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  27752. if ("development" !== 'production') {
  27753. // `event.componentType` and `event[componentTpype + 'Index']` must not
  27754. // be missed, otherwise there is no way to distinguish source component.
  27755. // See `dataFormat.getDataParams`.
  27756. if (!isGlobalOut && !(model && view)) {
  27757. warn('model or view can not be found by params');
  27758. }
  27759. }
  27760. params.event = e;
  27761. params.type = eveName;
  27762. _this._$eventProcessor.eventInfo = {
  27763. targetEl: el,
  27764. packedEvent: params,
  27765. model: model,
  27766. view: view
  27767. };
  27768. _this.trigger(eveName, params);
  27769. }
  27770. };
  27771. // Consider that some component (like tooltip, brush, ...)
  27772. // register zr event handler, but user event handler might
  27773. // do anything, such as call `setOption` or `dispatchAction`,
  27774. // which probably update any of the content and probably
  27775. // cause problem if it is called previous other inner handlers.
  27776. handler.zrEventfulCallAtLast = true;
  27777. _this._zr.on(eveName, handler, _this);
  27778. });
  27779. var messageCenter = this._messageCenter;
  27780. each(publicEventTypeMap, function (_, eventType) {
  27781. messageCenter.on(eventType, function (event) {
  27782. _this.trigger(eventType, event);
  27783. });
  27784. });
  27785. handleLegacySelectEvents(messageCenter, this, this._api);
  27786. };
  27787. ECharts.prototype.isDisposed = function () {
  27788. return this._disposed;
  27789. };
  27790. ECharts.prototype.clear = function () {
  27791. if (this._disposed) {
  27792. disposedWarning(this.id);
  27793. return;
  27794. }
  27795. this.setOption({
  27796. series: []
  27797. }, true);
  27798. };
  27799. ECharts.prototype.dispose = function () {
  27800. if (this._disposed) {
  27801. disposedWarning(this.id);
  27802. return;
  27803. }
  27804. this._disposed = true;
  27805. var dom = this.getDom();
  27806. if (dom) {
  27807. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  27808. }
  27809. var chart = this;
  27810. var api = chart._api;
  27811. var ecModel = chart._model;
  27812. each(chart._componentsViews, function (component) {
  27813. component.dispose(ecModel, api);
  27814. });
  27815. each(chart._chartsViews, function (chart) {
  27816. chart.dispose(ecModel, api);
  27817. });
  27818. // Dispose after all views disposed
  27819. chart._zr.dispose();
  27820. // Set properties to null.
  27821. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  27822. 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;
  27823. delete instances$1[chart.id];
  27824. };
  27825. /**
  27826. * Resize the chart
  27827. */
  27828. ECharts.prototype.resize = function (opts) {
  27829. if (this[IN_MAIN_PROCESS_KEY]) {
  27830. if ("development" !== 'production') {
  27831. error('`resize` should not be called during main process.');
  27832. }
  27833. return;
  27834. }
  27835. if (this._disposed) {
  27836. disposedWarning(this.id);
  27837. return;
  27838. }
  27839. this._zr.resize(opts);
  27840. var ecModel = this._model;
  27841. // Resize loading effect
  27842. this._loadingFX && this._loadingFX.resize();
  27843. if (!ecModel) {
  27844. return;
  27845. }
  27846. var needPrepare = ecModel.resetOption('media');
  27847. var silent = opts && opts.silent;
  27848. // There is some real cases that:
  27849. // chart.setOption(option, { lazyUpdate: true });
  27850. // chart.resize();
  27851. if (this[PENDING_UPDATE]) {
  27852. if (silent == null) {
  27853. silent = this[PENDING_UPDATE].silent;
  27854. }
  27855. needPrepare = true;
  27856. this[PENDING_UPDATE] = null;
  27857. }
  27858. this[IN_MAIN_PROCESS_KEY] = true;
  27859. updateMainProcessVersion(this);
  27860. try {
  27861. needPrepare && prepare(this);
  27862. updateMethods.update.call(this, {
  27863. type: 'resize',
  27864. animation: extend({
  27865. // Disable animation
  27866. duration: 0
  27867. }, opts && opts.animation)
  27868. });
  27869. } catch (e) {
  27870. this[IN_MAIN_PROCESS_KEY] = false;
  27871. throw e;
  27872. }
  27873. this[IN_MAIN_PROCESS_KEY] = false;
  27874. flushPendingActions.call(this, silent);
  27875. triggerUpdatedEvent.call(this, silent);
  27876. };
  27877. ECharts.prototype.showLoading = function (name, cfg) {
  27878. if (this._disposed) {
  27879. disposedWarning(this.id);
  27880. return;
  27881. }
  27882. if (isObject(name)) {
  27883. cfg = name;
  27884. name = '';
  27885. }
  27886. name = name || 'default';
  27887. this.hideLoading();
  27888. if (!loadingEffects[name]) {
  27889. if ("development" !== 'production') {
  27890. warn('Loading effects ' + name + ' not exists.');
  27891. }
  27892. return;
  27893. }
  27894. var el = loadingEffects[name](this._api, cfg);
  27895. var zr = this._zr;
  27896. this._loadingFX = el;
  27897. zr.add(el);
  27898. };
  27899. /**
  27900. * Hide loading effect
  27901. */
  27902. ECharts.prototype.hideLoading = function () {
  27903. if (this._disposed) {
  27904. disposedWarning(this.id);
  27905. return;
  27906. }
  27907. this._loadingFX && this._zr.remove(this._loadingFX);
  27908. this._loadingFX = null;
  27909. };
  27910. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  27911. var payload = extend({}, eventObj);
  27912. payload.type = connectionEventRevertMap[eventObj.type];
  27913. return payload;
  27914. };
  27915. /**
  27916. * @param opt If pass boolean, means opt.silent
  27917. * @param opt.silent Default `false`. Whether trigger events.
  27918. * @param opt.flush Default `undefined`.
  27919. * true: Flush immediately, and then pixel in canvas can be fetched
  27920. * immediately. Caution: it might affect performance.
  27921. * false: Not flush.
  27922. * undefined: Auto decide whether perform flush.
  27923. */
  27924. ECharts.prototype.dispatchAction = function (payload, opt) {
  27925. if (this._disposed) {
  27926. disposedWarning(this.id);
  27927. return;
  27928. }
  27929. if (!isObject(opt)) {
  27930. opt = {
  27931. silent: !!opt
  27932. };
  27933. }
  27934. if (!actions[payload.type]) {
  27935. return;
  27936. }
  27937. // Avoid dispatch action before setOption. Especially in `connect`.
  27938. if (!this._model) {
  27939. return;
  27940. }
  27941. // May dispatchAction in rendering procedure
  27942. if (this[IN_MAIN_PROCESS_KEY]) {
  27943. this._pendingActions.push(payload);
  27944. return;
  27945. }
  27946. var silent = opt.silent;
  27947. doDispatchAction.call(this, payload, silent);
  27948. var flush = opt.flush;
  27949. if (flush) {
  27950. this._zr.flush();
  27951. } else if (flush !== false && env.browser.weChat) {
  27952. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  27953. // hang when sliding page (on touch event), which cause that zr does not
  27954. // refresh until user interaction finished, which is not expected.
  27955. // But `dispatchAction` may be called too frequently when pan on touch
  27956. // screen, which impacts performance if do not throttle them.
  27957. this._throttledZrFlush();
  27958. }
  27959. flushPendingActions.call(this, silent);
  27960. triggerUpdatedEvent.call(this, silent);
  27961. };
  27962. ECharts.prototype.updateLabelLayout = function () {
  27963. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  27964. // Not adding series labels.
  27965. // TODO
  27966. updatedSeries: []
  27967. });
  27968. };
  27969. ECharts.prototype.appendData = function (params) {
  27970. if (this._disposed) {
  27971. disposedWarning(this.id);
  27972. return;
  27973. }
  27974. var seriesIndex = params.seriesIndex;
  27975. var ecModel = this.getModel();
  27976. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  27977. if ("development" !== 'production') {
  27978. assert(params.data && seriesModel);
  27979. }
  27980. seriesModel.appendData(params);
  27981. // Note: `appendData` does not support that update extent of coordinate
  27982. // system, util some scenario require that. In the expected usage of
  27983. // `appendData`, the initial extent of coordinate system should better
  27984. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  27985. // the extent changed while `appendData`, the location of the painted
  27986. // graphic elements have to be changed, which make the usage of
  27987. // `appendData` meaningless.
  27988. this._scheduler.unfinished = true;
  27989. this.getZr().wakeUp();
  27990. };
  27991. // A work around for no `internal` modifier in ts yet but
  27992. // need to strictly hide private methods to JS users.
  27993. ECharts.internalField = function () {
  27994. prepare = function (ecIns) {
  27995. var scheduler = ecIns._scheduler;
  27996. scheduler.restorePipelines(ecIns._model);
  27997. scheduler.prepareStageTasks();
  27998. prepareView(ecIns, true);
  27999. prepareView(ecIns, false);
  28000. scheduler.plan();
  28001. };
  28002. /**
  28003. * Prepare view instances of charts and components
  28004. */
  28005. prepareView = function (ecIns, isComponent) {
  28006. var ecModel = ecIns._model;
  28007. var scheduler = ecIns._scheduler;
  28008. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  28009. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  28010. var zr = ecIns._zr;
  28011. var api = ecIns._api;
  28012. for (var i = 0; i < viewList.length; i++) {
  28013. viewList[i].__alive = false;
  28014. }
  28015. isComponent ? ecModel.eachComponent(function (componentType, model) {
  28016. componentType !== 'series' && doPrepare(model);
  28017. }) : ecModel.eachSeries(doPrepare);
  28018. function doPrepare(model) {
  28019. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  28020. // mode and need to enable transition animation. (Usually, when they have the same id, or
  28021. // especially no id but have the same type & name & index. See the `model.id` generation
  28022. // rule in `makeIdAndName` and `viewId` generation rule here).
  28023. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  28024. // the new model has nothing to do with the old model.
  28025. var requireNewView = model.__requireNewView;
  28026. // This command should not work twice.
  28027. model.__requireNewView = false;
  28028. // Consider: id same and type changed.
  28029. var viewId = '_ec_' + model.id + '_' + model.type;
  28030. var view = !requireNewView && viewMap[viewId];
  28031. if (!view) {
  28032. var classType = parseClassType(model.type);
  28033. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) :
  28034. // FIXME:TS
  28035. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  28036. // For backward compat, still support a chart type declared as only subType
  28037. // like "liquidfill", but recommend "series.liquidfill"
  28038. // But need a base class to make a type series.
  28039. ChartView.getClass(classType.sub);
  28040. if ("development" !== 'production') {
  28041. assert(Clazz, classType.sub + ' does not exist.');
  28042. }
  28043. view = new Clazz();
  28044. view.init(ecModel, api);
  28045. viewMap[viewId] = view;
  28046. viewList.push(view);
  28047. zr.add(view.group);
  28048. }
  28049. model.__viewId = view.__id = viewId;
  28050. view.__alive = true;
  28051. view.__model = model;
  28052. view.group.__ecComponentInfo = {
  28053. mainType: model.mainType,
  28054. index: model.componentIndex
  28055. };
  28056. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  28057. }
  28058. for (var i = 0; i < viewList.length;) {
  28059. var view = viewList[i];
  28060. if (!view.__alive) {
  28061. !isComponent && view.renderTask.dispose();
  28062. zr.remove(view.group);
  28063. view.dispose(ecModel, api);
  28064. viewList.splice(i, 1);
  28065. if (viewMap[view.__id] === view) {
  28066. delete viewMap[view.__id];
  28067. }
  28068. view.__id = view.group.__ecComponentInfo = null;
  28069. } else {
  28070. i++;
  28071. }
  28072. }
  28073. };
  28074. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  28075. var ecModel = ecIns._model;
  28076. ecModel.setUpdatePayload(payload);
  28077. // broadcast
  28078. if (!mainType) {
  28079. // FIXME
  28080. // Chart will not be update directly here, except set dirty.
  28081. // But there is no such scenario now.
  28082. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  28083. return;
  28084. }
  28085. var query = {};
  28086. query[mainType + 'Id'] = payload[mainType + 'Id'];
  28087. query[mainType + 'Index'] = payload[mainType + 'Index'];
  28088. query[mainType + 'Name'] = payload[mainType + 'Name'];
  28089. var condition = {
  28090. mainType: mainType,
  28091. query: query
  28092. };
  28093. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  28094. var excludeSeriesId = payload.excludeSeriesId;
  28095. var excludeSeriesIdMap;
  28096. if (excludeSeriesId != null) {
  28097. excludeSeriesIdMap = createHashMap();
  28098. each(normalizeToArray(excludeSeriesId), function (id) {
  28099. var modelId = convertOptionIdName(id, null);
  28100. if (modelId != null) {
  28101. excludeSeriesIdMap.set(modelId, true);
  28102. }
  28103. });
  28104. }
  28105. // If dispatchAction before setOption, do nothing.
  28106. ecModel && ecModel.eachComponent(condition, function (model) {
  28107. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  28108. if (isExcluded) {
  28109. return;
  28110. }
  28111. if (isHighDownPayload(payload)) {
  28112. if (model instanceof SeriesModel) {
  28113. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  28114. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  28115. }
  28116. } else {
  28117. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  28118. focusSelf = _a.focusSelf,
  28119. dispatchers = _a.dispatchers;
  28120. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  28121. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  28122. }
  28123. // PENDING:
  28124. // Whether to put this "enter emphasis" code in `ComponentView`,
  28125. // which will be the same as `ChartView` but might be not necessary
  28126. // and will be far from this logic.
  28127. if (dispatchers) {
  28128. each(dispatchers, function (dispatcher) {
  28129. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  28130. });
  28131. }
  28132. }
  28133. } else if (isSelectChangePayload(payload)) {
  28134. // TODO geo
  28135. if (model instanceof SeriesModel) {
  28136. toggleSelectionFromPayload(model, payload, ecIns._api);
  28137. updateSeriesElementSelection(model);
  28138. markStatusToUpdate(ecIns);
  28139. }
  28140. }
  28141. }, ecIns);
  28142. ecModel && ecModel.eachComponent(condition, function (model) {
  28143. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  28144. if (isExcluded) {
  28145. return;
  28146. }
  28147. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  28148. }, ecIns);
  28149. function callView(view) {
  28150. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  28151. }
  28152. };
  28153. updateMethods = {
  28154. prepareAndUpdate: function (payload) {
  28155. prepare(this);
  28156. updateMethods.update.call(this, payload, payload && {
  28157. // Needs to mark option changed if newOption is given.
  28158. // It's from MagicType.
  28159. // TODO If use a separate flag optionChanged in payload?
  28160. optionChanged: payload.newOption != null
  28161. });
  28162. },
  28163. update: function (payload, updateParams) {
  28164. var ecModel = this._model;
  28165. var api = this._api;
  28166. var zr = this._zr;
  28167. var coordSysMgr = this._coordSysMgr;
  28168. var scheduler = this._scheduler;
  28169. // update before setOption
  28170. if (!ecModel) {
  28171. return;
  28172. }
  28173. ecModel.setUpdatePayload(payload);
  28174. scheduler.restoreData(ecModel, payload);
  28175. scheduler.performSeriesTasks(ecModel);
  28176. // TODO
  28177. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  28178. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  28179. // Create new coordinate system each update
  28180. // In LineView may save the old coordinate system and use it to get the original point.
  28181. coordSysMgr.create(ecModel, api);
  28182. scheduler.performDataProcessorTasks(ecModel, payload);
  28183. // Current stream render is not supported in data process. So we can update
  28184. // stream modes after data processing, where the filtered data is used to
  28185. // determine whether to use progressive rendering.
  28186. updateStreamModes(this, ecModel);
  28187. // We update stream modes before coordinate system updated, then the modes info
  28188. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  28189. // the drawback is the full coord info can not be fetched. Fortunately this full
  28190. // coord is not required in stream mode updater currently.
  28191. coordSysMgr.update(ecModel, api);
  28192. clearColorPalette(ecModel);
  28193. scheduler.performVisualTasks(ecModel, payload);
  28194. // Set background and dark mode before rendering, because they affect auto-color-determination
  28195. // in zrender Text, and consequently affect the bounding rect if stroke is added.
  28196. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  28197. zr.setBackgroundColor(backgroundColor);
  28198. // Force set dark mode.
  28199. var darkMode = ecModel.get('darkMode');
  28200. if (darkMode != null && darkMode !== 'auto') {
  28201. zr.setDarkMode(darkMode);
  28202. }
  28203. render(this, ecModel, api, payload, updateParams);
  28204. lifecycle.trigger('afterupdate', ecModel, api);
  28205. },
  28206. updateTransform: function (payload) {
  28207. var _this = this;
  28208. var ecModel = this._model;
  28209. var api = this._api;
  28210. // update before setOption
  28211. if (!ecModel) {
  28212. return;
  28213. }
  28214. ecModel.setUpdatePayload(payload);
  28215. // ChartView.markUpdateMethod(payload, 'updateTransform');
  28216. var componentDirtyList = [];
  28217. ecModel.eachComponent(function (componentType, componentModel) {
  28218. if (componentType === 'series') {
  28219. return;
  28220. }
  28221. var componentView = _this.getViewOfComponentModel(componentModel);
  28222. if (componentView && componentView.__alive) {
  28223. if (componentView.updateTransform) {
  28224. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  28225. result && result.update && componentDirtyList.push(componentView);
  28226. } else {
  28227. componentDirtyList.push(componentView);
  28228. }
  28229. }
  28230. });
  28231. var seriesDirtyMap = createHashMap();
  28232. ecModel.eachSeries(function (seriesModel) {
  28233. var chartView = _this._chartsMap[seriesModel.__viewId];
  28234. if (chartView.updateTransform) {
  28235. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  28236. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  28237. } else {
  28238. seriesDirtyMap.set(seriesModel.uid, 1);
  28239. }
  28240. });
  28241. clearColorPalette(ecModel);
  28242. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  28243. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  28244. this._scheduler.performVisualTasks(ecModel, payload, {
  28245. setDirty: true,
  28246. dirtyMap: seriesDirtyMap
  28247. });
  28248. // Currently, not call render of components. Geo render cost a lot.
  28249. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  28250. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  28251. lifecycle.trigger('afterupdate', ecModel, api);
  28252. },
  28253. updateView: function (payload) {
  28254. var ecModel = this._model;
  28255. // update before setOption
  28256. if (!ecModel) {
  28257. return;
  28258. }
  28259. ecModel.setUpdatePayload(payload);
  28260. ChartView.markUpdateMethod(payload, 'updateView');
  28261. clearColorPalette(ecModel);
  28262. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  28263. this._scheduler.performVisualTasks(ecModel, payload, {
  28264. setDirty: true
  28265. });
  28266. render(this, ecModel, this._api, payload, {});
  28267. lifecycle.trigger('afterupdate', ecModel, this._api);
  28268. },
  28269. updateVisual: function (payload) {
  28270. // updateMethods.update.call(this, payload);
  28271. var _this = this;
  28272. var ecModel = this._model;
  28273. // update before setOption
  28274. if (!ecModel) {
  28275. return;
  28276. }
  28277. ecModel.setUpdatePayload(payload);
  28278. // clear all visual
  28279. ecModel.eachSeries(function (seriesModel) {
  28280. seriesModel.getData().clearAllVisual();
  28281. });
  28282. // Perform visual
  28283. ChartView.markUpdateMethod(payload, 'updateVisual');
  28284. clearColorPalette(ecModel);
  28285. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  28286. this._scheduler.performVisualTasks(ecModel, payload, {
  28287. visualType: 'visual',
  28288. setDirty: true
  28289. });
  28290. ecModel.eachComponent(function (componentType, componentModel) {
  28291. if (componentType !== 'series') {
  28292. var componentView = _this.getViewOfComponentModel(componentModel);
  28293. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  28294. }
  28295. });
  28296. ecModel.eachSeries(function (seriesModel) {
  28297. var chartView = _this._chartsMap[seriesModel.__viewId];
  28298. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  28299. });
  28300. lifecycle.trigger('afterupdate', ecModel, this._api);
  28301. },
  28302. updateLayout: function (payload) {
  28303. updateMethods.update.call(this, payload);
  28304. }
  28305. };
  28306. function doConvertPixelImpl(ecIns, methodName, finder, value, opt) {
  28307. if (ecIns._disposed) {
  28308. disposedWarning(ecIns.id);
  28309. return;
  28310. }
  28311. var ecModel = ecIns._model;
  28312. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  28313. var result;
  28314. var parsedFinder = parseFinder(ecModel, finder);
  28315. for (var i = 0; i < coordSysList.length; i++) {
  28316. var coordSys = coordSysList[i];
  28317. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value, opt)) != null) {
  28318. return result;
  28319. }
  28320. }
  28321. if ("development" !== 'production') {
  28322. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  28323. }
  28324. }
  28325. doConvertPixel = doConvertPixelImpl;
  28326. updateStreamModes = function (ecIns, ecModel) {
  28327. var chartsMap = ecIns._chartsMap;
  28328. var scheduler = ecIns._scheduler;
  28329. ecModel.eachSeries(function (seriesModel) {
  28330. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  28331. });
  28332. };
  28333. doDispatchAction = function (payload, silent) {
  28334. var _this = this;
  28335. var ecModel = this.getModel();
  28336. var payloadType = payload.type;
  28337. var escapeConnect = payload.escapeConnect;
  28338. var actionInfo = actions[payloadType];
  28339. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  28340. var updateMethod = cptTypeTmp.pop();
  28341. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  28342. this[IN_MAIN_PROCESS_KEY] = true;
  28343. updateMainProcessVersion(this);
  28344. var payloads = [payload];
  28345. var batched = false;
  28346. // Batch action
  28347. if (payload.batch) {
  28348. batched = true;
  28349. payloads = map(payload.batch, function (item) {
  28350. item = defaults(extend({}, item), payload);
  28351. item.batch = null;
  28352. return item;
  28353. });
  28354. }
  28355. var eventObjBatch = [];
  28356. var eventObj;
  28357. var actionResultBatch = [];
  28358. var nonRefinedEventType = actionInfo.nonRefinedEventType;
  28359. var isSelectChange = isSelectChangePayload(payload);
  28360. var isHighDown = isHighDownPayload(payload);
  28361. // Only leave blur once if there are multiple batches.
  28362. if (isHighDown) {
  28363. allLeaveBlur(this._api);
  28364. }
  28365. each(payloads, function (batchItem) {
  28366. // Action can specify the event by return it.
  28367. var actionResult = actionInfo.action(batchItem, ecModel, _this._api);
  28368. if (actionInfo.refineEvent) {
  28369. actionResultBatch.push(actionResult);
  28370. } else {
  28371. eventObj = actionResult;
  28372. }
  28373. eventObj = eventObj || extend({}, batchItem);
  28374. eventObj.type = nonRefinedEventType;
  28375. eventObjBatch.push(eventObj);
  28376. // light update does not perform data process, layout and visual.
  28377. if (isHighDown) {
  28378. var _a = preParseFinder(payload),
  28379. queryOptionMap = _a.queryOptionMap,
  28380. mainTypeSpecified = _a.mainTypeSpecified;
  28381. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  28382. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  28383. markStatusToUpdate(_this);
  28384. } else if (isSelectChange) {
  28385. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  28386. // geo still use 'geoselect'.
  28387. updateDirectly(_this, updateMethod, batchItem, 'series');
  28388. markStatusToUpdate(_this);
  28389. } else if (cptType) {
  28390. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  28391. }
  28392. });
  28393. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  28394. try {
  28395. // Still dirty
  28396. if (this[PENDING_UPDATE]) {
  28397. prepare(this);
  28398. updateMethods.update.call(this, payload);
  28399. this[PENDING_UPDATE] = null;
  28400. } else {
  28401. updateMethods[updateMethod].call(this, payload);
  28402. }
  28403. } catch (e) {
  28404. this[IN_MAIN_PROCESS_KEY] = false;
  28405. throw e;
  28406. }
  28407. }
  28408. // Follow the rule of action batch
  28409. if (batched) {
  28410. eventObj = {
  28411. type: nonRefinedEventType,
  28412. escapeConnect: escapeConnect,
  28413. batch: eventObjBatch
  28414. };
  28415. } else {
  28416. eventObj = eventObjBatch[0];
  28417. }
  28418. this[IN_MAIN_PROCESS_KEY] = false;
  28419. if (!silent) {
  28420. var refinedEvent = void 0;
  28421. if (actionInfo.refineEvent) {
  28422. var eventContent = actionInfo.refineEvent(actionResultBatch, payload, ecModel, this._api).eventContent;
  28423. assert(isObject(eventContent));
  28424. refinedEvent = defaults({
  28425. type: actionInfo.refinedEventType
  28426. }, eventContent);
  28427. refinedEvent.fromAction = payload.type;
  28428. refinedEvent.fromActionPayload = payload;
  28429. refinedEvent.escapeConnect = true;
  28430. }
  28431. var messageCenter = this._messageCenter;
  28432. // - If `refineEvent` created a `refinedEvent`, `eventObj` (replicated from the original payload)
  28433. // is still needed to be triggered for the feature `connect`. But it will not be triggered to
  28434. // users in this case.
  28435. // - If no `refineEvent` used, `eventObj` will be triggered for both `connect` and users.
  28436. messageCenter.trigger(eventObj.type, eventObj);
  28437. if (refinedEvent) {
  28438. messageCenter.trigger(refinedEvent.type, refinedEvent);
  28439. }
  28440. }
  28441. };
  28442. flushPendingActions = function (silent) {
  28443. var pendingActions = this._pendingActions;
  28444. while (pendingActions.length) {
  28445. var payload = pendingActions.shift();
  28446. doDispatchAction.call(this, payload, silent);
  28447. }
  28448. };
  28449. triggerUpdatedEvent = function (silent) {
  28450. !silent && this.trigger('updated');
  28451. };
  28452. /**
  28453. * Event `rendered` is triggered when zr
  28454. * rendered. It is useful for realtime
  28455. * snapshot (reflect animation).
  28456. *
  28457. * Event `finished` is triggered when:
  28458. * (1) zrender rendering finished.
  28459. * (2) initial animation finished.
  28460. * (3) progressive rendering finished.
  28461. * (4) no pending action.
  28462. * (5) no delayed setOption needs to be processed.
  28463. */
  28464. bindRenderedEvent = function (zr, ecIns) {
  28465. zr.on('rendered', function (params) {
  28466. ecIns.trigger('rendered', params);
  28467. // The `finished` event should not be triggered repeatedly,
  28468. // so it should only be triggered when rendering indeed happens
  28469. // in zrender. (Consider the case that dipatchAction is keep
  28470. // triggering when mouse move).
  28471. if (
  28472. // Although zr is dirty if initial animation is not finished
  28473. // and this checking is called on frame, we also check
  28474. // animation finished for robustness.
  28475. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  28476. ecIns.trigger('finished');
  28477. }
  28478. });
  28479. };
  28480. bindMouseEvent = function (zr, ecIns) {
  28481. zr.on('mouseover', function (e) {
  28482. var el = e.target;
  28483. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  28484. if (dispatcher) {
  28485. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  28486. markStatusToUpdate(ecIns);
  28487. }
  28488. }).on('mouseout', function (e) {
  28489. var el = e.target;
  28490. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  28491. if (dispatcher) {
  28492. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  28493. markStatusToUpdate(ecIns);
  28494. }
  28495. }).on('click', function (e) {
  28496. var el = e.target;
  28497. var dispatcher = findEventDispatcher(el, function (target) {
  28498. return getECData(target).dataIndex != null;
  28499. }, true);
  28500. if (dispatcher) {
  28501. var actionType = dispatcher.selected ? 'unselect' : 'select';
  28502. var ecData = getECData(dispatcher);
  28503. ecIns._api.dispatchAction({
  28504. type: actionType,
  28505. dataType: ecData.dataType,
  28506. dataIndexInside: ecData.dataIndex,
  28507. seriesIndex: ecData.seriesIndex,
  28508. isFromClick: true
  28509. });
  28510. }
  28511. });
  28512. };
  28513. function clearColorPalette(ecModel) {
  28514. ecModel.clearColorPalette();
  28515. ecModel.eachSeries(function (seriesModel) {
  28516. seriesModel.clearColorPalette();
  28517. });
  28518. }
  28519. // Allocate zlevels for series and components
  28520. function allocateZlevels(ecModel) {
  28521. var componentZLevels = [];
  28522. var seriesZLevels = [];
  28523. var hasSeparateZLevel = false;
  28524. ecModel.eachComponent(function (componentType, componentModel) {
  28525. var zlevel = componentModel.get('zlevel') || 0;
  28526. var z = componentModel.get('z') || 0;
  28527. var zlevelKey = componentModel.getZLevelKey();
  28528. hasSeparateZLevel = hasSeparateZLevel || !!zlevelKey;
  28529. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  28530. zlevel: zlevel,
  28531. z: z,
  28532. idx: componentModel.componentIndex,
  28533. type: componentType,
  28534. key: zlevelKey
  28535. });
  28536. });
  28537. if (hasSeparateZLevel) {
  28538. // Series after component
  28539. var zLevels = componentZLevels.concat(seriesZLevels);
  28540. var lastSeriesZLevel_1;
  28541. var lastSeriesKey_1;
  28542. sort(zLevels, function (a, b) {
  28543. if (a.zlevel === b.zlevel) {
  28544. return a.z - b.z;
  28545. }
  28546. return a.zlevel - b.zlevel;
  28547. });
  28548. each(zLevels, function (item) {
  28549. var componentModel = ecModel.getComponent(item.type, item.idx);
  28550. var zlevel = item.zlevel;
  28551. var key = item.key;
  28552. if (lastSeriesZLevel_1 != null) {
  28553. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  28554. }
  28555. if (key) {
  28556. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  28557. zlevel++;
  28558. }
  28559. lastSeriesKey_1 = key;
  28560. } else if (lastSeriesKey_1) {
  28561. if (zlevel === lastSeriesZLevel_1) {
  28562. zlevel++;
  28563. }
  28564. lastSeriesKey_1 = '';
  28565. }
  28566. lastSeriesZLevel_1 = zlevel;
  28567. componentModel.setZLevel(zlevel);
  28568. });
  28569. }
  28570. }
  28571. render = function (ecIns, ecModel, api, payload, updateParams) {
  28572. allocateZlevels(ecModel);
  28573. renderComponents(ecIns, ecModel, api, payload, updateParams);
  28574. each(ecIns._chartsViews, function (chart) {
  28575. chart.__alive = false;
  28576. });
  28577. renderSeries(ecIns, ecModel, api, payload, updateParams);
  28578. // Remove groups of unrendered charts
  28579. each(ecIns._chartsViews, function (chart) {
  28580. if (!chart.__alive) {
  28581. chart.remove(ecModel, api);
  28582. }
  28583. });
  28584. };
  28585. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  28586. each(dirtyList || ecIns._componentsViews, function (componentView) {
  28587. var componentModel = componentView.__model;
  28588. clearStates(componentModel, componentView);
  28589. componentView.render(componentModel, ecModel, api, payload);
  28590. updateZ(componentModel, componentView);
  28591. updateStates(componentModel, componentView);
  28592. });
  28593. };
  28594. /**
  28595. * Render each chart and component
  28596. */
  28597. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  28598. // Render all charts
  28599. var scheduler = ecIns._scheduler;
  28600. updateParams = extend(updateParams || {}, {
  28601. updatedSeries: ecModel.getSeries()
  28602. });
  28603. // TODO progressive?
  28604. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  28605. var unfinished = false;
  28606. ecModel.eachSeries(function (seriesModel) {
  28607. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  28608. chartView.__alive = true;
  28609. var renderTask = chartView.renderTask;
  28610. scheduler.updatePayload(renderTask, payload);
  28611. // TODO states on marker.
  28612. clearStates(seriesModel, chartView);
  28613. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  28614. renderTask.dirty();
  28615. }
  28616. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  28617. unfinished = true;
  28618. }
  28619. chartView.group.silent = !!seriesModel.get('silent');
  28620. // Should not call markRedraw on group, because it will disable zrender
  28621. // incremental render (always render from the __startIndex each frame)
  28622. // chartView.group.markRedraw();
  28623. updateBlend(seriesModel, chartView);
  28624. updateSeriesElementSelection(seriesModel);
  28625. });
  28626. scheduler.unfinished = unfinished || scheduler.unfinished;
  28627. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams);
  28628. // transition after label is layouted.
  28629. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  28630. ecModel.eachSeries(function (seriesModel) {
  28631. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  28632. // Update Z after labels updated. Before applying states.
  28633. updateZ(seriesModel, chartView);
  28634. // NOTE: Update states after label is updated.
  28635. // label should be in normal status when layouting.
  28636. updateStates(seriesModel, chartView);
  28637. });
  28638. // If use hover layer
  28639. updateHoverLayerStatus(ecIns, ecModel);
  28640. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  28641. };
  28642. markStatusToUpdate = function (ecIns) {
  28643. ecIns[STATUS_NEEDS_UPDATE_KEY] = true;
  28644. // Wake up zrender if it's sleep. Let it update states in the next frame.
  28645. ecIns.getZr().wakeUp();
  28646. };
  28647. updateMainProcessVersion = function (ecIns) {
  28648. ecIns[MAIN_PROCESS_VERSION_KEY] = (ecIns[MAIN_PROCESS_VERSION_KEY] + 1) % 1000;
  28649. };
  28650. applyChangedStates = function (ecIns) {
  28651. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  28652. return;
  28653. }
  28654. ecIns.getZr().storage.traverse(function (el) {
  28655. // Not applied on removed elements, it may still in fading.
  28656. if (isElementRemoved(el)) {
  28657. return;
  28658. }
  28659. applyElementStates(el);
  28660. });
  28661. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  28662. };
  28663. function applyElementStates(el) {
  28664. var newStates = [];
  28665. var oldStates = el.currentStates;
  28666. // Keep other states.
  28667. for (var i = 0; i < oldStates.length; i++) {
  28668. var stateName = oldStates[i];
  28669. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  28670. newStates.push(stateName);
  28671. }
  28672. }
  28673. // Only use states when it's exists.
  28674. if (el.selected && el.states.select) {
  28675. newStates.push('select');
  28676. }
  28677. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  28678. newStates.push('emphasis');
  28679. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  28680. newStates.push('blur');
  28681. }
  28682. el.useStates(newStates);
  28683. }
  28684. function updateHoverLayerStatus(ecIns, ecModel) {
  28685. var zr = ecIns._zr;
  28686. var storage = zr.storage;
  28687. var elCount = 0;
  28688. storage.traverse(function (el) {
  28689. if (!el.isGroup) {
  28690. elCount++;
  28691. }
  28692. });
  28693. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  28694. ecModel.eachSeries(function (seriesModel) {
  28695. if (seriesModel.preventUsingHoverLayer) {
  28696. return;
  28697. }
  28698. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  28699. if (chartView.__alive) {
  28700. chartView.eachRendered(function (el) {
  28701. if (el.states.emphasis) {
  28702. el.states.emphasis.hoverLayer = true;
  28703. }
  28704. });
  28705. }
  28706. });
  28707. }
  28708. }
  28709. /**
  28710. * Update chart and blend.
  28711. */
  28712. function updateBlend(seriesModel, chartView) {
  28713. var blendMode = seriesModel.get('blendMode') || null;
  28714. chartView.eachRendered(function (el) {
  28715. // FIXME marker and other components
  28716. if (!el.isGroup) {
  28717. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  28718. el.style.blend = blendMode;
  28719. }
  28720. });
  28721. }
  28722. function updateZ(model, view) {
  28723. if (model.preventAutoZ) {
  28724. return;
  28725. }
  28726. var zInfo = retrieveZInfo(model);
  28727. // Set z and zlevel
  28728. view.eachRendered(function (el) {
  28729. traverseUpdateZ(el, zInfo.z, zInfo.zlevel);
  28730. // Don't traverse the children because it has been traversed in _updateZ.
  28731. return true;
  28732. });
  28733. }
  28734. // Clear states without animation.
  28735. // TODO States on component.
  28736. function clearStates(model, view) {
  28737. view.eachRendered(function (el) {
  28738. // Not applied on removed elements, it may still in fading.
  28739. if (isElementRemoved(el)) {
  28740. return;
  28741. }
  28742. var textContent = el.getTextContent();
  28743. var textGuide = el.getTextGuideLine();
  28744. if (el.stateTransition) {
  28745. el.stateTransition = null;
  28746. }
  28747. if (textContent && textContent.stateTransition) {
  28748. textContent.stateTransition = null;
  28749. }
  28750. if (textGuide && textGuide.stateTransition) {
  28751. textGuide.stateTransition = null;
  28752. }
  28753. // TODO If el is incremental.
  28754. if (el.hasState()) {
  28755. el.prevStates = el.currentStates;
  28756. el.clearStates();
  28757. } else if (el.prevStates) {
  28758. el.prevStates = null;
  28759. }
  28760. });
  28761. }
  28762. function updateStates(model, view) {
  28763. var stateAnimationModel = model.getModel('stateAnimation');
  28764. var enableAnimation = model.isAnimationEnabled();
  28765. var duration = stateAnimationModel.get('duration');
  28766. var stateTransition = duration > 0 ? {
  28767. duration: duration,
  28768. delay: stateAnimationModel.get('delay'),
  28769. easing: stateAnimationModel.get('easing')
  28770. // additive: stateAnimationModel.get('additive')
  28771. } : null;
  28772. view.eachRendered(function (el) {
  28773. if (el.states && el.states.emphasis) {
  28774. // Not applied on removed elements, it may still in fading.
  28775. if (isElementRemoved(el)) {
  28776. return;
  28777. }
  28778. if (el instanceof Path) {
  28779. savePathStates(el);
  28780. }
  28781. // Only updated on changed element. In case element is incremental and don't want to rerender.
  28782. // TODO, a more proper way?
  28783. if (el.__dirty) {
  28784. var prevStates = el.prevStates;
  28785. // Restore states without animation
  28786. if (prevStates) {
  28787. el.useStates(prevStates);
  28788. }
  28789. }
  28790. // Update state transition and enable animation again.
  28791. if (enableAnimation) {
  28792. el.stateTransition = stateTransition;
  28793. var textContent = el.getTextContent();
  28794. var textGuide = el.getTextGuideLine();
  28795. // TODO Is it necessary to animate label?
  28796. if (textContent) {
  28797. textContent.stateTransition = stateTransition;
  28798. }
  28799. if (textGuide) {
  28800. textGuide.stateTransition = stateTransition;
  28801. }
  28802. }
  28803. // Use highlighted and selected flag to toggle states.
  28804. if (el.__dirty) {
  28805. applyElementStates(el);
  28806. }
  28807. }
  28808. });
  28809. }
  28810. createExtensionAPI = function (ecIns) {
  28811. return new (/** @class */function (_super) {
  28812. __extends(class_1, _super);
  28813. function class_1() {
  28814. return _super !== null && _super.apply(this, arguments) || this;
  28815. }
  28816. class_1.prototype.getCoordinateSystems = function () {
  28817. return ecIns._coordSysMgr.getCoordinateSystems();
  28818. };
  28819. class_1.prototype.getComponentByElement = function (el) {
  28820. while (el) {
  28821. var modelInfo = el.__ecComponentInfo;
  28822. if (modelInfo != null) {
  28823. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  28824. }
  28825. el = el.parent;
  28826. }
  28827. };
  28828. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  28829. enterEmphasis(el, highlightDigit);
  28830. markStatusToUpdate(ecIns);
  28831. };
  28832. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  28833. leaveEmphasis(el, highlightDigit);
  28834. markStatusToUpdate(ecIns);
  28835. };
  28836. class_1.prototype.enterBlur = function (el) {
  28837. enterBlur(el);
  28838. markStatusToUpdate(ecIns);
  28839. };
  28840. class_1.prototype.leaveBlur = function (el) {
  28841. leaveBlur(el);
  28842. markStatusToUpdate(ecIns);
  28843. };
  28844. class_1.prototype.enterSelect = function (el) {
  28845. enterSelect(el);
  28846. markStatusToUpdate(ecIns);
  28847. };
  28848. class_1.prototype.leaveSelect = function (el) {
  28849. leaveSelect(el);
  28850. markStatusToUpdate(ecIns);
  28851. };
  28852. class_1.prototype.getModel = function () {
  28853. return ecIns.getModel();
  28854. };
  28855. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  28856. return ecIns.getViewOfComponentModel(componentModel);
  28857. };
  28858. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  28859. return ecIns.getViewOfSeriesModel(seriesModel);
  28860. };
  28861. class_1.prototype.getMainProcessVersion = function () {
  28862. return ecIns[MAIN_PROCESS_VERSION_KEY];
  28863. };
  28864. return class_1;
  28865. }(ExtensionAPI))(ecIns);
  28866. };
  28867. enableConnect = function (chart) {
  28868. function updateConnectedChartsStatus(charts, status) {
  28869. for (var i = 0; i < charts.length; i++) {
  28870. var otherChart = charts[i];
  28871. otherChart[CONNECT_STATUS_KEY] = status;
  28872. }
  28873. }
  28874. each(connectionEventRevertMap, function (_, eventType) {
  28875. chart._messageCenter.on(eventType, function (event) {
  28876. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  28877. if (event && event.escapeConnect) {
  28878. return;
  28879. }
  28880. var action_1 = chart.makeActionFromEvent(event);
  28881. var otherCharts_1 = [];
  28882. each(instances$1, function (otherChart) {
  28883. if (otherChart !== chart && otherChart.group === chart.group) {
  28884. otherCharts_1.push(otherChart);
  28885. }
  28886. });
  28887. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  28888. each(otherCharts_1, function (otherChart) {
  28889. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  28890. otherChart.dispatchAction(action_1);
  28891. }
  28892. });
  28893. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  28894. }
  28895. });
  28896. });
  28897. };
  28898. }();
  28899. return ECharts;
  28900. }(Eventful);
  28901. var echartsProto = ECharts.prototype;
  28902. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  28903. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  28904. /**
  28905. * @deprecated
  28906. */
  28907. // @ts-ignore
  28908. echartsProto.one = function (eventName, cb, ctx) {
  28909. var self = this;
  28910. deprecateLog('ECharts#one is deprecated.');
  28911. function wrapped() {
  28912. var args2 = [];
  28913. for (var _i = 0; _i < arguments.length; _i++) {
  28914. args2[_i] = arguments[_i];
  28915. }
  28916. cb && cb.apply && cb.apply(this, args2);
  28917. // @ts-ignore
  28918. self.off(eventName, wrapped);
  28919. }
  28920. // @ts-ignore
  28921. this.on.call(this, eventName, wrapped, ctx);
  28922. };
  28923. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  28924. function disposedWarning(id) {
  28925. if ("development" !== 'production') {
  28926. warn('Instance ' + id + ' has been disposed');
  28927. }
  28928. }
  28929. var actions = {};
  28930. /**
  28931. * Map event type to action type for reproducing action from event for `connect`.
  28932. */
  28933. var connectionEventRevertMap = {};
  28934. /**
  28935. * To remove duplication.
  28936. */
  28937. var publicEventTypeMap = {};
  28938. var dataProcessorFuncs = [];
  28939. var optionPreprocessorFuncs = [];
  28940. var visualFuncs = [];
  28941. var themeStorage = {};
  28942. var loadingEffects = {};
  28943. var instances$1 = {};
  28944. var connectedGroups = {};
  28945. var idBase = +new Date() - 0;
  28946. var groupIdBase = +new Date() - 0;
  28947. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  28948. /**
  28949. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  28950. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  28951. * @param opts.width Use clientWidth of the input `dom` by default.
  28952. * Can be 'auto' (the same as null/undefined)
  28953. * @param opts.height Use clientHeight of the input `dom` by default.
  28954. * Can be 'auto' (the same as null/undefined)
  28955. * @param opts.locale Specify the locale.
  28956. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  28957. */
  28958. function init$1(dom, theme, opts) {
  28959. var isClient = !(opts && opts.ssr);
  28960. if (isClient) {
  28961. if ("development" !== 'production') {
  28962. if (!dom) {
  28963. throw new Error('Initialize failed: invalid dom.');
  28964. }
  28965. }
  28966. var existInstance = getInstanceByDom(dom);
  28967. if (existInstance) {
  28968. if ("development" !== 'production') {
  28969. warn('There is a chart instance already initialized on the dom.');
  28970. }
  28971. return existInstance;
  28972. }
  28973. if ("development" !== 'production') {
  28974. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  28975. 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.');
  28976. }
  28977. }
  28978. }
  28979. var chart = new ECharts(dom, theme, opts);
  28980. chart.id = 'ec_' + idBase++;
  28981. instances$1[chart.id] = chart;
  28982. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  28983. enableConnect(chart);
  28984. lifecycle.trigger('afterinit', chart);
  28985. return chart;
  28986. }
  28987. /**
  28988. * @usage
  28989. * (A)
  28990. * ```js
  28991. * let chart1 = echarts.init(dom1);
  28992. * let chart2 = echarts.init(dom2);
  28993. * chart1.group = 'xxx';
  28994. * chart2.group = 'xxx';
  28995. * echarts.connect('xxx');
  28996. * ```
  28997. * (B)
  28998. * ```js
  28999. * let chart1 = echarts.init(dom1);
  29000. * let chart2 = echarts.init(dom2);
  29001. * echarts.connect('xxx', [chart1, chart2]);
  29002. * ```
  29003. */
  29004. function connect(groupId) {
  29005. // Is array of charts
  29006. if (isArray(groupId)) {
  29007. var charts = groupId;
  29008. groupId = null;
  29009. // If any chart has group
  29010. each(charts, function (chart) {
  29011. if (chart.group != null) {
  29012. groupId = chart.group;
  29013. }
  29014. });
  29015. groupId = groupId || 'g_' + groupIdBase++;
  29016. each(charts, function (chart) {
  29017. chart.group = groupId;
  29018. });
  29019. }
  29020. connectedGroups[groupId] = true;
  29021. return groupId;
  29022. }
  29023. function disconnect(groupId) {
  29024. connectedGroups[groupId] = false;
  29025. }
  29026. /**
  29027. * Alias and backward compatibility
  29028. * @deprecated
  29029. */
  29030. var disConnect = disconnect;
  29031. /**
  29032. * Dispose a chart instance
  29033. */
  29034. function dispose$1(chart) {
  29035. if (isString(chart)) {
  29036. chart = instances$1[chart];
  29037. } else if (!(chart instanceof ECharts)) {
  29038. // Try to treat as dom
  29039. chart = getInstanceByDom(chart);
  29040. }
  29041. if (chart instanceof ECharts && !chart.isDisposed()) {
  29042. chart.dispose();
  29043. }
  29044. }
  29045. function getInstanceByDom(dom) {
  29046. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  29047. }
  29048. function getInstanceById(key) {
  29049. return instances$1[key];
  29050. }
  29051. /**
  29052. * Register theme
  29053. */
  29054. function registerTheme(name, theme) {
  29055. themeStorage[name] = theme;
  29056. }
  29057. /**
  29058. * Register option preprocessor
  29059. */
  29060. function registerPreprocessor(preprocessorFunc) {
  29061. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  29062. optionPreprocessorFuncs.push(preprocessorFunc);
  29063. }
  29064. }
  29065. function registerProcessor(priority, processor) {
  29066. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  29067. }
  29068. /**
  29069. * Register postIniter
  29070. * @param {Function} postInitFunc
  29071. */
  29072. function registerPostInit(postInitFunc) {
  29073. registerUpdateLifecycle('afterinit', postInitFunc);
  29074. }
  29075. /**
  29076. * Register postUpdater
  29077. * @param {Function} postUpdateFunc
  29078. */
  29079. function registerPostUpdate(postUpdateFunc) {
  29080. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  29081. }
  29082. function registerUpdateLifecycle(name, cb) {
  29083. lifecycle.on(name, cb);
  29084. }
  29085. function registerAction(arg0, arg1, action) {
  29086. var actionType;
  29087. var publicEventType;
  29088. var refineEvent;
  29089. var update;
  29090. var publishNonRefinedEvent;
  29091. if (isFunction(arg1)) {
  29092. action = arg1;
  29093. arg1 = '';
  29094. }
  29095. if (isObject(arg0)) {
  29096. actionType = arg0.type;
  29097. publicEventType = arg0.event;
  29098. update = arg0.update;
  29099. publishNonRefinedEvent = arg0.publishNonRefinedEvent;
  29100. if (!action) {
  29101. action = arg0.action;
  29102. }
  29103. refineEvent = arg0.refineEvent;
  29104. } else {
  29105. actionType = arg0;
  29106. publicEventType = arg1;
  29107. }
  29108. function createEventType(actionOrEventType) {
  29109. // Event type should be all lowercase
  29110. return actionOrEventType.toLowerCase();
  29111. }
  29112. publicEventType = createEventType(publicEventType || actionType);
  29113. // See comments on {ActionInfo} for the reason.
  29114. var nonRefinedEventType = refineEvent ? createEventType(actionType) : publicEventType;
  29115. // Support calling `registerAction` multiple times with the same action
  29116. // type; subsequent calls have no effect.
  29117. if (actions[actionType]) {
  29118. return;
  29119. }
  29120. // Validate action type and event name.
  29121. assert(ACTION_REG.test(actionType) && ACTION_REG.test(publicEventType));
  29122. if (refineEvent) {
  29123. // An event replicated from the action will be triggered internally for `connect` in this case.
  29124. assert(publicEventType !== actionType);
  29125. }
  29126. actions[actionType] = {
  29127. actionType: actionType,
  29128. refinedEventType: publicEventType,
  29129. nonRefinedEventType: nonRefinedEventType,
  29130. update: update,
  29131. action: action,
  29132. refineEvent: refineEvent
  29133. };
  29134. publicEventTypeMap[publicEventType] = 1;
  29135. if (refineEvent && publishNonRefinedEvent) {
  29136. publicEventTypeMap[nonRefinedEventType] = 1;
  29137. }
  29138. if ("development" !== 'production' && connectionEventRevertMap[nonRefinedEventType]) {
  29139. error(nonRefinedEventType + " must not be shared; use \"refineEvent\" if you intend to share an event name.");
  29140. }
  29141. connectionEventRevertMap[nonRefinedEventType] = actionType;
  29142. }
  29143. function registerCoordinateSystem(type, coordSysCreator) {
  29144. CoordinateSystemManager.register(type, coordSysCreator);
  29145. }
  29146. /**
  29147. * Get dimensions of specified coordinate system.
  29148. * @param {string} type
  29149. * @return {Array.<string|Object>}
  29150. */
  29151. function getCoordinateSystemDimensions(type) {
  29152. var coordSysCreator = CoordinateSystemManager.get(type);
  29153. if (coordSysCreator) {
  29154. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  29155. }
  29156. }
  29157. function registerCustomSeries(seriesType, renderItem) {
  29158. }
  29159. function registerLayout(priority, layoutTask) {
  29160. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  29161. }
  29162. function registerVisual(priority, visualTask) {
  29163. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  29164. }
  29165. var registeredTasks = [];
  29166. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  29167. if (isFunction(priority) || isObject(priority)) {
  29168. fn = priority;
  29169. priority = defaultPriority;
  29170. }
  29171. if ("development" !== 'production') {
  29172. if (isNaN(priority) || priority == null) {
  29173. throw new Error('Illegal priority');
  29174. }
  29175. // Check duplicate
  29176. each(targetList, function (wrap) {
  29177. assert(wrap.__raw !== fn);
  29178. });
  29179. }
  29180. // Already registered
  29181. if (indexOf(registeredTasks, fn) >= 0) {
  29182. return;
  29183. }
  29184. registeredTasks.push(fn);
  29185. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  29186. stageHandler.__prio = priority;
  29187. stageHandler.__raw = fn;
  29188. targetList.push(stageHandler);
  29189. }
  29190. function registerLoading(name, loadingFx) {
  29191. loadingEffects[name] = loadingFx;
  29192. }
  29193. /**
  29194. * ZRender need a canvas context to do measureText.
  29195. * But in node environment canvas may be created by node-canvas.
  29196. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  29197. *
  29198. *
  29199. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  29200. *
  29201. * @example
  29202. * let Canvas = require('canvas');
  29203. * let echarts = require('echarts');
  29204. * echarts.setCanvasCreator(function () {
  29205. * // Small size is enough.
  29206. * return new Canvas(32, 32);
  29207. * });
  29208. */
  29209. function setCanvasCreator(creator) {
  29210. if ("development" !== 'production') {
  29211. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  29212. }
  29213. setPlatformAPI({
  29214. createCanvas: creator
  29215. });
  29216. }
  29217. /**
  29218. * The parameters and usage: see `geoSourceManager.registerMap`.
  29219. * Compatible with previous `echarts.registerMap`.
  29220. */
  29221. function registerMap(mapName, geoJson, specialAreas) {
  29222. var registerMap = getImpl('registerMap');
  29223. registerMap && registerMap(mapName, geoJson, specialAreas);
  29224. }
  29225. function getMap(mapName) {
  29226. var getMap = getImpl('getMap');
  29227. return getMap && getMap(mapName);
  29228. }
  29229. var registerTransform = registerExternalTransform;
  29230. /**
  29231. * Globa dispatchAction to a specified chart instance.
  29232. */
  29233. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  29234. // if (!payload || !payload.chartId) {
  29235. // // Must have chartId to find chart
  29236. // return;
  29237. // }
  29238. // const chart = instances[payload.chartId];
  29239. // if (chart) {
  29240. // chart.dispatchAction(payload, opt);
  29241. // }
  29242. // }
  29243. // Builtin global visual
  29244. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  29245. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  29246. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  29247. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  29248. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  29249. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  29250. registerPreprocessor(globalBackwardCompat);
  29251. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  29252. registerLoading('default', defaultLoading);
  29253. // Default actions
  29254. registerAction({
  29255. type: HIGHLIGHT_ACTION_TYPE,
  29256. event: HIGHLIGHT_ACTION_TYPE,
  29257. update: HIGHLIGHT_ACTION_TYPE
  29258. }, noop);
  29259. registerAction({
  29260. type: DOWNPLAY_ACTION_TYPE,
  29261. event: DOWNPLAY_ACTION_TYPE,
  29262. update: DOWNPLAY_ACTION_TYPE
  29263. }, noop);
  29264. registerAction({
  29265. type: SELECT_ACTION_TYPE,
  29266. event: SELECT_CHANGED_EVENT_TYPE,
  29267. update: SELECT_ACTION_TYPE,
  29268. action: noop,
  29269. refineEvent: makeSelectChangedEvent,
  29270. publishNonRefinedEvent: true
  29271. });
  29272. registerAction({
  29273. type: UNSELECT_ACTION_TYPE,
  29274. event: SELECT_CHANGED_EVENT_TYPE,
  29275. update: UNSELECT_ACTION_TYPE,
  29276. action: noop,
  29277. refineEvent: makeSelectChangedEvent,
  29278. publishNonRefinedEvent: true
  29279. });
  29280. registerAction({
  29281. type: TOGGLE_SELECT_ACTION_TYPE,
  29282. event: SELECT_CHANGED_EVENT_TYPE,
  29283. update: TOGGLE_SELECT_ACTION_TYPE,
  29284. action: noop,
  29285. refineEvent: makeSelectChangedEvent,
  29286. publishNonRefinedEvent: true
  29287. });
  29288. function makeSelectChangedEvent(actionResultBatch, payload, ecModel, api) {
  29289. return {
  29290. eventContent: {
  29291. selected: getAllSelectedIndices(ecModel),
  29292. isFromClick: payload.isFromClick || false
  29293. }
  29294. };
  29295. }
  29296. // Default theme, so that we can use `chart.setTheme('default')` to revert to
  29297. // the default theme after changing to other themes.
  29298. registerTheme('default', {});
  29299. registerTheme('dark', theme);
  29300. // For backward compatibility, where the namespace `dataTool` will
  29301. // be mounted on `echarts` is the extension `dataTool` is imported.
  29302. var dataTool = {};
  29303. var extensions = [];
  29304. var extensionRegisters = {
  29305. registerPreprocessor: registerPreprocessor,
  29306. registerProcessor: registerProcessor,
  29307. registerPostInit: registerPostInit,
  29308. registerPostUpdate: registerPostUpdate,
  29309. registerUpdateLifecycle: registerUpdateLifecycle,
  29310. registerAction: registerAction,
  29311. registerCoordinateSystem: registerCoordinateSystem,
  29312. registerLayout: registerLayout,
  29313. registerVisual: registerVisual,
  29314. registerTransform: registerTransform,
  29315. registerLoading: registerLoading,
  29316. registerMap: registerMap,
  29317. registerImpl: registerImpl,
  29318. PRIORITY: PRIORITY,
  29319. ComponentModel: ComponentModel,
  29320. ComponentView: ComponentView,
  29321. SeriesModel: SeriesModel,
  29322. ChartView: ChartView,
  29323. // TODO Use ComponentModel and SeriesModel instead of Constructor
  29324. registerComponentModel: function (ComponentModelClass) {
  29325. ComponentModel.registerClass(ComponentModelClass);
  29326. },
  29327. registerComponentView: function (ComponentViewClass) {
  29328. ComponentView.registerClass(ComponentViewClass);
  29329. },
  29330. registerSeriesModel: function (SeriesModelClass) {
  29331. SeriesModel.registerClass(SeriesModelClass);
  29332. },
  29333. registerChartView: function (ChartViewClass) {
  29334. ChartView.registerClass(ChartViewClass);
  29335. },
  29336. registerCustomSeries: function (seriesType, renderItem) {
  29337. },
  29338. registerSubTypeDefaulter: function (componentType, defaulter) {
  29339. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  29340. },
  29341. registerPainter: function (painterType, PainterCtor) {
  29342. registerPainter(painterType, PainterCtor);
  29343. }
  29344. };
  29345. function use(ext) {
  29346. if (isArray(ext)) {
  29347. // use([ChartLine, ChartBar]);
  29348. each(ext, function (singleExt) {
  29349. use(singleExt);
  29350. });
  29351. return;
  29352. }
  29353. if (indexOf(extensions, ext) >= 0) {
  29354. return;
  29355. }
  29356. extensions.push(ext);
  29357. if (isFunction(ext)) {
  29358. ext = {
  29359. install: ext
  29360. };
  29361. }
  29362. ext.install(extensionRegisters);
  29363. }
  29364. /*
  29365. * Licensed to the Apache Software Foundation (ASF) under one
  29366. * or more contributor license agreements. See the NOTICE file
  29367. * distributed with this work for additional information
  29368. * regarding copyright ownership. The ASF licenses this file
  29369. * to you under the Apache License, Version 2.0 (the
  29370. * "License"); you may not use this file except in compliance
  29371. * with the License. You may obtain a copy of the License at
  29372. *
  29373. * http://www.apache.org/licenses/LICENSE-2.0
  29374. *
  29375. * Unless required by applicable law or agreed to in writing,
  29376. * software distributed under the License is distributed on an
  29377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29378. * KIND, either express or implied. See the License for the
  29379. * specific language governing permissions and limitations
  29380. * under the License.
  29381. */
  29382. /**
  29383. * AUTO-GENERATED FILE. DO NOT MODIFY.
  29384. */
  29385. /*
  29386. * Licensed to the Apache Software Foundation (ASF) under one
  29387. * or more contributor license agreements. See the NOTICE file
  29388. * distributed with this work for additional information
  29389. * regarding copyright ownership. The ASF licenses this file
  29390. * to you under the Apache License, Version 2.0 (the
  29391. * "License"); you may not use this file except in compliance
  29392. * with the License. You may obtain a copy of the License at
  29393. *
  29394. * http://www.apache.org/licenses/LICENSE-2.0
  29395. *
  29396. * Unless required by applicable law or agreed to in writing,
  29397. * software distributed under the License is distributed on an
  29398. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29399. * KIND, either express or implied. See the License for the
  29400. * specific language governing permissions and limitations
  29401. * under the License.
  29402. */
  29403. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  29404. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  29405. }
  29406. function defaultKeyGetter(item) {
  29407. return item;
  29408. }
  29409. var DataDiffer = /** @class */function () {
  29410. /**
  29411. * @param context Can be visited by this.context in callback.
  29412. */
  29413. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context,
  29414. // By default: 'oneToOne'.
  29415. diffMode) {
  29416. this._old = oldArr;
  29417. this._new = newArr;
  29418. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  29419. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  29420. // Visible in callback via `this.context`;
  29421. this.context = context;
  29422. this._diffModeMultiple = diffMode === 'multiple';
  29423. }
  29424. /**
  29425. * Callback function when add a data
  29426. */
  29427. DataDiffer.prototype.add = function (func) {
  29428. this._add = func;
  29429. return this;
  29430. };
  29431. /**
  29432. * Callback function when update a data
  29433. */
  29434. DataDiffer.prototype.update = function (func) {
  29435. this._update = func;
  29436. return this;
  29437. };
  29438. /**
  29439. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  29440. */
  29441. DataDiffer.prototype.updateManyToOne = function (func) {
  29442. this._updateManyToOne = func;
  29443. return this;
  29444. };
  29445. /**
  29446. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  29447. */
  29448. DataDiffer.prototype.updateOneToMany = function (func) {
  29449. this._updateOneToMany = func;
  29450. return this;
  29451. };
  29452. /**
  29453. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  29454. */
  29455. DataDiffer.prototype.updateManyToMany = function (func) {
  29456. this._updateManyToMany = func;
  29457. return this;
  29458. };
  29459. /**
  29460. * Callback function when remove a data
  29461. */
  29462. DataDiffer.prototype.remove = function (func) {
  29463. this._remove = func;
  29464. return this;
  29465. };
  29466. DataDiffer.prototype.execute = function () {
  29467. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  29468. };
  29469. DataDiffer.prototype._executeOneToOne = function () {
  29470. var oldArr = this._old;
  29471. var newArr = this._new;
  29472. var newDataIndexMap = {};
  29473. var oldDataKeyArr = new Array(oldArr.length);
  29474. var newDataKeyArr = new Array(newArr.length);
  29475. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  29476. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  29477. for (var i = 0; i < oldArr.length; i++) {
  29478. var oldKey = oldDataKeyArr[i];
  29479. var newIdxMapVal = newDataIndexMap[oldKey];
  29480. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  29481. // idx can never be empty array here. see 'set null' logic below.
  29482. if (newIdxMapValLen > 1) {
  29483. // Consider there is duplicate key (for example, use dataItem.name as key).
  29484. // We should make sure every item in newArr and oldArr can be visited.
  29485. var newIdx = newIdxMapVal.shift();
  29486. if (newIdxMapVal.length === 1) {
  29487. newDataIndexMap[oldKey] = newIdxMapVal[0];
  29488. }
  29489. this._update && this._update(newIdx, i);
  29490. } else if (newIdxMapValLen === 1) {
  29491. newDataIndexMap[oldKey] = null;
  29492. this._update && this._update(newIdxMapVal, i);
  29493. } else {
  29494. this._remove && this._remove(i);
  29495. }
  29496. }
  29497. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  29498. };
  29499. /**
  29500. * For example, consider the case:
  29501. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  29502. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  29503. * Where:
  29504. * o0, o1, n0 has key 'a' (many to one)
  29505. * o5, n4, n5, n6 has key 'b' (one to many)
  29506. * o2, n1 has key 'c' (one to one)
  29507. * n2, n3 has key 'd' (add)
  29508. * o3, o4 has key 'e' (remove)
  29509. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  29510. * Then:
  29511. * (The order of the following directives are not ensured.)
  29512. * this._updateManyToOne(n0, [o0, o1]);
  29513. * this._updateOneToMany([n4, n5, n6], o5);
  29514. * this._update(n1, o2);
  29515. * this._remove(o3);
  29516. * this._remove(o4);
  29517. * this._remove(o6);
  29518. * this._remove(o7);
  29519. * this._add(n2);
  29520. * this._add(n3);
  29521. * this._add(n7);
  29522. * this._add(n8);
  29523. */
  29524. DataDiffer.prototype._executeMultiple = function () {
  29525. var oldArr = this._old;
  29526. var newArr = this._new;
  29527. var oldDataIndexMap = {};
  29528. var newDataIndexMap = {};
  29529. var oldDataKeyArr = [];
  29530. var newDataKeyArr = [];
  29531. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  29532. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  29533. for (var i = 0; i < oldDataKeyArr.length; i++) {
  29534. var oldKey = oldDataKeyArr[i];
  29535. var oldIdxMapVal = oldDataIndexMap[oldKey];
  29536. var newIdxMapVal = newDataIndexMap[oldKey];
  29537. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  29538. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  29539. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  29540. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  29541. newDataIndexMap[oldKey] = null;
  29542. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  29543. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  29544. newDataIndexMap[oldKey] = null;
  29545. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  29546. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  29547. newDataIndexMap[oldKey] = null;
  29548. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  29549. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  29550. newDataIndexMap[oldKey] = null;
  29551. } else if (oldIdxMapValLen > 1) {
  29552. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  29553. this._remove && this._remove(oldIdxMapVal[i_1]);
  29554. }
  29555. } else {
  29556. this._remove && this._remove(oldIdxMapVal);
  29557. }
  29558. }
  29559. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  29560. };
  29561. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  29562. for (var i = 0; i < newDataKeyArr.length; i++) {
  29563. var newKey = newDataKeyArr[i];
  29564. var newIdxMapVal = newDataIndexMap[newKey];
  29565. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  29566. if (idxMapValLen > 1) {
  29567. for (var j = 0; j < idxMapValLen; j++) {
  29568. this._add && this._add(newIdxMapVal[j]);
  29569. }
  29570. } else if (idxMapValLen === 1) {
  29571. this._add && this._add(newIdxMapVal);
  29572. }
  29573. // Support both `newDataKeyArr` are duplication removed or not removed.
  29574. newDataIndexMap[newKey] = null;
  29575. }
  29576. };
  29577. DataDiffer.prototype._initIndexMap = function (arr,
  29578. // Can be null.
  29579. map,
  29580. // In 'byKey', the output `keyArr` is duplication removed.
  29581. // In 'byIndex', the output `keyArr` is not duplication removed and
  29582. // its indices are accurately corresponding to `arr`.
  29583. keyArr, keyGetterName) {
  29584. var cbModeMultiple = this._diffModeMultiple;
  29585. for (var i = 0; i < arr.length; i++) {
  29586. // Add prefix to avoid conflict with Object.prototype.
  29587. var key = '_ec_' + this[keyGetterName](arr[i], i);
  29588. if (!cbModeMultiple) {
  29589. keyArr[i] = key;
  29590. }
  29591. if (!map) {
  29592. continue;
  29593. }
  29594. var idxMapVal = map[key];
  29595. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  29596. if (idxMapValLen === 0) {
  29597. // Simple optimize: in most cases, one index has one key,
  29598. // do not need array.
  29599. map[key] = i;
  29600. if (cbModeMultiple) {
  29601. keyArr.push(key);
  29602. }
  29603. } else if (idxMapValLen === 1) {
  29604. map[key] = [idxMapVal, i];
  29605. } else {
  29606. idxMapVal.push(i);
  29607. }
  29608. }
  29609. };
  29610. return DataDiffer;
  29611. }();
  29612. var DimensionUserOuput = /** @class */function () {
  29613. function DimensionUserOuput(encode, dimRequest) {
  29614. this._encode = encode;
  29615. this._schema = dimRequest;
  29616. }
  29617. DimensionUserOuput.prototype.get = function () {
  29618. return {
  29619. // Do not generate full dimension name until fist used.
  29620. fullDimensions: this._getFullDimensionNames(),
  29621. encode: this._encode
  29622. };
  29623. };
  29624. /**
  29625. * Get all data store dimension names.
  29626. * Theoretically a series data store is defined both by series and used dataset (if any).
  29627. * If some dimensions are omitted for performance reason in `this.dimensions`,
  29628. * the dimension name may not be auto-generated if user does not specify a dimension name.
  29629. * In this case, the dimension name is `null`/`undefined`.
  29630. */
  29631. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  29632. if (!this._cachedDimNames) {
  29633. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  29634. }
  29635. return this._cachedDimNames;
  29636. };
  29637. return DimensionUserOuput;
  29638. }();
  29639. function summarizeDimensions(data, schema) {
  29640. var summary = {};
  29641. var encode = summary.encode = {};
  29642. var notExtraCoordDimMap = createHashMap();
  29643. var defaultedLabel = [];
  29644. var defaultedTooltip = [];
  29645. var userOutputEncode = {};
  29646. each(data.dimensions, function (dimName) {
  29647. var dimItem = data.getDimensionInfo(dimName);
  29648. var coordDim = dimItem.coordDim;
  29649. if (coordDim) {
  29650. if ("development" !== 'production') {
  29651. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  29652. }
  29653. var coordDimIndex = dimItem.coordDimIndex;
  29654. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  29655. if (!dimItem.isExtraCoord) {
  29656. notExtraCoordDimMap.set(coordDim, 1);
  29657. // Use the last coord dim (and label friendly) as default label,
  29658. // because when dataset is used, it is hard to guess which dimension
  29659. // can be value dimension. If both show x, y on label is not look good,
  29660. // and conventionally y axis is focused more.
  29661. if (mayLabelDimType(dimItem.type)) {
  29662. defaultedLabel[0] = dimName;
  29663. }
  29664. // User output encode do not contain generated coords.
  29665. // And it only has index. User can use index to retrieve value from the raw item array.
  29666. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  29667. }
  29668. if (dimItem.defaultTooltip) {
  29669. defaultedTooltip.push(dimName);
  29670. }
  29671. }
  29672. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  29673. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  29674. var dimIndex = dimItem.otherDims[otherDim];
  29675. if (dimIndex != null && dimIndex !== false) {
  29676. encodeArr[dimIndex] = dimItem.name;
  29677. }
  29678. });
  29679. });
  29680. var dataDimsOnCoord = [];
  29681. var encodeFirstDimNotExtra = {};
  29682. notExtraCoordDimMap.each(function (v, coordDim) {
  29683. var dimArr = encode[coordDim];
  29684. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  29685. // Not necessary to remove duplicate, because a data
  29686. // dim canot on more than one coordDim.
  29687. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  29688. });
  29689. summary.dataDimsOnCoord = dataDimsOnCoord;
  29690. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  29691. return data.getDimensionInfo(dimName).storeDimIndex;
  29692. });
  29693. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  29694. var encodeLabel = encode.label;
  29695. // FIXME `encode.label` is not recommended, because formatter cannot be set
  29696. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  29697. if (encodeLabel && encodeLabel.length) {
  29698. defaultedLabel = encodeLabel.slice();
  29699. }
  29700. var encodeTooltip = encode.tooltip;
  29701. if (encodeTooltip && encodeTooltip.length) {
  29702. defaultedTooltip = encodeTooltip.slice();
  29703. } else if (!defaultedTooltip.length) {
  29704. defaultedTooltip = defaultedLabel.slice();
  29705. }
  29706. encode.defaultedLabel = defaultedLabel;
  29707. encode.defaultedTooltip = defaultedTooltip;
  29708. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  29709. return summary;
  29710. }
  29711. function getOrCreateEncodeArr(encode, dim) {
  29712. if (!encode.hasOwnProperty(dim)) {
  29713. encode[dim] = [];
  29714. }
  29715. return encode[dim];
  29716. }
  29717. // FIXME:TS should be type `AxisType`
  29718. function getDimensionTypeByAxis(axisType) {
  29719. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  29720. }
  29721. function mayLabelDimType(dimType) {
  29722. // In most cases, ordinal and time do not suitable for label.
  29723. // Ordinal info can be displayed on axis. Time is too long.
  29724. return !(dimType === 'ordinal' || dimType === 'time');
  29725. }
  29726. // function findTheLastDimMayLabel(data) {
  29727. // // Get last value dim
  29728. // let dimensions = data.dimensions.slice();
  29729. // let valueType;
  29730. // let valueDim;
  29731. // while (dimensions.length && (
  29732. // valueDim = dimensions.pop(),
  29733. // valueType = data.getDimensionInfo(valueDim).type,
  29734. // valueType === 'ordinal' || valueType === 'time'
  29735. // )) {} // jshint ignore:line
  29736. // return valueDim;
  29737. // }
  29738. var SeriesDimensionDefine = /** @class */function () {
  29739. /**
  29740. * @param opt All of the fields will be shallow copied.
  29741. */
  29742. function SeriesDimensionDefine(opt) {
  29743. /**
  29744. * The format of `otherDims` is:
  29745. * ```js
  29746. * {
  29747. * tooltip?: number
  29748. * label?: number
  29749. * itemName?: number
  29750. * seriesName?: number
  29751. * }
  29752. * ```
  29753. *
  29754. * A `series.encode` can specified these fields:
  29755. * ```js
  29756. * encode: {
  29757. * // "3, 1, 5" is the index of data dimension.
  29758. * tooltip: [3, 1, 5],
  29759. * label: [0, 3],
  29760. * ...
  29761. * }
  29762. * ```
  29763. * `otherDims` is the parse result of the `series.encode` above, like:
  29764. * ```js
  29765. * // Suppose the index of this data dimension is `3`.
  29766. * this.otherDims = {
  29767. * // `3` is at the index `0` of the `encode.tooltip`
  29768. * tooltip: 0,
  29769. * // `3` is at the index `1` of the `encode.label`
  29770. * label: 1
  29771. * };
  29772. * ```
  29773. *
  29774. * This prop should never be `null`/`undefined` after initialized.
  29775. */
  29776. this.otherDims = {};
  29777. if (opt != null) {
  29778. extend(this, opt);
  29779. }
  29780. }
  29781. return SeriesDimensionDefine;
  29782. }();
  29783. var inner$4 = makeInner();
  29784. var dimTypeShort = {
  29785. float: 'f',
  29786. int: 'i',
  29787. ordinal: 'o',
  29788. number: 'n',
  29789. time: 't'
  29790. };
  29791. /**
  29792. * Represents the dimension requirement of a series.
  29793. *
  29794. * NOTICE:
  29795. * When there are too many dimensions in dataset and many series, only the used dimensions
  29796. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  29797. * But users may query data by other unused dimension names.
  29798. * In this case, users can only query data if and only if they have defined dimension names
  29799. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  29800. * `source` dimensions.
  29801. */
  29802. var SeriesDataSchema = /** @class */function () {
  29803. function SeriesDataSchema(opt) {
  29804. this.dimensions = opt.dimensions;
  29805. this._dimOmitted = opt.dimensionOmitted;
  29806. this.source = opt.source;
  29807. this._fullDimCount = opt.fullDimensionCount;
  29808. this._updateDimOmitted(opt.dimensionOmitted);
  29809. }
  29810. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  29811. return this._dimOmitted;
  29812. };
  29813. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  29814. this._dimOmitted = dimensionOmitted;
  29815. if (!dimensionOmitted) {
  29816. return;
  29817. }
  29818. if (!this._dimNameMap) {
  29819. this._dimNameMap = ensureSourceDimNameMap(this.source);
  29820. }
  29821. };
  29822. /**
  29823. * @caution Can only be used when `dimensionOmitted: true`.
  29824. *
  29825. * Get index by user defined dimension name (i.e., not internal generate name).
  29826. * That is, get index from `dimensionsDefine`.
  29827. * If no `dimensionsDefine`, or no name get, return -1.
  29828. */
  29829. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  29830. return retrieve2(this._dimNameMap.get(dimName), -1);
  29831. };
  29832. /**
  29833. * @caution Can only be used when `dimensionOmitted: true`.
  29834. *
  29835. * Notice: may return `null`/`undefined` if user not specify dimension names.
  29836. */
  29837. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  29838. var dimensionsDefine = this.source.dimensionsDefine;
  29839. if (dimensionsDefine) {
  29840. return dimensionsDefine[dimIndex];
  29841. }
  29842. };
  29843. SeriesDataSchema.prototype.makeStoreSchema = function () {
  29844. var dimCount = this._fullDimCount;
  29845. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  29846. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount);
  29847. // If source don't have dimensions or series don't omit unsed dimensions.
  29848. // Generate from seriesDimList directly
  29849. var dimHash = '';
  29850. var dims = [];
  29851. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  29852. var property = void 0;
  29853. var type = void 0;
  29854. var ordinalMeta = void 0;
  29855. var seriesDimDef = this.dimensions[seriesDimIdx];
  29856. // The list has been sorted by `storeDimIndex` asc.
  29857. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  29858. property = willRetrieveDataByName ? seriesDimDef.name : null;
  29859. type = seriesDimDef.type;
  29860. ordinalMeta = seriesDimDef.ordinalMeta;
  29861. seriesDimIdx++;
  29862. } else {
  29863. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  29864. if (sourceDimDef) {
  29865. property = willRetrieveDataByName ? sourceDimDef.name : null;
  29866. type = sourceDimDef.type;
  29867. }
  29868. }
  29869. dims.push({
  29870. property: property,
  29871. type: type,
  29872. ordinalMeta: ordinalMeta
  29873. });
  29874. // If retrieving data by index,
  29875. // use <index, type, ordinalMeta> to determine whether data can be shared.
  29876. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  29877. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  29878. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  29879. // use <property, type, ordinalMeta> in hash.
  29880. if (willRetrieveDataByName && property != null
  29881. // For data stack, we have make sure each series has its own dim on this store.
  29882. // So we do not add property to hash to make sure they can share this store.
  29883. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  29884. dimHash += makeHashStrict
  29885. // Use escape character '`' in case that property name contains '$'.
  29886. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2')
  29887. // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  29888. : property;
  29889. }
  29890. dimHash += '$';
  29891. dimHash += dimTypeShort[type] || 'f';
  29892. if (ordinalMeta) {
  29893. dimHash += ordinalMeta.uid;
  29894. }
  29895. dimHash += '$';
  29896. }
  29897. // Source from endpoint(usually series) will be read differently
  29898. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  29899. // So we use this three props as key.
  29900. var source = this.source;
  29901. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  29902. return {
  29903. dimensions: dims,
  29904. hash: hash
  29905. };
  29906. };
  29907. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  29908. var result = [];
  29909. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  29910. var name_1 = void 0;
  29911. var seriesDimDef = this.dimensions[seriesDimIdx];
  29912. // The list has been sorted by `storeDimIndex` asc.
  29913. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  29914. if (!seriesDimDef.isCalculationCoord) {
  29915. name_1 = seriesDimDef.name;
  29916. }
  29917. seriesDimIdx++;
  29918. } else {
  29919. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  29920. if (sourceDimDef) {
  29921. name_1 = sourceDimDef.name;
  29922. }
  29923. }
  29924. result.push(name_1);
  29925. }
  29926. return result;
  29927. };
  29928. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  29929. this.dimensions.push(dimDef);
  29930. dimDef.isCalculationCoord = true;
  29931. this._fullDimCount++;
  29932. // If append dimension on a data store, consider the store
  29933. // might be shared by different series, series dimensions not
  29934. // really map to store dimensions.
  29935. this._updateDimOmitted(true);
  29936. };
  29937. return SeriesDataSchema;
  29938. }();
  29939. function isSeriesDataSchema(schema) {
  29940. return schema instanceof SeriesDataSchema;
  29941. }
  29942. function createDimNameMap(dimsDef) {
  29943. var dataDimNameMap = createHashMap();
  29944. for (var i = 0; i < (dimsDef || []).length; i++) {
  29945. var dimDefItemRaw = dimsDef[i];
  29946. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  29947. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  29948. dataDimNameMap.set(userDimName, i);
  29949. }
  29950. }
  29951. return dataDimNameMap;
  29952. }
  29953. function ensureSourceDimNameMap(source) {
  29954. var innerSource = inner$4(source);
  29955. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  29956. }
  29957. function shouldOmitUnusedDimensions(dimCount) {
  29958. return dimCount > 30;
  29959. }
  29960. var isObject$2 = isObject;
  29961. var map$1 = map;
  29962. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array;
  29963. // Use prefix to avoid index to be the same as otherIdList[idx],
  29964. // which will cause weird update animation.
  29965. var ID_PREFIX = 'e\0\0';
  29966. var INDEX_NOT_FOUND = -1;
  29967. // type SeriesDimensionIndex = DimensionIndex;
  29968. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  29969. var CLONE_PROPERTIES = ['_approximateExtent'];
  29970. // -----------------------------
  29971. // Internal method declarations:
  29972. // -----------------------------
  29973. var prepareInvertedIndex;
  29974. var getId;
  29975. var getIdNameFromStore;
  29976. var normalizeDimensions;
  29977. var transferProperties;
  29978. var cloneListForMapAndSample;
  29979. var makeIdFromName;
  29980. var SeriesData = /** @class */function () {
  29981. /**
  29982. * @param dimensionsInput.dimensions
  29983. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  29984. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  29985. */
  29986. function SeriesData(dimensionsInput, hostModel) {
  29987. this.type = 'list';
  29988. this._dimOmitted = false;
  29989. this._nameList = [];
  29990. this._idList = [];
  29991. // Models of data option is stored sparse for optimizing memory cost
  29992. // Never used yet (not used yet).
  29993. // private _optionModels: Model[] = [];
  29994. // Global visual properties after visual coding
  29995. this._visual = {};
  29996. // Global layout properties.
  29997. this._layout = {};
  29998. // Item visual properties after visual coding
  29999. this._itemVisuals = [];
  30000. // Item layout properties after layout
  30001. this._itemLayouts = [];
  30002. // Graphic elements
  30003. this._graphicEls = [];
  30004. // key: dim, value: extent
  30005. this._approximateExtent = {};
  30006. this._calculationInfo = {};
  30007. // Having detected that there is data item is non primitive type
  30008. // (in type `OptionDataItemObject`).
  30009. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  30010. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  30011. this.hasItemOption = false;
  30012. // Methods that create a new list based on this list should be listed here.
  30013. // Notice that those method should `RETURN` the new list.
  30014. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'minmaxDownSample', 'lttbDownSample', 'map'];
  30015. // Methods that change indices of this list should be listed here.
  30016. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  30017. this.DOWNSAMPLE_METHODS = ['downSample', 'minmaxDownSample', 'lttbDownSample'];
  30018. var dimensions;
  30019. var assignStoreDimIdx = false;
  30020. if (isSeriesDataSchema(dimensionsInput)) {
  30021. dimensions = dimensionsInput.dimensions;
  30022. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  30023. this._schema = dimensionsInput;
  30024. } else {
  30025. assignStoreDimIdx = true;
  30026. dimensions = dimensionsInput;
  30027. }
  30028. dimensions = dimensions || ['x', 'y'];
  30029. var dimensionInfos = {};
  30030. var dimensionNames = [];
  30031. var invertedIndicesMap = {};
  30032. var needsHasOwn = false;
  30033. var emptyObj = {};
  30034. for (var i = 0; i < dimensions.length; i++) {
  30035. // Use the original dimensions[i], where other flag props may exists.
  30036. var dimInfoInput = dimensions[i];
  30037. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  30038. name: dimInfoInput
  30039. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  30040. var dimensionName = dimensionInfo.name;
  30041. dimensionInfo.type = dimensionInfo.type || 'float';
  30042. if (!dimensionInfo.coordDim) {
  30043. dimensionInfo.coordDim = dimensionName;
  30044. dimensionInfo.coordDimIndex = 0;
  30045. }
  30046. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  30047. dimensionNames.push(dimensionName);
  30048. dimensionInfos[dimensionName] = dimensionInfo;
  30049. if (emptyObj[dimensionName] != null) {
  30050. needsHasOwn = true;
  30051. }
  30052. if (dimensionInfo.createInvertedIndices) {
  30053. invertedIndicesMap[dimensionName] = [];
  30054. }
  30055. var dimIdx = i;
  30056. if (isNumber(dimensionInfo.storeDimIndex)) {
  30057. dimIdx = dimensionInfo.storeDimIndex;
  30058. }
  30059. if (otherDims.itemName === 0) {
  30060. this._nameDimIdx = dimIdx;
  30061. }
  30062. if (otherDims.itemId === 0) {
  30063. this._idDimIdx = dimIdx;
  30064. }
  30065. if ("development" !== 'production') {
  30066. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  30067. }
  30068. if (assignStoreDimIdx) {
  30069. dimensionInfo.storeDimIndex = i;
  30070. }
  30071. }
  30072. this.dimensions = dimensionNames;
  30073. this._dimInfos = dimensionInfos;
  30074. this._initGetDimensionInfo(needsHasOwn);
  30075. this.hostModel = hostModel;
  30076. this._invertedIndicesMap = invertedIndicesMap;
  30077. if (this._dimOmitted) {
  30078. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  30079. each(dimensionNames, function (dimName) {
  30080. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  30081. });
  30082. }
  30083. }
  30084. /**
  30085. *
  30086. * Get concrete dimension name by dimension name or dimension index.
  30087. * If input a dimension name, do not validate whether the dimension name exits.
  30088. *
  30089. * @caution
  30090. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  30091. * Because only those dimensions will have auto-generated dimension names if not
  30092. * have a user-specified name, and other dimensions will get a return of null/undefined.
  30093. *
  30094. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  30095. * ```js
  30096. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  30097. * ```
  30098. *
  30099. * @return Concrete dim name.
  30100. */
  30101. SeriesData.prototype.getDimension = function (dim) {
  30102. var dimIdx = this._recognizeDimIndex(dim);
  30103. if (dimIdx == null) {
  30104. return dim;
  30105. }
  30106. dimIdx = dim;
  30107. if (!this._dimOmitted) {
  30108. return this.dimensions[dimIdx];
  30109. }
  30110. // Retrieve from series dimension definition because it probably contains
  30111. // generated dimension name (like 'x', 'y').
  30112. var dimName = this._dimIdxToName.get(dimIdx);
  30113. if (dimName != null) {
  30114. return dimName;
  30115. }
  30116. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  30117. if (sourceDimDef) {
  30118. return sourceDimDef.name;
  30119. }
  30120. };
  30121. /**
  30122. * Get dimension index in data store. Return -1 if not found.
  30123. * Can be used to index value from getRawValue.
  30124. */
  30125. SeriesData.prototype.getDimensionIndex = function (dim) {
  30126. var dimIdx = this._recognizeDimIndex(dim);
  30127. if (dimIdx != null) {
  30128. return dimIdx;
  30129. }
  30130. if (dim == null) {
  30131. return -1;
  30132. }
  30133. var dimInfo = this._getDimInfo(dim);
  30134. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  30135. };
  30136. /**
  30137. * The meanings of the input parameter `dim`:
  30138. *
  30139. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  30140. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  30141. * + If dim is a number-like string (e.g., `"1"`):
  30142. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  30143. * it means that concrete name.
  30144. * + If not, it will be converted to a number, which means the index of the dimension.
  30145. * (why? because of the backward compatibility. We have been tolerating number-like string in
  30146. * dimension setting, although now it seems that it is not a good idea.)
  30147. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  30148. * if no dimension name is defined as `"1"`.
  30149. * + If dim is a not-number-like string, it means the concrete dim name.
  30150. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  30151. * or customized in `dimensions` property of option like `"age"`.
  30152. *
  30153. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  30154. */
  30155. SeriesData.prototype._recognizeDimIndex = function (dim) {
  30156. if (isNumber(dim)
  30157. // If being a number-like string but not being defined as a dimension name.
  30158. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  30159. return +dim;
  30160. }
  30161. };
  30162. SeriesData.prototype._getStoreDimIndex = function (dim) {
  30163. var dimIdx = this.getDimensionIndex(dim);
  30164. if ("development" !== 'production') {
  30165. if (dimIdx == null) {
  30166. throw new Error('Unknown dimension ' + dim);
  30167. }
  30168. }
  30169. return dimIdx;
  30170. };
  30171. /**
  30172. * Get type and calculation info of particular dimension
  30173. * @param dim
  30174. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  30175. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  30176. */
  30177. SeriesData.prototype.getDimensionInfo = function (dim) {
  30178. // Do not clone, because there may be categories in dimInfo.
  30179. return this._getDimInfo(this.getDimension(dim));
  30180. };
  30181. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  30182. var dimensionInfos = this._dimInfos;
  30183. this._getDimInfo = needsHasOwn ? function (dimName) {
  30184. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  30185. } : function (dimName) {
  30186. return dimensionInfos[dimName];
  30187. };
  30188. };
  30189. /**
  30190. * concrete dimension name list on coord.
  30191. */
  30192. SeriesData.prototype.getDimensionsOnCoord = function () {
  30193. return this._dimSummary.dataDimsOnCoord.slice();
  30194. };
  30195. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  30196. var dimensionsSummary = this._dimSummary;
  30197. if (idx == null) {
  30198. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  30199. }
  30200. var dims = dimensionsSummary.encode[coordDim];
  30201. return dims ? dims[idx] : null;
  30202. };
  30203. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  30204. var dimensionsSummary = this._dimSummary;
  30205. var dims = dimensionsSummary.encode[coordDim];
  30206. return (dims || []).slice();
  30207. };
  30208. SeriesData.prototype.getStore = function () {
  30209. return this._store;
  30210. };
  30211. /**
  30212. * Initialize from data
  30213. * @param data source or data or data store.
  30214. * @param nameList The name of a datum is used on data diff and
  30215. * default label/tooltip.
  30216. * A name can be specified in encode.itemName,
  30217. * or dataItem.name (only for series option data),
  30218. * or provided in nameList from outside.
  30219. */
  30220. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  30221. var _this = this;
  30222. var store;
  30223. if (data instanceof DataStore) {
  30224. store = data;
  30225. }
  30226. if (!store) {
  30227. var dimensions = this.dimensions;
  30228. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  30229. store = new DataStore();
  30230. var dimensionInfos = map$1(dimensions, function (dimName) {
  30231. return {
  30232. type: _this._dimInfos[dimName].type,
  30233. property: dimName
  30234. };
  30235. });
  30236. store.initData(provider, dimensionInfos, dimValueGetter);
  30237. }
  30238. this._store = store;
  30239. // Reset
  30240. this._nameList = (nameList || []).slice();
  30241. this._idList = [];
  30242. this._nameRepeatCount = {};
  30243. this._doInit(0, store.count());
  30244. // Cache summary info for fast visit. See "dimensionHelper".
  30245. // Needs to be initialized after store is prepared.
  30246. this._dimSummary = summarizeDimensions(this, this._schema);
  30247. this.userOutput = this._dimSummary.userOutput;
  30248. };
  30249. /**
  30250. * Caution: Can be only called on raw data (before `this._indices` created).
  30251. */
  30252. SeriesData.prototype.appendData = function (data) {
  30253. var range = this._store.appendData(data);
  30254. this._doInit(range[0], range[1]);
  30255. };
  30256. /**
  30257. * Caution: Can be only called on raw data (before `this._indices` created).
  30258. * This method does not modify `rawData` (`dataProvider`), but only
  30259. * add values to store.
  30260. *
  30261. * The final count will be increased by `Math.max(values.length, names.length)`.
  30262. *
  30263. * @param values That is the SourceType: 'arrayRows', like
  30264. * [
  30265. * [12, 33, 44],
  30266. * [NaN, 43, 1],
  30267. * ['-', 'asdf', 0]
  30268. * ]
  30269. * Each item is exactly corresponding to a dimension.
  30270. */
  30271. SeriesData.prototype.appendValues = function (values, names) {
  30272. var _a = this._store.appendValues(values, names && names.length),
  30273. start = _a.start,
  30274. end = _a.end;
  30275. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  30276. this._updateOrdinalMeta();
  30277. if (names) {
  30278. for (var idx = start; idx < end; idx++) {
  30279. var sourceIdx = idx - start;
  30280. this._nameList[idx] = names[sourceIdx];
  30281. if (shouldMakeIdFromName) {
  30282. makeIdFromName(this, idx);
  30283. }
  30284. }
  30285. }
  30286. };
  30287. SeriesData.prototype._updateOrdinalMeta = function () {
  30288. var store = this._store;
  30289. var dimensions = this.dimensions;
  30290. for (var i = 0; i < dimensions.length; i++) {
  30291. var dimInfo = this._dimInfos[dimensions[i]];
  30292. if (dimInfo.ordinalMeta) {
  30293. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  30294. }
  30295. }
  30296. };
  30297. SeriesData.prototype._shouldMakeIdFromName = function () {
  30298. var provider = this._store.getProvider();
  30299. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  30300. };
  30301. SeriesData.prototype._doInit = function (start, end) {
  30302. if (start >= end) {
  30303. return;
  30304. }
  30305. var store = this._store;
  30306. var provider = store.getProvider();
  30307. this._updateOrdinalMeta();
  30308. var nameList = this._nameList;
  30309. var idList = this._idList;
  30310. var sourceFormat = provider.getSource().sourceFormat;
  30311. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  30312. // Each data item is value
  30313. // [1, 2]
  30314. // 2
  30315. // Bar chart, line chart which uses category axis
  30316. // only gives the 'y' value. 'x' value is the indices of category
  30317. // Use a tempValue to normalize the value to be a (x, y) value
  30318. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  30319. // This kind of ids and names are always stored `_nameList` and `_idList`.
  30320. if (isFormatOriginal && !provider.pure) {
  30321. var sharedDataItem = [];
  30322. for (var idx = start; idx < end; idx++) {
  30323. // NOTICE: Try not to write things into dataItem
  30324. var dataItem = provider.getItem(idx, sharedDataItem);
  30325. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  30326. this.hasItemOption = true;
  30327. }
  30328. if (dataItem) {
  30329. var itemName = dataItem.name;
  30330. if (nameList[idx] == null && itemName != null) {
  30331. nameList[idx] = convertOptionIdName(itemName, null);
  30332. }
  30333. var itemId = dataItem.id;
  30334. if (idList[idx] == null && itemId != null) {
  30335. idList[idx] = convertOptionIdName(itemId, null);
  30336. }
  30337. }
  30338. }
  30339. }
  30340. if (this._shouldMakeIdFromName()) {
  30341. for (var idx = start; idx < end; idx++) {
  30342. makeIdFromName(this, idx);
  30343. }
  30344. }
  30345. prepareInvertedIndex(this);
  30346. };
  30347. /**
  30348. * PENDING: In fact currently this function is only used to short-circuit
  30349. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  30350. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  30351. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  30352. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  30353. * But if we add "custom data filter" in future, which is not "axis related", this method may
  30354. * be still needed.
  30355. *
  30356. * Optimize for the scenario that data is filtered by a given extent.
  30357. * Consider that if data amount is more than hundreds of thousand,
  30358. * extent calculation will cost more than 10ms and the cache will
  30359. * be erased because of the filtering.
  30360. */
  30361. SeriesData.prototype.getApproximateExtent = function (dim) {
  30362. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  30363. };
  30364. /**
  30365. * Calculate extent on a filtered data might be time consuming.
  30366. * Approximate extent is only used for: calculate extent of filtered data outside.
  30367. */
  30368. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  30369. dim = this.getDimension(dim);
  30370. this._approximateExtent[dim] = extent.slice();
  30371. };
  30372. SeriesData.prototype.getCalculationInfo = function (key) {
  30373. return this._calculationInfo[key];
  30374. };
  30375. SeriesData.prototype.setCalculationInfo = function (key, value) {
  30376. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  30377. };
  30378. /**
  30379. * @return Never be null/undefined. `number` will be converted to string. Because:
  30380. * In most cases, name is used in display, where returning a string is more convenient.
  30381. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  30382. * rule that name `2` equals to name `'2'`.
  30383. */
  30384. SeriesData.prototype.getName = function (idx) {
  30385. var rawIndex = this.getRawIndex(idx);
  30386. var name = this._nameList[rawIndex];
  30387. if (name == null && this._nameDimIdx != null) {
  30388. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  30389. }
  30390. if (name == null) {
  30391. name = '';
  30392. }
  30393. return name;
  30394. };
  30395. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  30396. var ordinal = this._store.get(dimIdx, idx);
  30397. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  30398. if (ordinalMeta) {
  30399. return ordinalMeta.categories[ordinal];
  30400. }
  30401. return ordinal;
  30402. };
  30403. /**
  30404. * @return Never null/undefined. `number` will be converted to string. Because:
  30405. * In all cases having encountered at present, id is used in making diff comparison, which
  30406. * are usually based on hash map. We can keep the rule that the internal id are always string
  30407. * (treat `2` is the same as `'2'`) to make the related logic simple.
  30408. */
  30409. SeriesData.prototype.getId = function (idx) {
  30410. return getId(this, this.getRawIndex(idx));
  30411. };
  30412. SeriesData.prototype.count = function () {
  30413. return this._store.count();
  30414. };
  30415. /**
  30416. * Get value. Return NaN if idx is out of range.
  30417. *
  30418. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  30419. */
  30420. SeriesData.prototype.get = function (dim, idx) {
  30421. var store = this._store;
  30422. var dimInfo = this._dimInfos[dim];
  30423. if (dimInfo) {
  30424. return store.get(dimInfo.storeDimIndex, idx);
  30425. }
  30426. };
  30427. /**
  30428. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  30429. */
  30430. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  30431. var store = this._store;
  30432. var dimInfo = this._dimInfos[dim];
  30433. if (dimInfo) {
  30434. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  30435. }
  30436. };
  30437. SeriesData.prototype.getIndices = function () {
  30438. return this._store.getIndices();
  30439. };
  30440. SeriesData.prototype.getDataExtent = function (dim) {
  30441. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  30442. };
  30443. SeriesData.prototype.getSum = function (dim) {
  30444. return this._store.getSum(this._getStoreDimIndex(dim));
  30445. };
  30446. SeriesData.prototype.getMedian = function (dim) {
  30447. return this._store.getMedian(this._getStoreDimIndex(dim));
  30448. };
  30449. SeriesData.prototype.getValues = function (dimensions, idx) {
  30450. var _this = this;
  30451. var store = this._store;
  30452. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  30453. return _this._getStoreDimIndex(dim);
  30454. }), idx) : store.getValues(dimensions);
  30455. };
  30456. /**
  30457. * If value is NaN. Including '-'
  30458. * Only check the coord dimensions.
  30459. */
  30460. SeriesData.prototype.hasValue = function (idx) {
  30461. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  30462. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  30463. // Ordinal type originally can be string or number.
  30464. // But when an ordinal type is used on coord, it can
  30465. // not be string but only number. So we can also use isNaN.
  30466. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  30467. return false;
  30468. }
  30469. }
  30470. return true;
  30471. };
  30472. /**
  30473. * Retrieve the index with given name
  30474. */
  30475. SeriesData.prototype.indexOfName = function (name) {
  30476. for (var i = 0, len = this._store.count(); i < len; i++) {
  30477. if (this.getName(i) === name) {
  30478. return i;
  30479. }
  30480. }
  30481. return -1;
  30482. };
  30483. SeriesData.prototype.getRawIndex = function (idx) {
  30484. return this._store.getRawIndex(idx);
  30485. };
  30486. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  30487. return this._store.indexOfRawIndex(rawIndex);
  30488. };
  30489. /**
  30490. * Only support the dimension which inverted index created.
  30491. * Do not support other cases until required.
  30492. * @param dim concrete dim
  30493. * @param value ordinal index
  30494. * @return rawIndex
  30495. */
  30496. SeriesData.prototype.rawIndexOf = function (dim, value) {
  30497. var invertedIndices = dim && this._invertedIndicesMap[dim];
  30498. if ("development" !== 'production') {
  30499. if (!invertedIndices) {
  30500. throw new Error('Do not supported yet');
  30501. }
  30502. }
  30503. var rawIndex = invertedIndices && invertedIndices[value];
  30504. if (rawIndex == null || isNaN(rawIndex)) {
  30505. return INDEX_NOT_FOUND;
  30506. }
  30507. return rawIndex;
  30508. };
  30509. SeriesData.prototype.each = function (dims, cb, ctx) {
  30510. if (isFunction(dims)) {
  30511. ctx = cb;
  30512. cb = dims;
  30513. dims = [];
  30514. }
  30515. // ctxCompat just for compat echarts3
  30516. var fCtx = ctx || this;
  30517. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  30518. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  30519. };
  30520. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  30521. if (isFunction(dims)) {
  30522. ctx = cb;
  30523. cb = dims;
  30524. dims = [];
  30525. }
  30526. // ctxCompat just for compat echarts3
  30527. var fCtx = ctx || this;
  30528. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  30529. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  30530. return this;
  30531. };
  30532. /**
  30533. * Select data in range. (For optimization of filter)
  30534. * (Manually inline code, support 5 million data filtering in data zoom.)
  30535. */
  30536. SeriesData.prototype.selectRange = function (range) {
  30537. var _this = this;
  30538. var innerRange = {};
  30539. var dims = keys(range);
  30540. each(dims, function (dim) {
  30541. var dimIdx = _this._getStoreDimIndex(dim);
  30542. innerRange[dimIdx] = range[dim];
  30543. });
  30544. this._store = this._store.selectRange(innerRange);
  30545. return this;
  30546. };
  30547. /* eslint-enable max-len */
  30548. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  30549. if (isFunction(dims)) {
  30550. ctx = cb;
  30551. cb = dims;
  30552. dims = [];
  30553. }
  30554. // ctxCompat just for compat echarts3
  30555. ctx = ctx || this;
  30556. var result = [];
  30557. this.each(dims, function () {
  30558. result.push(cb && cb.apply(this, arguments));
  30559. }, ctx);
  30560. return result;
  30561. };
  30562. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  30563. // ctxCompat just for compat echarts3
  30564. var fCtx = ctx || ctxCompat || this;
  30565. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  30566. var list = cloneListForMapAndSample(this);
  30567. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  30568. return list;
  30569. };
  30570. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  30571. var _this = this;
  30572. // ctxCompat just for compat echarts3
  30573. var fCtx = ctx || ctxCompat || this;
  30574. if ("development" !== 'production') {
  30575. each(normalizeDimensions(dims), function (dim) {
  30576. var dimInfo = _this.getDimensionInfo(dim);
  30577. if (!dimInfo.isCalculationCoord) {
  30578. console.error('Danger: only stack dimension can be modified');
  30579. }
  30580. });
  30581. }
  30582. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  30583. // If do shallow clone here, if there are too many stacked series,
  30584. // it still cost lots of memory, because `_store.dimensions` are not shared.
  30585. // We should consider there probably be shallow clone happen in each series
  30586. // in consequent filter/map.
  30587. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  30588. };
  30589. /**
  30590. * Large data down sampling on given dimension
  30591. * @param sampleIndex Sample index for name and id
  30592. */
  30593. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  30594. var list = cloneListForMapAndSample(this);
  30595. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  30596. return list;
  30597. };
  30598. /**
  30599. * Large data down sampling using min-max
  30600. * @param {string} valueDimension
  30601. * @param {number} rate
  30602. */
  30603. SeriesData.prototype.minmaxDownSample = function (valueDimension, rate) {
  30604. var list = cloneListForMapAndSample(this);
  30605. list._store = this._store.minmaxDownSample(this._getStoreDimIndex(valueDimension), rate);
  30606. return list;
  30607. };
  30608. /**
  30609. * Large data down sampling using largest-triangle-three-buckets
  30610. * @param {string} valueDimension
  30611. * @param {number} targetCount
  30612. */
  30613. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  30614. var list = cloneListForMapAndSample(this);
  30615. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  30616. return list;
  30617. };
  30618. SeriesData.prototype.getRawDataItem = function (idx) {
  30619. return this._store.getRawDataItem(idx);
  30620. };
  30621. /**
  30622. * Get model of one data item.
  30623. */
  30624. // TODO: Type of data item
  30625. SeriesData.prototype.getItemModel = function (idx) {
  30626. var hostModel = this.hostModel;
  30627. var dataItem = this.getRawDataItem(idx);
  30628. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  30629. };
  30630. /**
  30631. * Create a data differ
  30632. */
  30633. SeriesData.prototype.diff = function (otherList) {
  30634. var thisList = this;
  30635. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  30636. return getId(otherList, idx);
  30637. }, function (idx) {
  30638. return getId(thisList, idx);
  30639. });
  30640. };
  30641. /**
  30642. * Get visual property.
  30643. */
  30644. SeriesData.prototype.getVisual = function (key) {
  30645. var visual = this._visual;
  30646. return visual && visual[key];
  30647. };
  30648. SeriesData.prototype.setVisual = function (kvObj, val) {
  30649. this._visual = this._visual || {};
  30650. if (isObject$2(kvObj)) {
  30651. extend(this._visual, kvObj);
  30652. } else {
  30653. this._visual[kvObj] = val;
  30654. }
  30655. };
  30656. /**
  30657. * Get visual property of single data item
  30658. */
  30659. // eslint-disable-next-line
  30660. SeriesData.prototype.getItemVisual = function (idx, key) {
  30661. var itemVisual = this._itemVisuals[idx];
  30662. var val = itemVisual && itemVisual[key];
  30663. if (val == null) {
  30664. // Use global visual property
  30665. return this.getVisual(key);
  30666. }
  30667. return val;
  30668. };
  30669. /**
  30670. * If exists visual property of single data item
  30671. */
  30672. SeriesData.prototype.hasItemVisual = function () {
  30673. return this._itemVisuals.length > 0;
  30674. };
  30675. /**
  30676. * Make sure itemVisual property is unique
  30677. */
  30678. // TODO: use key to save visual to reduce memory.
  30679. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  30680. var itemVisuals = this._itemVisuals;
  30681. var itemVisual = itemVisuals[idx];
  30682. if (!itemVisual) {
  30683. itemVisual = itemVisuals[idx] = {};
  30684. }
  30685. var val = itemVisual[key];
  30686. if (val == null) {
  30687. val = this.getVisual(key);
  30688. // TODO Performance?
  30689. if (isArray(val)) {
  30690. val = val.slice();
  30691. } else if (isObject$2(val)) {
  30692. val = extend({}, val);
  30693. }
  30694. itemVisual[key] = val;
  30695. }
  30696. return val;
  30697. };
  30698. // eslint-disable-next-line
  30699. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  30700. var itemVisual = this._itemVisuals[idx] || {};
  30701. this._itemVisuals[idx] = itemVisual;
  30702. if (isObject$2(key)) {
  30703. extend(itemVisual, key);
  30704. } else {
  30705. itemVisual[key] = value;
  30706. }
  30707. };
  30708. /**
  30709. * Clear itemVisuals and list visual.
  30710. */
  30711. SeriesData.prototype.clearAllVisual = function () {
  30712. this._visual = {};
  30713. this._itemVisuals = [];
  30714. };
  30715. SeriesData.prototype.setLayout = function (key, val) {
  30716. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  30717. };
  30718. /**
  30719. * Get layout property.
  30720. */
  30721. SeriesData.prototype.getLayout = function (key) {
  30722. return this._layout[key];
  30723. };
  30724. /**
  30725. * Get layout of single data item
  30726. */
  30727. SeriesData.prototype.getItemLayout = function (idx) {
  30728. return this._itemLayouts[idx];
  30729. };
  30730. /**
  30731. * Set layout of single data item
  30732. */
  30733. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  30734. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  30735. };
  30736. /**
  30737. * Clear all layout of single data item
  30738. */
  30739. SeriesData.prototype.clearItemLayouts = function () {
  30740. this._itemLayouts.length = 0;
  30741. };
  30742. /**
  30743. * Set graphic element relative to data. It can be set as null
  30744. */
  30745. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  30746. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  30747. setCommonECData(seriesIndex, this.dataType, idx, el);
  30748. this._graphicEls[idx] = el;
  30749. };
  30750. SeriesData.prototype.getItemGraphicEl = function (idx) {
  30751. return this._graphicEls[idx];
  30752. };
  30753. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  30754. each(this._graphicEls, function (el, idx) {
  30755. if (el) {
  30756. cb && cb.call(context, el, idx);
  30757. }
  30758. });
  30759. };
  30760. /**
  30761. * Shallow clone a new list except visual and layout properties, and graph elements.
  30762. * New list only change the indices.
  30763. */
  30764. SeriesData.prototype.cloneShallow = function (list) {
  30765. if (!list) {
  30766. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  30767. }
  30768. transferProperties(list, this);
  30769. list._store = this._store;
  30770. return list;
  30771. };
  30772. /**
  30773. * Wrap some method to add more feature
  30774. */
  30775. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  30776. var originalMethod = this[methodName];
  30777. if (!isFunction(originalMethod)) {
  30778. return;
  30779. }
  30780. this.__wrappedMethods = this.__wrappedMethods || [];
  30781. this.__wrappedMethods.push(methodName);
  30782. this[methodName] = function () {
  30783. var res = originalMethod.apply(this, arguments);
  30784. return injectFunction.apply(this, [res].concat(slice(arguments)));
  30785. };
  30786. };
  30787. // ----------------------------------------------------------
  30788. // A work around for internal method visiting private member.
  30789. // ----------------------------------------------------------
  30790. SeriesData.internalField = function () {
  30791. prepareInvertedIndex = function (data) {
  30792. var invertedIndicesMap = data._invertedIndicesMap;
  30793. each(invertedIndicesMap, function (invertedIndices, dim) {
  30794. var dimInfo = data._dimInfos[dim];
  30795. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  30796. var ordinalMeta = dimInfo.ordinalMeta;
  30797. var store = data._store;
  30798. if (ordinalMeta) {
  30799. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length);
  30800. // The default value of TypedArray is 0. To avoid miss
  30801. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  30802. for (var i = 0; i < invertedIndices.length; i++) {
  30803. invertedIndices[i] = INDEX_NOT_FOUND;
  30804. }
  30805. for (var i = 0; i < store.count(); i++) {
  30806. // Only support the case that all values are distinct.
  30807. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  30808. }
  30809. }
  30810. });
  30811. };
  30812. getIdNameFromStore = function (data, dimIdx, idx) {
  30813. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  30814. };
  30815. /**
  30816. * @see the comment of `List['getId']`.
  30817. */
  30818. getId = function (data, rawIndex) {
  30819. var id = data._idList[rawIndex];
  30820. if (id == null && data._idDimIdx != null) {
  30821. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  30822. }
  30823. if (id == null) {
  30824. id = ID_PREFIX + rawIndex;
  30825. }
  30826. return id;
  30827. };
  30828. normalizeDimensions = function (dimensions) {
  30829. if (!isArray(dimensions)) {
  30830. dimensions = dimensions != null ? [dimensions] : [];
  30831. }
  30832. return dimensions;
  30833. };
  30834. /**
  30835. * Data in excludeDimensions is copied, otherwise transferred.
  30836. */
  30837. cloneListForMapAndSample = function (original) {
  30838. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel);
  30839. // FIXME If needs stackedOn, value may already been stacked
  30840. transferProperties(list, original);
  30841. return list;
  30842. };
  30843. transferProperties = function (target, source) {
  30844. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  30845. if (source.hasOwnProperty(propName)) {
  30846. target[propName] = source[propName];
  30847. }
  30848. });
  30849. target.__wrappedMethods = source.__wrappedMethods;
  30850. each(CLONE_PROPERTIES, function (propName) {
  30851. target[propName] = clone(source[propName]);
  30852. });
  30853. target._calculationInfo = extend({}, source._calculationInfo);
  30854. };
  30855. makeIdFromName = function (data, idx) {
  30856. var nameList = data._nameList;
  30857. var idList = data._idList;
  30858. var nameDimIdx = data._nameDimIdx;
  30859. var idDimIdx = data._idDimIdx;
  30860. var name = nameList[idx];
  30861. var id = idList[idx];
  30862. if (name == null && nameDimIdx != null) {
  30863. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  30864. }
  30865. if (id == null && idDimIdx != null) {
  30866. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  30867. }
  30868. if (id == null && name != null) {
  30869. var nameRepeatCount = data._nameRepeatCount;
  30870. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  30871. id = name;
  30872. if (nmCnt > 1) {
  30873. id += '__ec__' + nmCnt;
  30874. }
  30875. idList[idx] = id;
  30876. }
  30877. };
  30878. }();
  30879. return SeriesData;
  30880. }();
  30881. /**
  30882. * For outside usage compat (like echarts-gl are using it).
  30883. */
  30884. function createDimensions(source, opt) {
  30885. return prepareSeriesDataSchema(source, opt).dimensions;
  30886. }
  30887. /**
  30888. * This method builds the relationship between:
  30889. * + "what the coord sys or series requires (see `coordDimensions`)",
  30890. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  30891. * + "what the data source provids (see `source`)".
  30892. *
  30893. * Some guess strategy will be adapted if user does not define something.
  30894. * If no 'value' dimension specified, the first no-named dimension will be
  30895. * named as 'value'.
  30896. *
  30897. * @return The results are always sorted by `storeDimIndex` asc.
  30898. */
  30899. function prepareSeriesDataSchema(
  30900. // TODO: TYPE completeDimensions type
  30901. source, opt) {
  30902. if (!isSourceInstance(source)) {
  30903. source = createSourceFromSeriesDataOption(source);
  30904. }
  30905. opt = opt || {};
  30906. var sysDims = opt.coordDimensions || [];
  30907. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  30908. var coordDimNameMap = createHashMap();
  30909. var resultList = [];
  30910. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount);
  30911. // Try to ignore unused dimensions if sharing a high dimension datastore
  30912. // 30 is an experience value.
  30913. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  30914. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  30915. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  30916. var encodeDef = opt.encodeDefine;
  30917. if (!encodeDef && opt.encodeDefaulter) {
  30918. encodeDef = opt.encodeDefaulter(source, dimCount);
  30919. }
  30920. var encodeDefMap = createHashMap(encodeDef);
  30921. var indicesMap = new CtorInt32Array(dimCount);
  30922. for (var i = 0; i < indicesMap.length; i++) {
  30923. indicesMap[i] = -1;
  30924. }
  30925. function getResultItem(dimIdx) {
  30926. var idx = indicesMap[dimIdx];
  30927. if (idx < 0) {
  30928. var dimDefItemRaw = dimsDef[dimIdx];
  30929. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  30930. name: dimDefItemRaw
  30931. };
  30932. var resultItem = new SeriesDimensionDefine();
  30933. var userDimName = dimDefItem.name;
  30934. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  30935. // Only if `series.dimensions` is defined in option
  30936. // displayName, will be set, and dimension will be displayed vertically in
  30937. // tooltip by default.
  30938. resultItem.name = resultItem.displayName = userDimName;
  30939. }
  30940. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  30941. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  30942. var newIdx = resultList.length;
  30943. indicesMap[dimIdx] = newIdx;
  30944. resultItem.storeDimIndex = dimIdx;
  30945. resultList.push(resultItem);
  30946. return resultItem;
  30947. }
  30948. return resultList[idx];
  30949. }
  30950. if (!omitUnusedDimensions) {
  30951. for (var i = 0; i < dimCount; i++) {
  30952. getResultItem(i);
  30953. }
  30954. }
  30955. // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  30956. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  30957. var dataDims = normalizeToArray(dataDimsRaw).slice();
  30958. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  30959. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  30960. // this case.
  30961. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  30962. encodeDefMap.set(coordDim, false);
  30963. return;
  30964. }
  30965. var validDataDims = encodeDefMap.set(coordDim, []);
  30966. each(dataDims, function (resultDimIdxOrName, idx) {
  30967. // The input resultDimIdx can be dim name or index.
  30968. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  30969. if (resultDimIdx != null && resultDimIdx < dimCount) {
  30970. validDataDims[idx] = resultDimIdx;
  30971. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  30972. }
  30973. });
  30974. });
  30975. // Apply templates and default order from `sysDims`.
  30976. var availDimIdx = 0;
  30977. each(sysDims, function (sysDimItemRaw) {
  30978. var coordDim;
  30979. var sysDimItemDimsDef;
  30980. var sysDimItemOtherDims;
  30981. var sysDimItem;
  30982. if (isString(sysDimItemRaw)) {
  30983. coordDim = sysDimItemRaw;
  30984. sysDimItem = {};
  30985. } else {
  30986. sysDimItem = sysDimItemRaw;
  30987. coordDim = sysDimItem.name;
  30988. var ordinalMeta = sysDimItem.ordinalMeta;
  30989. sysDimItem.ordinalMeta = null;
  30990. sysDimItem = extend({}, sysDimItem);
  30991. sysDimItem.ordinalMeta = ordinalMeta;
  30992. // `coordDimIndex` should not be set directly.
  30993. sysDimItemDimsDef = sysDimItem.dimsDef;
  30994. sysDimItemOtherDims = sysDimItem.otherDims;
  30995. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  30996. }
  30997. var dataDims = encodeDefMap.get(coordDim);
  30998. // negative resultDimIdx means no need to mapping.
  30999. if (dataDims === false) {
  31000. return;
  31001. }
  31002. dataDims = normalizeToArray(dataDims);
  31003. // dimensions provides default dim sequences.
  31004. if (!dataDims.length) {
  31005. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  31006. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  31007. availDimIdx++;
  31008. }
  31009. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  31010. }
  31011. }
  31012. // Apply templates.
  31013. each(dataDims, function (resultDimIdx, coordDimIndex) {
  31014. var resultItem = getResultItem(resultDimIdx);
  31015. // Coordinate system has a higher priority on dim type than source.
  31016. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  31017. resultItem.type = sysDimItem.type;
  31018. }
  31019. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  31020. if (resultItem.name == null && sysDimItemDimsDef) {
  31021. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  31022. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  31023. name: sysDimItemDimsDefItem
  31024. });
  31025. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  31026. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  31027. }
  31028. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  31029. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  31030. });
  31031. });
  31032. function applyDim(resultItem, coordDim, coordDimIndex) {
  31033. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  31034. resultItem.otherDims[coordDim] = coordDimIndex;
  31035. } else {
  31036. resultItem.coordDim = coordDim;
  31037. resultItem.coordDimIndex = coordDimIndex;
  31038. coordDimNameMap.set(coordDim, true);
  31039. }
  31040. }
  31041. // Make sure the first extra dim is 'value'.
  31042. var generateCoord = opt.generateCoord;
  31043. var generateCoordCount = opt.generateCoordCount;
  31044. var fromZero = generateCoordCount != null;
  31045. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  31046. var extra = generateCoord || 'value';
  31047. function ifNoNameFillWithCoordName(resultItem) {
  31048. if (resultItem.name == null) {
  31049. // Duplication will be removed in the next step.
  31050. resultItem.name = resultItem.coordDim;
  31051. }
  31052. }
  31053. // Set dim `name` and other `coordDim` and other props.
  31054. if (!omitUnusedDimensions) {
  31055. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  31056. var resultItem = getResultItem(resultDimIdx);
  31057. var coordDim = resultItem.coordDim;
  31058. if (coordDim == null) {
  31059. // TODO no need to generate coordDim for isExtraCoord?
  31060. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  31061. resultItem.coordDimIndex = 0;
  31062. // Series specified generateCoord is using out.
  31063. if (!generateCoord || generateCoordCount <= 0) {
  31064. resultItem.isExtraCoord = true;
  31065. }
  31066. generateCoordCount--;
  31067. }
  31068. ifNoNameFillWithCoordName(resultItem);
  31069. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must
  31070. // Consider the case:
  31071. // {
  31072. // dataset: {source: [
  31073. // ['2001', 123],
  31074. // ['2002', 456],
  31075. // ...
  31076. // ['The others', 987],
  31077. // ]},
  31078. // series: {type: 'pie'}
  31079. // }
  31080. // The first column should better be treated as a "ordinal" although it
  31081. // might not be detected as an "ordinal" by `guessOrdinal`.
  31082. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  31083. resultItem.type = 'ordinal';
  31084. }
  31085. }
  31086. } else {
  31087. each(resultList, function (resultItem) {
  31088. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  31089. ifNoNameFillWithCoordName(resultItem);
  31090. });
  31091. // Sort dimensions: there are some rule that use the last dim as label,
  31092. // and for some latter travel process easier.
  31093. resultList.sort(function (item0, item1) {
  31094. return item0.storeDimIndex - item1.storeDimIndex;
  31095. });
  31096. }
  31097. removeDuplication(resultList);
  31098. return new SeriesDataSchema({
  31099. source: source,
  31100. dimensions: resultList,
  31101. fullDimensionCount: dimCount,
  31102. dimensionOmitted: omitUnusedDimensions
  31103. });
  31104. }
  31105. function removeDuplication(result) {
  31106. var duplicationMap = createHashMap();
  31107. for (var i = 0; i < result.length; i++) {
  31108. var dim = result[i];
  31109. var dimOriginalName = dim.name;
  31110. var count = duplicationMap.get(dimOriginalName) || 0;
  31111. if (count > 0) {
  31112. // Starts from 0.
  31113. dim.name = dimOriginalName + (count - 1);
  31114. }
  31115. count++;
  31116. duplicationMap.set(dimOriginalName, count);
  31117. }
  31118. }
  31119. // ??? TODO
  31120. // Originally detect dimCount by data[0]. Should we
  31121. // optimize it to only by sysDims and dimensions and encode.
  31122. // So only necessary dims will be initialized.
  31123. // But
  31124. // (1) custom series should be considered. where other dims
  31125. // may be visited.
  31126. // (2) sometimes user need to calculate bubble size or use visualMap
  31127. // on other dimensions besides coordSys needed.
  31128. // So, dims that is not used by system, should be shared in data store?
  31129. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  31130. // Note that the result dimCount should not small than columns count
  31131. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  31132. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  31133. each(sysDims, function (sysDimItem) {
  31134. var sysDimItemDimsDef;
  31135. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  31136. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  31137. }
  31138. });
  31139. return dimCount;
  31140. }
  31141. function genCoordDimName(name, map, fromZero) {
  31142. if (fromZero || map.hasKey(name)) {
  31143. var i = 0;
  31144. while (map.hasKey(name + i)) {
  31145. i++;
  31146. }
  31147. name += i;
  31148. }
  31149. map.set(name, true);
  31150. return name;
  31151. }
  31152. /**
  31153. * @class
  31154. * For example:
  31155. * {
  31156. * coordSysName: 'cartesian2d',
  31157. * coordSysDims: ['x', 'y', ...],
  31158. * axisMap: HashMap({
  31159. * x: xAxisModel,
  31160. * y: yAxisModel
  31161. * }),
  31162. * categoryAxisMap: HashMap({
  31163. * x: xAxisModel,
  31164. * y: undefined
  31165. * }),
  31166. * // The index of the first category axis in `coordSysDims`.
  31167. * // `null/undefined` means no category axis exists.
  31168. * firstCategoryDimIndex: 1,
  31169. * // To replace user specified encode.
  31170. * }
  31171. */
  31172. var CoordSysInfo = /** @class */function () {
  31173. function CoordSysInfo(coordSysName) {
  31174. this.coordSysDims = [];
  31175. this.axisMap = createHashMap();
  31176. this.categoryAxisMap = createHashMap();
  31177. this.coordSysName = coordSysName;
  31178. }
  31179. return CoordSysInfo;
  31180. }();
  31181. function getCoordSysInfoBySeries(seriesModel) {
  31182. var coordSysName = seriesModel.get('coordinateSystem');
  31183. var result = new CoordSysInfo(coordSysName);
  31184. var fetch = fetchers[coordSysName];
  31185. if (fetch) {
  31186. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  31187. return result;
  31188. }
  31189. }
  31190. // TODO: refactor them to static member of each coord sys, rather than hard code here.
  31191. var fetchers = {
  31192. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  31193. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  31194. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  31195. if ("development" !== 'production') {
  31196. if (!xAxisModel) {
  31197. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  31198. }
  31199. if (!yAxisModel) {
  31200. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  31201. }
  31202. }
  31203. result.coordSysDims = ['x', 'y'];
  31204. axisMap.set('x', xAxisModel);
  31205. axisMap.set('y', yAxisModel);
  31206. if (isCategory(xAxisModel)) {
  31207. categoryAxisMap.set('x', xAxisModel);
  31208. result.firstCategoryDimIndex = 0;
  31209. }
  31210. if (isCategory(yAxisModel)) {
  31211. categoryAxisMap.set('y', yAxisModel);
  31212. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  31213. }
  31214. },
  31215. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  31216. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  31217. if ("development" !== 'production') {
  31218. if (!singleAxisModel) {
  31219. throw new Error('singleAxis should be specified.');
  31220. }
  31221. }
  31222. result.coordSysDims = ['single'];
  31223. axisMap.set('single', singleAxisModel);
  31224. if (isCategory(singleAxisModel)) {
  31225. categoryAxisMap.set('single', singleAxisModel);
  31226. result.firstCategoryDimIndex = 0;
  31227. }
  31228. },
  31229. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  31230. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  31231. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  31232. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  31233. if ("development" !== 'production') {
  31234. if (!angleAxisModel) {
  31235. throw new Error('angleAxis option not found');
  31236. }
  31237. if (!radiusAxisModel) {
  31238. throw new Error('radiusAxis option not found');
  31239. }
  31240. }
  31241. result.coordSysDims = ['radius', 'angle'];
  31242. axisMap.set('radius', radiusAxisModel);
  31243. axisMap.set('angle', angleAxisModel);
  31244. if (isCategory(radiusAxisModel)) {
  31245. categoryAxisMap.set('radius', radiusAxisModel);
  31246. result.firstCategoryDimIndex = 0;
  31247. }
  31248. if (isCategory(angleAxisModel)) {
  31249. categoryAxisMap.set('angle', angleAxisModel);
  31250. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  31251. }
  31252. },
  31253. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  31254. result.coordSysDims = ['lng', 'lat'];
  31255. },
  31256. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  31257. var ecModel = seriesModel.ecModel;
  31258. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  31259. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  31260. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  31261. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  31262. var axisDim = coordSysDims[index];
  31263. axisMap.set(axisDim, axisModel);
  31264. if (isCategory(axisModel)) {
  31265. categoryAxisMap.set(axisDim, axisModel);
  31266. if (result.firstCategoryDimIndex == null) {
  31267. result.firstCategoryDimIndex = index;
  31268. }
  31269. }
  31270. });
  31271. },
  31272. matrix: function (seriesModel, result, axisMap, categoryAxisMap) {
  31273. var matrixModel = seriesModel.getReferringComponents('matrix', SINGLE_REFERRING).models[0];
  31274. if ("development" !== 'production') {
  31275. if (!matrixModel) {
  31276. throw new Error('matrix coordinate system should be specified.');
  31277. }
  31278. }
  31279. result.coordSysDims = ['x', 'y'];
  31280. var xModel = matrixModel.getDimensionModel('x');
  31281. var yModel = matrixModel.getDimensionModel('y');
  31282. axisMap.set('x', xModel);
  31283. axisMap.set('y', yModel);
  31284. categoryAxisMap.set('x', xModel);
  31285. categoryAxisMap.set('y', yModel);
  31286. }
  31287. };
  31288. function isCategory(axisModel) {
  31289. return axisModel.get('type') === 'category';
  31290. }
  31291. /**
  31292. * Note that it is too complicated to support 3d stack by value
  31293. * (have to create two-dimension inverted index), so in 3d case
  31294. * we just support that stacked by index.
  31295. *
  31296. * @param seriesModel
  31297. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  31298. * The input will be modified.
  31299. * @param opt
  31300. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  31301. * @param opt.byIndex=false
  31302. * @return calculationInfo
  31303. * {
  31304. * stackedDimension: string
  31305. * stackedByDimension: string
  31306. * isStackedByIndex: boolean
  31307. * stackedOverDimension: string
  31308. * stackResultDimension: string
  31309. * }
  31310. */
  31311. function enableDataStack(seriesModel, dimensionsInput, opt) {
  31312. opt = opt || {};
  31313. var byIndex = opt.byIndex;
  31314. var stackedCoordDimension = opt.stackedCoordDimension;
  31315. var dimensionDefineList;
  31316. var schema;
  31317. var store;
  31318. if (isLegacyDimensionsInput(dimensionsInput)) {
  31319. dimensionDefineList = dimensionsInput;
  31320. } else {
  31321. schema = dimensionsInput.schema;
  31322. dimensionDefineList = schema.dimensions;
  31323. store = dimensionsInput.store;
  31324. }
  31325. // Compatibal: when `stack` is set as '', do not stack.
  31326. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  31327. var stackedByDimInfo;
  31328. var stackedDimInfo;
  31329. var stackResultDimension;
  31330. var stackedOverDimension;
  31331. each(dimensionDefineList, function (dimensionInfo, index) {
  31332. if (isString(dimensionInfo)) {
  31333. dimensionDefineList[index] = dimensionInfo = {
  31334. name: dimensionInfo
  31335. };
  31336. }
  31337. if (mayStack && !dimensionInfo.isExtraCoord) {
  31338. // Find the first ordinal dimension as the stackedByDimInfo.
  31339. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  31340. stackedByDimInfo = dimensionInfo;
  31341. }
  31342. // Find the first stackable dimension as the stackedDimInfo.
  31343. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  31344. stackedDimInfo = dimensionInfo;
  31345. }
  31346. }
  31347. });
  31348. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  31349. // Compatible with previous design, value axis (time axis) only stack by index.
  31350. // It may make sense if the user provides elaborately constructed data.
  31351. byIndex = true;
  31352. }
  31353. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  31354. // That put stack logic in List is for using conveniently in echarts extensions, but it
  31355. // might not be a good way.
  31356. if (stackedDimInfo) {
  31357. // Use a weird name that not duplicated with other names.
  31358. // Also need to use seriesModel.id as postfix because different
  31359. // series may share same data store. The stack dimension needs to be distinguished.
  31360. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  31361. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id;
  31362. // Create inverted index to fast query index by value.
  31363. if (stackedByDimInfo) {
  31364. stackedByDimInfo.createInvertedIndices = true;
  31365. }
  31366. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  31367. var stackedDimType = stackedDimInfo.type;
  31368. var stackedDimCoordIndex_1 = 0;
  31369. each(dimensionDefineList, function (dimensionInfo) {
  31370. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  31371. stackedDimCoordIndex_1++;
  31372. }
  31373. });
  31374. var stackedOverDimensionDefine = {
  31375. name: stackResultDimension,
  31376. coordDim: stackedDimCoordDim_1,
  31377. coordDimIndex: stackedDimCoordIndex_1,
  31378. type: stackedDimType,
  31379. isExtraCoord: true,
  31380. isCalculationCoord: true,
  31381. storeDimIndex: dimensionDefineList.length
  31382. };
  31383. var stackResultDimensionDefine = {
  31384. name: stackedOverDimension,
  31385. // This dimension contains stack base (generally, 0), so do not set it as
  31386. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  31387. coordDim: stackedOverDimension,
  31388. coordDimIndex: stackedDimCoordIndex_1 + 1,
  31389. type: stackedDimType,
  31390. isExtraCoord: true,
  31391. isCalculationCoord: true,
  31392. storeDimIndex: dimensionDefineList.length + 1
  31393. };
  31394. if (schema) {
  31395. if (store) {
  31396. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  31397. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  31398. }
  31399. schema.appendCalculationDimension(stackedOverDimensionDefine);
  31400. schema.appendCalculationDimension(stackResultDimensionDefine);
  31401. } else {
  31402. dimensionDefineList.push(stackedOverDimensionDefine);
  31403. dimensionDefineList.push(stackResultDimensionDefine);
  31404. }
  31405. }
  31406. return {
  31407. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  31408. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  31409. isStackedByIndex: byIndex,
  31410. stackedOverDimension: stackedOverDimension,
  31411. stackResultDimension: stackResultDimension
  31412. };
  31413. }
  31414. function isLegacyDimensionsInput(dimensionsInput) {
  31415. return !isSeriesDataSchema(dimensionsInput.schema);
  31416. }
  31417. function isDimensionStacked(data, stackedDim) {
  31418. // Each single series only maps to one pair of axis. So we do not need to
  31419. // check stackByDim, whatever stacked by a dimension or stacked by index.
  31420. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  31421. }
  31422. function getStackedDimension(data, targetDim) {
  31423. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  31424. }
  31425. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  31426. var coordSysName = seriesModel.get('coordinateSystem');
  31427. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  31428. var coordSysDimDefs;
  31429. if (coordSysInfo && coordSysInfo.coordSysDims) {
  31430. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  31431. var dimInfo = {
  31432. name: dim
  31433. };
  31434. var axisModel = coordSysInfo.axisMap.get(dim);
  31435. if (axisModel) {
  31436. var axisType = axisModel.get('type');
  31437. dimInfo.type = getDimensionTypeByAxis(axisType);
  31438. }
  31439. return dimInfo;
  31440. });
  31441. }
  31442. if (!coordSysDimDefs) {
  31443. // Get dimensions from registered coordinate system
  31444. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  31445. }
  31446. return coordSysDimDefs;
  31447. }
  31448. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  31449. var firstCategoryDimIndex;
  31450. var hasNameEncode;
  31451. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  31452. var coordDim = dimInfo.coordDim;
  31453. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  31454. if (categoryAxisModel) {
  31455. if (firstCategoryDimIndex == null) {
  31456. firstCategoryDimIndex = dimIndex;
  31457. }
  31458. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  31459. if (createInvertedIndices) {
  31460. dimInfo.createInvertedIndices = true;
  31461. }
  31462. }
  31463. if (dimInfo.otherDims.itemName != null) {
  31464. hasNameEncode = true;
  31465. }
  31466. });
  31467. if (!hasNameEncode && firstCategoryDimIndex != null) {
  31468. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  31469. }
  31470. return firstCategoryDimIndex;
  31471. }
  31472. /**
  31473. * Caution: there are side effects to `sourceManager` in this method.
  31474. * Should better only be called in `Series['getInitialData']`.
  31475. */
  31476. function createSeriesData(sourceRaw, seriesModel, opt) {
  31477. opt = opt || {};
  31478. var sourceManager = seriesModel.getSourceManager();
  31479. var source;
  31480. var isOriginalSource = false;
  31481. if (sourceRaw) {
  31482. isOriginalSource = true;
  31483. source = createSourceFromSeriesDataOption(sourceRaw);
  31484. } else {
  31485. source = sourceManager.getSource();
  31486. // Is series.data. not dataset.
  31487. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  31488. }
  31489. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  31490. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  31491. var useEncodeDefaulter = opt.useEncodeDefaulter;
  31492. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  31493. var createDimensionOptions = {
  31494. coordDimensions: coordSysDimDefs,
  31495. generateCoord: opt.generateCoord,
  31496. encodeDefine: seriesModel.getEncode(),
  31497. encodeDefaulter: encodeDefaulter,
  31498. canOmitUnusedDimensions: !isOriginalSource
  31499. };
  31500. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  31501. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  31502. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  31503. var stackCalculationInfo = enableDataStack(seriesModel, {
  31504. schema: schema,
  31505. store: store
  31506. });
  31507. var data = new SeriesData(schema, seriesModel);
  31508. data.setCalculationInfo(stackCalculationInfo);
  31509. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source)
  31510. /**
  31511. * This serves this case:
  31512. * var echarts_option = {
  31513. * xAxis: { data: ['a', 'b', 'c'] },
  31514. * yAxis: {}
  31515. * series: { data: [555, 666, 777] }
  31516. * };
  31517. * The `series.data` is completed to:
  31518. * [[0, 555], [1, 666], [2, 777]]
  31519. */ ? function (itemOpt, dimName, dataIndex, dimIndex) {
  31520. // Use dataIndex as ordinal value in categoryAxis
  31521. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  31522. } : null;
  31523. data.hasItemOption = false;
  31524. data.initData(
  31525. // Try to reuse the data store in sourceManager if using dataset.
  31526. isOriginalSource ? source : store, null, dimValueGetter);
  31527. return data;
  31528. }
  31529. function isNeedCompleteOrdinalData(source) {
  31530. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  31531. var sampleItem = firstDataNotNull(source.data || []);
  31532. return !isArray(getDataItemValue(sampleItem));
  31533. }
  31534. }
  31535. function firstDataNotNull(arr) {
  31536. var i = 0;
  31537. while (i < arr.length && arr[i] == null) {
  31538. i++;
  31539. }
  31540. return arr[i];
  31541. }
  31542. function isValueNice(val) {
  31543. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  31544. var f = Math.abs(val / exp10);
  31545. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  31546. }
  31547. function isIntervalOrLogScale(scale) {
  31548. return scale.type === 'interval' || scale.type === 'log';
  31549. }
  31550. /**
  31551. * @param extent Both extent[0] and extent[1] should be valid number.
  31552. * Should be extent[0] < extent[1].
  31553. * @param splitNumber splitNumber should be >= 1.
  31554. */
  31555. function intervalScaleNiceTicks(extent, spanWithBreaks, splitNumber, minInterval, maxInterval) {
  31556. var result = {};
  31557. var interval = result.interval = nice(spanWithBreaks / splitNumber, true);
  31558. if (minInterval != null && interval < minInterval) {
  31559. interval = result.interval = minInterval;
  31560. }
  31561. if (maxInterval != null && interval > maxInterval) {
  31562. interval = result.interval = maxInterval;
  31563. }
  31564. // Tow more digital for tick.
  31565. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  31566. // Niced extent inside original extent
  31567. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  31568. fixExtent(niceTickExtent, extent);
  31569. return result;
  31570. }
  31571. function increaseInterval(interval) {
  31572. var exp10 = Math.pow(10, quantityExponent(interval));
  31573. // Increase interval
  31574. var f = interval / exp10;
  31575. if (!f) {
  31576. f = 1;
  31577. } else if (f === 2) {
  31578. f = 3;
  31579. } else if (f === 3) {
  31580. f = 5;
  31581. } else {
  31582. // f is 1 or 5
  31583. f *= 2;
  31584. }
  31585. return round(f * exp10);
  31586. }
  31587. /**
  31588. * @return interval precision
  31589. */
  31590. function getIntervalPrecision(interval) {
  31591. // Tow more digital for tick.
  31592. return getPrecision(interval) + 2;
  31593. }
  31594. function clamp(niceTickExtent, idx, extent) {
  31595. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  31596. }
  31597. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  31598. function fixExtent(niceTickExtent, extent) {
  31599. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  31600. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  31601. clamp(niceTickExtent, 0, extent);
  31602. clamp(niceTickExtent, 1, extent);
  31603. if (niceTickExtent[0] > niceTickExtent[1]) {
  31604. niceTickExtent[0] = niceTickExtent[1];
  31605. }
  31606. }
  31607. function contain$1(val, extent) {
  31608. return val >= extent[0] && val <= extent[1];
  31609. }
  31610. var ScaleCalculator = /** @class */function () {
  31611. function ScaleCalculator() {
  31612. this.normalize = normalize$1;
  31613. this.scale = scale$2;
  31614. }
  31615. ScaleCalculator.prototype.updateMethods = function (brkCtx) {
  31616. if (brkCtx.hasBreaks()) {
  31617. this.normalize = bind(brkCtx.normalize, brkCtx);
  31618. this.scale = bind(brkCtx.scale, brkCtx);
  31619. } else {
  31620. this.normalize = normalize$1;
  31621. this.scale = scale$2;
  31622. }
  31623. };
  31624. return ScaleCalculator;
  31625. }();
  31626. function normalize$1(val, extent) {
  31627. if (extent[1] === extent[0]) {
  31628. return 0.5;
  31629. }
  31630. return (val - extent[0]) / (extent[1] - extent[0]);
  31631. }
  31632. function scale$2(val, extent) {
  31633. return val * (extent[1] - extent[0]) + extent[0];
  31634. }
  31635. function logTransform(base, extent, noClampNegative) {
  31636. var loggedBase = Math.log(base);
  31637. return [
  31638. // log(negative) is NaN, so safe guard here.
  31639. // PENDING: But even getting a -Infinity still does not make sense in extent.
  31640. // Just keep it as is, getting a NaN to make some previous cases works by coincidence.
  31641. Math.log(noClampNegative ? extent[0] : Math.max(0, extent[0])) / loggedBase, Math.log(noClampNegative ? extent[1] : Math.max(0, extent[1])) / loggedBase];
  31642. }
  31643. var Scale = /** @class */function () {
  31644. function Scale(setting) {
  31645. this._calculator = new ScaleCalculator();
  31646. this._setting = setting || {};
  31647. this._extent = [Infinity, -Infinity];
  31648. var scaleBreakHelper = getScaleBreakHelper();
  31649. if (scaleBreakHelper) {
  31650. this._brkCtx = scaleBreakHelper.createScaleBreakContext();
  31651. this._brkCtx.update(this._extent);
  31652. }
  31653. }
  31654. Scale.prototype.getSetting = function (name) {
  31655. return this._setting[name];
  31656. };
  31657. /**
  31658. * [CAVEAT]: It should not be overridden!
  31659. */
  31660. Scale.prototype._innerUnionExtent = function (other) {
  31661. var extent = this._extent;
  31662. // Considered that number could be NaN and should not write into the extent.
  31663. this._innerSetExtent(other[0] < extent[0] ? other[0] : extent[0], other[1] > extent[1] ? other[1] : extent[1]);
  31664. };
  31665. /**
  31666. * Set extent from data
  31667. */
  31668. Scale.prototype.unionExtentFromData = function (data, dim) {
  31669. this._innerUnionExtent(data.getApproximateExtent(dim));
  31670. };
  31671. /**
  31672. * Get a new slice of extent.
  31673. * Extent is always in increase order.
  31674. */
  31675. Scale.prototype.getExtent = function () {
  31676. return this._extent.slice();
  31677. };
  31678. Scale.prototype.setExtent = function (start, end) {
  31679. this._innerSetExtent(start, end);
  31680. };
  31681. /**
  31682. * [CAVEAT]: It should not be overridden!
  31683. */
  31684. Scale.prototype._innerSetExtent = function (start, end) {
  31685. var thisExtent = this._extent;
  31686. if (!isNaN(start)) {
  31687. thisExtent[0] = start;
  31688. }
  31689. if (!isNaN(end)) {
  31690. thisExtent[1] = end;
  31691. }
  31692. this._brkCtx && this._brkCtx.update(thisExtent);
  31693. };
  31694. /**
  31695. * Prerequisite: Scale#parse is ready.
  31696. */
  31697. Scale.prototype.setBreaksFromOption = function (breakOptionList) {
  31698. var scaleBreakHelper = getScaleBreakHelper();
  31699. if (scaleBreakHelper) {
  31700. this._innerSetBreak(scaleBreakHelper.parseAxisBreakOption(breakOptionList, bind(this.parse, this)));
  31701. }
  31702. };
  31703. /**
  31704. * [CAVEAT]: It should not be overridden!
  31705. */
  31706. Scale.prototype._innerSetBreak = function (parsed) {
  31707. if (this._brkCtx) {
  31708. this._brkCtx.setBreaks(parsed);
  31709. this._calculator.updateMethods(this._brkCtx);
  31710. this._brkCtx.update(this._extent);
  31711. }
  31712. };
  31713. /**
  31714. * [CAVEAT]: It should not be overridden!
  31715. */
  31716. Scale.prototype._innerGetBreaks = function () {
  31717. return this._brkCtx ? this._brkCtx.breaks : [];
  31718. };
  31719. /**
  31720. * Do not expose the internal `_breaks` unless necessary.
  31721. */
  31722. Scale.prototype.hasBreaks = function () {
  31723. return this._brkCtx ? this._brkCtx.hasBreaks() : false;
  31724. };
  31725. Scale.prototype._getExtentSpanWithBreaks = function () {
  31726. return this._brkCtx && this._brkCtx.hasBreaks() ? this._brkCtx.getExtentSpan() : this._extent[1] - this._extent[0];
  31727. };
  31728. /**
  31729. * If value is in extent range
  31730. */
  31731. Scale.prototype.isInExtentRange = function (value) {
  31732. return this._extent[0] <= value && this._extent[1] >= value;
  31733. };
  31734. /**
  31735. * When axis extent depends on data and no data exists,
  31736. * axis ticks should not be drawn, which is named 'blank'.
  31737. */
  31738. Scale.prototype.isBlank = function () {
  31739. return this._isBlank;
  31740. };
  31741. /**
  31742. * When axis extent depends on data and no data exists,
  31743. * axis ticks should not be drawn, which is named 'blank'.
  31744. */
  31745. Scale.prototype.setBlank = function (isBlank) {
  31746. this._isBlank = isBlank;
  31747. };
  31748. return Scale;
  31749. }();
  31750. enableClassManagement(Scale);
  31751. var uidBase = 0;
  31752. var OrdinalMeta = /** @class */function () {
  31753. /**
  31754. * PENDING - Regarding forcibly converting to string:
  31755. * In the early days, the underlying hash map impl used JS plain object and converted the key to
  31756. * string; later in https://github.com/ecomfe/zrender/pull/966 it was changed to a JS Map (in supported
  31757. * platforms), which does not require string keys. But consider any input that `scale/Ordinal['parse']`
  31758. * is involved, a number input represents an `OrdinalNumber` (i.e., an index), and affect the query
  31759. * behavior:
  31760. * - If forcbily converting to string:
  31761. * pros: users can use numeric string (such as, '123') to query the raw data (123), tho it's probably
  31762. * still confusing.
  31763. * cons: NaN/null/undefined in data will be equals to 'NaN'/'null'/'undefined', if simply using
  31764. * `val + ''` to convert them, like currently `getName` does.
  31765. * - Otherwise:
  31766. * pros: see NaN/null/undefined case above.
  31767. * cons: users cannot query the raw data (123) any more.
  31768. * There are two inconsistent behaviors in the current impl:
  31769. * - Force conversion is applied on the case `xAxis{data: ['aaa', 'bbb', ...]}`,
  31770. * but no conversion applied to the case `xAxis{data: [{value: 'aaa'}, ...]}` and
  31771. * the case `dataset: {source: [['aaa', 123], ['bbb', 234], ...]}`.
  31772. * - behaves differently according to whether JS Map is supported (the polyfill is simply using JS
  31773. * plain object) (tho it seems rare platform that do not support it).
  31774. * Since there's no sufficient good solution to offset cost of the breaking change, we preserve the
  31775. * current behavior, until real issues is reported.
  31776. */
  31777. function OrdinalMeta(opt) {
  31778. this.categories = opt.categories || [];
  31779. this._needCollect = opt.needCollect;
  31780. this._deduplication = opt.deduplication;
  31781. this.uid = ++uidBase;
  31782. this._onCollect = opt.onCollect;
  31783. }
  31784. OrdinalMeta.createByAxisModel = function (axisModel) {
  31785. var option = axisModel.option;
  31786. var data = option.data;
  31787. var categories = data && map(data, getName);
  31788. return new OrdinalMeta({
  31789. categories: categories,
  31790. needCollect: !categories,
  31791. // deduplication is default in axis.
  31792. deduplication: option.dedplication !== false
  31793. });
  31794. };
  31795. OrdinalMeta.prototype.getOrdinal = function (category) {
  31796. return this._getOrCreateMap().get(category);
  31797. };
  31798. /**
  31799. * @return The ordinal. If not found, return NaN.
  31800. */
  31801. OrdinalMeta.prototype.parseAndCollect = function (category) {
  31802. var index;
  31803. var needCollect = this._needCollect;
  31804. // The value of category dim can be the index of the given category set.
  31805. // This feature is only supported when !needCollect, because we should
  31806. // consider a common case: a value is 2017, which is a number but is
  31807. // expected to be tread as a category. This case usually happen in dataset,
  31808. // where it happent to be no need of the index feature.
  31809. if (!isString(category) && !needCollect) {
  31810. return category;
  31811. }
  31812. // Optimize for the scenario:
  31813. // category is ['2012-01-01', '2012-01-02', ...], where the input
  31814. // data has been ensured not duplicate and is large data.
  31815. // Notice, if a dataset dimension provide categroies, usually echarts
  31816. // should remove duplication except user tell echarts dont do that
  31817. // (set axis.deduplication = false), because echarts do not know whether
  31818. // the values in the category dimension has duplication (consider the
  31819. // parallel-aqi example)
  31820. if (needCollect && !this._deduplication) {
  31821. index = this.categories.length;
  31822. this.categories[index] = category;
  31823. this._onCollect && this._onCollect(category, index);
  31824. return index;
  31825. }
  31826. var map = this._getOrCreateMap();
  31827. index = map.get(category);
  31828. if (index == null) {
  31829. if (needCollect) {
  31830. index = this.categories.length;
  31831. this.categories[index] = category;
  31832. map.set(category, index);
  31833. this._onCollect && this._onCollect(category, index);
  31834. } else {
  31835. index = NaN;
  31836. }
  31837. }
  31838. return index;
  31839. };
  31840. // Consider big data, do not create map until needed.
  31841. OrdinalMeta.prototype._getOrCreateMap = function () {
  31842. return this._map || (this._map = createHashMap(this.categories));
  31843. };
  31844. return OrdinalMeta;
  31845. }();
  31846. function getName(obj) {
  31847. if (isObject(obj) && obj.value != null) {
  31848. return obj.value;
  31849. } else {
  31850. return obj + '';
  31851. }
  31852. }
  31853. var OrdinalScale = /** @class */function (_super) {
  31854. __extends(OrdinalScale, _super);
  31855. function OrdinalScale(setting) {
  31856. var _this = _super.call(this, setting) || this;
  31857. _this.type = 'ordinal';
  31858. var ordinalMeta = _this.getSetting('ordinalMeta');
  31859. // Caution: Should not use instanceof, consider ec-extensions using
  31860. // import approach to get OrdinalMeta class.
  31861. if (!ordinalMeta) {
  31862. ordinalMeta = new OrdinalMeta({});
  31863. }
  31864. if (isArray(ordinalMeta)) {
  31865. ordinalMeta = new OrdinalMeta({
  31866. categories: map(ordinalMeta, function (item) {
  31867. return isObject(item) ? item.value : item;
  31868. })
  31869. });
  31870. }
  31871. _this._ordinalMeta = ordinalMeta;
  31872. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  31873. return _this;
  31874. }
  31875. OrdinalScale.prototype.parse = function (val) {
  31876. // Caution: Math.round(null) will return `0` rather than `NaN`
  31877. if (val == null) {
  31878. return NaN;
  31879. }
  31880. return isString(val) ? this._ordinalMeta.getOrdinal(val)
  31881. // val might be float.
  31882. : Math.round(val);
  31883. };
  31884. OrdinalScale.prototype.contain = function (val) {
  31885. return contain$1(val, this._extent) && val >= 0 && val < this._ordinalMeta.categories.length;
  31886. };
  31887. /**
  31888. * Normalize given rank or name to linear [0, 1]
  31889. * @param val raw ordinal number.
  31890. * @return normalized value in [0, 1].
  31891. */
  31892. OrdinalScale.prototype.normalize = function (val) {
  31893. val = this._getTickNumber(val);
  31894. return this._calculator.normalize(val, this._extent);
  31895. };
  31896. /**
  31897. * @param val normalized value in [0, 1].
  31898. * @return raw ordinal number.
  31899. */
  31900. OrdinalScale.prototype.scale = function (val) {
  31901. val = Math.round(this._calculator.scale(val, this._extent));
  31902. return this.getRawOrdinalNumber(val);
  31903. };
  31904. OrdinalScale.prototype.getTicks = function () {
  31905. var ticks = [];
  31906. var extent = this._extent;
  31907. var rank = extent[0];
  31908. while (rank <= extent[1]) {
  31909. ticks.push({
  31910. value: rank
  31911. });
  31912. rank++;
  31913. }
  31914. return ticks;
  31915. };
  31916. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  31917. // Not support.
  31918. return;
  31919. };
  31920. /**
  31921. * @see `Ordinal['_ordinalNumbersByTick']`
  31922. */
  31923. OrdinalScale.prototype.setSortInfo = function (info) {
  31924. if (info == null) {
  31925. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  31926. return;
  31927. }
  31928. var infoOrdinalNumbers = info.ordinalNumbers;
  31929. var ordinalsByTick = this._ordinalNumbersByTick = [];
  31930. var ticksByOrdinal = this._ticksByOrdinalNumber = [];
  31931. // Unnecessary support negative tick in `realtimeSort`.
  31932. var tickNum = 0;
  31933. var allCategoryLen = this._ordinalMeta.categories.length;
  31934. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  31935. var ordinalNumber = infoOrdinalNumbers[tickNum];
  31936. ordinalsByTick[tickNum] = ordinalNumber;
  31937. ticksByOrdinal[ordinalNumber] = tickNum;
  31938. }
  31939. // Handle that `series.data` only covers part of the `axis.category.data`.
  31940. var unusedOrdinal = 0;
  31941. for (; tickNum < allCategoryLen; ++tickNum) {
  31942. while (ticksByOrdinal[unusedOrdinal] != null) {
  31943. unusedOrdinal++;
  31944. }
  31945. ordinalsByTick.push(unusedOrdinal);
  31946. ticksByOrdinal[unusedOrdinal] = tickNum;
  31947. }
  31948. };
  31949. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  31950. var ticksByOrdinalNumber = this._ticksByOrdinalNumber;
  31951. // also support ordinal out of range of `ordinalMeta.categories.length`,
  31952. // where ordinal numbers are used as tick value directly.
  31953. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  31954. };
  31955. /**
  31956. * @usage
  31957. * ```js
  31958. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  31959. *
  31960. * // case0
  31961. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  31962. * // case1
  31963. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  31964. * // case2
  31965. * const coord = axis.dataToCoord(ordinalNumber);
  31966. * ```
  31967. *
  31968. * @param {OrdinalNumber} tickNumber index of display
  31969. */
  31970. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  31971. var ordinalNumbersByTick = this._ordinalNumbersByTick;
  31972. // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  31973. // where ordinal numbers are used as tick value directly.
  31974. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  31975. };
  31976. /**
  31977. * Get item on tick
  31978. */
  31979. OrdinalScale.prototype.getLabel = function (tick) {
  31980. if (!this.isBlank()) {
  31981. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  31982. var cateogry = this._ordinalMeta.categories[ordinalNumber];
  31983. // Note that if no data, ordinalMeta.categories is an empty array.
  31984. // Return empty if it's not exist.
  31985. return cateogry == null ? '' : cateogry + '';
  31986. }
  31987. };
  31988. OrdinalScale.prototype.count = function () {
  31989. return this._extent[1] - this._extent[0] + 1;
  31990. };
  31991. /**
  31992. * @override
  31993. * If value is in extent range
  31994. */
  31995. OrdinalScale.prototype.isInExtentRange = function (value) {
  31996. value = this._getTickNumber(value);
  31997. return this._extent[0] <= value && this._extent[1] >= value;
  31998. };
  31999. OrdinalScale.prototype.getOrdinalMeta = function () {
  32000. return this._ordinalMeta;
  32001. };
  32002. OrdinalScale.prototype.calcNiceTicks = function () {};
  32003. OrdinalScale.prototype.calcNiceExtent = function () {};
  32004. OrdinalScale.type = 'ordinal';
  32005. return OrdinalScale;
  32006. }(Scale);
  32007. Scale.registerClass(OrdinalScale);
  32008. var roundNumber = round;
  32009. var IntervalScale = /** @class */function (_super) {
  32010. __extends(IntervalScale, _super);
  32011. function IntervalScale() {
  32012. var _this = _super !== null && _super.apply(this, arguments) || this;
  32013. _this.type = 'interval';
  32014. // Step is calculated in adjustExtent.
  32015. _this._interval = 0;
  32016. _this._intervalPrecision = 2;
  32017. return _this;
  32018. }
  32019. IntervalScale.prototype.parse = function (val) {
  32020. // `Scale#parse` (and its overrids) are typically applied at the axis values input
  32021. // in echarts option. e.g., `axis.min/max`, `dataZoom.min/max`, etc.
  32022. // but `series.data` is not included, which uses `dataValueHelper.ts`#`parseDataValue`.
  32023. // `Scale#parse` originally introduced in fb8c813215098b9d2458966229bb95c510883d5e
  32024. // at 2016 for dataZoom start/end settings (See `parseAxisModelMinMax`).
  32025. //
  32026. // Historically `scale/Interval.ts` returns the input value directly. But numeric
  32027. // values (such as a number-like string '123') effectively passed through here and
  32028. // were involved in calculations, which was error-prone and inconsistent with the
  32029. // declared TS return type. Previously such issues are fixed separately in different
  32030. // places case by case (such as #2475).
  32031. //
  32032. // Now, we perform actual parse to ensure its `number` type here. The parsing rule
  32033. // follows the series data parsing rule (`dataValueHelper.ts`#`parseDataValue`)
  32034. // and maintains compatibility as much as possible (thus a more strict parsing
  32035. // `number.ts`#`numericToNumber` is not used here.)
  32036. //
  32037. // FIXME: `ScaleDataValue` also need to be modified to include numeric string type,
  32038. // since it effectively does.
  32039. return val == null || val === '' ? NaN
  32040. // If string (like '-'), using '+' parse to NaN
  32041. // If object, also parse to NaN
  32042. : Number(val);
  32043. };
  32044. IntervalScale.prototype.contain = function (val) {
  32045. return contain$1(val, this._extent);
  32046. };
  32047. IntervalScale.prototype.normalize = function (val) {
  32048. return this._calculator.normalize(val, this._extent);
  32049. };
  32050. IntervalScale.prototype.scale = function (val) {
  32051. return this._calculator.scale(val, this._extent);
  32052. };
  32053. IntervalScale.prototype.getInterval = function () {
  32054. return this._interval;
  32055. };
  32056. IntervalScale.prototype.setInterval = function (interval) {
  32057. this._interval = interval;
  32058. // Dropped auto calculated niceExtent and use user-set extent.
  32059. // We assume user wants to set both interval, min, max to get a better result.
  32060. this._niceExtent = this._extent.slice();
  32061. this._intervalPrecision = getIntervalPrecision(interval);
  32062. };
  32063. /**
  32064. * @override
  32065. */
  32066. IntervalScale.prototype.getTicks = function (opt) {
  32067. opt = opt || {};
  32068. var interval = this._interval;
  32069. var extent = this._extent;
  32070. var niceTickExtent = this._niceExtent;
  32071. var intervalPrecision = this._intervalPrecision;
  32072. var scaleBreakHelper = getScaleBreakHelper();
  32073. var ticks = [];
  32074. // If interval is 0, return [];
  32075. if (!interval) {
  32076. return ticks;
  32077. }
  32078. if (opt.breakTicks === 'only_break' && scaleBreakHelper) {
  32079. scaleBreakHelper.addBreaksToTicks(ticks, this._brkCtx.breaks, this._extent);
  32080. return ticks;
  32081. }
  32082. // Consider this case: using dataZoom toolbox, zoom and zoom.
  32083. var safeLimit = 10000;
  32084. if (extent[0] < niceTickExtent[0]) {
  32085. if (opt.expandToNicedExtent) {
  32086. ticks.push({
  32087. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  32088. });
  32089. } else {
  32090. ticks.push({
  32091. value: extent[0]
  32092. });
  32093. }
  32094. }
  32095. var estimateNiceMultiple = function (tickVal, targetTick) {
  32096. return Math.round((targetTick - tickVal) / interval);
  32097. };
  32098. var tick = niceTickExtent[0];
  32099. while (tick <= niceTickExtent[1]) {
  32100. ticks.push({
  32101. value: tick
  32102. });
  32103. // Avoid rounding error
  32104. tick = roundNumber(tick + interval, intervalPrecision);
  32105. if (this._brkCtx) {
  32106. var moreMultiple = this._brkCtx.calcNiceTickMultiple(tick, estimateNiceMultiple);
  32107. if (moreMultiple >= 0) {
  32108. tick = roundNumber(tick + moreMultiple * interval, intervalPrecision);
  32109. }
  32110. }
  32111. if (ticks.length > 0 && tick === ticks[ticks.length - 1].value) {
  32112. // Consider out of safe float point, e.g.,
  32113. // -3711126.9907707 + 2e-10 === -3711126.9907707
  32114. break;
  32115. }
  32116. if (ticks.length > safeLimit) {
  32117. return [];
  32118. }
  32119. }
  32120. // Consider this case: the last item of ticks is smaller
  32121. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  32122. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  32123. if (extent[1] > lastNiceTick) {
  32124. if (opt.expandToNicedExtent) {
  32125. ticks.push({
  32126. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  32127. });
  32128. } else {
  32129. ticks.push({
  32130. value: extent[1]
  32131. });
  32132. }
  32133. }
  32134. if (scaleBreakHelper) {
  32135. scaleBreakHelper.pruneTicksByBreak(opt.pruneByBreak, ticks, this._brkCtx.breaks, function (item) {
  32136. return item.value;
  32137. }, this._interval, this._extent);
  32138. }
  32139. if (opt.breakTicks !== 'none' && scaleBreakHelper) {
  32140. scaleBreakHelper.addBreaksToTicks(ticks, this._brkCtx.breaks, this._extent);
  32141. }
  32142. return ticks;
  32143. };
  32144. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  32145. var ticks = this.getTicks({
  32146. expandToNicedExtent: true
  32147. });
  32148. // NOTE: In log-scale, do not support minor ticks when breaks exist.
  32149. // because currently log-scale minor ticks is calculated based on raw values
  32150. // rather than log-transformed value, due to an odd effect when breaks exist.
  32151. var minorTicks = [];
  32152. var extent = this.getExtent();
  32153. for (var i = 1; i < ticks.length; i++) {
  32154. var nextTick = ticks[i];
  32155. var prevTick = ticks[i - 1];
  32156. if (prevTick["break"] || nextTick["break"]) {
  32157. // Do not build minor ticks to the adjacent ticks to breaks ticks,
  32158. // since the interval might be irregular.
  32159. continue;
  32160. }
  32161. var count = 0;
  32162. var minorTicksGroup = [];
  32163. var interval = nextTick.value - prevTick.value;
  32164. var minorInterval = interval / splitNumber;
  32165. var minorIntervalPrecision = getIntervalPrecision(minorInterval);
  32166. while (count < splitNumber - 1) {
  32167. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval, minorIntervalPrecision);
  32168. // For the first and last interval. The count may be less than splitNumber.
  32169. if (minorTick > extent[0] && minorTick < extent[1]) {
  32170. minorTicksGroup.push(minorTick);
  32171. }
  32172. count++;
  32173. }
  32174. var scaleBreakHelper = getScaleBreakHelper();
  32175. scaleBreakHelper && scaleBreakHelper.pruneTicksByBreak('auto', minorTicksGroup, this._getNonTransBreaks(), function (value) {
  32176. return value;
  32177. }, this._interval, extent);
  32178. minorTicks.push(minorTicksGroup);
  32179. }
  32180. return minorTicks;
  32181. };
  32182. IntervalScale.prototype._getNonTransBreaks = function () {
  32183. return this._brkCtx ? this._brkCtx.breaks : [];
  32184. };
  32185. /**
  32186. * @param opt.precision If 'auto', use nice presision.
  32187. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  32188. */
  32189. IntervalScale.prototype.getLabel = function (data, opt) {
  32190. if (data == null) {
  32191. return '';
  32192. }
  32193. var precision = opt && opt.precision;
  32194. if (precision == null) {
  32195. precision = getPrecision(data.value) || 0;
  32196. } else if (precision === 'auto') {
  32197. // Should be more precise then tick.
  32198. precision = this._intervalPrecision;
  32199. }
  32200. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  32201. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  32202. var dataNum = roundNumber(data.value, precision, true);
  32203. return addCommas(dataNum);
  32204. };
  32205. /**
  32206. * FIXME: refactor - disallow override, use composition instead.
  32207. *
  32208. * The override of `calcNiceTicks` should ensure these members are provided:
  32209. * this._intervalPrecision
  32210. * this._interval
  32211. *
  32212. * @param splitNumber By default `5`.
  32213. */
  32214. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  32215. splitNumber = splitNumber || 5;
  32216. var extent = this._extent.slice();
  32217. var span = this._getExtentSpanWithBreaks();
  32218. if (!isFinite(span)) {
  32219. return;
  32220. }
  32221. // User may set axis min 0 and data are all negative
  32222. // FIXME If it needs to reverse ?
  32223. if (span < 0) {
  32224. span = -span;
  32225. extent.reverse();
  32226. this._innerSetExtent(extent[0], extent[1]);
  32227. extent = this._extent.slice();
  32228. }
  32229. var result = intervalScaleNiceTicks(extent, span, splitNumber, minInterval, maxInterval);
  32230. this._intervalPrecision = result.intervalPrecision;
  32231. this._interval = result.interval;
  32232. this._niceExtent = result.niceTickExtent;
  32233. };
  32234. IntervalScale.prototype.calcNiceExtent = function (opt) {
  32235. var extent = this._extent.slice();
  32236. // If extent start and end are same, expand them
  32237. if (extent[0] === extent[1]) {
  32238. if (extent[0] !== 0) {
  32239. // Expand extent
  32240. // Note that extents can be both negative. See #13154
  32241. var expandSize = Math.abs(extent[0]);
  32242. // In the fowllowing case
  32243. // Axis has been fixed max 100
  32244. // Plus data are all 100 and axis extent are [100, 100].
  32245. // Extend to the both side will cause expanded max is larger than fixed max.
  32246. // So only expand to the smaller side.
  32247. if (!opt.fixMax) {
  32248. extent[1] += expandSize / 2;
  32249. extent[0] -= expandSize / 2;
  32250. } else {
  32251. extent[0] -= expandSize / 2;
  32252. }
  32253. } else {
  32254. extent[1] = 1;
  32255. }
  32256. }
  32257. var span = extent[1] - extent[0];
  32258. // If there are no data and extent are [Infinity, -Infinity]
  32259. if (!isFinite(span)) {
  32260. extent[0] = 0;
  32261. extent[1] = 1;
  32262. }
  32263. this._innerSetExtent(extent[0], extent[1]);
  32264. extent = this._extent.slice();
  32265. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  32266. var interval = this._interval;
  32267. var intervalPrecition = this._intervalPrecision;
  32268. if (!opt.fixMin) {
  32269. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval, intervalPrecition);
  32270. }
  32271. if (!opt.fixMax) {
  32272. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval, intervalPrecition);
  32273. }
  32274. this._innerSetExtent(extent[0], extent[1]);
  32275. };
  32276. IntervalScale.prototype.setNiceExtent = function (min, max) {
  32277. this._niceExtent = [min, max];
  32278. };
  32279. IntervalScale.type = 'interval';
  32280. return IntervalScale;
  32281. }(Scale);
  32282. Scale.registerClass(IntervalScale);
  32283. /* global Float32Array */
  32284. var supportFloat32Array = typeof Float32Array !== 'undefined';
  32285. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  32286. function createFloat32Array(arg) {
  32287. if (isArray(arg)) {
  32288. // Return self directly if don't support TypedArray.
  32289. return supportFloat32Array ? new Float32Array(arg) : arg;
  32290. }
  32291. // Else is number
  32292. return new Float32ArrayCtor(arg);
  32293. }
  32294. var STACK_PREFIX = '__ec_stack_';
  32295. function getSeriesStackId(seriesModel) {
  32296. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  32297. }
  32298. function getAxisKey(axis) {
  32299. return axis.dim + axis.index;
  32300. }
  32301. function prepareLayoutBarSeries(seriesType, ecModel) {
  32302. var seriesModels = [];
  32303. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32304. // Check series coordinate, do layout for cartesian2d only
  32305. if (isOnCartesian(seriesModel)) {
  32306. seriesModels.push(seriesModel);
  32307. }
  32308. });
  32309. return seriesModels;
  32310. }
  32311. /**
  32312. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  32313. * values.
  32314. * This works for time axes, value axes, and log axes.
  32315. * For a single time axis, return value is in the form like
  32316. * {'x_0': [1000000]}.
  32317. * The value of 1000000 is in milliseconds.
  32318. */
  32319. function getValueAxesMinGaps(barSeries) {
  32320. /**
  32321. * Map from axis.index to values.
  32322. * For a single time axis, axisValues is in the form like
  32323. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  32324. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  32325. * series.
  32326. */
  32327. var axisValues = {};
  32328. each(barSeries, function (seriesModel) {
  32329. var cartesian = seriesModel.coordinateSystem;
  32330. var baseAxis = cartesian.getBaseAxis();
  32331. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  32332. return;
  32333. }
  32334. var data = seriesModel.getData();
  32335. var key = baseAxis.dim + '_' + baseAxis.index;
  32336. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  32337. var store = data.getStore();
  32338. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  32339. var value = store.get(dimIdx, i);
  32340. if (!axisValues[key]) {
  32341. // No previous data for the axis
  32342. axisValues[key] = [value];
  32343. } else {
  32344. // No value in previous series
  32345. axisValues[key].push(value);
  32346. }
  32347. // Ignore duplicated time values in the same axis
  32348. }
  32349. });
  32350. var axisMinGaps = {};
  32351. for (var key in axisValues) {
  32352. if (axisValues.hasOwnProperty(key)) {
  32353. var valuesInAxis = axisValues[key];
  32354. if (valuesInAxis) {
  32355. // Sort axis values into ascending order to calculate gaps
  32356. valuesInAxis.sort(function (a, b) {
  32357. return a - b;
  32358. });
  32359. var min = null;
  32360. for (var j = 1; j < valuesInAxis.length; ++j) {
  32361. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  32362. if (delta > 0) {
  32363. // Ignore 0 delta because they are of the same axis value
  32364. min = min === null ? delta : Math.min(min, delta);
  32365. }
  32366. }
  32367. // Set to null if only have one data
  32368. axisMinGaps[key] = min;
  32369. }
  32370. }
  32371. }
  32372. return axisMinGaps;
  32373. }
  32374. function makeColumnLayout(barSeries) {
  32375. var axisMinGaps = getValueAxesMinGaps(barSeries);
  32376. var seriesInfoList = [];
  32377. each(barSeries, function (seriesModel) {
  32378. var cartesian = seriesModel.coordinateSystem;
  32379. var baseAxis = cartesian.getBaseAxis();
  32380. var axisExtent = baseAxis.getExtent();
  32381. var bandWidth;
  32382. if (baseAxis.type === 'category') {
  32383. bandWidth = baseAxis.getBandWidth();
  32384. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  32385. var key = baseAxis.dim + '_' + baseAxis.index;
  32386. var minGap = axisMinGaps[key];
  32387. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  32388. var scale = baseAxis.scale.getExtent();
  32389. var scaleSpan = Math.abs(scale[1] - scale[0]);
  32390. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  32391. } else {
  32392. var data = seriesModel.getData();
  32393. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  32394. }
  32395. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  32396. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  32397. var barMinWidth = parsePercent$1(
  32398. // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  32399. // the auto-calculated bar width might be less than 0.5 / 1.
  32400. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  32401. var barGap = seriesModel.get('barGap');
  32402. var barCategoryGap = seriesModel.get('barCategoryGap');
  32403. var defaultBarGap = seriesModel.get('defaultBarGap');
  32404. seriesInfoList.push({
  32405. bandWidth: bandWidth,
  32406. barWidth: barWidth,
  32407. barMaxWidth: barMaxWidth,
  32408. barMinWidth: barMinWidth,
  32409. barGap: barGap,
  32410. barCategoryGap: barCategoryGap,
  32411. defaultBarGap: defaultBarGap,
  32412. axisKey: getAxisKey(baseAxis),
  32413. stackId: getSeriesStackId(seriesModel)
  32414. });
  32415. });
  32416. return doCalBarWidthAndOffset(seriesInfoList);
  32417. }
  32418. function doCalBarWidthAndOffset(seriesInfoList) {
  32419. // Columns info on each category axis. Key is cartesian name
  32420. var columnsMap = {};
  32421. each(seriesInfoList, function (seriesInfo, idx) {
  32422. var axisKey = seriesInfo.axisKey;
  32423. var bandWidth = seriesInfo.bandWidth;
  32424. var columnsOnAxis = columnsMap[axisKey] || {
  32425. bandWidth: bandWidth,
  32426. remainedWidth: bandWidth,
  32427. autoWidthCount: 0,
  32428. categoryGap: null,
  32429. gap: seriesInfo.defaultBarGap || 0,
  32430. stacks: {}
  32431. };
  32432. var stacks = columnsOnAxis.stacks;
  32433. columnsMap[axisKey] = columnsOnAxis;
  32434. var stackId = seriesInfo.stackId;
  32435. if (!stacks[stackId]) {
  32436. columnsOnAxis.autoWidthCount++;
  32437. }
  32438. stacks[stackId] = stacks[stackId] || {
  32439. width: 0,
  32440. maxWidth: 0
  32441. };
  32442. // Caution: In a single coordinate system, these barGrid attributes
  32443. // will be shared by series. Consider that they have default values,
  32444. // only the attributes set on the last series will work.
  32445. // Do not change this fact unless there will be a break change.
  32446. var barWidth = seriesInfo.barWidth;
  32447. if (barWidth && !stacks[stackId].width) {
  32448. // See #6312, do not restrict width.
  32449. stacks[stackId].width = barWidth;
  32450. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  32451. columnsOnAxis.remainedWidth -= barWidth;
  32452. }
  32453. var barMaxWidth = seriesInfo.barMaxWidth;
  32454. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  32455. var barMinWidth = seriesInfo.barMinWidth;
  32456. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  32457. var barGap = seriesInfo.barGap;
  32458. barGap != null && (columnsOnAxis.gap = barGap);
  32459. var barCategoryGap = seriesInfo.barCategoryGap;
  32460. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  32461. });
  32462. var result = {};
  32463. each(columnsMap, function (columnsOnAxis, coordSysName) {
  32464. result[coordSysName] = {};
  32465. var stacks = columnsOnAxis.stacks;
  32466. var bandWidth = columnsOnAxis.bandWidth;
  32467. var categoryGapPercent = columnsOnAxis.categoryGap;
  32468. if (categoryGapPercent == null) {
  32469. var columnCount = keys(stacks).length;
  32470. // More columns in one group
  32471. // the spaces between group is smaller. Or the column will be too thin.
  32472. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  32473. }
  32474. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  32475. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  32476. var remainedWidth = columnsOnAxis.remainedWidth;
  32477. var autoWidthCount = columnsOnAxis.autoWidthCount;
  32478. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  32479. autoWidth = Math.max(autoWidth, 0);
  32480. // Find if any auto calculated bar exceeded maxBarWidth
  32481. each(stacks, function (column) {
  32482. var maxWidth = column.maxWidth;
  32483. var minWidth = column.minWidth;
  32484. if (!column.width) {
  32485. var finalWidth = autoWidth;
  32486. if (maxWidth && maxWidth < finalWidth) {
  32487. finalWidth = Math.min(maxWidth, remainedWidth);
  32488. }
  32489. // `minWidth` has higher priority. `minWidth` decide that whether the
  32490. // bar is able to be visible. So `minWidth` should not be restricted
  32491. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  32492. // the extreme cases for `value` axis, bars are allowed to overlap
  32493. // with each other if `minWidth` specified.
  32494. if (minWidth && minWidth > finalWidth) {
  32495. finalWidth = minWidth;
  32496. }
  32497. if (finalWidth !== autoWidth) {
  32498. column.width = finalWidth;
  32499. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  32500. autoWidthCount--;
  32501. }
  32502. } else {
  32503. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  32504. // CSS does. Because barWidth can be a percent value, where
  32505. // `barMaxWidth` can be used to restrict the final width.
  32506. var finalWidth = column.width;
  32507. if (maxWidth) {
  32508. finalWidth = Math.min(finalWidth, maxWidth);
  32509. }
  32510. // `minWidth` has higher priority, as described above
  32511. if (minWidth) {
  32512. finalWidth = Math.max(finalWidth, minWidth);
  32513. }
  32514. column.width = finalWidth;
  32515. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  32516. autoWidthCount--;
  32517. }
  32518. });
  32519. // Recalculate width again
  32520. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  32521. autoWidth = Math.max(autoWidth, 0);
  32522. var widthSum = 0;
  32523. var lastColumn;
  32524. each(stacks, function (column, idx) {
  32525. if (!column.width) {
  32526. column.width = autoWidth;
  32527. }
  32528. lastColumn = column;
  32529. widthSum += column.width * (1 + barGapPercent);
  32530. });
  32531. if (lastColumn) {
  32532. widthSum -= lastColumn.width * barGapPercent;
  32533. }
  32534. var offset = -widthSum / 2;
  32535. each(stacks, function (column, stackId) {
  32536. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  32537. bandWidth: bandWidth,
  32538. offset: offset,
  32539. width: column.width
  32540. };
  32541. offset += column.width * (1 + barGapPercent);
  32542. });
  32543. });
  32544. return result;
  32545. }
  32546. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  32547. if (barWidthAndOffset && axis) {
  32548. var result = barWidthAndOffset[getAxisKey(axis)];
  32549. if (result != null && seriesModel != null) {
  32550. return result[getSeriesStackId(seriesModel)];
  32551. }
  32552. return result;
  32553. }
  32554. }
  32555. function layout(seriesType, ecModel) {
  32556. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  32557. var barWidthAndOffset = makeColumnLayout(seriesModels);
  32558. each(seriesModels, function (seriesModel) {
  32559. var data = seriesModel.getData();
  32560. var cartesian = seriesModel.coordinateSystem;
  32561. var baseAxis = cartesian.getBaseAxis();
  32562. var stackId = getSeriesStackId(seriesModel);
  32563. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  32564. var columnOffset = columnLayoutInfo.offset;
  32565. var columnWidth = columnLayoutInfo.width;
  32566. data.setLayout({
  32567. bandWidth: columnLayoutInfo.bandWidth,
  32568. offset: columnOffset,
  32569. size: columnWidth
  32570. });
  32571. });
  32572. }
  32573. // TODO: Do not support stack in large mode yet.
  32574. function createProgressiveLayout(seriesType) {
  32575. return {
  32576. seriesType: seriesType,
  32577. plan: createRenderPlanner(),
  32578. reset: function (seriesModel) {
  32579. if (!isOnCartesian(seriesModel)) {
  32580. return;
  32581. }
  32582. var data = seriesModel.getData();
  32583. var cartesian = seriesModel.coordinateSystem;
  32584. var baseAxis = cartesian.getBaseAxis();
  32585. var valueAxis = cartesian.getOtherAxis(baseAxis);
  32586. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  32587. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  32588. var drawBackground = seriesModel.get('showBackground', true);
  32589. var valueDim = data.mapDimension(valueAxis.dim);
  32590. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  32591. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  32592. var isValueAxisH = valueAxis.isHorizontal();
  32593. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  32594. var isLarge = isInLargeMode(seriesModel);
  32595. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  32596. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim);
  32597. // Layout info.
  32598. var columnWidth = data.getLayout('size');
  32599. var columnOffset = data.getLayout('offset');
  32600. return {
  32601. progress: function (params, data) {
  32602. var count = params.count;
  32603. var largePoints = isLarge && createFloat32Array(count * 3);
  32604. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  32605. var largeDataIndices = isLarge && createFloat32Array(count);
  32606. var coordLayout = cartesian.master.getRect();
  32607. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  32608. var dataIndex;
  32609. var store = data.getStore();
  32610. var idxOffset = 0;
  32611. while ((dataIndex = params.next()) != null) {
  32612. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  32613. var baseValue = store.get(baseDimIdx, dataIndex);
  32614. var baseCoord = valueAxisStart;
  32615. var stackStartValue = void 0;
  32616. // Because of the barMinHeight, we can not use the value in
  32617. // stackResultDimension directly.
  32618. if (stacked) {
  32619. stackStartValue = +value - store.get(valueDimIdx, dataIndex);
  32620. }
  32621. var x = void 0;
  32622. var y = void 0;
  32623. var width = void 0;
  32624. var height = void 0;
  32625. if (isValueAxisH) {
  32626. var coord = cartesian.dataToPoint([value, baseValue]);
  32627. if (stacked) {
  32628. var startCoord = cartesian.dataToPoint([stackStartValue, baseValue]);
  32629. baseCoord = startCoord[0];
  32630. }
  32631. x = baseCoord;
  32632. y = coord[1] + columnOffset;
  32633. width = coord[0] - baseCoord;
  32634. height = columnWidth;
  32635. if (Math.abs(width) < barMinHeight) {
  32636. width = (width < 0 ? -1 : 1) * barMinHeight;
  32637. }
  32638. } else {
  32639. var coord = cartesian.dataToPoint([baseValue, value]);
  32640. if (stacked) {
  32641. var startCoord = cartesian.dataToPoint([baseValue, stackStartValue]);
  32642. baseCoord = startCoord[1];
  32643. }
  32644. x = coord[0] + columnOffset;
  32645. y = baseCoord;
  32646. width = columnWidth;
  32647. height = coord[1] - baseCoord;
  32648. if (Math.abs(height) < barMinHeight) {
  32649. // Include zero to has a positive bar
  32650. height = (height <= 0 ? -1 : 1) * barMinHeight;
  32651. }
  32652. }
  32653. if (!isLarge) {
  32654. data.setItemLayout(dataIndex, {
  32655. x: x,
  32656. y: y,
  32657. width: width,
  32658. height: height
  32659. });
  32660. } else {
  32661. largePoints[idxOffset] = x;
  32662. largePoints[idxOffset + 1] = y;
  32663. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  32664. if (largeBackgroundPoints) {
  32665. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  32666. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  32667. largeBackgroundPoints[idxOffset + 2] = bgSize;
  32668. }
  32669. largeDataIndices[dataIndex] = dataIndex;
  32670. }
  32671. idxOffset += 3;
  32672. }
  32673. if (isLarge) {
  32674. data.setLayout({
  32675. largePoints: largePoints,
  32676. largeDataIndices: largeDataIndices,
  32677. largeBackgroundPoints: largeBackgroundPoints,
  32678. valueAxisHorizontal: isValueAxisH
  32679. });
  32680. }
  32681. }
  32682. };
  32683. }
  32684. };
  32685. }
  32686. function isOnCartesian(seriesModel) {
  32687. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  32688. }
  32689. function isInLargeMode(seriesModel) {
  32690. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  32691. }
  32692. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  32693. function getValueAxisStart(baseAxis, valueAxis) {
  32694. var startValue = valueAxis.model.get('startValue');
  32695. if (!startValue) {
  32696. startValue = 0;
  32697. }
  32698. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? startValue > 0 ? startValue : 1 : startValue));
  32699. }
  32700. // FIXME 公用?
  32701. var bisect = function (a, x, lo, hi) {
  32702. while (lo < hi) {
  32703. var mid = lo + hi >>> 1;
  32704. if (a[mid][1] < x) {
  32705. lo = mid + 1;
  32706. } else {
  32707. hi = mid;
  32708. }
  32709. }
  32710. return lo;
  32711. };
  32712. var TimeScale = /** @class */function (_super) {
  32713. __extends(TimeScale, _super);
  32714. function TimeScale(settings) {
  32715. var _this = _super.call(this, settings) || this;
  32716. _this.type = 'time';
  32717. return _this;
  32718. }
  32719. /**
  32720. * Get label is mainly for other components like dataZoom, tooltip.
  32721. */
  32722. TimeScale.prototype.getLabel = function (tick) {
  32723. var useUTC = this.getSetting('useUTC');
  32724. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  32725. };
  32726. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  32727. var isUTC = this.getSetting('useUTC');
  32728. var lang = this.getSetting('locale');
  32729. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  32730. };
  32731. /**
  32732. * @override
  32733. */
  32734. TimeScale.prototype.getTicks = function (opt) {
  32735. opt = opt || {};
  32736. var interval = this._interval;
  32737. var extent = this._extent;
  32738. var scaleBreakHelper = getScaleBreakHelper();
  32739. var ticks = [];
  32740. // If interval is 0, return [];
  32741. if (!interval) {
  32742. return ticks;
  32743. }
  32744. var useUTC = this.getSetting('useUTC');
  32745. if (scaleBreakHelper && opt.breakTicks === 'only_break') {
  32746. getScaleBreakHelper().addBreaksToTicks(ticks, this._brkCtx.breaks, this._extent);
  32747. return ticks;
  32748. }
  32749. var extent0Unit = getUnitFromValue(extent[1], useUTC);
  32750. ticks.push({
  32751. value: extent[0],
  32752. time: {
  32753. level: 0,
  32754. upperTimeUnit: extent0Unit,
  32755. lowerTimeUnit: extent0Unit
  32756. }
  32757. });
  32758. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent, this._getExtentSpanWithBreaks(), this._brkCtx);
  32759. ticks = ticks.concat(innerTicks);
  32760. var extent1Unit = getUnitFromValue(extent[1], useUTC);
  32761. ticks.push({
  32762. value: extent[1],
  32763. time: {
  32764. level: 0,
  32765. upperTimeUnit: extent1Unit,
  32766. lowerTimeUnit: extent1Unit
  32767. }
  32768. });
  32769. var isUTC = this.getSetting('useUTC');
  32770. var upperUnitIndex = primaryTimeUnits.length - 1;
  32771. var maxLevel = 0;
  32772. each(ticks, function (tick) {
  32773. upperUnitIndex = Math.min(upperUnitIndex, indexOf(primaryTimeUnits, tick.time.upperTimeUnit));
  32774. maxLevel = Math.max(maxLevel, tick.time.level);
  32775. });
  32776. if (scaleBreakHelper) {
  32777. getScaleBreakHelper().pruneTicksByBreak(opt.pruneByBreak, ticks, this._brkCtx.breaks, function (item) {
  32778. return item.value;
  32779. }, this._approxInterval, this._extent);
  32780. }
  32781. if (scaleBreakHelper && opt.breakTicks !== 'none') {
  32782. getScaleBreakHelper().addBreaksToTicks(ticks, this._brkCtx.breaks, this._extent, function (trimmedBrk) {
  32783. // @see `parseTimeAxisLabelFormatterDictionary`.
  32784. var lowerBrkUnitIndex = Math.max(indexOf(primaryTimeUnits, getUnitFromValue(trimmedBrk.vmin, isUTC)), indexOf(primaryTimeUnits, getUnitFromValue(trimmedBrk.vmax, isUTC)));
  32785. var upperBrkUnitIndex = 0;
  32786. for (var unitIdx = 0; unitIdx < primaryTimeUnits.length; unitIdx++) {
  32787. if (!isPrimaryUnitValueAndGreaterSame(primaryTimeUnits[unitIdx], trimmedBrk.vmin, trimmedBrk.vmax, isUTC)) {
  32788. upperBrkUnitIndex = unitIdx;
  32789. break;
  32790. }
  32791. }
  32792. var upperIdx = Math.min(upperBrkUnitIndex, upperUnitIndex);
  32793. var lowerIdx = Math.max(upperIdx, lowerBrkUnitIndex);
  32794. return {
  32795. level: maxLevel,
  32796. lowerTimeUnit: primaryTimeUnits[lowerIdx],
  32797. upperTimeUnit: primaryTimeUnits[upperIdx]
  32798. };
  32799. });
  32800. }
  32801. return ticks;
  32802. };
  32803. TimeScale.prototype.calcNiceExtent = function (opt) {
  32804. var extent = this.getExtent();
  32805. // If extent start and end are same, expand them
  32806. if (extent[0] === extent[1]) {
  32807. // Expand extent
  32808. extent[0] -= ONE_DAY;
  32809. extent[1] += ONE_DAY;
  32810. }
  32811. // If there are no data and extent are [Infinity, -Infinity]
  32812. if (extent[1] === -Infinity && extent[0] === Infinity) {
  32813. var d = new Date();
  32814. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  32815. extent[0] = extent[1] - ONE_DAY;
  32816. }
  32817. this._innerSetExtent(extent[0], extent[1]);
  32818. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  32819. };
  32820. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  32821. approxTickNum = approxTickNum || 10;
  32822. var span = this._getExtentSpanWithBreaks();
  32823. this._approxInterval = span / approxTickNum;
  32824. if (minInterval != null && this._approxInterval < minInterval) {
  32825. this._approxInterval = minInterval;
  32826. }
  32827. if (maxInterval != null && this._approxInterval > maxInterval) {
  32828. this._approxInterval = maxInterval;
  32829. }
  32830. var scaleIntervalsLen = scaleIntervals.length;
  32831. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1);
  32832. // Interval that can be used to calculate ticks
  32833. this._interval = scaleIntervals[idx][1];
  32834. this._intervalPrecision = getIntervalPrecision(this._interval);
  32835. // Min level used when picking ticks from top down.
  32836. // We check one more level to avoid the ticks are to sparse in some case.
  32837. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  32838. };
  32839. TimeScale.prototype.parse = function (val) {
  32840. // val might be float.
  32841. return isNumber(val) ? val : +parseDate(val);
  32842. };
  32843. TimeScale.prototype.contain = function (val) {
  32844. return contain$1(val, this._extent);
  32845. };
  32846. TimeScale.prototype.normalize = function (val) {
  32847. return this._calculator.normalize(val, this._extent);
  32848. };
  32849. TimeScale.prototype.scale = function (val) {
  32850. return this._calculator.scale(val, this._extent);
  32851. };
  32852. TimeScale.type = 'time';
  32853. return TimeScale;
  32854. }(IntervalScale);
  32855. /**
  32856. * This implementation was originally copied from "d3.js"
  32857. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  32858. * with some modifications made for this program.
  32859. * See the license statement at the head of this file.
  32860. */
  32861. var scaleIntervals = [
  32862. // Format interval
  32863. ['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
  32864. ];
  32865. function isPrimaryUnitValueAndGreaterSame(unit, valueA, valueB, isUTC) {
  32866. return roundTime(new Date(valueA), unit, isUTC).getTime() === roundTime(new Date(valueB), unit, isUTC).getTime();
  32867. }
  32868. // function isUnitValueSame(
  32869. // unit: PrimaryTimeUnit,
  32870. // valueA: number,
  32871. // valueB: number,
  32872. // isUTC: boolean
  32873. // ): boolean {
  32874. // const dateA = numberUtil.parseDate(valueA) as any;
  32875. // const dateB = numberUtil.parseDate(valueB) as any;
  32876. // const isSame = (unit: PrimaryTimeUnit) => {
  32877. // return getUnitValue(dateA, unit, isUTC)
  32878. // === getUnitValue(dateB, unit, isUTC);
  32879. // };
  32880. // const isSameYear = () => isSame('year');
  32881. // // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  32882. // // const isSameQuater = () => isSameYear() && isSame('quarter');
  32883. // const isSameMonth = () => isSameYear() && isSame('month');
  32884. // const isSameDay = () => isSameMonth() && isSame('day');
  32885. // // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  32886. // const isSameHour = () => isSameDay() && isSame('hour');
  32887. // const isSameMinute = () => isSameHour() && isSame('minute');
  32888. // const isSameSecond = () => isSameMinute() && isSame('second');
  32889. // const isSameMilliSecond = () => isSameSecond() && isSame('millisecond');
  32890. // switch (unit) {
  32891. // case 'year':
  32892. // return isSameYear();
  32893. // case 'month':
  32894. // return isSameMonth();
  32895. // case 'day':
  32896. // return isSameDay();
  32897. // case 'hour':
  32898. // return isSameHour();
  32899. // case 'minute':
  32900. // return isSameMinute();
  32901. // case 'second':
  32902. // return isSameSecond();
  32903. // case 'millisecond':
  32904. // return isSameMilliSecond();
  32905. // }
  32906. // }
  32907. // const primaryUnitGetters = {
  32908. // year: fullYearGetterName(),
  32909. // month: monthGetterName(),
  32910. // day: dateGetterName(),
  32911. // hour: hoursGetterName(),
  32912. // minute: minutesGetterName(),
  32913. // second: secondsGetterName(),
  32914. // millisecond: millisecondsGetterName()
  32915. // };
  32916. // const primaryUnitUTCGetters = {
  32917. // year: fullYearGetterName(true),
  32918. // month: monthGetterName(true),
  32919. // day: dateGetterName(true),
  32920. // hour: hoursGetterName(true),
  32921. // minute: minutesGetterName(true),
  32922. // second: secondsGetterName(true),
  32923. // millisecond: millisecondsGetterName(true)
  32924. // };
  32925. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  32926. // step = step || 1;
  32927. // switch (getPrimaryTimeUnit(unitName)) {
  32928. // case 'year':
  32929. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  32930. // break;
  32931. // case 'month':
  32932. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  32933. // break;
  32934. // case 'day':
  32935. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  32936. // break;
  32937. // case 'hour':
  32938. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  32939. // break;
  32940. // case 'minute':
  32941. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  32942. // break;
  32943. // case 'second':
  32944. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  32945. // break;
  32946. // case 'millisecond':
  32947. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  32948. // break;
  32949. // }
  32950. // return date.getTime();
  32951. // }
  32952. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  32953. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  32954. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  32955. function getDateInterval(approxInterval, daysInMonth) {
  32956. approxInterval /= ONE_DAY;
  32957. return approxInterval > 16 ? 16
  32958. // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  32959. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  32960. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  32961. }
  32962. function getMonthInterval(approxInterval) {
  32963. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  32964. approxInterval /= APPROX_ONE_MONTH;
  32965. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  32966. }
  32967. function getHourInterval(approxInterval) {
  32968. approxInterval /= ONE_HOUR;
  32969. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  32970. }
  32971. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  32972. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  32973. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  32974. }
  32975. function getMillisecondsInterval(approxInterval) {
  32976. return nice(approxInterval, true);
  32977. }
  32978. // e.g., if the input unit is 'day', start calculate ticks from the first day of
  32979. // that month to make ticks "nice".
  32980. function getFirstTimestampOfUnit(timestamp, unitName, isUTC) {
  32981. var upperUnitIdx = Math.max(0, indexOf(primaryTimeUnits, unitName) - 1);
  32982. return roundTime(new Date(timestamp), primaryTimeUnits[upperUnitIdx], isUTC).getTime();
  32983. }
  32984. function createEstimateNiceMultiple(setMethodName, dateMethodInterval) {
  32985. var tmpDate = new Date(0);
  32986. tmpDate[setMethodName](1);
  32987. var tmpTime = tmpDate.getTime();
  32988. tmpDate[setMethodName](1 + dateMethodInterval);
  32989. var approxTimeInterval = tmpDate.getTime() - tmpTime;
  32990. return function (tickVal, targetValue) {
  32991. // Only in month that accurate result can not get by division of
  32992. // timestamp interval, but no need accurate here.
  32993. return Math.max(0, Math.round((targetValue - tickVal) / approxTimeInterval));
  32994. };
  32995. }
  32996. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent, extentSpanWithBreaks, brkCtx) {
  32997. var safeLimit = 10000;
  32998. var unitNames = timeUnits;
  32999. var iter = 0;
  33000. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  33001. var estimateNiceMultiple = createEstimateNiceMultiple(setMethodName, interval);
  33002. var dateTime = minTimestamp;
  33003. var date = new Date(dateTime);
  33004. // if (isDate) {
  33005. // d -= 1; // Starts with 0; PENDING
  33006. // }
  33007. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  33008. out.push({
  33009. value: dateTime
  33010. });
  33011. if (iter++ > safeLimit) {
  33012. if ("development" !== 'production') {
  33013. warn('Exceed safe limit in time scale.');
  33014. }
  33015. break;
  33016. }
  33017. date[setMethodName](date[getMethodName]() + interval);
  33018. dateTime = date.getTime();
  33019. if (brkCtx) {
  33020. var moreMultiple = brkCtx.calcNiceTickMultiple(dateTime, estimateNiceMultiple);
  33021. if (moreMultiple > 0) {
  33022. date[setMethodName](date[getMethodName]() + moreMultiple * interval);
  33023. dateTime = date.getTime();
  33024. }
  33025. }
  33026. }
  33027. // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  33028. out.push({
  33029. value: dateTime,
  33030. notAdd: true
  33031. });
  33032. }
  33033. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  33034. var newAddedTicks = [];
  33035. var isFirstLevel = !lastLevelTicks.length;
  33036. if (isPrimaryUnitValueAndGreaterSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  33037. return;
  33038. }
  33039. if (isFirstLevel) {
  33040. lastLevelTicks = [{
  33041. value: getFirstTimestampOfUnit(extent[0], unitName, isUTC)
  33042. }, {
  33043. value: extent[1]
  33044. }];
  33045. }
  33046. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  33047. var startTick = lastLevelTicks[i].value;
  33048. var endTick = lastLevelTicks[i + 1].value;
  33049. if (startTick === endTick) {
  33050. continue;
  33051. }
  33052. var interval = void 0;
  33053. var getterName = void 0;
  33054. var setterName = void 0;
  33055. var isDate = false;
  33056. switch (unitName) {
  33057. case 'year':
  33058. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  33059. getterName = fullYearGetterName(isUTC);
  33060. setterName = fullYearSetterName(isUTC);
  33061. break;
  33062. case 'half-year':
  33063. case 'quarter':
  33064. case 'month':
  33065. interval = getMonthInterval(approxInterval);
  33066. getterName = monthGetterName(isUTC);
  33067. setterName = monthSetterName(isUTC);
  33068. break;
  33069. case 'week': // PENDING If week is added. Ignore day.
  33070. case 'half-week':
  33071. case 'day':
  33072. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  33073. getterName = dateGetterName(isUTC);
  33074. setterName = dateSetterName(isUTC);
  33075. isDate = true;
  33076. break;
  33077. case 'half-day':
  33078. case 'quarter-day':
  33079. case 'hour':
  33080. interval = getHourInterval(approxInterval);
  33081. getterName = hoursGetterName(isUTC);
  33082. setterName = hoursSetterName(isUTC);
  33083. break;
  33084. case 'minute':
  33085. interval = getMinutesAndSecondsInterval(approxInterval, true);
  33086. getterName = minutesGetterName(isUTC);
  33087. setterName = minutesSetterName(isUTC);
  33088. break;
  33089. case 'second':
  33090. interval = getMinutesAndSecondsInterval(approxInterval, false);
  33091. getterName = secondsGetterName(isUTC);
  33092. setterName = secondsSetterName(isUTC);
  33093. break;
  33094. case 'millisecond':
  33095. interval = getMillisecondsInterval(approxInterval);
  33096. getterName = millisecondsGetterName(isUTC);
  33097. setterName = millisecondsSetterName(isUTC);
  33098. break;
  33099. }
  33100. // Notice: This expansion by `getFirstTimestampOfUnit` may cause too many ticks and
  33101. // iteration. e.g., when three levels of ticks is displayed, which can be caused by
  33102. // data zoom and axis breaks. Thus trim them here.
  33103. if (endTick >= extent[0] && startTick <= extent[1]) {
  33104. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  33105. }
  33106. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  33107. // Add nearest years to the left extent.
  33108. levelTicks.unshift({
  33109. value: levelTicks[0].value - interval
  33110. });
  33111. }
  33112. }
  33113. for (var i = 0; i < newAddedTicks.length; i++) {
  33114. levelTicks.push(newAddedTicks[i]);
  33115. }
  33116. }
  33117. var levelsTicks = [];
  33118. var currentLevelTicks = [];
  33119. var tickCount = 0;
  33120. var lastLevelTickCount = 0;
  33121. for (var i = 0; i < unitNames.length; ++i) {
  33122. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  33123. if (!isPrimaryTimeUnit(unitNames[i])) {
  33124. // TODO
  33125. continue;
  33126. }
  33127. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  33128. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  33129. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  33130. if (currentLevelTicks.length) {
  33131. lastLevelTickCount = tickCount;
  33132. // Remove the duplicate so the tick count can be precisely.
  33133. currentLevelTicks.sort(function (a, b) {
  33134. return a.value - b.value;
  33135. });
  33136. var levelTicksRemoveDuplicated = [];
  33137. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  33138. var tickValue = currentLevelTicks[i_1].value;
  33139. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  33140. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  33141. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  33142. tickCount++;
  33143. }
  33144. }
  33145. }
  33146. var targetTickNum = extentSpanWithBreaks / approxInterval;
  33147. // Added too much in this level and not too less in last level
  33148. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  33149. break;
  33150. }
  33151. // Only treat primary time unit as one level.
  33152. levelsTicks.push(levelTicksRemoveDuplicated);
  33153. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  33154. break;
  33155. }
  33156. }
  33157. // Reset if next unitName is primary
  33158. currentLevelTicks = [];
  33159. }
  33160. }
  33161. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  33162. return filter(levelTicks, function (tick) {
  33163. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  33164. });
  33165. }), function (levelTicks) {
  33166. return levelTicks.length > 0;
  33167. });
  33168. var ticks = [];
  33169. var maxLevel = levelsTicksInExtent.length - 1;
  33170. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  33171. var levelTicks = levelsTicksInExtent[i];
  33172. for (var k = 0; k < levelTicks.length; ++k) {
  33173. var unit = getUnitFromValue(levelTicks[k].value, isUTC);
  33174. ticks.push({
  33175. value: levelTicks[k].value,
  33176. time: {
  33177. level: maxLevel - i,
  33178. upperTimeUnit: unit,
  33179. lowerTimeUnit: unit
  33180. }
  33181. });
  33182. }
  33183. }
  33184. ticks.sort(function (a, b) {
  33185. return a.value - b.value;
  33186. });
  33187. // Remove duplicates
  33188. var result = [];
  33189. for (var i = 0; i < ticks.length; ++i) {
  33190. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  33191. result.push(ticks[i]);
  33192. }
  33193. }
  33194. return result;
  33195. }
  33196. Scale.registerClass(TimeScale);
  33197. var fixRound = round;
  33198. var mathFloor = Math.floor;
  33199. var mathCeil = Math.ceil;
  33200. var mathPow$1 = Math.pow;
  33201. var mathLog = Math.log;
  33202. var LogScale = /** @class */function (_super) {
  33203. __extends(LogScale, _super);
  33204. function LogScale() {
  33205. var _this = _super !== null && _super.apply(this, arguments) || this;
  33206. _this.type = 'log';
  33207. _this.base = 10;
  33208. _this._originalScale = new IntervalScale();
  33209. return _this;
  33210. }
  33211. /**
  33212. * @param Whether expand the ticks to niced extent.
  33213. */
  33214. LogScale.prototype.getTicks = function (opt) {
  33215. opt = opt || {};
  33216. var extent = this._extent.slice();
  33217. var originalExtent = this._originalScale.getExtent();
  33218. var ticks = _super.prototype.getTicks.call(this, opt);
  33219. var base = this.base;
  33220. var originalBreaks = this._originalScale._innerGetBreaks();
  33221. var scaleBreakHelper = getScaleBreakHelper();
  33222. return map(ticks, function (tick) {
  33223. var val = tick.value;
  33224. var roundingCriterion = null;
  33225. var powVal = mathPow$1(base, val);
  33226. // Fix #4158
  33227. if (val === extent[0] && this._fixMin) {
  33228. roundingCriterion = originalExtent[0];
  33229. } else if (val === extent[1] && this._fixMax) {
  33230. roundingCriterion = originalExtent[1];
  33231. }
  33232. var vBreak;
  33233. if (scaleBreakHelper) {
  33234. var transformed = scaleBreakHelper.getTicksLogTransformBreak(tick, base, originalBreaks, fixRoundingError);
  33235. vBreak = transformed.vBreak;
  33236. if (roundingCriterion == null) {
  33237. roundingCriterion = transformed.brkRoundingCriterion;
  33238. }
  33239. }
  33240. if (roundingCriterion != null) {
  33241. powVal = fixRoundingError(powVal, roundingCriterion);
  33242. }
  33243. return {
  33244. value: powVal,
  33245. "break": vBreak
  33246. };
  33247. }, this);
  33248. };
  33249. LogScale.prototype._getNonTransBreaks = function () {
  33250. return this._originalScale._innerGetBreaks();
  33251. };
  33252. LogScale.prototype.setExtent = function (start, end) {
  33253. this._originalScale.setExtent(start, end);
  33254. var loggedExtent = logTransform(this.base, [start, end]);
  33255. _super.prototype.setExtent.call(this, loggedExtent[0], loggedExtent[1]);
  33256. };
  33257. /**
  33258. * @return {number} end
  33259. */
  33260. LogScale.prototype.getExtent = function () {
  33261. var base = this.base;
  33262. var extent = _super.prototype.getExtent.call(this);
  33263. extent[0] = mathPow$1(base, extent[0]);
  33264. extent[1] = mathPow$1(base, extent[1]);
  33265. // Fix #4158
  33266. var originalExtent = this._originalScale.getExtent();
  33267. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  33268. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  33269. return extent;
  33270. };
  33271. LogScale.prototype.unionExtentFromData = function (data, dim) {
  33272. this._originalScale.unionExtentFromData(data, dim);
  33273. var loggedOther = logTransform(this.base, data.getApproximateExtent(dim), true);
  33274. this._innerUnionExtent(loggedOther);
  33275. };
  33276. /**
  33277. * Update interval and extent of intervals for nice ticks
  33278. * @param approxTickNum default 10 Given approx tick number
  33279. */
  33280. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  33281. approxTickNum = approxTickNum || 10;
  33282. var extent = this._extent.slice();
  33283. var span = this._getExtentSpanWithBreaks();
  33284. if (!isFinite(span) || span <= 0) {
  33285. return;
  33286. }
  33287. var interval = quantity(span);
  33288. var err = approxTickNum / span * interval;
  33289. // Filter ticks to get closer to the desired count.
  33290. if (err <= 0.5) {
  33291. interval *= 10;
  33292. }
  33293. // Interval should be integer
  33294. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  33295. interval *= 10;
  33296. }
  33297. var niceExtent = [fixRound(mathCeil(extent[0] / interval) * interval), fixRound(mathFloor(extent[1] / interval) * interval)];
  33298. this._interval = interval;
  33299. this._intervalPrecision = getIntervalPrecision(interval);
  33300. this._niceExtent = niceExtent;
  33301. };
  33302. LogScale.prototype.calcNiceExtent = function (opt) {
  33303. _super.prototype.calcNiceExtent.call(this, opt);
  33304. this._fixMin = opt.fixMin;
  33305. this._fixMax = opt.fixMax;
  33306. };
  33307. LogScale.prototype.contain = function (val) {
  33308. val = mathLog(val) / mathLog(this.base);
  33309. return _super.prototype.contain.call(this, val);
  33310. };
  33311. LogScale.prototype.normalize = function (val) {
  33312. val = mathLog(val) / mathLog(this.base);
  33313. return _super.prototype.normalize.call(this, val);
  33314. };
  33315. LogScale.prototype.scale = function (val) {
  33316. val = _super.prototype.scale.call(this, val);
  33317. return mathPow$1(this.base, val);
  33318. };
  33319. LogScale.prototype.setBreaksFromOption = function (breakOptionList) {
  33320. var scaleBreakHelper = getScaleBreakHelper();
  33321. if (!scaleBreakHelper) {
  33322. return;
  33323. }
  33324. var _a = scaleBreakHelper.logarithmicParseBreaksFromOption(breakOptionList, this.base, bind(this.parse, this)),
  33325. parsedOriginal = _a.parsedOriginal,
  33326. parsedLogged = _a.parsedLogged;
  33327. this._originalScale._innerSetBreak(parsedOriginal);
  33328. this._innerSetBreak(parsedLogged);
  33329. };
  33330. LogScale.type = 'log';
  33331. return LogScale;
  33332. }(IntervalScale);
  33333. function fixRoundingError(val, originalVal) {
  33334. return fixRound(val, getPrecision(originalVal));
  33335. }
  33336. Scale.registerClass(LogScale);
  33337. var ScaleRawExtentInfo = /** @class */function () {
  33338. function ScaleRawExtentInfo(scale, model,
  33339. // Usually: data extent from all series on this axis.
  33340. originalExtent) {
  33341. this._prepareParams(scale, model, originalExtent);
  33342. }
  33343. /**
  33344. * Parameters depending on outside (like model, user callback)
  33345. * are prepared and fixed here.
  33346. */
  33347. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model,
  33348. // Usually: data extent from all series on this axis.
  33349. dataExtent) {
  33350. if (dataExtent[1] < dataExtent[0]) {
  33351. dataExtent = [NaN, NaN];
  33352. }
  33353. this._dataMin = dataExtent[0];
  33354. this._dataMax = dataExtent[1];
  33355. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  33356. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  33357. var axisMinValue = model.get('min', true);
  33358. if (axisMinValue == null) {
  33359. axisMinValue = model.get('startValue', true);
  33360. }
  33361. var modelMinRaw = this._modelMinRaw = axisMinValue;
  33362. if (isFunction(modelMinRaw)) {
  33363. // This callback always provides users the full data extent (before data is filtered).
  33364. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  33365. min: dataExtent[0],
  33366. max: dataExtent[1]
  33367. }));
  33368. } else if (modelMinRaw !== 'dataMin') {
  33369. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  33370. }
  33371. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  33372. if (isFunction(modelMaxRaw)) {
  33373. // This callback always provides users the full data extent (before data is filtered).
  33374. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  33375. min: dataExtent[0],
  33376. max: dataExtent[1]
  33377. }));
  33378. } else if (modelMaxRaw !== 'dataMax') {
  33379. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  33380. }
  33381. if (isOrdinal) {
  33382. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  33383. // and progressive rendering is using, here the category result might just only contain
  33384. // the processed chunk rather than the entire result.
  33385. this._axisDataLen = model.getCategories().length;
  33386. } else {
  33387. var boundaryGap = model.get('boundaryGap');
  33388. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  33389. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  33390. if ("development" !== 'production') {
  33391. 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.');
  33392. }
  33393. this._boundaryGapInner = [0, 0];
  33394. } else {
  33395. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  33396. }
  33397. }
  33398. };
  33399. /**
  33400. * Calculate extent by prepared parameters.
  33401. * This method has no external dependency and can be called duplicatedly,
  33402. * getting the same result.
  33403. * If parameters changed, should call this method to recalcuate.
  33404. */
  33405. ScaleRawExtentInfo.prototype.calculate = function () {
  33406. // Notice: When min/max is not set (that is, when there are null/undefined,
  33407. // which is the most common case), these cases should be ensured:
  33408. // (1) For 'ordinal', show all axis.data.
  33409. // (2) For others:
  33410. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  33411. // disabled).
  33412. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  33413. // be the result that originalExtent enlarged by boundaryGap.
  33414. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  33415. var isOrdinal = this._isOrdinal;
  33416. var dataMin = this._dataMin;
  33417. var dataMax = this._dataMax;
  33418. var axisDataLen = this._axisDataLen;
  33419. var boundaryGapInner = this._boundaryGapInner;
  33420. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null;
  33421. // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  33422. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  33423. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  33424. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum;
  33425. // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  33426. var minFixed = min != null;
  33427. var maxFixed = max != null;
  33428. if (min == null) {
  33429. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  33430. }
  33431. if (max == null) {
  33432. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  33433. }
  33434. (min == null || !isFinite(min)) && (min = NaN);
  33435. (max == null || !isFinite(max)) && (max = NaN);
  33436. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen;
  33437. // If data extent modified, need to recalculated to ensure cross zero.
  33438. if (this._needCrossZero) {
  33439. // Axis is over zero and min is not set
  33440. if (min > 0 && max > 0 && !minFixed) {
  33441. min = 0;
  33442. // minFixed = true;
  33443. }
  33444. // Axis is under zero and max is not set
  33445. if (min < 0 && max < 0 && !maxFixed) {
  33446. max = 0;
  33447. // maxFixed = true;
  33448. }
  33449. // PENDING:
  33450. // When `needCrossZero` and all data is positive/negative, should it be ensured
  33451. // that the results processed by boundaryGap are positive/negative?
  33452. // If so, here `minFixed`/`maxFixed` need to be set.
  33453. }
  33454. var determinedMin = this._determinedMin;
  33455. var determinedMax = this._determinedMax;
  33456. if (determinedMin != null) {
  33457. min = determinedMin;
  33458. minFixed = true;
  33459. }
  33460. if (determinedMax != null) {
  33461. max = determinedMax;
  33462. maxFixed = true;
  33463. }
  33464. // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  33465. // `NaN` means min/max axis is blank.
  33466. return {
  33467. min: min,
  33468. max: max,
  33469. minFixed: minFixed,
  33470. maxFixed: maxFixed,
  33471. isBlank: isBlank
  33472. };
  33473. };
  33474. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  33475. if ("development" !== 'production') {
  33476. assert(!this.frozen);
  33477. }
  33478. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  33479. };
  33480. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  33481. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  33482. if ("development" !== 'production') {
  33483. assert(!this.frozen
  33484. // Earse them usually means logic flaw.
  33485. && this[attr] == null);
  33486. }
  33487. this[attr] = val;
  33488. };
  33489. ScaleRawExtentInfo.prototype.freeze = function () {
  33490. // @ts-ignore
  33491. this.frozen = true;
  33492. };
  33493. return ScaleRawExtentInfo;
  33494. }();
  33495. var DETERMINED_MIN_MAX_ATTR = {
  33496. min: '_determinedMin',
  33497. max: '_determinedMax'
  33498. };
  33499. var DATA_MIN_MAX_ATTR = {
  33500. min: '_dataMin',
  33501. max: '_dataMax'
  33502. };
  33503. /**
  33504. * Get scale min max and related info only depends on model settings.
  33505. * This method can be called after coordinate system created.
  33506. * For example, in data processing stage.
  33507. *
  33508. * Scale extent info probably be required multiple times during a workflow.
  33509. * For example:
  33510. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  33511. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  33512. * (3) `coordSys.update` use it to finally decide the scale extent.
  33513. * But the callback of `min`/`max` should not be called multiple times.
  33514. * The code below should not be implemented repeatedly either.
  33515. * So we cache the result in the scale instance, which will be recreated at the beginning
  33516. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  33517. */
  33518. function ensureScaleRawExtentInfo(scale, model,
  33519. // Usually: data extent from all series on this axis.
  33520. originalExtent) {
  33521. // Do not permit to recreate.
  33522. var rawExtentInfo = scale.rawExtentInfo;
  33523. if (rawExtentInfo) {
  33524. return rawExtentInfo;
  33525. }
  33526. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent);
  33527. // @ts-ignore
  33528. scale.rawExtentInfo = rawExtentInfo;
  33529. return rawExtentInfo;
  33530. }
  33531. function parseAxisModelMinMax(scale, minMax) {
  33532. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  33533. }
  33534. /**
  33535. * Get axis scale extent before niced.
  33536. * Item of returned array can only be number (including Infinity and NaN).
  33537. *
  33538. * Caution:
  33539. * Precondition of calling this method:
  33540. * The scale extent has been initialized using series data extent via
  33541. * `scale.setExtent` or `scale.unionExtentFromData`;
  33542. */
  33543. function getScaleExtent(scale, model) {
  33544. var scaleType = scale.type;
  33545. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  33546. scale.setBlank(rawExtentResult.isBlank);
  33547. var min = rawExtentResult.min;
  33548. var max = rawExtentResult.max;
  33549. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  33550. // is base axis
  33551. // FIXME
  33552. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  33553. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  33554. // Should not depend on series type `bar`?
  33555. // (3) Fix that might overlap when using dataZoom.
  33556. // (4) Consider other chart types using `barGrid`?
  33557. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  33558. var ecModel = model.ecModel;
  33559. if (ecModel && scaleType === 'time' /* || scaleType === 'interval' */) {
  33560. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  33561. var isBaseAxisAndHasBarSeries_1 = false;
  33562. each(barSeriesModels, function (seriesModel) {
  33563. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  33564. });
  33565. if (isBaseAxisAndHasBarSeries_1) {
  33566. // Calculate placement of bars on axis. TODO should be decoupled
  33567. // with barLayout
  33568. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  33569. // Adjust axis min and max to account for overflow
  33570. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  33571. min = adjustedScale.min;
  33572. max = adjustedScale.max;
  33573. }
  33574. }
  33575. return {
  33576. extent: [min, max],
  33577. // "fix" means "fixed", the value should not be
  33578. // changed in the subsequent steps.
  33579. fixMin: rawExtentResult.minFixed,
  33580. fixMax: rawExtentResult.maxFixed
  33581. };
  33582. }
  33583. function adjustScaleForOverflow(min, max, model,
  33584. // Only support cartesian coord yet.
  33585. barWidthAndOffset) {
  33586. // Get Axis Length
  33587. var axisExtent = model.axis.getExtent();
  33588. var axisLength = Math.abs(axisExtent[1] - axisExtent[0]);
  33589. // Get bars on current base axis and calculate min and max overflow
  33590. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  33591. if (barsOnCurrentAxis === undefined) {
  33592. return {
  33593. min: min,
  33594. max: max
  33595. };
  33596. }
  33597. var minOverflow = Infinity;
  33598. each(barsOnCurrentAxis, function (item) {
  33599. minOverflow = Math.min(item.offset, minOverflow);
  33600. });
  33601. var maxOverflow = -Infinity;
  33602. each(barsOnCurrentAxis, function (item) {
  33603. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  33604. });
  33605. minOverflow = Math.abs(minOverflow);
  33606. maxOverflow = Math.abs(maxOverflow);
  33607. var totalOverFlow = minOverflow + maxOverflow;
  33608. // Calculate required buffer based on old range and overflow
  33609. var oldRange = max - min;
  33610. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  33611. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  33612. max += overflowBuffer * (maxOverflow / totalOverFlow);
  33613. min -= overflowBuffer * (minOverflow / totalOverFlow);
  33614. return {
  33615. min: min,
  33616. max: max
  33617. };
  33618. }
  33619. // Precondition of calling this method:
  33620. // The scale extent has been initialized using series data extent via
  33621. // `scale.setExtent` or `scale.unionExtentFromData`;
  33622. function niceScaleExtent(scale, inModel) {
  33623. var model = inModel;
  33624. var extentInfo = getScaleExtent(scale, model);
  33625. var extent = extentInfo.extent;
  33626. var splitNumber = model.get('splitNumber');
  33627. if (scale instanceof LogScale) {
  33628. scale.base = model.get('logBase');
  33629. }
  33630. var scaleType = scale.type;
  33631. var interval = model.get('interval');
  33632. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  33633. scale.setBreaksFromOption(retrieveAxisBreaksOption(model));
  33634. scale.setExtent(extent[0], extent[1]);
  33635. scale.calcNiceExtent({
  33636. splitNumber: splitNumber,
  33637. fixMin: extentInfo.fixMin,
  33638. fixMax: extentInfo.fixMax,
  33639. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  33640. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  33641. });
  33642. // If some one specified the min, max. And the default calculated interval
  33643. // is not good enough. He can specify the interval. It is often appeared
  33644. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  33645. // to be 60.
  33646. // FIXME
  33647. if (interval != null) {
  33648. scale.setInterval && scale.setInterval(interval);
  33649. }
  33650. }
  33651. /**
  33652. * @param axisType Default retrieve from model.type
  33653. */
  33654. function createScaleByModel(model, axisType) {
  33655. axisType = axisType || model.get('type');
  33656. if (axisType) {
  33657. switch (axisType) {
  33658. // Buildin scale
  33659. case 'category':
  33660. return new OrdinalScale({
  33661. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  33662. extent: [Infinity, -Infinity]
  33663. });
  33664. case 'time':
  33665. return new TimeScale({
  33666. locale: model.ecModel.getLocaleModel(),
  33667. useUTC: model.ecModel.get('useUTC')
  33668. });
  33669. default:
  33670. // case 'value'/'interval', 'log', or others.
  33671. return new (Scale.getClass(axisType) || IntervalScale)();
  33672. }
  33673. }
  33674. }
  33675. /**
  33676. * Check if the axis cross 0
  33677. */
  33678. function ifAxisCrossZero(axis) {
  33679. var dataExtent = axis.scale.getExtent();
  33680. var min = dataExtent[0];
  33681. var max = dataExtent[1];
  33682. return !(min > 0 && max > 0 || min < 0 && max < 0);
  33683. }
  33684. /**
  33685. * @param axis
  33686. * @return Label formatter function.
  33687. * param: {number} tickValue,
  33688. * param: {number} idx, the index in all ticks.
  33689. * If category axis, this param is not required.
  33690. * return: {string} label string.
  33691. */
  33692. function makeLabelFormatter(axis) {
  33693. var labelFormatter = axis.getLabelModel().get('formatter');
  33694. if (axis.type === 'time') {
  33695. var parsed_1 = parseTimeAxisLabelFormatter(labelFormatter);
  33696. return function (tick, idx) {
  33697. return axis.scale.getFormattedLabel(tick, idx, parsed_1);
  33698. };
  33699. } else if (isString(labelFormatter)) {
  33700. return function (tick) {
  33701. // For category axis, get raw value; for numeric axis,
  33702. // get formatted label like '1,333,444'.
  33703. var label = axis.scale.getLabel(tick);
  33704. var text = labelFormatter.replace('{value}', label != null ? label : '');
  33705. return text;
  33706. };
  33707. } else if (isFunction(labelFormatter)) {
  33708. if (axis.type === 'category') {
  33709. return function (tick, idx) {
  33710. // The original intention of `idx` is "the index of the tick in all ticks".
  33711. // But the previous implementation of category axis do not consider the
  33712. // `axisLabel.interval`, which cause that, for example, the `interval` is
  33713. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  33714. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  33715. // the definition here for back compatibility.
  33716. return labelFormatter(getAxisRawValue(axis, tick), tick.value - axis.scale.getExtent()[0], null // Using `null` just for backward compat.
  33717. );
  33718. };
  33719. }
  33720. var scaleBreakHelper_1 = getScaleBreakHelper();
  33721. return function (tick, idx) {
  33722. // Using `null` just for backward compat. It's been found that in the `test/axis-customTicks.html`,
  33723. // there is a formatter `function (value, index, revers = true) { ... }`. Although the third param
  33724. // `revers` is incorrect and always `null`, changing it might introduce a breaking change.
  33725. var extra = null;
  33726. if (scaleBreakHelper_1) {
  33727. extra = scaleBreakHelper_1.makeAxisLabelFormatterParamBreak(extra, tick["break"]);
  33728. }
  33729. return labelFormatter(getAxisRawValue(axis, tick), idx, extra);
  33730. };
  33731. } else {
  33732. return function (tick) {
  33733. return axis.scale.getLabel(tick);
  33734. };
  33735. }
  33736. }
  33737. function getAxisRawValue(axis, tick) {
  33738. // In category axis with data zoom, tick is not the original
  33739. // index of axis.data. So tick should not be exposed to user
  33740. // in category axis.
  33741. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  33742. }
  33743. /**
  33744. * @param model axisLabelModel or axisTickModel
  33745. * @return {number|String} Can be null|'auto'|number|function
  33746. */
  33747. function getOptionCategoryInterval(model) {
  33748. var interval = model.get('interval');
  33749. return interval == null ? 'auto' : interval;
  33750. }
  33751. /**
  33752. * Set `categoryInterval` as 0 implicitly indicates that
  33753. * show all labels regardless of overlap.
  33754. * @param {Object} axis axisModel.axis
  33755. */
  33756. function shouldShowAllLabels(axis) {
  33757. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  33758. }
  33759. function getDataDimensionsOnAxis(data, axisDim) {
  33760. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  33761. var dataDimMap = {};
  33762. // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  33763. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  33764. // there has been stacked result dim?
  33765. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  33766. // For example, the extent of the original dimension
  33767. // is [0.1, 0.5], the extent of the `stackResultDimension`
  33768. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  33769. // because there is no graphic corresponding to [0.1, 0.5].
  33770. // See the case in `test/area-stack.html` `main1`, where area line
  33771. // stack needs `yAxis` not start from 0.
  33772. dataDimMap[getStackedDimension(data, dataDim)] = true;
  33773. });
  33774. return keys(dataDimMap);
  33775. }
  33776. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  33777. if (data) {
  33778. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  33779. var seriesExtent = data.getApproximateExtent(dim);
  33780. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  33781. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  33782. });
  33783. }
  33784. }
  33785. function isNameLocationCenter(nameLocation) {
  33786. return nameLocation === 'middle' || nameLocation === 'center';
  33787. }
  33788. function shouldAxisShow(axisModel) {
  33789. return axisModel.getShallow('show');
  33790. }
  33791. function retrieveAxisBreaksOption(model) {
  33792. var option = model.get('breaks', true);
  33793. if (option != null) {
  33794. if (!getScaleBreakHelper()) {
  33795. if ("development" !== 'production') {
  33796. error('Must `import {AxisBreak} from "echarts/features.js"; use(AxisBreak);` first if using breaks option.');
  33797. }
  33798. return undefined;
  33799. }
  33800. if (!isSupportAxisBreak(model.axis)) {
  33801. if ("development" !== 'production') {
  33802. error("Axis '" + model.axis.dim + "'-'" + model.axis.type + "' does not support break.");
  33803. }
  33804. return undefined;
  33805. }
  33806. return option;
  33807. }
  33808. }
  33809. function isSupportAxisBreak(axis) {
  33810. // The polar radius axis can also support break feasibly. Do not do it until the requirements are met.
  33811. return (axis.dim === 'x' || axis.dim === 'y' || axis.dim === 'z' || axis.dim === 'single') && axis.type !== 'category';
  33812. }
  33813. /*
  33814. * Licensed to the Apache Software Foundation (ASF) under one
  33815. * or more contributor license agreements. See the NOTICE file
  33816. * distributed with this work for additional information
  33817. * regarding copyright ownership. The ASF licenses this file
  33818. * to you under the Apache License, Version 2.0 (the
  33819. * "License"); you may not use this file except in compliance
  33820. * with the License. You may obtain a copy of the License at
  33821. *
  33822. * http://www.apache.org/licenses/LICENSE-2.0
  33823. *
  33824. * Unless required by applicable law or agreed to in writing,
  33825. * software distributed under the License is distributed on an
  33826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33827. * KIND, either express or implied. See the License for the
  33828. * specific language governing permissions and limitations
  33829. * under the License.
  33830. */
  33831. /**
  33832. * AUTO-GENERATED FILE. DO NOT MODIFY.
  33833. */
  33834. /*
  33835. * Licensed to the Apache Software Foundation (ASF) under one
  33836. * or more contributor license agreements. See the NOTICE file
  33837. * distributed with this work for additional information
  33838. * regarding copyright ownership. The ASF licenses this file
  33839. * to you under the Apache License, Version 2.0 (the
  33840. * "License"); you may not use this file except in compliance
  33841. * with the License. You may obtain a copy of the License at
  33842. *
  33843. * http://www.apache.org/licenses/LICENSE-2.0
  33844. *
  33845. * Unless required by applicable law or agreed to in writing,
  33846. * software distributed under the License is distributed on an
  33847. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33848. * KIND, either express or implied. See the License for the
  33849. * specific language governing permissions and limitations
  33850. * under the License.
  33851. */
  33852. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  33853. var AxisModelCommonMixin = /** @class */function () {
  33854. function AxisModelCommonMixin() {}
  33855. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  33856. var option = this.option;
  33857. return !option.scale;
  33858. };
  33859. /**
  33860. * Should be implemented by each axis model if necessary.
  33861. * @return coordinate system model
  33862. */
  33863. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  33864. return;
  33865. };
  33866. return AxisModelCommonMixin;
  33867. }();
  33868. /**
  33869. * Create a multi dimension List structure from seriesModel.
  33870. */
  33871. function createList(seriesModel) {
  33872. return createSeriesData(null, seriesModel);
  33873. }
  33874. var dataStack$1 = {
  33875. isDimensionStacked: isDimensionStacked,
  33876. enableDataStack: enableDataStack,
  33877. getStackedDimension: getStackedDimension
  33878. };
  33879. /**
  33880. * Create scale
  33881. * @param {Array.<number>} dataExtent
  33882. * @param {Object|module:echarts/Model} option If `optoin.type`
  33883. * is secified, it can only be `'value'` currently.
  33884. */
  33885. function createScale(dataExtent, option) {
  33886. var axisModel = option;
  33887. if (!(option instanceof Model)) {
  33888. axisModel = new Model(option);
  33889. // FIXME
  33890. // Currently AxisModelCommonMixin has nothing to do with the
  33891. // the requirements of `axisHelper.createScaleByModel`. For
  33892. // example the methods `getCategories` and `getOrdinalMeta`
  33893. // are required for `'category'` axis, and ecModel is required
  33894. // for `'time'` axis. But occasionally echarts-gl happened
  33895. // to only use `'value'` axis.
  33896. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  33897. }
  33898. var scale = createScaleByModel(axisModel);
  33899. scale.setExtent(dataExtent[0], dataExtent[1]);
  33900. niceScaleExtent(scale, axisModel);
  33901. return scale;
  33902. }
  33903. /**
  33904. * Mixin common methods to axis model,
  33905. *
  33906. * Include methods
  33907. * `getFormattedLabels() => Array.<string>`
  33908. * `getCategories() => Array.<string>`
  33909. * `getMin(origin: boolean) => number`
  33910. * `getMax(origin: boolean) => number`
  33911. * `getNeedCrossZero() => boolean`
  33912. */
  33913. function mixinAxisModelCommonMethods(Model) {
  33914. mixin(Model, AxisModelCommonMixin);
  33915. }
  33916. function createTextStyle$1(textStyleModel, opts) {
  33917. opts = opts || {};
  33918. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  33919. }
  33920. var helper = /*#__PURE__*/Object.freeze({
  33921. __proto__: null,
  33922. createList: createList,
  33923. getLayoutRect: getLayoutRect,
  33924. dataStack: dataStack$1,
  33925. createScale: createScale,
  33926. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  33927. getECData: getECData,
  33928. createTextStyle: createTextStyle$1,
  33929. createDimensions: createDimensions,
  33930. createSymbol: createSymbol,
  33931. enableHoverEmphasis: enableHoverEmphasis
  33932. });
  33933. var EPSILON$5 = 1e-8;
  33934. function isAroundEqual$1(a, b) {
  33935. return Math.abs(a - b) < EPSILON$5;
  33936. }
  33937. function contain$2(points, x, y) {
  33938. var w = 0;
  33939. var p = points[0];
  33940. if (!p) {
  33941. return false;
  33942. }
  33943. for (var i = 1; i < points.length; i++) {
  33944. var p2 = points[i];
  33945. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  33946. p = p2;
  33947. }
  33948. var p0 = points[0];
  33949. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  33950. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  33951. }
  33952. return w !== 0;
  33953. }
  33954. var TMP_TRANSFORM = [];
  33955. function transformPoints(points, transform) {
  33956. for (var p = 0; p < points.length; p++) {
  33957. applyTransform(points[p], points[p], transform);
  33958. }
  33959. }
  33960. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  33961. for (var i = 0; i < points.length; i++) {
  33962. var p = points[i];
  33963. if (projection) {
  33964. // projection may return null point.
  33965. p = projection.project(p);
  33966. }
  33967. if (p && isFinite(p[0]) && isFinite(p[1])) {
  33968. min(min$1, min$1, p);
  33969. max(max$1, max$1, p);
  33970. }
  33971. }
  33972. }
  33973. function centroid(points) {
  33974. var signedArea = 0;
  33975. var cx = 0;
  33976. var cy = 0;
  33977. var len = points.length;
  33978. var x0 = points[len - 1][0];
  33979. var y0 = points[len - 1][1];
  33980. // Polygon should been closed.
  33981. for (var i = 0; i < len; i++) {
  33982. var x1 = points[i][0];
  33983. var y1 = points[i][1];
  33984. var a = x0 * y1 - x1 * y0;
  33985. signedArea += a;
  33986. cx += (x0 + x1) * a;
  33987. cy += (y0 + y1) * a;
  33988. x0 = x1;
  33989. y0 = y1;
  33990. }
  33991. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  33992. }
  33993. var Region = /** @class */function () {
  33994. function Region(name) {
  33995. this.name = name;
  33996. }
  33997. Region.prototype.setCenter = function (center) {
  33998. this._center = center;
  33999. };
  34000. /**
  34001. * Get center point in data unit. That is,
  34002. * for GeoJSONRegion, the unit is lat/lng,
  34003. * for GeoSVGRegion, the unit is SVG local coord.
  34004. */
  34005. Region.prototype.getCenter = function () {
  34006. var center = this._center;
  34007. if (!center) {
  34008. // In most cases there are no need to calculate this center.
  34009. // So calculate only when called.
  34010. center = this._center = this.calcCenter();
  34011. }
  34012. return center;
  34013. };
  34014. return Region;
  34015. }();
  34016. var GeoJSONPolygonGeometry = /** @class */function () {
  34017. function GeoJSONPolygonGeometry(exterior, interiors) {
  34018. this.type = 'polygon';
  34019. this.exterior = exterior;
  34020. this.interiors = interiors;
  34021. }
  34022. return GeoJSONPolygonGeometry;
  34023. }();
  34024. var GeoJSONLineStringGeometry = /** @class */function () {
  34025. function GeoJSONLineStringGeometry(points) {
  34026. this.type = 'linestring';
  34027. this.points = points;
  34028. }
  34029. return GeoJSONLineStringGeometry;
  34030. }();
  34031. var GeoJSONRegion = /** @class */function (_super) {
  34032. __extends(GeoJSONRegion, _super);
  34033. function GeoJSONRegion(name, geometries, cp) {
  34034. var _this = _super.call(this, name) || this;
  34035. _this.type = 'geoJSON';
  34036. _this.geometries = geometries;
  34037. _this._center = cp && [cp[0], cp[1]];
  34038. return _this;
  34039. }
  34040. GeoJSONRegion.prototype.calcCenter = function () {
  34041. var geometries = this.geometries;
  34042. var largestGeo;
  34043. var largestGeoSize = 0;
  34044. for (var i = 0; i < geometries.length; i++) {
  34045. var geo = geometries[i];
  34046. var exterior = geo.exterior;
  34047. // Simple trick to use points count instead of polygon area as region size.
  34048. // Ignore linestring
  34049. var size = exterior && exterior.length;
  34050. if (size > largestGeoSize) {
  34051. largestGeo = geo;
  34052. largestGeoSize = size;
  34053. }
  34054. }
  34055. if (largestGeo) {
  34056. return centroid(largestGeo.exterior);
  34057. }
  34058. // from bounding rect by default.
  34059. var rect = this.getBoundingRect();
  34060. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  34061. };
  34062. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  34063. var rect = this._rect;
  34064. // Always recalculate if using projection.
  34065. if (rect && !projection) {
  34066. return rect;
  34067. }
  34068. var min = [Infinity, Infinity];
  34069. var max = [-Infinity, -Infinity];
  34070. var geometries = this.geometries;
  34071. each(geometries, function (geo) {
  34072. if (geo.type === 'polygon') {
  34073. // Doesn't consider hole
  34074. updateBBoxFromPoints(geo.exterior, min, max, projection);
  34075. } else {
  34076. each(geo.points, function (points) {
  34077. updateBBoxFromPoints(points, min, max, projection);
  34078. });
  34079. }
  34080. });
  34081. // Normalie invalid bounding.
  34082. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  34083. min[0] = min[1] = max[0] = max[1] = 0;
  34084. }
  34085. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  34086. if (!projection) {
  34087. this._rect = rect;
  34088. }
  34089. return rect;
  34090. };
  34091. GeoJSONRegion.prototype.contain = function (coord) {
  34092. var rect = this.getBoundingRect();
  34093. var geometries = this.geometries;
  34094. if (!rect.contain(coord[0], coord[1])) {
  34095. return false;
  34096. }
  34097. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  34098. var geo = geometries[i];
  34099. // Only support polygon.
  34100. if (geo.type !== 'polygon') {
  34101. continue;
  34102. }
  34103. var exterior = geo.exterior;
  34104. var interiors = geo.interiors;
  34105. if (contain$2(exterior, coord[0], coord[1])) {
  34106. // Not in the region if point is in the hole.
  34107. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  34108. if (contain$2(interiors[k], coord[0], coord[1])) {
  34109. continue loopGeo;
  34110. }
  34111. }
  34112. return true;
  34113. }
  34114. }
  34115. return false;
  34116. };
  34117. /**
  34118. * Transform the raw coords to target bounding.
  34119. * @param x
  34120. * @param y
  34121. * @param width
  34122. * @param height
  34123. */
  34124. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  34125. var rect = this.getBoundingRect();
  34126. var aspect = rect.width / rect.height;
  34127. if (!width) {
  34128. width = aspect * height;
  34129. } else if (!height) {
  34130. height = width / aspect;
  34131. }
  34132. var target = new BoundingRect(x, y, width, height);
  34133. var transform = rect.calculateTransform(target);
  34134. var geometries = this.geometries;
  34135. for (var i = 0; i < geometries.length; i++) {
  34136. var geo = geometries[i];
  34137. if (geo.type === 'polygon') {
  34138. transformPoints(geo.exterior, transform);
  34139. each(geo.interiors, function (interior) {
  34140. transformPoints(interior, transform);
  34141. });
  34142. } else {
  34143. each(geo.points, function (points) {
  34144. transformPoints(points, transform);
  34145. });
  34146. }
  34147. }
  34148. rect = this._rect;
  34149. rect.copy(target);
  34150. // Update center
  34151. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  34152. };
  34153. GeoJSONRegion.prototype.cloneShallow = function (name) {
  34154. name == null && (name = this.name);
  34155. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  34156. newRegion._rect = this._rect;
  34157. newRegion.transformTo = null; // Simply avoid to be called.
  34158. return newRegion;
  34159. };
  34160. return GeoJSONRegion;
  34161. }(Region);
  34162. var GeoSVGRegion = /** @class */function (_super) {
  34163. __extends(GeoSVGRegion, _super);
  34164. function GeoSVGRegion(name, elOnlyForCalculate) {
  34165. var _this = _super.call(this, name) || this;
  34166. _this.type = 'geoSVG';
  34167. _this._elOnlyForCalculate = elOnlyForCalculate;
  34168. return _this;
  34169. }
  34170. GeoSVGRegion.prototype.calcCenter = function () {
  34171. var el = this._elOnlyForCalculate;
  34172. var rect = el.getBoundingRect();
  34173. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  34174. var mat = identity(TMP_TRANSFORM);
  34175. var target = el;
  34176. while (target && !target.isGeoSVGGraphicRoot) {
  34177. mul$1(mat, target.getLocalTransform(), mat);
  34178. target = target.parent;
  34179. }
  34180. invert(mat, mat);
  34181. applyTransform(center, center, mat);
  34182. return center;
  34183. };
  34184. return GeoSVGRegion;
  34185. }(Region);
  34186. function decode(json) {
  34187. if (!json.UTF8Encoding) {
  34188. return json;
  34189. }
  34190. var jsonCompressed = json;
  34191. var encodeScale = jsonCompressed.UTF8Scale;
  34192. if (encodeScale == null) {
  34193. encodeScale = 1024;
  34194. }
  34195. var features = jsonCompressed.features;
  34196. each(features, function (feature) {
  34197. var geometry = feature.geometry;
  34198. var encodeOffsets = geometry.encodeOffsets;
  34199. var coordinates = geometry.coordinates;
  34200. // Geometry may be appeded manually in the script after json loaded.
  34201. // In this case this geometry is usually not encoded.
  34202. if (!encodeOffsets) {
  34203. return;
  34204. }
  34205. switch (geometry.type) {
  34206. case 'LineString':
  34207. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  34208. break;
  34209. case 'Polygon':
  34210. decodeRings(coordinates, encodeOffsets, encodeScale);
  34211. break;
  34212. case 'MultiLineString':
  34213. decodeRings(coordinates, encodeOffsets, encodeScale);
  34214. break;
  34215. case 'MultiPolygon':
  34216. each(coordinates, function (rings, idx) {
  34217. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  34218. });
  34219. }
  34220. });
  34221. // Has been decoded
  34222. jsonCompressed.UTF8Encoding = false;
  34223. return jsonCompressed;
  34224. }
  34225. function decodeRings(rings, encodeOffsets, encodeScale) {
  34226. for (var c = 0; c < rings.length; c++) {
  34227. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  34228. }
  34229. }
  34230. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  34231. var result = [];
  34232. var prevX = encodeOffsets[0];
  34233. var prevY = encodeOffsets[1];
  34234. for (var i = 0; i < coordinate.length; i += 2) {
  34235. var x = coordinate.charCodeAt(i) - 64;
  34236. var y = coordinate.charCodeAt(i + 1) - 64;
  34237. // ZigZag decoding
  34238. x = x >> 1 ^ -(x & 1);
  34239. y = y >> 1 ^ -(y & 1);
  34240. // Delta deocding
  34241. x += prevX;
  34242. y += prevY;
  34243. prevX = x;
  34244. prevY = y;
  34245. // Dequantize
  34246. result.push([x / encodeScale, y / encodeScale]);
  34247. }
  34248. return result;
  34249. }
  34250. function parseGeoJSON(geoJson, nameProperty) {
  34251. geoJson = decode(geoJson);
  34252. return map(filter(geoJson.features, function (featureObj) {
  34253. // Output of mapshaper may have geometry null
  34254. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  34255. }), function (featureObj) {
  34256. var properties = featureObj.properties;
  34257. var geo = featureObj.geometry;
  34258. var geometries = [];
  34259. switch (geo.type) {
  34260. case 'Polygon':
  34261. var coordinates = geo.coordinates;
  34262. // According to the GeoJSON specification.
  34263. // First must be exterior, and the rest are all interior(holes).
  34264. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  34265. break;
  34266. case 'MultiPolygon':
  34267. each(geo.coordinates, function (item) {
  34268. if (item[0]) {
  34269. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  34270. }
  34271. });
  34272. break;
  34273. case 'LineString':
  34274. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  34275. break;
  34276. case 'MultiLineString':
  34277. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  34278. }
  34279. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  34280. region.properties = properties;
  34281. return region;
  34282. });
  34283. }
  34284. var number = /*#__PURE__*/Object.freeze({
  34285. __proto__: null,
  34286. linearMap: linearMap,
  34287. round: round,
  34288. asc: asc,
  34289. getPrecision: getPrecision,
  34290. getPrecisionSafe: getPrecisionSafe,
  34291. getPixelPrecision: getPixelPrecision,
  34292. getPercentWithPrecision: getPercentWithPrecision,
  34293. parsePercent: parsePercent$1,
  34294. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  34295. remRadian: remRadian,
  34296. isRadianAroundZero: isRadianAroundZero,
  34297. parseDate: parseDate,
  34298. quantity: quantity,
  34299. quantityExponent: quantityExponent,
  34300. nice: nice,
  34301. quantile: quantile,
  34302. reformIntervals: reformIntervals,
  34303. isNumeric: isNumeric,
  34304. numericToNumber: numericToNumber
  34305. });
  34306. var time = /*#__PURE__*/Object.freeze({
  34307. __proto__: null,
  34308. parse: parseDate,
  34309. format: format,
  34310. roundTime: roundTime
  34311. });
  34312. var graphic$1 = /*#__PURE__*/Object.freeze({
  34313. __proto__: null,
  34314. extendShape: extendShape,
  34315. extendPath: extendPath,
  34316. makePath: makePath,
  34317. makeImage: makeImage,
  34318. mergePath: mergePath$1,
  34319. resizePath: resizePath,
  34320. createIcon: createIcon,
  34321. updateProps: updateProps,
  34322. initProps: initProps,
  34323. getTransform: getTransform,
  34324. clipPointsByRect: clipPointsByRect,
  34325. clipRectByRect: clipRectByRect,
  34326. registerShape: registerShape,
  34327. getShapeClass: getShapeClass,
  34328. Group: Group,
  34329. Image: ZRImage,
  34330. Text: ZRText,
  34331. Circle: Circle,
  34332. Ellipse: Ellipse,
  34333. Sector: Sector,
  34334. Ring: Ring,
  34335. Polygon: Polygon,
  34336. Polyline: Polyline,
  34337. Rect: Rect,
  34338. Line: Line,
  34339. BezierCurve: BezierCurve,
  34340. Arc: Arc,
  34341. IncrementalDisplayable: IncrementalDisplayable,
  34342. CompoundPath: CompoundPath,
  34343. LinearGradient: LinearGradient,
  34344. RadialGradient: RadialGradient,
  34345. BoundingRect: BoundingRect
  34346. });
  34347. var format$1 = /*#__PURE__*/Object.freeze({
  34348. __proto__: null,
  34349. addCommas: addCommas,
  34350. toCamelCase: toCamelCase,
  34351. normalizeCssArray: normalizeCssArray$1,
  34352. encodeHTML: encodeHTML,
  34353. formatTpl: formatTpl,
  34354. getTooltipMarker: getTooltipMarker,
  34355. formatTime: formatTime,
  34356. capitalFirst: capitalFirst,
  34357. truncateText: truncateText,
  34358. getTextRect: getTextRect
  34359. });
  34360. var util$1 = /*#__PURE__*/Object.freeze({
  34361. __proto__: null,
  34362. map: map,
  34363. each: each,
  34364. indexOf: indexOf,
  34365. inherits: inherits,
  34366. reduce: reduce,
  34367. filter: filter,
  34368. bind: bind,
  34369. curry: curry,
  34370. isArray: isArray,
  34371. isString: isString,
  34372. isObject: isObject,
  34373. isFunction: isFunction,
  34374. extend: extend,
  34375. defaults: defaults,
  34376. clone: clone,
  34377. merge: merge
  34378. });
  34379. var modelInner = makeInner();
  34380. var axisInner = makeInner();
  34381. var AxisTickLabelComputingKind = {
  34382. estimate: 1,
  34383. determine: 2
  34384. };
  34385. function createAxisLabelsComputingContext(kind) {
  34386. return {
  34387. out: {
  34388. noPxChangeTryDetermine: []
  34389. },
  34390. kind: kind
  34391. };
  34392. }
  34393. function tickValuesToNumbers(axis, values) {
  34394. var nums = map(values, function (val) {
  34395. return axis.scale.parse(val);
  34396. });
  34397. if (axis.type === 'time' && nums.length > 0) {
  34398. // Time axis needs duplicate first/last tick (see TimeScale.getTicks())
  34399. // The first and last tick/label don't get drawn
  34400. nums.sort();
  34401. nums.unshift(nums[0]);
  34402. nums.push(nums[nums.length - 1]);
  34403. }
  34404. return nums;
  34405. }
  34406. function createAxisLabels(axis, ctx) {
  34407. var custom = axis.getLabelModel().get('customValues');
  34408. if (custom) {
  34409. var labelFormatter_1 = makeLabelFormatter(axis);
  34410. var extent_1 = axis.scale.getExtent();
  34411. var tickNumbers = tickValuesToNumbers(axis, custom);
  34412. var ticks = filter(tickNumbers, function (val) {
  34413. return val >= extent_1[0] && val <= extent_1[1];
  34414. });
  34415. return {
  34416. labels: map(ticks, function (numval) {
  34417. var tick = {
  34418. value: numval
  34419. };
  34420. return {
  34421. formattedLabel: labelFormatter_1(tick),
  34422. rawLabel: axis.scale.getLabel(tick),
  34423. tickValue: numval,
  34424. time: undefined,
  34425. "break": undefined
  34426. };
  34427. })
  34428. };
  34429. }
  34430. // Only ordinal scale support tick interval
  34431. return axis.type === 'category' ? makeCategoryLabels(axis, ctx) : makeRealNumberLabels(axis);
  34432. }
  34433. /**
  34434. * @param tickModel For example, can be axisTick, splitLine, splitArea.
  34435. */
  34436. function createAxisTicks(axis, tickModel, opt) {
  34437. var custom = axis.getTickModel().get('customValues');
  34438. if (custom) {
  34439. var extent_2 = axis.scale.getExtent();
  34440. var tickNumbers = tickValuesToNumbers(axis, custom);
  34441. return {
  34442. ticks: filter(tickNumbers, function (val) {
  34443. return val >= extent_2[0] && val <= extent_2[1];
  34444. })
  34445. };
  34446. }
  34447. // Only ordinal scale support tick interval
  34448. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  34449. ticks: map(axis.scale.getTicks(opt), function (tick) {
  34450. return tick.value;
  34451. })
  34452. };
  34453. }
  34454. function makeCategoryLabels(axis, ctx) {
  34455. var labelModel = axis.getLabelModel();
  34456. var result = makeCategoryLabelsActually(axis, labelModel, ctx);
  34457. return !labelModel.get('show') || axis.scale.isBlank() ? {
  34458. labels: []
  34459. } : result;
  34460. }
  34461. function makeCategoryLabelsActually(axis, labelModel, ctx) {
  34462. var labelsCache = ensureCategoryLabelCache(axis);
  34463. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  34464. var isEstimate = ctx.kind === AxisTickLabelComputingKind.estimate;
  34465. // In AxisTickLabelComputingKind.estimate, the result likely varies during a single
  34466. // pass of ec main process,due to the change of axisExtent, and will not be shared with
  34467. // splitLine. Therefore no cache is used.
  34468. if (!isEstimate) {
  34469. // PENDING: check necessary?
  34470. var result_1 = axisCacheGet(labelsCache, optionLabelInterval);
  34471. if (result_1) {
  34472. return result_1;
  34473. }
  34474. }
  34475. var labels;
  34476. var numericLabelInterval;
  34477. if (isFunction(optionLabelInterval)) {
  34478. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  34479. } else {
  34480. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis, ctx) : optionLabelInterval;
  34481. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  34482. }
  34483. var result = {
  34484. labels: labels,
  34485. labelCategoryInterval: numericLabelInterval
  34486. };
  34487. if (!isEstimate) {
  34488. axisCacheSet(labelsCache, optionLabelInterval, result);
  34489. } else {
  34490. ctx.out.noPxChangeTryDetermine.push(function () {
  34491. axisCacheSet(labelsCache, optionLabelInterval, result);
  34492. return true;
  34493. });
  34494. }
  34495. return result;
  34496. }
  34497. function makeCategoryTicks(axis, tickModel) {
  34498. var ticksCache = ensureCategoryTickCache(axis);
  34499. var optionTickInterval = getOptionCategoryInterval(tickModel);
  34500. var result = axisCacheGet(ticksCache, optionTickInterval);
  34501. if (result) {
  34502. return result;
  34503. }
  34504. var ticks;
  34505. var tickCategoryInterval;
  34506. // Optimize for the case that large category data and no label displayed,
  34507. // we should not return all ticks.
  34508. if (!tickModel.get('show') || axis.scale.isBlank()) {
  34509. ticks = [];
  34510. }
  34511. if (isFunction(optionTickInterval)) {
  34512. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  34513. }
  34514. // Always use label interval by default despite label show. Consider this
  34515. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  34516. // labels. `splitLine` and `axisTick` should be consistent in this case.
  34517. else if (optionTickInterval === 'auto') {
  34518. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel(), createAxisLabelsComputingContext(AxisTickLabelComputingKind.determine));
  34519. tickCategoryInterval = labelsResult.labelCategoryInterval;
  34520. ticks = map(labelsResult.labels, function (labelItem) {
  34521. return labelItem.tickValue;
  34522. });
  34523. } else {
  34524. tickCategoryInterval = optionTickInterval;
  34525. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  34526. }
  34527. // Cache to avoid calling interval function repeatedly.
  34528. return axisCacheSet(ticksCache, optionTickInterval, {
  34529. ticks: ticks,
  34530. tickCategoryInterval: tickCategoryInterval
  34531. });
  34532. }
  34533. function makeRealNumberLabels(axis) {
  34534. var ticks = axis.scale.getTicks();
  34535. var labelFormatter = makeLabelFormatter(axis);
  34536. return {
  34537. labels: map(ticks, function (tick, idx) {
  34538. return {
  34539. formattedLabel: labelFormatter(tick, idx),
  34540. rawLabel: axis.scale.getLabel(tick),
  34541. tickValue: tick.value,
  34542. time: tick.time,
  34543. "break": tick["break"]
  34544. };
  34545. })
  34546. };
  34547. }
  34548. // Large category data calculation is performance sensitive, and ticks and label probably will
  34549. // be fetched multiple times (e.g. shared by splitLine and axisTick). So we cache the result.
  34550. // axis is created each time during a ec process, so we do not need to clear cache.
  34551. var ensureCategoryTickCache = initAxisCacheMethod('axisTick');
  34552. var ensureCategoryLabelCache = initAxisCacheMethod('axisLabel');
  34553. /**
  34554. * PENDING: refactor to JS Map? Because key can be a function or more complicated object, and
  34555. * cache size always is small, and currently no JS Map object key polyfill, we use a simple
  34556. * array cache instead of plain object hash.
  34557. */
  34558. function initAxisCacheMethod(prop) {
  34559. return function ensureCache(axis) {
  34560. return axisInner(axis)[prop] || (axisInner(axis)[prop] = {
  34561. list: []
  34562. });
  34563. };
  34564. }
  34565. function axisCacheGet(cache, key) {
  34566. for (var i = 0; i < cache.list.length; i++) {
  34567. if (cache.list[i].key === key) {
  34568. return cache.list[i].value;
  34569. }
  34570. }
  34571. }
  34572. function axisCacheSet(cache, key, value) {
  34573. cache.list.push({
  34574. key: key,
  34575. value: value
  34576. });
  34577. return value;
  34578. }
  34579. function makeAutoCategoryInterval(axis, ctx) {
  34580. if (ctx.kind === AxisTickLabelComputingKind.estimate) {
  34581. // Currently axisTick is not involved in estimate kind, and the result likely varies during a
  34582. // single pass of ec main process, due to the change of axisExtent. Therefore no cache is used.
  34583. var result_2 = axis.calculateCategoryInterval(ctx);
  34584. ctx.out.noPxChangeTryDetermine.push(function () {
  34585. axisInner(axis).autoInterval = result_2;
  34586. return true;
  34587. });
  34588. return result_2;
  34589. }
  34590. // Both tick and label uses this result, cacah it to avoid recompute.
  34591. var result = axisInner(axis).autoInterval;
  34592. return result != null ? result : axisInner(axis).autoInterval = axis.calculateCategoryInterval(ctx);
  34593. }
  34594. /**
  34595. * Calculate interval for category axis ticks and labels.
  34596. * Use a stretegy to try to avoid overlapping.
  34597. * To get precise result, at least one of `getRotate` and `isHorizontal`
  34598. * should be implemented in axis.
  34599. */
  34600. function calculateCategoryInterval(axis, ctx) {
  34601. var kind = ctx.kind;
  34602. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  34603. var labelFormatter = makeLabelFormatter(axis);
  34604. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  34605. var ordinalScale = axis.scale;
  34606. var ordinalExtent = ordinalScale.getExtent();
  34607. // Providing this method is for optimization:
  34608. // avoid generating a long array by `getTicks`
  34609. // in large category data case.
  34610. var tickCount = ordinalScale.count();
  34611. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  34612. return 0;
  34613. }
  34614. var step = 1;
  34615. // Simple optimization. Arbitrary value.
  34616. var maxCount = 40;
  34617. if (tickCount > maxCount) {
  34618. step = Math.max(1, Math.floor(tickCount / maxCount));
  34619. }
  34620. var tickValue = ordinalExtent[0];
  34621. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  34622. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  34623. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  34624. var maxW = 0;
  34625. var maxH = 0;
  34626. // Caution: Performance sensitive for large category data.
  34627. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  34628. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  34629. var width = 0;
  34630. var height = 0;
  34631. // Not precise, do not consider align and vertical align
  34632. // and each distance from axis line yet.
  34633. var rect = getBoundingRect(labelFormatter({
  34634. value: tickValue
  34635. }), params.font, 'center', 'top');
  34636. // Magic number
  34637. width = rect.width * 1.3;
  34638. height = rect.height * 1.3;
  34639. // Min size, void long loop.
  34640. maxW = Math.max(maxW, width, 7);
  34641. maxH = Math.max(maxH, height, 7);
  34642. }
  34643. var dw = maxW / unitW;
  34644. var dh = maxH / unitH;
  34645. // 0/0 is NaN, 1/0 is Infinity.
  34646. isNaN(dw) && (dw = Infinity);
  34647. isNaN(dh) && (dh = Infinity);
  34648. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  34649. if (kind === AxisTickLabelComputingKind.estimate) {
  34650. // In estimate kind, the inteval likely varies, thus do not erase the cache.
  34651. ctx.out.noPxChangeTryDetermine.push(bind(calculateCategoryIntervalTryDetermine, null, axis, interval, tickCount));
  34652. return interval;
  34653. }
  34654. var lastInterval = calculateCategoryIntervalDealCache(axis, interval, tickCount);
  34655. return lastInterval != null ? lastInterval : interval;
  34656. }
  34657. function calculateCategoryIntervalTryDetermine(axis, interval, tickCount) {
  34658. return calculateCategoryIntervalDealCache(axis, interval, tickCount) == null;
  34659. }
  34660. // Return the lastInterval if need to use it, otherwise return NullUndefined and save cache.
  34661. function calculateCategoryIntervalDealCache(axis, interval, tickCount) {
  34662. var cache = modelInner(axis.model);
  34663. var axisExtent = axis.getExtent();
  34664. var lastAutoInterval = cache.lastAutoInterval;
  34665. var lastTickCount = cache.lastTickCount;
  34666. // Use cache to keep interval stable while moving zoom window,
  34667. // otherwise the calculated interval might jitter when the zoom
  34668. // window size is close to the interval-changing size.
  34669. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  34670. // The jitter will cause that sometimes the displayed labels are
  34671. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  34672. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1
  34673. // Always choose the bigger one, otherwise the critical
  34674. // point is not the same when zooming in or zooming out.
  34675. && lastAutoInterval > interval
  34676. // If the axis change is caused by chart resize, the cache should not
  34677. // be used. Otherwise some hidden labels might not be shown again.
  34678. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  34679. return lastAutoInterval;
  34680. }
  34681. // Only update cache if cache not used, otherwise the
  34682. // changing of interval is too insensitive.
  34683. else {
  34684. cache.lastTickCount = tickCount;
  34685. cache.lastAutoInterval = interval;
  34686. cache.axisExtent0 = axisExtent[0];
  34687. cache.axisExtent1 = axisExtent[1];
  34688. }
  34689. }
  34690. function fetchAutoCategoryIntervalCalculationParams(axis) {
  34691. var labelModel = axis.getLabelModel();
  34692. return {
  34693. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  34694. labelRotate: labelModel.get('rotate') || 0,
  34695. font: labelModel.getFont()
  34696. };
  34697. }
  34698. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  34699. var labelFormatter = makeLabelFormatter(axis);
  34700. var ordinalScale = axis.scale;
  34701. var ordinalExtent = ordinalScale.getExtent();
  34702. var labelModel = axis.getLabelModel();
  34703. var result = [];
  34704. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  34705. var step = Math.max((categoryInterval || 0) + 1, 1);
  34706. var startTick = ordinalExtent[0];
  34707. var tickCount = ordinalScale.count();
  34708. // Calculate start tick based on zero if possible to keep label consistent
  34709. // while zooming and moving while interval > 0. Otherwise the selection
  34710. // of displayable ticks and symbols probably keep changing.
  34711. // 3 is empirical value.
  34712. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  34713. startTick = Math.round(Math.ceil(startTick / step) * step);
  34714. }
  34715. // (1) Only add min max label here but leave overlap checking
  34716. // to render stage, which also ensure the returned list
  34717. // suitable for splitLine and splitArea rendering.
  34718. // (2) Scales except category always contain min max label so
  34719. // do not need to perform this process.
  34720. var showAllLabel = shouldShowAllLabels(axis);
  34721. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  34722. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  34723. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  34724. addItem(ordinalExtent[0]);
  34725. }
  34726. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  34727. var tickValue = startTick;
  34728. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  34729. addItem(tickValue);
  34730. }
  34731. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  34732. addItem(ordinalExtent[1]);
  34733. }
  34734. function addItem(tickValue) {
  34735. var tickObj = {
  34736. value: tickValue
  34737. };
  34738. result.push(onlyTick ? tickValue : {
  34739. formattedLabel: labelFormatter(tickObj),
  34740. rawLabel: ordinalScale.getLabel(tickObj),
  34741. tickValue: tickValue,
  34742. time: undefined,
  34743. "break": undefined
  34744. });
  34745. }
  34746. return result;
  34747. }
  34748. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  34749. var ordinalScale = axis.scale;
  34750. var labelFormatter = makeLabelFormatter(axis);
  34751. var result = [];
  34752. each(ordinalScale.getTicks(), function (tick) {
  34753. var rawLabel = ordinalScale.getLabel(tick);
  34754. var tickValue = tick.value;
  34755. if (categoryInterval(tick.value, rawLabel)) {
  34756. result.push(onlyTick ? tickValue : {
  34757. formattedLabel: labelFormatter(tick),
  34758. rawLabel: rawLabel,
  34759. tickValue: tickValue,
  34760. time: undefined,
  34761. "break": undefined
  34762. });
  34763. }
  34764. });
  34765. return result;
  34766. }
  34767. var NORMALIZED_EXTENT = [0, 1];
  34768. /**
  34769. * Base class of Axis.
  34770. *
  34771. * Lifetime: recreate for each main process.
  34772. * [NOTICE]: Some caches is stored on the axis instance (see `axisTickLabelBuilder.ts`)
  34773. * which is based on this lifetime.
  34774. */
  34775. var Axis = /** @class */function () {
  34776. function Axis(dim, scale, extent) {
  34777. this.onBand = false;
  34778. // Make sure that `extent[0] > extent[1]` only if `inverse: true`.
  34779. // `inverse` can be inferred by `extent` unless `extent[0] === extent[1]`.
  34780. this.inverse = false;
  34781. this.dim = dim;
  34782. this.scale = scale;
  34783. this._extent = extent || [0, 0];
  34784. }
  34785. /**
  34786. * If axis extent contain given coord
  34787. */
  34788. Axis.prototype.contain = function (coord) {
  34789. var extent = this._extent;
  34790. var min = Math.min(extent[0], extent[1]);
  34791. var max = Math.max(extent[0], extent[1]);
  34792. return coord >= min && coord <= max;
  34793. };
  34794. /**
  34795. * If axis extent contain given data
  34796. */
  34797. Axis.prototype.containData = function (data) {
  34798. return this.scale.contain(this.scale.parse(data));
  34799. };
  34800. /**
  34801. * Get coord extent.
  34802. */
  34803. Axis.prototype.getExtent = function () {
  34804. return this._extent.slice();
  34805. };
  34806. /**
  34807. * Get precision used for formatting
  34808. */
  34809. Axis.prototype.getPixelPrecision = function (dataExtent) {
  34810. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  34811. };
  34812. /**
  34813. * Set coord extent
  34814. */
  34815. Axis.prototype.setExtent = function (start, end) {
  34816. var extent = this._extent;
  34817. extent[0] = start;
  34818. extent[1] = end;
  34819. };
  34820. /**
  34821. * Convert data to coord. Data is the rank if it has an ordinal scale
  34822. */
  34823. Axis.prototype.dataToCoord = function (data, clamp) {
  34824. var extent = this._extent;
  34825. var scale = this.scale;
  34826. data = scale.normalize(scale.parse(data));
  34827. if (this.onBand && scale.type === 'ordinal') {
  34828. extent = extent.slice();
  34829. fixExtentWithBands(extent, scale.count());
  34830. }
  34831. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  34832. };
  34833. /**
  34834. * Convert coord to data. Data is the rank if it has an ordinal scale
  34835. */
  34836. Axis.prototype.coordToData = function (coord, clamp) {
  34837. var extent = this._extent;
  34838. var scale = this.scale;
  34839. if (this.onBand && scale.type === 'ordinal') {
  34840. extent = extent.slice();
  34841. fixExtentWithBands(extent, scale.count());
  34842. }
  34843. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  34844. return this.scale.scale(t);
  34845. };
  34846. /**
  34847. * Convert pixel point to data in axis
  34848. */
  34849. Axis.prototype.pointToData = function (point, clamp) {
  34850. // Should be implemented in derived class if necessary.
  34851. return;
  34852. };
  34853. /**
  34854. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  34855. * `axis.getTicksCoords` considers `onBand`, which is used by
  34856. * `boundaryGap:true` of category axis and splitLine and splitArea.
  34857. * @param opt.tickModel default: axis.model.getModel('axisTick')
  34858. * @param opt.clamp If `true`, the first and the last
  34859. * tick must be at the axis end points. Otherwise, clip ticks
  34860. * that outside the axis extent.
  34861. */
  34862. Axis.prototype.getTicksCoords = function (opt) {
  34863. opt = opt || {};
  34864. var tickModel = opt.tickModel || this.getTickModel();
  34865. var result = createAxisTicks(this, tickModel, {
  34866. breakTicks: opt.breakTicks,
  34867. pruneByBreak: opt.pruneByBreak
  34868. });
  34869. var ticks = result.ticks;
  34870. var ticksCoords = map(ticks, function (tickVal) {
  34871. return {
  34872. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  34873. tickValue: tickVal
  34874. };
  34875. }, this);
  34876. var alignWithLabel = tickModel.get('alignWithLabel');
  34877. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  34878. return ticksCoords;
  34879. };
  34880. Axis.prototype.getMinorTicksCoords = function () {
  34881. if (this.scale.type === 'ordinal') {
  34882. // Category axis doesn't support minor ticks
  34883. return [];
  34884. }
  34885. var minorTickModel = this.model.getModel('minorTick');
  34886. var splitNumber = minorTickModel.get('splitNumber');
  34887. // Protection.
  34888. if (!(splitNumber > 0 && splitNumber < 100)) {
  34889. splitNumber = 5;
  34890. }
  34891. var minorTicks = this.scale.getMinorTicks(splitNumber);
  34892. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  34893. return map(minorTicksGroup, function (minorTick) {
  34894. return {
  34895. coord: this.dataToCoord(minorTick),
  34896. tickValue: minorTick
  34897. };
  34898. }, this);
  34899. }, this);
  34900. return minorTicksCoords;
  34901. };
  34902. Axis.prototype.getViewLabels = function (ctx) {
  34903. ctx = ctx || createAxisLabelsComputingContext(AxisTickLabelComputingKind.determine);
  34904. return createAxisLabels(this, ctx).labels;
  34905. };
  34906. Axis.prototype.getLabelModel = function () {
  34907. return this.model.getModel('axisLabel');
  34908. };
  34909. /**
  34910. * Notice here we only get the default tick model. For splitLine
  34911. * or splitArea, we should pass the splitLineModel or splitAreaModel
  34912. * manually when calling `getTicksCoords`.
  34913. * In GL, this method may be overridden to:
  34914. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  34915. */
  34916. Axis.prototype.getTickModel = function () {
  34917. return this.model.getModel('axisTick');
  34918. };
  34919. /**
  34920. * Get width of band
  34921. */
  34922. Axis.prototype.getBandWidth = function () {
  34923. var axisExtent = this._extent;
  34924. var dataExtent = this.scale.getExtent();
  34925. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  34926. // Fix #2728, avoid NaN when only one data.
  34927. len === 0 && (len = 1);
  34928. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  34929. return Math.abs(size) / len;
  34930. };
  34931. /**
  34932. * Only be called in category axis.
  34933. * Can be overridden, consider other axes like in 3D.
  34934. * @return Auto interval for cateogry axis tick and label
  34935. */
  34936. Axis.prototype.calculateCategoryInterval = function (ctx) {
  34937. ctx = ctx || createAxisLabelsComputingContext(AxisTickLabelComputingKind.determine);
  34938. return calculateCategoryInterval(this, ctx);
  34939. };
  34940. return Axis;
  34941. }();
  34942. function fixExtentWithBands(extent, nTick) {
  34943. var size = extent[1] - extent[0];
  34944. var len = nTick;
  34945. var margin = size / len / 2;
  34946. extent[0] += margin;
  34947. extent[1] -= margin;
  34948. }
  34949. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  34950. // |---1---|---2---|---3---|---4---|.
  34951. // So the displayed ticks and splitLine/splitArea should between
  34952. // each data item, otherwise cause misleading (e.g., split tow bars
  34953. // of a single data item when there are two bar series).
  34954. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  34955. // splitLine/spliteArea should layout appropriately corresponding
  34956. // to displayed labels. (So we should not use `getBandWidth` in this
  34957. // case).
  34958. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  34959. var ticksLen = ticksCoords.length;
  34960. if (!axis.onBand || alignWithLabel || !ticksLen) {
  34961. return;
  34962. }
  34963. var axisExtent = axis.getExtent();
  34964. var last;
  34965. var diffSize;
  34966. if (ticksLen === 1) {
  34967. ticksCoords[0].coord = axisExtent[0];
  34968. ticksCoords[0].onBand = true;
  34969. last = ticksCoords[1] = {
  34970. coord: axisExtent[1],
  34971. tickValue: ticksCoords[0].tickValue,
  34972. onBand: true
  34973. };
  34974. } else {
  34975. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  34976. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  34977. each(ticksCoords, function (ticksItem) {
  34978. ticksItem.coord -= shift_1 / 2;
  34979. ticksItem.onBand = true;
  34980. });
  34981. var dataExtent = axis.scale.getExtent();
  34982. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  34983. last = {
  34984. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize,
  34985. tickValue: dataExtent[1] + 1,
  34986. onBand: true
  34987. };
  34988. ticksCoords.push(last);
  34989. }
  34990. var inverse = axisExtent[0] > axisExtent[1];
  34991. // Handling clamp.
  34992. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  34993. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  34994. }
  34995. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  34996. ticksCoords.unshift({
  34997. coord: axisExtent[0],
  34998. onBand: true
  34999. });
  35000. }
  35001. if (littleThan(axisExtent[1], last.coord)) {
  35002. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  35003. }
  35004. if (clamp && littleThan(last.coord, axisExtent[1])) {
  35005. ticksCoords.push({
  35006. coord: axisExtent[1],
  35007. onBand: true
  35008. });
  35009. }
  35010. function littleThan(a, b) {
  35011. // Avoid rounding error cause calculated tick coord different with extent.
  35012. // It may cause an extra unnecessary tick added.
  35013. a = round(a);
  35014. b = round(b);
  35015. return inverse ? a > b : a < b;
  35016. }
  35017. }
  35018. // --------------------- Deprecated Extension Methods ---------------------
  35019. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  35020. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  35021. // class Bar3DModel extends ComponentModel {}
  35022. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  35023. // echarts.use(install);
  35024. function extendComponentModel(proto) {
  35025. var Model = ComponentModel.extend(proto);
  35026. ComponentModel.registerClass(Model);
  35027. return Model;
  35028. }
  35029. function extendComponentView(proto) {
  35030. var View = ComponentView.extend(proto);
  35031. ComponentView.registerClass(View);
  35032. return View;
  35033. }
  35034. function extendSeriesModel(proto) {
  35035. var Model = SeriesModel.extend(proto);
  35036. SeriesModel.registerClass(Model);
  35037. return Model;
  35038. }
  35039. function extendChartView(proto) {
  35040. var View = ChartView.extend(proto);
  35041. ChartView.registerClass(View);
  35042. return View;
  35043. }
  35044. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  35045. var dx = x - x1;
  35046. var dy = y - y1;
  35047. var dx1 = x2 - x1;
  35048. var dy1 = y2 - y1;
  35049. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  35050. dx1 /= lineLen;
  35051. dy1 /= lineLen;
  35052. // dot product
  35053. var projectedLen = dx * dx1 + dy * dy1;
  35054. var t = projectedLen / lineLen;
  35055. if (limitToEnds) {
  35056. t = Math.min(Math.max(t, 0), 1);
  35057. }
  35058. t *= lineLen;
  35059. var ox = out[0] = x1 + t * dx1;
  35060. var oy = out[1] = y1 + t * dy1;
  35061. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  35062. }
  35063. // Temporal variable for intermediate usage.
  35064. var pt0 = new Point();
  35065. var pt1 = new Point();
  35066. var pt2 = new Point();
  35067. var dir = new Point();
  35068. var dir2 = new Point();
  35069. // Temporal variable for the limitTurnAngle function
  35070. var tmpArr = [];
  35071. var tmpProjPoint = new Point();
  35072. /**
  35073. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  35074. * @param linePoints
  35075. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  35076. */
  35077. function limitTurnAngle(linePoints, minTurnAngle) {
  35078. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  35079. return;
  35080. }
  35081. minTurnAngle = minTurnAngle / 180 * Math.PI;
  35082. // The line points can be
  35083. // /pt1----pt2 (label)
  35084. // /
  35085. // pt0/
  35086. pt0.fromArray(linePoints[0]);
  35087. pt1.fromArray(linePoints[1]);
  35088. pt2.fromArray(linePoints[2]);
  35089. Point.sub(dir, pt0, pt1);
  35090. Point.sub(dir2, pt2, pt1);
  35091. var len1 = dir.len();
  35092. var len2 = dir2.len();
  35093. if (len1 < 1e-3 || len2 < 1e-3) {
  35094. return;
  35095. }
  35096. dir.scale(1 / len1);
  35097. dir2.scale(1 / len2);
  35098. var angleCos = dir.dot(dir2);
  35099. var minTurnAngleCos = Math.cos(minTurnAngle);
  35100. if (minTurnAngleCos < angleCos) {
  35101. // Smaller than minTurnAngle
  35102. // Calculate project point of pt0 on pt1-pt2
  35103. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  35104. tmpProjPoint.fromArray(tmpArr);
  35105. // Calculate new projected length with limited minTurnAngle and get the new connect point
  35106. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle));
  35107. // Limit the new calculated connect point between pt1 and pt2.
  35108. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  35109. if (isNaN(t)) {
  35110. return;
  35111. }
  35112. if (t < 0) {
  35113. Point.copy(tmpProjPoint, pt1);
  35114. } else if (t > 1) {
  35115. Point.copy(tmpProjPoint, pt2);
  35116. }
  35117. tmpProjPoint.toArray(linePoints[1]);
  35118. }
  35119. }
  35120. /**
  35121. * Limit the angle of line and the surface
  35122. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  35123. */
  35124. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  35125. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  35126. return;
  35127. }
  35128. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  35129. pt0.fromArray(linePoints[0]);
  35130. pt1.fromArray(linePoints[1]);
  35131. pt2.fromArray(linePoints[2]);
  35132. Point.sub(dir, pt1, pt0);
  35133. Point.sub(dir2, pt2, pt1);
  35134. var len1 = dir.len();
  35135. var len2 = dir2.len();
  35136. if (len1 < 1e-3 || len2 < 1e-3) {
  35137. return;
  35138. }
  35139. dir.scale(1 / len1);
  35140. dir2.scale(1 / len2);
  35141. var angleCos = dir.dot(surfaceNormal);
  35142. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  35143. if (angleCos < maxSurfaceAngleCos) {
  35144. // Calculate project point of pt0 on pt1-pt2
  35145. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  35146. tmpProjPoint.fromArray(tmpArr);
  35147. var HALF_PI = Math.PI / 2;
  35148. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  35149. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  35150. if (newAngle >= HALF_PI) {
  35151. // parallel
  35152. Point.copy(tmpProjPoint, pt2);
  35153. } else {
  35154. // Calculate new projected length with limited minTurnAngle and get the new connect point
  35155. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle));
  35156. // Limit the new calculated connect point between pt1 and pt2.
  35157. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  35158. if (isNaN(t)) {
  35159. return;
  35160. }
  35161. if (t < 0) {
  35162. Point.copy(tmpProjPoint, pt1);
  35163. } else if (t > 1) {
  35164. Point.copy(tmpProjPoint, pt2);
  35165. }
  35166. }
  35167. tmpProjPoint.toArray(linePoints[1]);
  35168. }
  35169. }
  35170. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  35171. var isNormal = stateName === 'normal';
  35172. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName);
  35173. // Make sure display.
  35174. stateObj.ignore = ignore;
  35175. // Set smooth
  35176. var smooth = stateModel.get('smooth');
  35177. if (smooth && smooth === true) {
  35178. smooth = 0.3;
  35179. }
  35180. stateObj.shape = stateObj.shape || {};
  35181. if (smooth > 0) {
  35182. stateObj.shape.smooth = smooth;
  35183. }
  35184. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  35185. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  35186. }
  35187. function buildLabelLinePath(path, shape) {
  35188. var smooth = shape.smooth;
  35189. var points = shape.points;
  35190. if (!points) {
  35191. return;
  35192. }
  35193. path.moveTo(points[0][0], points[0][1]);
  35194. if (smooth > 0 && points.length >= 3) {
  35195. var len1 = dist(points[0], points[1]);
  35196. var len2 = dist(points[1], points[2]);
  35197. if (!len1 || !len2) {
  35198. path.lineTo(points[1][0], points[1][1]);
  35199. path.lineTo(points[2][0], points[2][1]);
  35200. return;
  35201. }
  35202. var moveLen = Math.min(len1, len2) * smooth;
  35203. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  35204. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  35205. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  35206. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  35207. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  35208. } else {
  35209. for (var i = 1; i < points.length; i++) {
  35210. path.lineTo(points[i][0], points[i][1]);
  35211. }
  35212. }
  35213. }
  35214. /**
  35215. * Create a label line if necessary and set it's style.
  35216. */
  35217. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  35218. var labelLine = targetEl.getTextGuideLine();
  35219. var label = targetEl.getTextContent();
  35220. if (!label) {
  35221. // Not show label line if there is no label.
  35222. if (labelLine) {
  35223. targetEl.removeTextGuideLine();
  35224. }
  35225. return;
  35226. }
  35227. var normalModel = statesModels.normal;
  35228. var showNormal = normalModel.get('show');
  35229. var labelIgnoreNormal = label.ignore;
  35230. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  35231. var stateName = DISPLAY_STATES[i];
  35232. var stateModel = statesModels[stateName];
  35233. var isNormal = stateName === 'normal';
  35234. if (stateModel) {
  35235. var stateShow = stateModel.get('show');
  35236. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  35237. if (isLabelIgnored // Not show when label is not shown in this state.
  35238. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  35239. ) {
  35240. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  35241. if (stateObj) {
  35242. stateObj.ignore = true;
  35243. }
  35244. if (!!labelLine) {
  35245. setLabelLineState(labelLine, true, stateName, stateModel);
  35246. }
  35247. continue;
  35248. }
  35249. // Create labelLine if not exists
  35250. if (!labelLine) {
  35251. labelLine = new Polyline();
  35252. targetEl.setTextGuideLine(labelLine);
  35253. // Reset state of normal because it's new created.
  35254. // NOTE: NORMAL should always been the first!
  35255. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  35256. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  35257. }
  35258. // Use same state proxy.
  35259. if (targetEl.stateProxy) {
  35260. labelLine.stateProxy = targetEl.stateProxy;
  35261. }
  35262. }
  35263. setLabelLineState(labelLine, false, stateName, stateModel);
  35264. }
  35265. }
  35266. if (labelLine) {
  35267. defaults(labelLine.style, defaultStyle);
  35268. // Not fill.
  35269. labelLine.style.fill = null;
  35270. var showAbove = normalModel.get('showAbove');
  35271. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  35272. labelLineConfig.showAbove = showAbove || false;
  35273. // Custom the buildPath.
  35274. labelLine.buildPath = buildLabelLinePath;
  35275. }
  35276. }
  35277. function getLabelLineStatesModels(itemModel, labelLineName) {
  35278. labelLineName = labelLineName || 'labelLine';
  35279. var statesModels = {
  35280. normal: itemModel.getModel(labelLineName)
  35281. };
  35282. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  35283. var stateName = SPECIAL_STATES[i];
  35284. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  35285. }
  35286. return statesModels;
  35287. }
  35288. var LABEL_LAYOUT_BASE_PROPS = ['label', 'labelLine', 'layoutOption', 'priority', 'defaultAttr', 'marginForce', 'minMarginForce', 'marginDefault', 'suggestIgnore'];
  35289. var LABEL_LAYOUT_DIRTY_BIT_OTHERS = 1;
  35290. var LABEL_LAYOUT_DIRTY_BIT_OBB = 2;
  35291. var LABEL_LAYOUT_DIRTY_ALL = LABEL_LAYOUT_DIRTY_BIT_OTHERS | LABEL_LAYOUT_DIRTY_BIT_OBB;
  35292. function setLabelLayoutDirty(labelGeometry, dirtyOrClear, dirtyBits) {
  35293. dirtyBits = dirtyBits || LABEL_LAYOUT_DIRTY_ALL;
  35294. dirtyOrClear ? labelGeometry.dirty |= dirtyBits : labelGeometry.dirty &= ~dirtyBits;
  35295. }
  35296. function isLabelLayoutDirty(labelGeometry, dirtyBits) {
  35297. dirtyBits = dirtyBits || LABEL_LAYOUT_DIRTY_ALL;
  35298. return labelGeometry.dirty == null || !!(labelGeometry.dirty & dirtyBits);
  35299. }
  35300. /**
  35301. * [CAUTION]
  35302. * - No auto dirty propagation mechanism yet. If the transform of the raw label or any of its ancestors is
  35303. * changed, must sync the changes to the props of `LabelGeometry` by:
  35304. * either explicitly call:
  35305. * `setLabelLayoutDirty(labelLayout, true); ensureLabelLayoutWithGeometry(labelLayout);`
  35306. * or call (if only translation is performed):
  35307. * `labelLayoutApplyTranslation(labelLayout);`
  35308. * - `label.ignore` is not necessarily falsy, and not considered in computing `LabelGeometry`,
  35309. * since it might be modified by some overlap resolving handling.
  35310. * - To duplicate or make a variation:
  35311. * use `newLabelLayoutWithGeometry`.
  35312. *
  35313. * The result can also be the input of this method.
  35314. * @return `NullUndefined` if and only if `labelLayout` is `NullUndefined`.
  35315. */
  35316. function ensureLabelLayoutWithGeometry(labelLayout) {
  35317. if (!labelLayout) {
  35318. return;
  35319. }
  35320. if (isLabelLayoutDirty(labelLayout)) {
  35321. computeLabelGeometry(labelLayout, labelLayout.label, labelLayout);
  35322. }
  35323. return labelLayout;
  35324. }
  35325. /**
  35326. * The props in `out` will be filled if existing, or created.
  35327. */
  35328. function computeLabelGeometry(out, label, opt) {
  35329. // [CAUTION] These props may be modified directly for performance consideration,
  35330. // therefore, do not output the internal data structure of zrender Element.
  35331. var rawTransform = label.getComputedTransform();
  35332. out.transform = ensureCopyTransform(out.transform, rawTransform);
  35333. // NOTE: should call `getBoundingRect` after `getComputedTransform`, or may get an inaccurate bounding rect.
  35334. // The reason is that `getComputedTransform` calls `__host.updateInnerText()` internally, which updates the label
  35335. // by `textConfig` mounted on the host.
  35336. // PENDING: add a dirty bit for that in zrender?
  35337. var outLocalRect = out.localRect = ensureCopyRect(out.localRect, label.getBoundingRect());
  35338. var labelStyleExt = label.style;
  35339. var margin = labelStyleExt.margin;
  35340. var marginForce = opt && opt.marginForce;
  35341. var minMarginForce = opt && opt.minMarginForce;
  35342. var marginDefault = opt && opt.marginDefault;
  35343. var marginType = labelStyleExt.__marginType;
  35344. if (marginType == null && marginDefault) {
  35345. margin = marginDefault;
  35346. marginType = LabelMarginType.textMargin;
  35347. }
  35348. // `textMargin` and `minMargin` can not exist both.
  35349. for (var i = 0; i < 4; i++) {
  35350. _tmpLabelMargin[i] = marginType === LabelMarginType.minMargin && minMarginForce && minMarginForce[i] != null ? minMarginForce[i] : marginForce && marginForce[i] != null ? marginForce[i] : margin ? margin[i] : 0;
  35351. }
  35352. if (marginType === LabelMarginType.textMargin) {
  35353. expandOrShrinkRect(outLocalRect, _tmpLabelMargin, false, false);
  35354. }
  35355. var outGlobalRect = out.rect = ensureCopyRect(out.rect, outLocalRect);
  35356. if (rawTransform) {
  35357. outGlobalRect.applyTransform(rawTransform);
  35358. }
  35359. // Notice: label.style.margin is actually `minMargin / 2`, handled by `setTextStyleCommon`.
  35360. if (marginType === LabelMarginType.minMargin) {
  35361. expandOrShrinkRect(outGlobalRect, _tmpLabelMargin, false, false);
  35362. }
  35363. out.axisAligned = isBoundingRectAxisAligned(rawTransform);
  35364. (out.label = out.label || {}).ignore = label.ignore;
  35365. setLabelLayoutDirty(out, false);
  35366. setLabelLayoutDirty(out, true, LABEL_LAYOUT_DIRTY_BIT_OBB);
  35367. // Do not remove `obb` (if existing) for reuse, just reset the dirty bit.
  35368. return out;
  35369. }
  35370. var _tmpLabelMargin = [0, 0, 0, 0];
  35371. /**
  35372. * The props in `out` will be filled if existing, or created.
  35373. */
  35374. function computeLabelGeometry2(out, rawLocalRect, rawTransform) {
  35375. out.transform = ensureCopyTransform(out.transform, rawTransform);
  35376. out.localRect = ensureCopyRect(out.localRect, rawLocalRect);
  35377. out.rect = ensureCopyRect(out.rect, rawLocalRect);
  35378. if (rawTransform) {
  35379. out.rect.applyTransform(rawTransform);
  35380. }
  35381. out.axisAligned = isBoundingRectAxisAligned(rawTransform);
  35382. out.obb = undefined; // Reset to undefined, will be created by `ensureOBB` when using.
  35383. (out.label = out.label || {}).ignore = false;
  35384. return out;
  35385. }
  35386. /**
  35387. * This is a shortcut of
  35388. * ```js
  35389. * labelLayout.label.x = newX;
  35390. * labelLayout.label.y = newY;
  35391. * setLabelLayoutDirty(labelLayout, true);
  35392. * ensureLabelLayoutWithGeometry(labelLayout);
  35393. * ```
  35394. * and provide better performance in this common case.
  35395. */
  35396. function labelLayoutApplyTranslation(labelLayout, offset) {
  35397. if (!labelLayout) {
  35398. return;
  35399. }
  35400. labelLayout.label.x += offset.x;
  35401. labelLayout.label.y += offset.y;
  35402. labelLayout.label.markRedraw();
  35403. var transform = labelLayout.transform;
  35404. if (transform) {
  35405. transform[4] += offset.x;
  35406. transform[5] += offset.y;
  35407. }
  35408. var globalRect = labelLayout.rect;
  35409. if (globalRect) {
  35410. globalRect.x += offset.x;
  35411. globalRect.y += offset.y;
  35412. }
  35413. var obb = labelLayout.obb;
  35414. if (obb) {
  35415. obb.fromBoundingRect(labelLayout.localRect, transform);
  35416. }
  35417. }
  35418. /**
  35419. * To duplicate or make a variation of a label layout.
  35420. * Copy the only relevant properties to avoid the conflict or wrongly reuse of the props of `LabelLayoutWithGeometry`.
  35421. */
  35422. function newLabelLayoutWithGeometry(newBaseWithDefaults, source) {
  35423. for (var i = 0; i < LABEL_LAYOUT_BASE_PROPS.length; i++) {
  35424. var prop = LABEL_LAYOUT_BASE_PROPS[i];
  35425. if (newBaseWithDefaults[prop] == null) {
  35426. newBaseWithDefaults[prop] = source[prop];
  35427. }
  35428. }
  35429. return ensureLabelLayoutWithGeometry(newBaseWithDefaults);
  35430. }
  35431. /**
  35432. * Create obb if no one, can cache it.
  35433. */
  35434. function ensureOBB(labelGeometry) {
  35435. var obb = labelGeometry.obb;
  35436. if (!obb || isLabelLayoutDirty(labelGeometry, LABEL_LAYOUT_DIRTY_BIT_OBB)) {
  35437. labelGeometry.obb = obb = obb || new OrientedBoundingRect();
  35438. obb.fromBoundingRect(labelGeometry.localRect, labelGeometry.transform);
  35439. setLabelLayoutDirty(labelGeometry, false, LABEL_LAYOUT_DIRTY_BIT_OBB);
  35440. }
  35441. return obb;
  35442. }
  35443. /**
  35444. * Adjust labels on x/y direction to avoid overlap.
  35445. *
  35446. * PENDING: the current implementation is based on the global bounding rect rather than the local rect,
  35447. * which may be not preferable in some edge cases when the label has rotation, but works for most cases,
  35448. * since rotation is unnecessary when there is sufficient space, while squeezing is applied regardless
  35449. * of overlapping when there is no enough space.
  35450. *
  35451. * NOTICE:
  35452. * - The input `list` and its content will be modified (sort, label.x/y, rect).
  35453. * - The caller should sync the modifications to the other parts by
  35454. * `setLabelLayoutDirty` and `ensureLabelLayoutWithGeometry` if needed.
  35455. *
  35456. * @return adjusted
  35457. */
  35458. function shiftLayoutOnXY(list, xyDimIdx,
  35459. // 0 for x, 1 for y
  35460. minBound,
  35461. // for x, leftBound; for y, topBound
  35462. maxBound,
  35463. // for x, rightBound; for y, bottomBound
  35464. // If average the shifts on all labels and add them to 0
  35465. // TODO: Not sure if should enable it.
  35466. // Pros: The angle of lines will distribute more equally
  35467. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  35468. balanceShift) {
  35469. var len = list.length;
  35470. var xyDim = XY$1[xyDimIdx];
  35471. var sizeDim = WH$1[xyDimIdx];
  35472. if (len < 2) {
  35473. return false;
  35474. }
  35475. list.sort(function (a, b) {
  35476. return a.rect[xyDim] - b.rect[xyDim];
  35477. });
  35478. var lastPos = 0;
  35479. var delta;
  35480. var adjusted = false;
  35481. // const shifts = [];
  35482. var totalShifts = 0;
  35483. for (var i = 0; i < len; i++) {
  35484. var item = list[i];
  35485. var rect = item.rect;
  35486. delta = rect[xyDim] - lastPos;
  35487. if (delta < 0) {
  35488. // shiftForward(i, len, -delta);
  35489. rect[xyDim] -= delta;
  35490. item.label[xyDim] -= delta;
  35491. adjusted = true;
  35492. }
  35493. var shift = Math.max(-delta, 0);
  35494. // shifts.push(shift);
  35495. totalShifts += shift;
  35496. lastPos = rect[xyDim] + rect[sizeDim];
  35497. }
  35498. if (totalShifts > 0 && balanceShift) {
  35499. // Shift back to make the distribution more equally.
  35500. shiftList(-totalShifts / len, 0, len);
  35501. }
  35502. // TODO bleedMargin?
  35503. var first = list[0];
  35504. var last = list[len - 1];
  35505. var minGap;
  35506. var maxGap;
  35507. updateMinMaxGap();
  35508. // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  35509. minGap < 0 && squeezeGaps(-minGap, 0.8);
  35510. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  35511. updateMinMaxGap();
  35512. takeBoundsGap(minGap, maxGap, 1);
  35513. takeBoundsGap(maxGap, minGap, -1);
  35514. // Handle bailout when there is not enough space.
  35515. updateMinMaxGap();
  35516. if (minGap < 0) {
  35517. squeezeWhenBailout(-minGap);
  35518. }
  35519. if (maxGap < 0) {
  35520. squeezeWhenBailout(maxGap);
  35521. }
  35522. function updateMinMaxGap() {
  35523. minGap = first.rect[xyDim] - minBound;
  35524. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  35525. }
  35526. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  35527. if (gapThisBound < 0) {
  35528. // Move from other gap if can.
  35529. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  35530. if (moveFromMaxGap > 0) {
  35531. shiftList(moveFromMaxGap * moveDir, 0, len);
  35532. var remained = moveFromMaxGap + gapThisBound;
  35533. if (remained < 0) {
  35534. squeezeGaps(-remained * moveDir, 1);
  35535. }
  35536. } else {
  35537. squeezeGaps(-gapThisBound * moveDir, 1);
  35538. }
  35539. }
  35540. }
  35541. function shiftList(delta, start, end) {
  35542. if (delta !== 0) {
  35543. adjusted = true;
  35544. }
  35545. for (var i = start; i < end; i++) {
  35546. var item = list[i];
  35547. var rect = item.rect;
  35548. rect[xyDim] += delta;
  35549. item.label[xyDim] += delta;
  35550. }
  35551. }
  35552. // Squeeze gaps if the labels exceed margin.
  35553. function squeezeGaps(delta, maxSqeezePercent) {
  35554. var gaps = [];
  35555. var totalGaps = 0;
  35556. for (var i = 1; i < len; i++) {
  35557. var prevItemRect = list[i - 1].rect;
  35558. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  35559. gaps.push(gap);
  35560. totalGaps += gap;
  35561. }
  35562. if (!totalGaps) {
  35563. return;
  35564. }
  35565. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  35566. if (delta > 0) {
  35567. for (var i = 0; i < len - 1; i++) {
  35568. // Distribute the shift delta to all gaps.
  35569. var movement = gaps[i] * squeezePercent;
  35570. // Forward
  35571. shiftList(movement, 0, i + 1);
  35572. }
  35573. } else {
  35574. // Backward
  35575. for (var i = len - 1; i > 0; i--) {
  35576. // Distribute the shift delta to all gaps.
  35577. var movement = gaps[i - 1] * squeezePercent;
  35578. shiftList(-movement, i, len);
  35579. }
  35580. }
  35581. }
  35582. /**
  35583. * Squeeze to allow overlap if there is no more space available.
  35584. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  35585. */
  35586. function squeezeWhenBailout(delta) {
  35587. var dir = delta < 0 ? -1 : 1;
  35588. delta = Math.abs(delta);
  35589. var moveForEachLabel = Math.ceil(delta / (len - 1));
  35590. for (var i = 0; i < len - 1; i++) {
  35591. if (dir > 0) {
  35592. // Forward
  35593. shiftList(moveForEachLabel, 0, i + 1);
  35594. } else {
  35595. // Backward
  35596. shiftList(-moveForEachLabel, len - i - 1, len);
  35597. }
  35598. delta -= moveForEachLabel;
  35599. if (delta <= 0) {
  35600. return;
  35601. }
  35602. }
  35603. }
  35604. return adjusted;
  35605. }
  35606. /**
  35607. * [NOTICE - restore]:
  35608. * 'series:layoutlabels' may be triggered during some shortcut passes, such as zooming in series.graph/geo
  35609. * (`updateLabelLayout`), where the modified `Element` props should be restorable from `defaultAttr`.
  35610. * @see `SavedLabelAttr` in `LabelManager.ts`
  35611. * `restoreIgnore` can be called to perform the restore, if needed.
  35612. *
  35613. * [NOTICE - state]:
  35614. * Regarding Element's states, this method is only designed for the normal state.
  35615. * PENDING: although currently this method is effectively called in other states in `updateLabelLayout` case,
  35616. * the bad case is not noticeable in the zooming scenario.
  35617. */
  35618. function hideOverlap(labelList) {
  35619. var displayedLabels = [];
  35620. // TODO, render overflow visible first, put in the displayedLabels.
  35621. labelList.sort(function (a, b) {
  35622. return (b.suggestIgnore ? 1 : 0) - (a.suggestIgnore ? 1 : 0) || b.priority - a.priority;
  35623. });
  35624. function hideEl(el) {
  35625. if (!el.ignore) {
  35626. // Show on emphasis.
  35627. var emphasisState = el.ensureState('emphasis');
  35628. if (emphasisState.ignore == null) {
  35629. emphasisState.ignore = false;
  35630. }
  35631. }
  35632. el.ignore = true;
  35633. }
  35634. for (var i = 0; i < labelList.length; i++) {
  35635. var labelItem = ensureLabelLayoutWithGeometry(labelList[i]);
  35636. // The current `el.ignore` is involved, since some previous overlap
  35637. // resolving strategies may have set `el.ignore` to true.
  35638. if (labelItem.label.ignore) {
  35639. continue;
  35640. }
  35641. var label = labelItem.label;
  35642. var labelLine = labelItem.labelLine;
  35643. // NOTICE: even when the with/height of globalRect of a label is 0, the label line should
  35644. // still be displayed, since we should follow the concept of "truncation", meaning that
  35645. // something exists even if it cannot be fully displayed. A visible label line is necessary
  35646. // to allow users to get a tooltip with label info on hover.
  35647. var overlapped = false;
  35648. for (var j = 0; j < displayedLabels.length; j++) {
  35649. if (labelIntersect(labelItem, displayedLabels[j], null, {
  35650. touchThreshold: 0.05
  35651. })) {
  35652. overlapped = true;
  35653. break;
  35654. }
  35655. }
  35656. // TODO Callback to determine if this overlap should be handled?
  35657. if (overlapped) {
  35658. hideEl(label);
  35659. labelLine && hideEl(labelLine);
  35660. } else {
  35661. displayedLabels.push(labelItem);
  35662. }
  35663. }
  35664. }
  35665. /**
  35666. * Enable fast check for performance; use obb if inevitable.
  35667. * If `mtv` is used, `targetLayoutInfo` can be moved based on the values filled into `mtv`.
  35668. *
  35669. * This method is based only on the current `Element` states (regardless of other states).
  35670. * Typically this method (and the entire layout process) is performed in normal state.
  35671. */
  35672. function labelIntersect(baseLayoutInfo, targetLayoutInfo, mtv, intersectOpt) {
  35673. if (!baseLayoutInfo || !targetLayoutInfo) {
  35674. return false;
  35675. }
  35676. if (baseLayoutInfo.label && baseLayoutInfo.label.ignore || targetLayoutInfo.label && targetLayoutInfo.label.ignore) {
  35677. return false;
  35678. }
  35679. // Fast rejection.
  35680. if (!baseLayoutInfo.rect.intersect(targetLayoutInfo.rect, mtv, intersectOpt)) {
  35681. return false;
  35682. }
  35683. if (baseLayoutInfo.axisAligned && targetLayoutInfo.axisAligned) {
  35684. return true; // obb is the same as the normal bounding rect.
  35685. }
  35686. return ensureOBB(baseLayoutInfo).intersect(ensureOBB(targetLayoutInfo), mtv, intersectOpt);
  35687. }
  35688. var mathSin$4 = Math.sin;
  35689. var mathCos$4 = Math.cos;
  35690. var PI$4 = Math.PI;
  35691. var PI2$6 = Math.PI * 2;
  35692. var degree = 180 / PI$4;
  35693. var SVGPathRebuilder = (function () {
  35694. function SVGPathRebuilder() {
  35695. }
  35696. SVGPathRebuilder.prototype.reset = function (precision) {
  35697. this._start = true;
  35698. this._d = [];
  35699. this._str = '';
  35700. this._p = Math.pow(10, precision || 4);
  35701. };
  35702. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  35703. this._add('M', x, y);
  35704. };
  35705. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  35706. this._add('L', x, y);
  35707. };
  35708. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  35709. this._add('C', x, y, x2, y2, x3, y3);
  35710. };
  35711. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  35712. this._add('Q', x, y, x2, y2);
  35713. };
  35714. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  35715. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  35716. };
  35717. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  35718. var dTheta = endAngle - startAngle;
  35719. var clockwise = !anticlockwise;
  35720. var dThetaPositive = Math.abs(dTheta);
  35721. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  35722. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  35723. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  35724. var large = false;
  35725. if (isCircle) {
  35726. large = true;
  35727. }
  35728. else if (isAroundZero$1(dThetaPositive)) {
  35729. large = false;
  35730. }
  35731. else {
  35732. large = (unifiedTheta >= PI$4) === !!clockwise;
  35733. }
  35734. var x0 = cx + rx * mathCos$4(startAngle);
  35735. var y0 = cy + ry * mathSin$4(startAngle);
  35736. if (this._start) {
  35737. this._add('M', x0, y0);
  35738. }
  35739. var xRot = Math.round(psi * degree);
  35740. if (isCircle) {
  35741. var p = 1 / this._p;
  35742. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$6 - p);
  35743. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  35744. if (p > 1e-2) {
  35745. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  35746. }
  35747. }
  35748. else {
  35749. var x = cx + rx * mathCos$4(endAngle);
  35750. var y = cy + ry * mathSin$4(endAngle);
  35751. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  35752. }
  35753. };
  35754. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  35755. this._add('M', x, y);
  35756. this._add('l', w, 0);
  35757. this._add('l', 0, h);
  35758. this._add('l', -w, 0);
  35759. this._add('Z');
  35760. };
  35761. SVGPathRebuilder.prototype.closePath = function () {
  35762. if (this._d.length > 0) {
  35763. this._add('Z');
  35764. }
  35765. };
  35766. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  35767. var vals = [];
  35768. var p = this._p;
  35769. for (var i = 1; i < arguments.length; i++) {
  35770. var val = arguments[i];
  35771. if (isNaN(val)) {
  35772. this._invalid = true;
  35773. return;
  35774. }
  35775. vals.push(Math.round(val * p) / p);
  35776. }
  35777. this._d.push(cmd + vals.join(' '));
  35778. this._start = cmd === 'Z';
  35779. };
  35780. SVGPathRebuilder.prototype.generateStr = function () {
  35781. this._str = this._invalid ? '' : this._d.join('');
  35782. this._d = [];
  35783. };
  35784. SVGPathRebuilder.prototype.getStr = function () {
  35785. return this._str;
  35786. };
  35787. return SVGPathRebuilder;
  35788. }());
  35789. var NONE = 'none';
  35790. var mathRound$1 = Math.round;
  35791. function pathHasFill(style) {
  35792. var fill = style.fill;
  35793. return fill != null && fill !== NONE;
  35794. }
  35795. function pathHasStroke(style) {
  35796. var stroke = style.stroke;
  35797. return stroke != null && stroke !== NONE;
  35798. }
  35799. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  35800. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  35801. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  35802. var opacity = style.opacity == null ? 1 : style.opacity;
  35803. if (el instanceof ZRImage) {
  35804. updateAttr('opacity', opacity);
  35805. return;
  35806. }
  35807. if (pathHasFill(style)) {
  35808. var fill = normalizeColor(style.fill);
  35809. updateAttr('fill', fill.color);
  35810. var fillOpacity = style.fillOpacity != null
  35811. ? style.fillOpacity * fill.opacity * opacity
  35812. : fill.opacity * opacity;
  35813. if (forceUpdate || fillOpacity < 1) {
  35814. updateAttr('fill-opacity', fillOpacity);
  35815. }
  35816. }
  35817. else {
  35818. updateAttr('fill', NONE);
  35819. }
  35820. if (pathHasStroke(style)) {
  35821. var stroke = normalizeColor(style.stroke);
  35822. updateAttr('stroke', stroke.color);
  35823. var strokeScale = style.strokeNoScale
  35824. ? el.getLineScale()
  35825. : 1;
  35826. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  35827. var strokeOpacity = style.strokeOpacity != null
  35828. ? style.strokeOpacity * stroke.opacity * opacity
  35829. : stroke.opacity * opacity;
  35830. var strokeFirst = style.strokeFirst;
  35831. if (forceUpdate || strokeWidth !== 1) {
  35832. updateAttr('stroke-width', strokeWidth);
  35833. }
  35834. if (forceUpdate || strokeFirst) {
  35835. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  35836. }
  35837. if (forceUpdate || strokeOpacity < 1) {
  35838. updateAttr('stroke-opacity', strokeOpacity);
  35839. }
  35840. if (style.lineDash) {
  35841. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  35842. if (lineDash) {
  35843. lineDashOffset = mathRound$1(lineDashOffset || 0);
  35844. updateAttr('stroke-dasharray', lineDash.join(','));
  35845. if (lineDashOffset || forceUpdate) {
  35846. updateAttr('stroke-dashoffset', lineDashOffset);
  35847. }
  35848. }
  35849. }
  35850. else if (forceUpdate) {
  35851. updateAttr('stroke-dasharray', NONE);
  35852. }
  35853. for (var i = 0; i < strokeProps.length; i++) {
  35854. var propName = strokeProps[i];
  35855. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  35856. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  35857. val && updateAttr(svgStrokeProps[i], val);
  35858. }
  35859. }
  35860. }
  35861. else if (forceUpdate) {
  35862. updateAttr('stroke', NONE);
  35863. }
  35864. }
  35865. var SVGNS = 'http://www.w3.org/2000/svg';
  35866. var XLINKNS = 'http://www.w3.org/1999/xlink';
  35867. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  35868. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  35869. var META_DATA_PREFIX = 'ecmeta_';
  35870. function createElement(name) {
  35871. return document.createElementNS(SVGNS, name);
  35872. }
  35873. function createVNode(tag, key, attrs, children, text) {
  35874. return {
  35875. tag: tag,
  35876. attrs: attrs || {},
  35877. children: children,
  35878. text: text,
  35879. key: key
  35880. };
  35881. }
  35882. function createElementOpen(name, attrs) {
  35883. var attrsStr = [];
  35884. if (attrs) {
  35885. for (var key in attrs) {
  35886. var val = attrs[key];
  35887. var part = key;
  35888. if (val === false) {
  35889. continue;
  35890. }
  35891. else if (val !== true && val != null) {
  35892. part += "=\"" + val + "\"";
  35893. }
  35894. attrsStr.push(part);
  35895. }
  35896. }
  35897. return "<" + name + " " + attrsStr.join(' ') + ">";
  35898. }
  35899. function createElementClose(name) {
  35900. return "</" + name + ">";
  35901. }
  35902. function vNodeToString(el, opts) {
  35903. opts = opts || {};
  35904. var S = opts.newline ? '\n' : '';
  35905. function convertElToString(el) {
  35906. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  35907. return createElementOpen(tag, attrs)
  35908. + (tag !== 'style' ? encodeHTML(text) : text || '')
  35909. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  35910. + createElementClose(tag);
  35911. }
  35912. return convertElToString(el);
  35913. }
  35914. function getCssString(selectorNodes, animationNodes, opts) {
  35915. opts = opts || {};
  35916. var S = opts.newline ? '\n' : '';
  35917. var bracketBegin = " {" + S;
  35918. var bracketEnd = S + "}";
  35919. var selectors = map(keys(selectorNodes), function (className) {
  35920. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  35921. return attrName + ":" + selectorNodes[className][attrName] + ";";
  35922. }).join(S) + bracketEnd;
  35923. }).join(S);
  35924. var animations = map(keys(animationNodes), function (animationName) {
  35925. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  35926. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  35927. var val = animationNodes[animationName][percent][attrName];
  35928. if (attrName === 'd') {
  35929. val = "path(\"" + val + "\")";
  35930. }
  35931. return attrName + ":" + val + ";";
  35932. }).join(S) + bracketEnd;
  35933. }).join(S) + bracketEnd;
  35934. }).join(S);
  35935. if (!selectors && !animations) {
  35936. return '';
  35937. }
  35938. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  35939. }
  35940. function createBrushScope(zrId) {
  35941. return {
  35942. zrId: zrId,
  35943. shadowCache: {},
  35944. patternCache: {},
  35945. gradientCache: {},
  35946. clipPathCache: {},
  35947. defs: {},
  35948. cssNodes: {},
  35949. cssAnims: {},
  35950. cssStyleCache: {},
  35951. cssAnimIdx: 0,
  35952. shadowIdx: 0,
  35953. gradientIdx: 0,
  35954. patternIdx: 0,
  35955. clipPathIdx: 0
  35956. };
  35957. }
  35958. function createSVGVNode(width, height, children, useViewBox) {
  35959. return createVNode('svg', 'root', {
  35960. 'width': width,
  35961. 'height': height,
  35962. 'xmlns': SVGNS,
  35963. 'xmlns:xlink': XLINKNS,
  35964. 'version': '1.1',
  35965. 'baseProfile': 'full',
  35966. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  35967. }, children);
  35968. }
  35969. var cssClassIdx = 0;
  35970. function getClassId() {
  35971. return cssClassIdx++;
  35972. }
  35973. var EASING_MAP = {
  35974. cubicIn: '0.32,0,0.67,0',
  35975. cubicOut: '0.33,1,0.68,1',
  35976. cubicInOut: '0.65,0,0.35,1',
  35977. quadraticIn: '0.11,0,0.5,0',
  35978. quadraticOut: '0.5,1,0.89,1',
  35979. quadraticInOut: '0.45,0,0.55,1',
  35980. quarticIn: '0.5,0,0.75,0',
  35981. quarticOut: '0.25,1,0.5,1',
  35982. quarticInOut: '0.76,0,0.24,1',
  35983. quinticIn: '0.64,0,0.78,0',
  35984. quinticOut: '0.22,1,0.36,1',
  35985. quinticInOut: '0.83,0,0.17,1',
  35986. sinusoidalIn: '0.12,0,0.39,0',
  35987. sinusoidalOut: '0.61,1,0.88,1',
  35988. sinusoidalInOut: '0.37,0,0.63,1',
  35989. exponentialIn: '0.7,0,0.84,0',
  35990. exponentialOut: '0.16,1,0.3,1',
  35991. exponentialInOut: '0.87,0,0.13,1',
  35992. circularIn: '0.55,0,1,0.45',
  35993. circularOut: '0,0.55,0.45,1',
  35994. circularInOut: '0.85,0,0.15,1'
  35995. };
  35996. var transformOriginKey = 'transform-origin';
  35997. function buildPathString(el, kfShape, path) {
  35998. var shape = extend({}, el.shape);
  35999. extend(shape, kfShape);
  36000. el.buildPath(path, shape);
  36001. var svgPathBuilder = new SVGPathRebuilder();
  36002. svgPathBuilder.reset(getPathPrecision(el));
  36003. path.rebuildPath(svgPathBuilder, 1);
  36004. svgPathBuilder.generateStr();
  36005. return svgPathBuilder.getStr();
  36006. }
  36007. function setTransformOrigin(target, transform) {
  36008. var originX = transform.originX, originY = transform.originY;
  36009. if (originX || originY) {
  36010. target[transformOriginKey] = originX + "px " + originY + "px";
  36011. }
  36012. }
  36013. var ANIMATE_STYLE_MAP = {
  36014. fill: 'fill',
  36015. opacity: 'opacity',
  36016. lineWidth: 'stroke-width',
  36017. lineDashOffset: 'stroke-dashoffset'
  36018. };
  36019. function addAnimation(cssAnim, scope) {
  36020. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  36021. scope.cssAnims[animationName] = cssAnim;
  36022. return animationName;
  36023. }
  36024. function createCompoundPathCSSAnimation(el, attrs, scope) {
  36025. var paths = el.shape.paths;
  36026. var composedAnim = {};
  36027. var cssAnimationCfg;
  36028. var cssAnimationName;
  36029. each(paths, function (path) {
  36030. var subScope = createBrushScope(scope.zrId);
  36031. subScope.animation = true;
  36032. createCSSAnimation(path, {}, subScope, true);
  36033. var cssAnims = subScope.cssAnims;
  36034. var cssNodes = subScope.cssNodes;
  36035. var animNames = keys(cssAnims);
  36036. var len = animNames.length;
  36037. if (!len) {
  36038. return;
  36039. }
  36040. cssAnimationName = animNames[len - 1];
  36041. var lastAnim = cssAnims[cssAnimationName];
  36042. for (var percent in lastAnim) {
  36043. var kf = lastAnim[percent];
  36044. composedAnim[percent] = composedAnim[percent] || { d: '' };
  36045. composedAnim[percent].d += kf.d || '';
  36046. }
  36047. for (var className in cssNodes) {
  36048. var val = cssNodes[className].animation;
  36049. if (val.indexOf(cssAnimationName) >= 0) {
  36050. cssAnimationCfg = val;
  36051. }
  36052. }
  36053. });
  36054. if (!cssAnimationCfg) {
  36055. return;
  36056. }
  36057. attrs.d = false;
  36058. var animationName = addAnimation(composedAnim, scope);
  36059. return cssAnimationCfg.replace(cssAnimationName, animationName);
  36060. }
  36061. function getEasingFunc(easing) {
  36062. return isString(easing)
  36063. ? EASING_MAP[easing]
  36064. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  36065. : createCubicEasingFunc(easing) ? easing : ''
  36066. : '';
  36067. }
  36068. function createCSSAnimation(el, attrs, scope, onlyShape) {
  36069. var animators = el.animators;
  36070. var len = animators.length;
  36071. var cssAnimations = [];
  36072. if (el instanceof CompoundPath) {
  36073. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  36074. if (animationCfg) {
  36075. cssAnimations.push(animationCfg);
  36076. }
  36077. else if (!len) {
  36078. return;
  36079. }
  36080. }
  36081. else if (!len) {
  36082. return;
  36083. }
  36084. var groupAnimators = {};
  36085. for (var i = 0; i < len; i++) {
  36086. var animator = animators[i];
  36087. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  36088. var easing = getEasingFunc(animator.getClip().easing);
  36089. var delay = animator.getDelay();
  36090. if (easing) {
  36091. cfgArr.push(easing);
  36092. }
  36093. else {
  36094. cfgArr.push('linear');
  36095. }
  36096. if (delay) {
  36097. cfgArr.push(delay / 1000 + 's');
  36098. }
  36099. if (animator.getLoop()) {
  36100. cfgArr.push('infinite');
  36101. }
  36102. var cfg = cfgArr.join(' ');
  36103. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  36104. groupAnimators[cfg][1].push(animator);
  36105. }
  36106. function createSingleCSSAnimation(groupAnimator) {
  36107. var animators = groupAnimator[1];
  36108. var len = animators.length;
  36109. var transformKfs = {};
  36110. var shapeKfs = {};
  36111. var finalKfs = {};
  36112. var animationTimingFunctionAttrName = 'animation-timing-function';
  36113. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  36114. var tracks = animator.getTracks();
  36115. var maxTime = animator.getMaxTime();
  36116. for (var k = 0; k < tracks.length; k++) {
  36117. var track = tracks[k];
  36118. if (track.needsAnimate()) {
  36119. var kfs = track.keyframes;
  36120. var attrName = track.propName;
  36121. toCssAttrName && (attrName = toCssAttrName(attrName));
  36122. if (attrName) {
  36123. for (var i = 0; i < kfs.length; i++) {
  36124. var kf = kfs[i];
  36125. var percent = Math.round(kf.time / maxTime * 100) + '%';
  36126. var kfEasing = getEasingFunc(kf.easing);
  36127. var rawValue = kf.rawValue;
  36128. if (isString(rawValue) || isNumber(rawValue)) {
  36129. cssKfs[percent] = cssKfs[percent] || {};
  36130. cssKfs[percent][attrName] = kf.rawValue;
  36131. if (kfEasing) {
  36132. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  36133. }
  36134. }
  36135. }
  36136. }
  36137. }
  36138. }
  36139. }
  36140. for (var i = 0; i < len; i++) {
  36141. var animator = animators[i];
  36142. var targetProp = animator.targetName;
  36143. if (!targetProp) {
  36144. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  36145. }
  36146. else if (targetProp === 'shape') {
  36147. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  36148. }
  36149. }
  36150. for (var percent in transformKfs) {
  36151. var transform = {};
  36152. copyTransform(transform, el);
  36153. extend(transform, transformKfs[percent]);
  36154. var str = getSRTTransformString(transform);
  36155. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  36156. finalKfs[percent] = str ? {
  36157. transform: str
  36158. } : {};
  36159. setTransformOrigin(finalKfs[percent], transform);
  36160. if (timingFunction) {
  36161. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  36162. }
  36163. }
  36164. var path;
  36165. var canAnimateShape = true;
  36166. for (var percent in shapeKfs) {
  36167. finalKfs[percent] = finalKfs[percent] || {};
  36168. var isFirst = !path;
  36169. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  36170. if (isFirst) {
  36171. path = new PathProxy();
  36172. }
  36173. var len_1 = path.len();
  36174. path.reset();
  36175. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  36176. var newLen = path.len();
  36177. if (!isFirst && len_1 !== newLen) {
  36178. canAnimateShape = false;
  36179. break;
  36180. }
  36181. if (timingFunction) {
  36182. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  36183. }
  36184. }
  36185. if (!canAnimateShape) {
  36186. for (var percent in finalKfs) {
  36187. delete finalKfs[percent].d;
  36188. }
  36189. }
  36190. if (!onlyShape) {
  36191. for (var i = 0; i < len; i++) {
  36192. var animator = animators[i];
  36193. var targetProp = animator.targetName;
  36194. if (targetProp === 'style') {
  36195. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  36196. }
  36197. }
  36198. }
  36199. var percents = keys(finalKfs);
  36200. var allTransformOriginSame = true;
  36201. var transformOrigin;
  36202. for (var i = 1; i < percents.length; i++) {
  36203. var p0 = percents[i - 1];
  36204. var p1 = percents[i];
  36205. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  36206. allTransformOriginSame = false;
  36207. break;
  36208. }
  36209. transformOrigin = finalKfs[p0][transformOriginKey];
  36210. }
  36211. if (allTransformOriginSame && transformOrigin) {
  36212. for (var percent in finalKfs) {
  36213. if (finalKfs[percent][transformOriginKey]) {
  36214. delete finalKfs[percent][transformOriginKey];
  36215. }
  36216. }
  36217. attrs[transformOriginKey] = transformOrigin;
  36218. }
  36219. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  36220. var animationName = addAnimation(finalKfs, scope);
  36221. return animationName + " " + groupAnimator[0] + " both";
  36222. }
  36223. }
  36224. for (var key in groupAnimators) {
  36225. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  36226. if (animationCfg) {
  36227. cssAnimations.push(animationCfg);
  36228. }
  36229. }
  36230. if (cssAnimations.length) {
  36231. var className = scope.zrId + '-cls-' + getClassId();
  36232. scope.cssNodes['.' + className] = {
  36233. animation: cssAnimations.join(',')
  36234. };
  36235. attrs["class"] = className;
  36236. }
  36237. }
  36238. function createCSSEmphasis(el, attrs, scope) {
  36239. if (!el.ignore) {
  36240. if (el.isSilent()) {
  36241. var style = {
  36242. 'pointer-events': 'none'
  36243. };
  36244. setClassAttribute(style, attrs, scope, true);
  36245. }
  36246. else {
  36247. var emphasisStyle = el.states.emphasis && el.states.emphasis.style
  36248. ? el.states.emphasis.style
  36249. : {};
  36250. var fill = emphasisStyle.fill;
  36251. if (!fill) {
  36252. var normalFill = el.style && el.style.fill;
  36253. var selectFill = el.states.select
  36254. && el.states.select.style
  36255. && el.states.select.style.fill;
  36256. var fromFill = el.currentStates.indexOf('select') >= 0
  36257. ? (selectFill || normalFill)
  36258. : normalFill;
  36259. if (fromFill) {
  36260. fill = liftColor(fromFill);
  36261. }
  36262. }
  36263. var lineWidth = emphasisStyle.lineWidth;
  36264. if (lineWidth) {
  36265. var scaleX = (!emphasisStyle.strokeNoScale && el.transform)
  36266. ? el.transform[0]
  36267. : 1;
  36268. lineWidth = lineWidth / scaleX;
  36269. }
  36270. var style = {
  36271. cursor: 'pointer'
  36272. };
  36273. if (fill) {
  36274. style.fill = fill;
  36275. }
  36276. if (emphasisStyle.stroke) {
  36277. style.stroke = emphasisStyle.stroke;
  36278. }
  36279. if (lineWidth) {
  36280. style['stroke-width'] = lineWidth;
  36281. }
  36282. setClassAttribute(style, attrs, scope, true);
  36283. }
  36284. }
  36285. }
  36286. function setClassAttribute(style, attrs, scope, withHover) {
  36287. var styleKey = JSON.stringify(style);
  36288. var className = scope.cssStyleCache[styleKey];
  36289. if (!className) {
  36290. className = scope.zrId + '-cls-' + getClassId();
  36291. scope.cssStyleCache[styleKey] = className;
  36292. scope.cssNodes['.' + className + (withHover ? ':hover' : '')] = style;
  36293. }
  36294. attrs["class"] = attrs["class"] ? (attrs["class"] + ' ' + className) : className;
  36295. }
  36296. var round$2 = Math.round;
  36297. function isImageLike$1(val) {
  36298. return val && isString(val.src);
  36299. }
  36300. function isCanvasLike(val) {
  36301. return val && isFunction(val.toDataURL);
  36302. }
  36303. function setStyleAttrs(attrs, style, el, scope) {
  36304. mapStyleToAttrs(function (key, val) {
  36305. var isFillStroke = key === 'fill' || key === 'stroke';
  36306. if (isFillStroke && isGradient(val)) {
  36307. setGradient(style, attrs, key, scope);
  36308. }
  36309. else if (isFillStroke && isPattern(val)) {
  36310. setPattern(el, attrs, key, scope);
  36311. }
  36312. else {
  36313. attrs[key] = val;
  36314. }
  36315. if (isFillStroke && scope.ssr && val === 'none') {
  36316. attrs['pointer-events'] = 'visible';
  36317. }
  36318. }, style, el, false);
  36319. setShadow(el, attrs, scope);
  36320. }
  36321. function setMetaData(attrs, el) {
  36322. var metaData = getElementSSRData(el);
  36323. if (metaData) {
  36324. metaData.each(function (val, key) {
  36325. val != null && (attrs[(META_DATA_PREFIX + key).toLowerCase()] = val + '');
  36326. });
  36327. if (el.isSilent()) {
  36328. attrs[META_DATA_PREFIX + 'silent'] = 'true';
  36329. }
  36330. }
  36331. }
  36332. function noRotateScale(m) {
  36333. return isAroundZero$1(m[0] - 1)
  36334. && isAroundZero$1(m[1])
  36335. && isAroundZero$1(m[2])
  36336. && isAroundZero$1(m[3] - 1);
  36337. }
  36338. function noTranslate(m) {
  36339. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  36340. }
  36341. function setTransform(attrs, m, compress) {
  36342. if (m && !(noTranslate(m) && noRotateScale(m))) {
  36343. var mul = compress ? 10 : 1e4;
  36344. attrs.transform = noRotateScale(m)
  36345. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  36346. }
  36347. }
  36348. function convertPolyShape(shape, attrs, mul) {
  36349. var points = shape.points;
  36350. var strArr = [];
  36351. for (var i = 0; i < points.length; i++) {
  36352. strArr.push(round$2(points[i][0] * mul) / mul);
  36353. strArr.push(round$2(points[i][1] * mul) / mul);
  36354. }
  36355. attrs.points = strArr.join(' ');
  36356. }
  36357. function validatePolyShape(shape) {
  36358. return !shape.smooth;
  36359. }
  36360. function createAttrsConvert(desc) {
  36361. var normalizedDesc = map(desc, function (item) {
  36362. return (typeof item === 'string' ? [item, item] : item);
  36363. });
  36364. return function (shape, attrs, mul) {
  36365. for (var i = 0; i < normalizedDesc.length; i++) {
  36366. var item = normalizedDesc[i];
  36367. var val = shape[item[0]];
  36368. if (val != null) {
  36369. attrs[item[1]] = round$2(val * mul) / mul;
  36370. }
  36371. }
  36372. };
  36373. }
  36374. var builtinShapesDef = {
  36375. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  36376. polyline: [convertPolyShape, validatePolyShape],
  36377. polygon: [convertPolyShape, validatePolyShape]
  36378. };
  36379. function hasShapeAnimation(el) {
  36380. var animators = el.animators;
  36381. for (var i = 0; i < animators.length; i++) {
  36382. if (animators[i].targetName === 'shape') {
  36383. return true;
  36384. }
  36385. }
  36386. return false;
  36387. }
  36388. function brushSVGPath(el, scope) {
  36389. var style = el.style;
  36390. var shape = el.shape;
  36391. var builtinShpDef = builtinShapesDef[el.type];
  36392. var attrs = {};
  36393. var needsAnimate = scope.animation;
  36394. var svgElType = 'path';
  36395. var strokePercent = el.style.strokePercent;
  36396. var precision = (scope.compress && getPathPrecision(el)) || 4;
  36397. if (builtinShpDef
  36398. && !scope.willUpdate
  36399. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  36400. && !(needsAnimate && hasShapeAnimation(el))
  36401. && !(strokePercent < 1)) {
  36402. svgElType = el.type;
  36403. var mul = Math.pow(10, precision);
  36404. builtinShpDef[0](shape, attrs, mul);
  36405. }
  36406. else {
  36407. var needBuildPath = !el.path || el.shapeChanged();
  36408. if (!el.path) {
  36409. el.createPathProxy();
  36410. }
  36411. var path = el.path;
  36412. if (needBuildPath) {
  36413. path.beginPath();
  36414. el.buildPath(path, el.shape);
  36415. el.pathUpdated();
  36416. }
  36417. var pathVersion = path.getVersion();
  36418. var elExt = el;
  36419. var svgPathBuilder = elExt.__svgPathBuilder;
  36420. if (elExt.__svgPathVersion !== pathVersion
  36421. || !svgPathBuilder
  36422. || strokePercent !== elExt.__svgPathStrokePercent) {
  36423. if (!svgPathBuilder) {
  36424. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  36425. }
  36426. svgPathBuilder.reset(precision);
  36427. path.rebuildPath(svgPathBuilder, strokePercent);
  36428. svgPathBuilder.generateStr();
  36429. elExt.__svgPathVersion = pathVersion;
  36430. elExt.__svgPathStrokePercent = strokePercent;
  36431. }
  36432. attrs.d = svgPathBuilder.getStr();
  36433. }
  36434. setTransform(attrs, el.transform);
  36435. setStyleAttrs(attrs, style, el, scope);
  36436. setMetaData(attrs, el);
  36437. scope.animation && createCSSAnimation(el, attrs, scope);
  36438. scope.emphasis && createCSSEmphasis(el, attrs, scope);
  36439. return createVNode(svgElType, el.id + '', attrs);
  36440. }
  36441. function brushSVGImage(el, scope) {
  36442. var style = el.style;
  36443. var image = style.image;
  36444. if (image && !isString(image)) {
  36445. if (isImageLike$1(image)) {
  36446. image = image.src;
  36447. }
  36448. else if (isCanvasLike(image)) {
  36449. image = image.toDataURL();
  36450. }
  36451. }
  36452. if (!image) {
  36453. return;
  36454. }
  36455. var x = style.x || 0;
  36456. var y = style.y || 0;
  36457. var dw = style.width;
  36458. var dh = style.height;
  36459. var attrs = {
  36460. href: image,
  36461. width: dw,
  36462. height: dh
  36463. };
  36464. if (x) {
  36465. attrs.x = x;
  36466. }
  36467. if (y) {
  36468. attrs.y = y;
  36469. }
  36470. setTransform(attrs, el.transform);
  36471. setStyleAttrs(attrs, style, el, scope);
  36472. setMetaData(attrs, el);
  36473. scope.animation && createCSSAnimation(el, attrs, scope);
  36474. return createVNode('image', el.id + '', attrs);
  36475. }
  36476. function brushSVGTSpan(el, scope) {
  36477. var style = el.style;
  36478. var text = style.text;
  36479. text != null && (text += '');
  36480. if (!text || isNaN(style.x) || isNaN(style.y)) {
  36481. return;
  36482. }
  36483. var font = style.font || DEFAULT_FONT;
  36484. var x = style.x || 0;
  36485. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  36486. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  36487. || style.textAlign;
  36488. var attrs = {
  36489. 'dominant-baseline': 'central',
  36490. 'text-anchor': textAlign
  36491. };
  36492. if (hasSeparateFont(style)) {
  36493. var separatedFontStr = '';
  36494. var fontStyle = style.fontStyle;
  36495. var fontSize = parseFontSize(style.fontSize);
  36496. if (!parseFloat(fontSize)) {
  36497. return;
  36498. }
  36499. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  36500. var fontWeight = style.fontWeight;
  36501. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  36502. if (fontStyle && fontStyle !== 'normal') {
  36503. separatedFontStr += "font-style:" + fontStyle + ";";
  36504. }
  36505. if (fontWeight && fontWeight !== 'normal') {
  36506. separatedFontStr += "font-weight:" + fontWeight + ";";
  36507. }
  36508. attrs.style = separatedFontStr;
  36509. }
  36510. else {
  36511. attrs.style = "font: " + font;
  36512. }
  36513. if (text.match(/\s/)) {
  36514. attrs['xml:space'] = 'preserve';
  36515. }
  36516. if (x) {
  36517. attrs.x = x;
  36518. }
  36519. if (y) {
  36520. attrs.y = y;
  36521. }
  36522. setTransform(attrs, el.transform);
  36523. setStyleAttrs(attrs, style, el, scope);
  36524. setMetaData(attrs, el);
  36525. scope.animation && createCSSAnimation(el, attrs, scope);
  36526. return createVNode('text', el.id + '', attrs, undefined, text);
  36527. }
  36528. function brush$1(el, scope) {
  36529. if (el instanceof Path) {
  36530. return brushSVGPath(el, scope);
  36531. }
  36532. else if (el instanceof ZRImage) {
  36533. return brushSVGImage(el, scope);
  36534. }
  36535. else if (el instanceof TSpan) {
  36536. return brushSVGTSpan(el, scope);
  36537. }
  36538. }
  36539. function setShadow(el, attrs, scope) {
  36540. var style = el.style;
  36541. if (hasShadow(style)) {
  36542. var shadowKey = getShadowKey(el);
  36543. var shadowCache = scope.shadowCache;
  36544. var shadowId = shadowCache[shadowKey];
  36545. if (!shadowId) {
  36546. var globalScale = el.getGlobalScale();
  36547. var scaleX = globalScale[0];
  36548. var scaleY = globalScale[1];
  36549. if (!scaleX || !scaleY) {
  36550. return;
  36551. }
  36552. var offsetX = style.shadowOffsetX || 0;
  36553. var offsetY = style.shadowOffsetY || 0;
  36554. var blur_1 = style.shadowBlur;
  36555. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  36556. var stdDx = blur_1 / 2 / scaleX;
  36557. var stdDy = blur_1 / 2 / scaleY;
  36558. var stdDeviation = stdDx + ' ' + stdDy;
  36559. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  36560. scope.defs[shadowId] = createVNode('filter', shadowId, {
  36561. 'id': shadowId,
  36562. 'x': '-100%',
  36563. 'y': '-100%',
  36564. 'width': '300%',
  36565. 'height': '300%'
  36566. }, [
  36567. createVNode('feDropShadow', '', {
  36568. 'dx': offsetX / scaleX,
  36569. 'dy': offsetY / scaleY,
  36570. 'stdDeviation': stdDeviation,
  36571. 'flood-color': color,
  36572. 'flood-opacity': opacity
  36573. })
  36574. ]);
  36575. shadowCache[shadowKey] = shadowId;
  36576. }
  36577. attrs.filter = getIdURL(shadowId);
  36578. }
  36579. }
  36580. function setGradient(style, attrs, target, scope) {
  36581. var val = style[target];
  36582. var gradientTag;
  36583. var gradientAttrs = {
  36584. 'gradientUnits': val.global
  36585. ? 'userSpaceOnUse'
  36586. : 'objectBoundingBox'
  36587. };
  36588. if (isLinearGradient(val)) {
  36589. gradientTag = 'linearGradient';
  36590. gradientAttrs.x1 = val.x;
  36591. gradientAttrs.y1 = val.y;
  36592. gradientAttrs.x2 = val.x2;
  36593. gradientAttrs.y2 = val.y2;
  36594. }
  36595. else if (isRadialGradient(val)) {
  36596. gradientTag = 'radialGradient';
  36597. gradientAttrs.cx = retrieve2(val.x, 0.5);
  36598. gradientAttrs.cy = retrieve2(val.y, 0.5);
  36599. gradientAttrs.r = retrieve2(val.r, 0.5);
  36600. }
  36601. else {
  36602. if ("development" !== 'production') {
  36603. logError('Illegal gradient type.');
  36604. }
  36605. return;
  36606. }
  36607. var colors = val.colorStops;
  36608. var colorStops = [];
  36609. for (var i = 0, len = colors.length; i < len; ++i) {
  36610. var offset = round4(colors[i].offset) * 100 + '%';
  36611. var stopColor = colors[i].color;
  36612. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  36613. var stopsAttrs = {
  36614. 'offset': offset
  36615. };
  36616. stopsAttrs['stop-color'] = color;
  36617. if (opacity < 1) {
  36618. stopsAttrs['stop-opacity'] = opacity;
  36619. }
  36620. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  36621. }
  36622. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  36623. var gradientKey = vNodeToString(gradientVNode);
  36624. var gradientCache = scope.gradientCache;
  36625. var gradientId = gradientCache[gradientKey];
  36626. if (!gradientId) {
  36627. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  36628. gradientCache[gradientKey] = gradientId;
  36629. gradientAttrs.id = gradientId;
  36630. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  36631. }
  36632. attrs[target] = getIdURL(gradientId);
  36633. }
  36634. function setPattern(el, attrs, target, scope) {
  36635. var val = el.style[target];
  36636. var boundingRect = el.getBoundingRect();
  36637. var patternAttrs = {};
  36638. var repeat = val.repeat;
  36639. var noRepeat = repeat === 'no-repeat';
  36640. var repeatX = repeat === 'repeat-x';
  36641. var repeatY = repeat === 'repeat-y';
  36642. var child;
  36643. if (isImagePattern(val)) {
  36644. var imageWidth_1 = val.imageWidth;
  36645. var imageHeight_1 = val.imageHeight;
  36646. var imageSrc = void 0;
  36647. var patternImage = val.image;
  36648. if (isString(patternImage)) {
  36649. imageSrc = patternImage;
  36650. }
  36651. else if (isImageLike$1(patternImage)) {
  36652. imageSrc = patternImage.src;
  36653. }
  36654. else if (isCanvasLike(patternImage)) {
  36655. imageSrc = patternImage.toDataURL();
  36656. }
  36657. if (typeof Image === 'undefined') {
  36658. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  36659. assert(imageWidth_1, errMsg);
  36660. assert(imageHeight_1, errMsg);
  36661. }
  36662. else if (imageWidth_1 == null || imageHeight_1 == null) {
  36663. var setSizeToVNode_1 = function (vNode, img) {
  36664. if (vNode) {
  36665. var svgEl = vNode.elm;
  36666. var width = imageWidth_1 || img.width;
  36667. var height = imageHeight_1 || img.height;
  36668. if (vNode.tag === 'pattern') {
  36669. if (repeatX) {
  36670. height = 1;
  36671. width /= boundingRect.width;
  36672. }
  36673. else if (repeatY) {
  36674. width = 1;
  36675. height /= boundingRect.height;
  36676. }
  36677. }
  36678. vNode.attrs.width = width;
  36679. vNode.attrs.height = height;
  36680. if (svgEl) {
  36681. svgEl.setAttribute('width', width);
  36682. svgEl.setAttribute('height', height);
  36683. }
  36684. }
  36685. };
  36686. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  36687. noRepeat || setSizeToVNode_1(patternVNode, img);
  36688. setSizeToVNode_1(child, img);
  36689. });
  36690. if (createdImage && createdImage.width && createdImage.height) {
  36691. imageWidth_1 = imageWidth_1 || createdImage.width;
  36692. imageHeight_1 = imageHeight_1 || createdImage.height;
  36693. }
  36694. }
  36695. child = createVNode('image', 'img', {
  36696. href: imageSrc,
  36697. width: imageWidth_1,
  36698. height: imageHeight_1
  36699. });
  36700. patternAttrs.width = imageWidth_1;
  36701. patternAttrs.height = imageHeight_1;
  36702. }
  36703. else if (val.svgElement) {
  36704. child = clone(val.svgElement);
  36705. patternAttrs.width = val.svgWidth;
  36706. patternAttrs.height = val.svgHeight;
  36707. }
  36708. if (!child) {
  36709. return;
  36710. }
  36711. var patternWidth;
  36712. var patternHeight;
  36713. if (noRepeat) {
  36714. patternWidth = patternHeight = 1;
  36715. }
  36716. else if (repeatX) {
  36717. patternHeight = 1;
  36718. patternWidth = patternAttrs.width / boundingRect.width;
  36719. }
  36720. else if (repeatY) {
  36721. patternWidth = 1;
  36722. patternHeight = patternAttrs.height / boundingRect.height;
  36723. }
  36724. else {
  36725. patternAttrs.patternUnits = 'userSpaceOnUse';
  36726. }
  36727. if (patternWidth != null && !isNaN(patternWidth)) {
  36728. patternAttrs.width = patternWidth;
  36729. }
  36730. if (patternHeight != null && !isNaN(patternHeight)) {
  36731. patternAttrs.height = patternHeight;
  36732. }
  36733. var patternTransform = getSRTTransformString(val);
  36734. patternTransform && (patternAttrs.patternTransform = patternTransform);
  36735. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  36736. var patternKey = vNodeToString(patternVNode);
  36737. var patternCache = scope.patternCache;
  36738. var patternId = patternCache[patternKey];
  36739. if (!patternId) {
  36740. patternId = scope.zrId + '-p' + scope.patternIdx++;
  36741. patternCache[patternKey] = patternId;
  36742. patternAttrs.id = patternId;
  36743. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  36744. }
  36745. attrs[target] = getIdURL(patternId);
  36746. }
  36747. function setClipPath(clipPath, attrs, scope) {
  36748. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  36749. var clipPathId = clipPathCache[clipPath.id];
  36750. if (!clipPathId) {
  36751. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  36752. var clipPathAttrs = {
  36753. id: clipPathId
  36754. };
  36755. clipPathCache[clipPath.id] = clipPathId;
  36756. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  36757. }
  36758. attrs['clip-path'] = getIdURL(clipPathId);
  36759. }
  36760. function createTextNode(text) {
  36761. return document.createTextNode(text);
  36762. }
  36763. function insertBefore(parentNode, newNode, referenceNode) {
  36764. parentNode.insertBefore(newNode, referenceNode);
  36765. }
  36766. function removeChild(node, child) {
  36767. node.removeChild(child);
  36768. }
  36769. function appendChild(node, child) {
  36770. node.appendChild(child);
  36771. }
  36772. function parentNode(node) {
  36773. return node.parentNode;
  36774. }
  36775. function nextSibling(node) {
  36776. return node.nextSibling;
  36777. }
  36778. function setTextContent(node, text) {
  36779. node.textContent = text;
  36780. }
  36781. var colonChar = 58;
  36782. var xChar = 120;
  36783. var emptyNode = createVNode('', '');
  36784. function isUndef(s) {
  36785. return s === undefined;
  36786. }
  36787. function isDef(s) {
  36788. return s !== undefined;
  36789. }
  36790. function createKeyToOldIdx(children, beginIdx, endIdx) {
  36791. var map = {};
  36792. for (var i = beginIdx; i <= endIdx; ++i) {
  36793. var key = children[i].key;
  36794. if (key !== undefined) {
  36795. if ("development" !== 'production') {
  36796. if (map[key] != null) {
  36797. console.error("Duplicate key " + key);
  36798. }
  36799. }
  36800. map[key] = i;
  36801. }
  36802. }
  36803. return map;
  36804. }
  36805. function sameVnode(vnode1, vnode2) {
  36806. var isSameKey = vnode1.key === vnode2.key;
  36807. var isSameTag = vnode1.tag === vnode2.tag;
  36808. return isSameTag && isSameKey;
  36809. }
  36810. function createElm(vnode) {
  36811. var i;
  36812. var children = vnode.children;
  36813. var tag = vnode.tag;
  36814. if (isDef(tag)) {
  36815. var elm = (vnode.elm = createElement(tag));
  36816. updateAttrs(emptyNode, vnode);
  36817. if (isArray(children)) {
  36818. for (i = 0; i < children.length; ++i) {
  36819. var ch = children[i];
  36820. if (ch != null) {
  36821. appendChild(elm, createElm(ch));
  36822. }
  36823. }
  36824. }
  36825. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  36826. appendChild(elm, createTextNode(vnode.text));
  36827. }
  36828. }
  36829. else {
  36830. vnode.elm = createTextNode(vnode.text);
  36831. }
  36832. return vnode.elm;
  36833. }
  36834. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  36835. for (; startIdx <= endIdx; ++startIdx) {
  36836. var ch = vnodes[startIdx];
  36837. if (ch != null) {
  36838. insertBefore(parentElm, createElm(ch), before);
  36839. }
  36840. }
  36841. }
  36842. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  36843. for (; startIdx <= endIdx; ++startIdx) {
  36844. var ch = vnodes[startIdx];
  36845. if (ch != null) {
  36846. if (isDef(ch.tag)) {
  36847. var parent_1 = parentNode(ch.elm);
  36848. removeChild(parent_1, ch.elm);
  36849. }
  36850. else {
  36851. removeChild(parentElm, ch.elm);
  36852. }
  36853. }
  36854. }
  36855. }
  36856. function updateAttrs(oldVnode, vnode) {
  36857. var key;
  36858. var elm = vnode.elm;
  36859. var oldAttrs = oldVnode && oldVnode.attrs || {};
  36860. var attrs = vnode.attrs || {};
  36861. if (oldAttrs === attrs) {
  36862. return;
  36863. }
  36864. for (key in attrs) {
  36865. var cur = attrs[key];
  36866. var old = oldAttrs[key];
  36867. if (old !== cur) {
  36868. if (cur === true) {
  36869. elm.setAttribute(key, '');
  36870. }
  36871. else if (cur === false) {
  36872. elm.removeAttribute(key);
  36873. }
  36874. else {
  36875. if (key === 'style') {
  36876. elm.style.cssText = cur;
  36877. }
  36878. else if (key.charCodeAt(0) !== xChar) {
  36879. elm.setAttribute(key, cur);
  36880. }
  36881. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  36882. elm.setAttributeNS(XMLNS, key, cur);
  36883. }
  36884. else if (key.charCodeAt(3) === colonChar) {
  36885. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  36886. }
  36887. else if (key.charCodeAt(5) === colonChar) {
  36888. elm.setAttributeNS(XLINKNS, key, cur);
  36889. }
  36890. else {
  36891. elm.setAttribute(key, cur);
  36892. }
  36893. }
  36894. }
  36895. }
  36896. for (key in oldAttrs) {
  36897. if (!(key in attrs)) {
  36898. elm.removeAttribute(key);
  36899. }
  36900. }
  36901. }
  36902. function updateChildren(parentElm, oldCh, newCh) {
  36903. var oldStartIdx = 0;
  36904. var newStartIdx = 0;
  36905. var oldEndIdx = oldCh.length - 1;
  36906. var oldStartVnode = oldCh[0];
  36907. var oldEndVnode = oldCh[oldEndIdx];
  36908. var newEndIdx = newCh.length - 1;
  36909. var newStartVnode = newCh[0];
  36910. var newEndVnode = newCh[newEndIdx];
  36911. var oldKeyToIdx;
  36912. var idxInOld;
  36913. var elmToMove;
  36914. var before;
  36915. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  36916. if (oldStartVnode == null) {
  36917. oldStartVnode = oldCh[++oldStartIdx];
  36918. }
  36919. else if (oldEndVnode == null) {
  36920. oldEndVnode = oldCh[--oldEndIdx];
  36921. }
  36922. else if (newStartVnode == null) {
  36923. newStartVnode = newCh[++newStartIdx];
  36924. }
  36925. else if (newEndVnode == null) {
  36926. newEndVnode = newCh[--newEndIdx];
  36927. }
  36928. else if (sameVnode(oldStartVnode, newStartVnode)) {
  36929. patchVnode(oldStartVnode, newStartVnode);
  36930. oldStartVnode = oldCh[++oldStartIdx];
  36931. newStartVnode = newCh[++newStartIdx];
  36932. }
  36933. else if (sameVnode(oldEndVnode, newEndVnode)) {
  36934. patchVnode(oldEndVnode, newEndVnode);
  36935. oldEndVnode = oldCh[--oldEndIdx];
  36936. newEndVnode = newCh[--newEndIdx];
  36937. }
  36938. else if (sameVnode(oldStartVnode, newEndVnode)) {
  36939. patchVnode(oldStartVnode, newEndVnode);
  36940. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  36941. oldStartVnode = oldCh[++oldStartIdx];
  36942. newEndVnode = newCh[--newEndIdx];
  36943. }
  36944. else if (sameVnode(oldEndVnode, newStartVnode)) {
  36945. patchVnode(oldEndVnode, newStartVnode);
  36946. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  36947. oldEndVnode = oldCh[--oldEndIdx];
  36948. newStartVnode = newCh[++newStartIdx];
  36949. }
  36950. else {
  36951. if (isUndef(oldKeyToIdx)) {
  36952. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  36953. }
  36954. idxInOld = oldKeyToIdx[newStartVnode.key];
  36955. if (isUndef(idxInOld)) {
  36956. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  36957. }
  36958. else {
  36959. elmToMove = oldCh[idxInOld];
  36960. if (elmToMove.tag !== newStartVnode.tag) {
  36961. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  36962. }
  36963. else {
  36964. patchVnode(elmToMove, newStartVnode);
  36965. oldCh[idxInOld] = undefined;
  36966. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  36967. }
  36968. }
  36969. newStartVnode = newCh[++newStartIdx];
  36970. }
  36971. }
  36972. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  36973. if (oldStartIdx > oldEndIdx) {
  36974. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  36975. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  36976. }
  36977. else {
  36978. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  36979. }
  36980. }
  36981. }
  36982. function patchVnode(oldVnode, vnode) {
  36983. var elm = (vnode.elm = oldVnode.elm);
  36984. var oldCh = oldVnode.children;
  36985. var ch = vnode.children;
  36986. if (oldVnode === vnode) {
  36987. return;
  36988. }
  36989. updateAttrs(oldVnode, vnode);
  36990. if (isUndef(vnode.text)) {
  36991. if (isDef(oldCh) && isDef(ch)) {
  36992. if (oldCh !== ch) {
  36993. updateChildren(elm, oldCh, ch);
  36994. }
  36995. }
  36996. else if (isDef(ch)) {
  36997. if (isDef(oldVnode.text)) {
  36998. setTextContent(elm, '');
  36999. }
  37000. addVnodes(elm, null, ch, 0, ch.length - 1);
  37001. }
  37002. else if (isDef(oldCh)) {
  37003. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  37004. }
  37005. else if (isDef(oldVnode.text)) {
  37006. setTextContent(elm, '');
  37007. }
  37008. }
  37009. else if (oldVnode.text !== vnode.text) {
  37010. if (isDef(oldCh)) {
  37011. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  37012. }
  37013. setTextContent(elm, vnode.text);
  37014. }
  37015. }
  37016. function patch(oldVnode, vnode) {
  37017. if (sameVnode(oldVnode, vnode)) {
  37018. patchVnode(oldVnode, vnode);
  37019. }
  37020. else {
  37021. var elm = oldVnode.elm;
  37022. var parent_2 = parentNode(elm);
  37023. createElm(vnode);
  37024. if (parent_2 !== null) {
  37025. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  37026. removeVnodes(parent_2, [oldVnode], 0, 0);
  37027. }
  37028. }
  37029. return vnode;
  37030. }
  37031. var svgId = 0;
  37032. var SVGPainter = (function () {
  37033. function SVGPainter(root, storage, opts) {
  37034. this.type = 'svg';
  37035. this.refreshHover = createMethodNotSupport('refreshHover');
  37036. this.configLayer = createMethodNotSupport('configLayer');
  37037. this.storage = storage;
  37038. this._opts = opts = extend({}, opts);
  37039. this.root = root;
  37040. this._id = 'zr' + svgId++;
  37041. this._oldVNode = createSVGVNode(opts.width, opts.height);
  37042. if (root && !opts.ssr) {
  37043. var viewport = this._viewport = document.createElement('div');
  37044. viewport.style.cssText = 'position:relative;overflow:hidden';
  37045. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  37046. updateAttrs(null, this._oldVNode);
  37047. viewport.appendChild(svgDom);
  37048. root.appendChild(viewport);
  37049. }
  37050. this.resize(opts.width, opts.height);
  37051. }
  37052. SVGPainter.prototype.getType = function () {
  37053. return this.type;
  37054. };
  37055. SVGPainter.prototype.getViewportRoot = function () {
  37056. return this._viewport;
  37057. };
  37058. SVGPainter.prototype.getViewportRootOffset = function () {
  37059. var viewportRoot = this.getViewportRoot();
  37060. if (viewportRoot) {
  37061. return {
  37062. offsetLeft: viewportRoot.offsetLeft || 0,
  37063. offsetTop: viewportRoot.offsetTop || 0
  37064. };
  37065. }
  37066. };
  37067. SVGPainter.prototype.getSvgDom = function () {
  37068. return this._svgDom;
  37069. };
  37070. SVGPainter.prototype.refresh = function () {
  37071. if (this.root) {
  37072. var vnode = this.renderToVNode({
  37073. willUpdate: true
  37074. });
  37075. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  37076. patch(this._oldVNode, vnode);
  37077. this._oldVNode = vnode;
  37078. }
  37079. };
  37080. SVGPainter.prototype.renderOneToVNode = function (el) {
  37081. return brush$1(el, createBrushScope(this._id));
  37082. };
  37083. SVGPainter.prototype.renderToVNode = function (opts) {
  37084. opts = opts || {};
  37085. var list = this.storage.getDisplayList(true);
  37086. var width = this._width;
  37087. var height = this._height;
  37088. var scope = createBrushScope(this._id);
  37089. scope.animation = opts.animation;
  37090. scope.willUpdate = opts.willUpdate;
  37091. scope.compress = opts.compress;
  37092. scope.emphasis = opts.emphasis;
  37093. scope.ssr = this._opts.ssr;
  37094. var children = [];
  37095. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  37096. bgVNode && children.push(bgVNode);
  37097. var mainVNode = !opts.compress
  37098. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  37099. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  37100. mainVNode && children.push(mainVNode);
  37101. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  37102. if (defs.length) {
  37103. children.push(createVNode('defs', 'defs', {}, defs));
  37104. }
  37105. if (opts.animation) {
  37106. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  37107. if (animationCssStr) {
  37108. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  37109. children.push(styleNode);
  37110. }
  37111. }
  37112. return createSVGVNode(width, height, children, opts.useViewBox);
  37113. };
  37114. SVGPainter.prototype.renderToString = function (opts) {
  37115. opts = opts || {};
  37116. return vNodeToString(this.renderToVNode({
  37117. animation: retrieve2(opts.cssAnimation, true),
  37118. emphasis: retrieve2(opts.cssEmphasis, true),
  37119. willUpdate: false,
  37120. compress: true,
  37121. useViewBox: retrieve2(opts.useViewBox, true)
  37122. }), { newline: true });
  37123. };
  37124. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  37125. this._backgroundColor = backgroundColor;
  37126. };
  37127. SVGPainter.prototype.getSvgRoot = function () {
  37128. return this._mainVNode && this._mainVNode.elm;
  37129. };
  37130. SVGPainter.prototype._paintList = function (list, scope, out) {
  37131. var listLen = list.length;
  37132. var clipPathsGroupsStack = [];
  37133. var clipPathsGroupsStackDepth = 0;
  37134. var currentClipPathGroup;
  37135. var prevClipPaths;
  37136. var clipGroupNodeIdx = 0;
  37137. for (var i = 0; i < listLen; i++) {
  37138. var displayable = list[i];
  37139. if (!displayable.invisible) {
  37140. var clipPaths = displayable.__clipPaths;
  37141. var len = clipPaths && clipPaths.length || 0;
  37142. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  37143. var lca = void 0;
  37144. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  37145. if (clipPaths && prevClipPaths
  37146. && clipPaths[lca] === prevClipPaths[lca]) {
  37147. break;
  37148. }
  37149. }
  37150. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  37151. clipPathsGroupsStackDepth--;
  37152. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  37153. }
  37154. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  37155. var groupAttrs = {};
  37156. setClipPath(clipPaths[i_2], groupAttrs, scope);
  37157. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  37158. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  37159. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  37160. currentClipPathGroup = g;
  37161. }
  37162. prevClipPaths = clipPaths;
  37163. var ret = brush$1(displayable, scope);
  37164. if (ret) {
  37165. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  37166. }
  37167. }
  37168. }
  37169. };
  37170. SVGPainter.prototype.resize = function (width, height) {
  37171. var opts = this._opts;
  37172. var root = this.root;
  37173. var viewport = this._viewport;
  37174. width != null && (opts.width = width);
  37175. height != null && (opts.height = height);
  37176. if (root && viewport) {
  37177. viewport.style.display = 'none';
  37178. width = getSize(root, 0, opts);
  37179. height = getSize(root, 1, opts);
  37180. viewport.style.display = '';
  37181. }
  37182. if (this._width !== width || this._height !== height) {
  37183. this._width = width;
  37184. this._height = height;
  37185. if (viewport) {
  37186. var viewportStyle = viewport.style;
  37187. viewportStyle.width = width + 'px';
  37188. viewportStyle.height = height + 'px';
  37189. }
  37190. if (!isPattern(this._backgroundColor)) {
  37191. var svgDom = this._svgDom;
  37192. if (svgDom) {
  37193. svgDom.setAttribute('width', width);
  37194. svgDom.setAttribute('height', height);
  37195. }
  37196. var bgEl = this._bgVNode && this._bgVNode.elm;
  37197. if (bgEl) {
  37198. bgEl.setAttribute('width', width);
  37199. bgEl.setAttribute('height', height);
  37200. }
  37201. }
  37202. else {
  37203. this.refresh();
  37204. }
  37205. }
  37206. };
  37207. SVGPainter.prototype.getWidth = function () {
  37208. return this._width;
  37209. };
  37210. SVGPainter.prototype.getHeight = function () {
  37211. return this._height;
  37212. };
  37213. SVGPainter.prototype.dispose = function () {
  37214. if (this.root) {
  37215. this.root.innerHTML = '';
  37216. }
  37217. this._svgDom =
  37218. this._viewport =
  37219. this.storage =
  37220. this._oldVNode =
  37221. this._bgVNode =
  37222. this._mainVNode = null;
  37223. };
  37224. SVGPainter.prototype.clear = function () {
  37225. if (this._svgDom) {
  37226. this._svgDom.innerHTML = null;
  37227. }
  37228. this._oldVNode = null;
  37229. };
  37230. SVGPainter.prototype.toDataURL = function (base64) {
  37231. var str = this.renderToString();
  37232. var prefix = 'data:image/svg+xml;';
  37233. if (base64) {
  37234. str = encodeBase64(str);
  37235. return str && prefix + 'base64,' + str;
  37236. }
  37237. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  37238. };
  37239. return SVGPainter;
  37240. }());
  37241. function createMethodNotSupport(method) {
  37242. return function () {
  37243. if ("development" !== 'production') {
  37244. logError('In SVG mode painter not support method "' + method + '"');
  37245. }
  37246. };
  37247. }
  37248. function createBackgroundVNode(width, height, backgroundColor, scope) {
  37249. var bgVNode;
  37250. if (backgroundColor && backgroundColor !== 'none') {
  37251. bgVNode = createVNode('rect', 'bg', {
  37252. width: width,
  37253. height: height,
  37254. x: '0',
  37255. y: '0'
  37256. });
  37257. if (isGradient(backgroundColor)) {
  37258. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  37259. }
  37260. else if (isPattern(backgroundColor)) {
  37261. setPattern({
  37262. style: {
  37263. fill: backgroundColor
  37264. },
  37265. dirty: noop,
  37266. getBoundingRect: function () { return ({ width: width, height: height }); }
  37267. }, bgVNode.attrs, 'fill', scope);
  37268. }
  37269. else {
  37270. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  37271. bgVNode.attrs.fill = color;
  37272. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  37273. }
  37274. }
  37275. return bgVNode;
  37276. }
  37277. function install(registers) {
  37278. registers.registerPainter('svg', SVGPainter);
  37279. }
  37280. function createDom(id, painter, dpr) {
  37281. var newDom = platformApi.createCanvas();
  37282. var width = painter.getWidth();
  37283. var height = painter.getHeight();
  37284. var newDomStyle = newDom.style;
  37285. if (newDomStyle) {
  37286. newDomStyle.position = 'absolute';
  37287. newDomStyle.left = '0';
  37288. newDomStyle.top = '0';
  37289. newDomStyle.width = width + 'px';
  37290. newDomStyle.height = height + 'px';
  37291. newDom.setAttribute('data-zr-dom-id', id);
  37292. }
  37293. newDom.width = width * dpr;
  37294. newDom.height = height * dpr;
  37295. return newDom;
  37296. }
  37297. var Layer = (function (_super) {
  37298. __extends(Layer, _super);
  37299. function Layer(id, painter, dpr) {
  37300. var _this = _super.call(this) || this;
  37301. _this.motionBlur = false;
  37302. _this.lastFrameAlpha = 0.7;
  37303. _this.dpr = 1;
  37304. _this.virtual = false;
  37305. _this.config = {};
  37306. _this.incremental = false;
  37307. _this.zlevel = 0;
  37308. _this.maxRepaintRectCount = 5;
  37309. _this.__dirty = true;
  37310. _this.__firstTimePaint = true;
  37311. _this.__used = false;
  37312. _this.__drawIndex = 0;
  37313. _this.__startIndex = 0;
  37314. _this.__endIndex = 0;
  37315. _this.__prevStartIndex = null;
  37316. _this.__prevEndIndex = null;
  37317. var dom;
  37318. dpr = dpr || devicePixelRatio;
  37319. if (typeof id === 'string') {
  37320. dom = createDom(id, painter, dpr);
  37321. }
  37322. else if (isObject(id)) {
  37323. dom = id;
  37324. id = dom.id;
  37325. }
  37326. _this.id = id;
  37327. _this.dom = dom;
  37328. var domStyle = dom.style;
  37329. if (domStyle) {
  37330. disableUserSelect(dom);
  37331. dom.onselectstart = function () { return false; };
  37332. domStyle.padding = '0';
  37333. domStyle.margin = '0';
  37334. domStyle.borderWidth = '0';
  37335. }
  37336. _this.painter = painter;
  37337. _this.dpr = dpr;
  37338. return _this;
  37339. }
  37340. Layer.prototype.getElementCount = function () {
  37341. return this.__endIndex - this.__startIndex;
  37342. };
  37343. Layer.prototype.afterBrush = function () {
  37344. this.__prevStartIndex = this.__startIndex;
  37345. this.__prevEndIndex = this.__endIndex;
  37346. };
  37347. Layer.prototype.initContext = function () {
  37348. this.ctx = this.dom.getContext('2d');
  37349. this.ctx.dpr = this.dpr;
  37350. };
  37351. Layer.prototype.setUnpainted = function () {
  37352. this.__firstTimePaint = true;
  37353. };
  37354. Layer.prototype.createBackBuffer = function () {
  37355. var dpr = this.dpr;
  37356. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  37357. this.ctxBack = this.domBack.getContext('2d');
  37358. if (dpr !== 1) {
  37359. this.ctxBack.scale(dpr, dpr);
  37360. }
  37361. };
  37362. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  37363. if (this.__firstTimePaint) {
  37364. this.__firstTimePaint = false;
  37365. return null;
  37366. }
  37367. var mergedRepaintRects = [];
  37368. var maxRepaintRectCount = this.maxRepaintRectCount;
  37369. var full = false;
  37370. var pendingRect = new BoundingRect(0, 0, 0, 0);
  37371. function addRectToMergePool(rect) {
  37372. if (!rect.isFinite() || rect.isZero()) {
  37373. return;
  37374. }
  37375. if (mergedRepaintRects.length === 0) {
  37376. var boundingRect = new BoundingRect(0, 0, 0, 0);
  37377. boundingRect.copy(rect);
  37378. mergedRepaintRects.push(boundingRect);
  37379. }
  37380. else {
  37381. var isMerged = false;
  37382. var minDeltaArea = Infinity;
  37383. var bestRectToMergeIdx = 0;
  37384. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  37385. var mergedRect = mergedRepaintRects[i];
  37386. if (mergedRect.intersect(rect)) {
  37387. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  37388. pendingRect_1.copy(mergedRect);
  37389. pendingRect_1.union(rect);
  37390. mergedRepaintRects[i] = pendingRect_1;
  37391. isMerged = true;
  37392. break;
  37393. }
  37394. else if (full) {
  37395. pendingRect.copy(rect);
  37396. pendingRect.union(mergedRect);
  37397. var aArea = rect.width * rect.height;
  37398. var bArea = mergedRect.width * mergedRect.height;
  37399. var pendingArea = pendingRect.width * pendingRect.height;
  37400. var deltaArea = pendingArea - aArea - bArea;
  37401. if (deltaArea < minDeltaArea) {
  37402. minDeltaArea = deltaArea;
  37403. bestRectToMergeIdx = i;
  37404. }
  37405. }
  37406. }
  37407. if (full) {
  37408. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  37409. isMerged = true;
  37410. }
  37411. if (!isMerged) {
  37412. var boundingRect = new BoundingRect(0, 0, 0, 0);
  37413. boundingRect.copy(rect);
  37414. mergedRepaintRects.push(boundingRect);
  37415. }
  37416. if (!full) {
  37417. full = mergedRepaintRects.length >= maxRepaintRectCount;
  37418. }
  37419. }
  37420. }
  37421. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  37422. var el = displayList[i];
  37423. if (el) {
  37424. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  37425. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  37426. ? el.getPrevPaintRect()
  37427. : null;
  37428. if (prevRect) {
  37429. addRectToMergePool(prevRect);
  37430. }
  37431. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  37432. ? el.getPaintRect()
  37433. : null;
  37434. if (curRect) {
  37435. addRectToMergePool(curRect);
  37436. }
  37437. }
  37438. }
  37439. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  37440. var el = prevList[i];
  37441. var shouldPaint = el && el.shouldBePainted(viewWidth, viewHeight, true, true);
  37442. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  37443. var prevRect = el.getPrevPaintRect();
  37444. if (prevRect) {
  37445. addRectToMergePool(prevRect);
  37446. }
  37447. }
  37448. }
  37449. var hasIntersections;
  37450. do {
  37451. hasIntersections = false;
  37452. for (var i = 0; i < mergedRepaintRects.length;) {
  37453. if (mergedRepaintRects[i].isZero()) {
  37454. mergedRepaintRects.splice(i, 1);
  37455. continue;
  37456. }
  37457. for (var j = i + 1; j < mergedRepaintRects.length;) {
  37458. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  37459. hasIntersections = true;
  37460. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  37461. mergedRepaintRects.splice(j, 1);
  37462. }
  37463. else {
  37464. j++;
  37465. }
  37466. }
  37467. i++;
  37468. }
  37469. } while (hasIntersections);
  37470. this._paintRects = mergedRepaintRects;
  37471. return mergedRepaintRects;
  37472. };
  37473. Layer.prototype.debugGetPaintRects = function () {
  37474. return (this._paintRects || []).slice();
  37475. };
  37476. Layer.prototype.resize = function (width, height) {
  37477. var dpr = this.dpr;
  37478. var dom = this.dom;
  37479. var domStyle = dom.style;
  37480. var domBack = this.domBack;
  37481. if (domStyle) {
  37482. domStyle.width = width + 'px';
  37483. domStyle.height = height + 'px';
  37484. }
  37485. dom.width = width * dpr;
  37486. dom.height = height * dpr;
  37487. if (domBack) {
  37488. domBack.width = width * dpr;
  37489. domBack.height = height * dpr;
  37490. if (dpr !== 1) {
  37491. this.ctxBack.scale(dpr, dpr);
  37492. }
  37493. }
  37494. };
  37495. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  37496. var dom = this.dom;
  37497. var ctx = this.ctx;
  37498. var width = dom.width;
  37499. var height = dom.height;
  37500. clearColor = clearColor || this.clearColor;
  37501. var haveMotionBLur = this.motionBlur && !clearAll;
  37502. var lastFrameAlpha = this.lastFrameAlpha;
  37503. var dpr = this.dpr;
  37504. var self = this;
  37505. if (haveMotionBLur) {
  37506. if (!this.domBack) {
  37507. this.createBackBuffer();
  37508. }
  37509. this.ctxBack.globalCompositeOperation = 'copy';
  37510. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  37511. }
  37512. var domBack = this.domBack;
  37513. function doClear(x, y, width, height) {
  37514. ctx.clearRect(x, y, width, height);
  37515. if (clearColor && clearColor !== 'transparent') {
  37516. var clearColorGradientOrPattern = void 0;
  37517. if (isGradientObject(clearColor)) {
  37518. var shouldCache = clearColor.global || (clearColor.__width === width
  37519. && clearColor.__height === height);
  37520. clearColorGradientOrPattern = shouldCache
  37521. && clearColor.__canvasGradient
  37522. || getCanvasGradient(ctx, clearColor, {
  37523. x: 0,
  37524. y: 0,
  37525. width: width,
  37526. height: height
  37527. });
  37528. clearColor.__canvasGradient = clearColorGradientOrPattern;
  37529. clearColor.__width = width;
  37530. clearColor.__height = height;
  37531. }
  37532. else if (isImagePatternObject(clearColor)) {
  37533. clearColor.scaleX = clearColor.scaleX || dpr;
  37534. clearColor.scaleY = clearColor.scaleY || dpr;
  37535. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  37536. dirty: function () {
  37537. self.setUnpainted();
  37538. self.painter.refresh();
  37539. }
  37540. });
  37541. }
  37542. ctx.save();
  37543. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  37544. ctx.fillRect(x, y, width, height);
  37545. ctx.restore();
  37546. }
  37547. if (haveMotionBLur) {
  37548. ctx.save();
  37549. ctx.globalAlpha = lastFrameAlpha;
  37550. ctx.drawImage(domBack, x, y, width, height);
  37551. ctx.restore();
  37552. }
  37553. }
  37554. if (!repaintRects || haveMotionBLur) {
  37555. doClear(0, 0, width, height);
  37556. }
  37557. else if (repaintRects.length) {
  37558. each(repaintRects, function (rect) {
  37559. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  37560. });
  37561. }
  37562. };
  37563. return Layer;
  37564. }(Eventful));
  37565. var HOVER_LAYER_ZLEVEL = 1e5;
  37566. var CANVAS_ZLEVEL = 314159;
  37567. var EL_AFTER_INCREMENTAL_INC = 0.01;
  37568. var INCREMENTAL_INC = 0.001;
  37569. function isLayerValid(layer) {
  37570. if (!layer) {
  37571. return false;
  37572. }
  37573. if (layer.__builtin__) {
  37574. return true;
  37575. }
  37576. if (typeof (layer.resize) !== 'function'
  37577. || typeof (layer.refresh) !== 'function') {
  37578. return false;
  37579. }
  37580. return true;
  37581. }
  37582. function createRoot(width, height) {
  37583. var domRoot = document.createElement('div');
  37584. domRoot.style.cssText = [
  37585. 'position:relative',
  37586. 'width:' + width + 'px',
  37587. 'height:' + height + 'px',
  37588. 'padding:0',
  37589. 'margin:0',
  37590. 'border-width:0'
  37591. ].join(';') + ';';
  37592. return domRoot;
  37593. }
  37594. var CanvasPainter = (function () {
  37595. function CanvasPainter(root, storage, opts, id) {
  37596. this.type = 'canvas';
  37597. this._zlevelList = [];
  37598. this._prevDisplayList = [];
  37599. this._layers = {};
  37600. this._layerConfig = {};
  37601. this._needsManuallyCompositing = false;
  37602. this.type = 'canvas';
  37603. var singleCanvas = !root.nodeName
  37604. || root.nodeName.toUpperCase() === 'CANVAS';
  37605. this._opts = opts = extend({}, opts || {});
  37606. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  37607. this._singleCanvas = singleCanvas;
  37608. this.root = root;
  37609. var rootStyle = root.style;
  37610. if (rootStyle) {
  37611. disableUserSelect(root);
  37612. root.innerHTML = '';
  37613. }
  37614. this.storage = storage;
  37615. var zlevelList = this._zlevelList;
  37616. this._prevDisplayList = [];
  37617. var layers = this._layers;
  37618. if (!singleCanvas) {
  37619. this._width = getSize(root, 0, opts);
  37620. this._height = getSize(root, 1, opts);
  37621. var domRoot = this._domRoot = createRoot(this._width, this._height);
  37622. root.appendChild(domRoot);
  37623. }
  37624. else {
  37625. var rootCanvas = root;
  37626. var width = rootCanvas.width;
  37627. var height = rootCanvas.height;
  37628. if (opts.width != null) {
  37629. width = opts.width;
  37630. }
  37631. if (opts.height != null) {
  37632. height = opts.height;
  37633. }
  37634. this.dpr = opts.devicePixelRatio || 1;
  37635. rootCanvas.width = width * this.dpr;
  37636. rootCanvas.height = height * this.dpr;
  37637. this._width = width;
  37638. this._height = height;
  37639. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  37640. mainLayer.__builtin__ = true;
  37641. mainLayer.initContext();
  37642. layers[CANVAS_ZLEVEL] = mainLayer;
  37643. mainLayer.zlevel = CANVAS_ZLEVEL;
  37644. zlevelList.push(CANVAS_ZLEVEL);
  37645. this._domRoot = root;
  37646. }
  37647. }
  37648. CanvasPainter.prototype.getType = function () {
  37649. return 'canvas';
  37650. };
  37651. CanvasPainter.prototype.isSingleCanvas = function () {
  37652. return this._singleCanvas;
  37653. };
  37654. CanvasPainter.prototype.getViewportRoot = function () {
  37655. return this._domRoot;
  37656. };
  37657. CanvasPainter.prototype.getViewportRootOffset = function () {
  37658. var viewportRoot = this.getViewportRoot();
  37659. if (viewportRoot) {
  37660. return {
  37661. offsetLeft: viewportRoot.offsetLeft || 0,
  37662. offsetTop: viewportRoot.offsetTop || 0
  37663. };
  37664. }
  37665. };
  37666. CanvasPainter.prototype.refresh = function (paintAll) {
  37667. var list = this.storage.getDisplayList(true);
  37668. var prevList = this._prevDisplayList;
  37669. var zlevelList = this._zlevelList;
  37670. this._redrawId = Math.random();
  37671. this._paintList(list, prevList, paintAll, this._redrawId);
  37672. for (var i = 0; i < zlevelList.length; i++) {
  37673. var z = zlevelList[i];
  37674. var layer = this._layers[z];
  37675. if (!layer.__builtin__ && layer.refresh) {
  37676. var clearColor = i === 0 ? this._backgroundColor : null;
  37677. layer.refresh(clearColor);
  37678. }
  37679. }
  37680. if (this._opts.useDirtyRect) {
  37681. this._prevDisplayList = list.slice();
  37682. }
  37683. return this;
  37684. };
  37685. CanvasPainter.prototype.refreshHover = function () {
  37686. this._paintHoverList(this.storage.getDisplayList(false));
  37687. };
  37688. CanvasPainter.prototype._paintHoverList = function (list) {
  37689. var len = list.length;
  37690. var hoverLayer = this._hoverlayer;
  37691. hoverLayer && hoverLayer.clear();
  37692. if (!len) {
  37693. return;
  37694. }
  37695. var scope = {
  37696. inHover: true,
  37697. viewWidth: this._width,
  37698. viewHeight: this._height
  37699. };
  37700. var ctx;
  37701. for (var i = 0; i < len; i++) {
  37702. var el = list[i];
  37703. if (el.__inHover) {
  37704. if (!hoverLayer) {
  37705. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  37706. }
  37707. if (!ctx) {
  37708. ctx = hoverLayer.ctx;
  37709. ctx.save();
  37710. }
  37711. brush(ctx, el, scope, i === len - 1);
  37712. }
  37713. }
  37714. if (ctx) {
  37715. ctx.restore();
  37716. }
  37717. };
  37718. CanvasPainter.prototype.getHoverLayer = function () {
  37719. return this.getLayer(HOVER_LAYER_ZLEVEL);
  37720. };
  37721. CanvasPainter.prototype.paintOne = function (ctx, el) {
  37722. brushSingle(ctx, el);
  37723. };
  37724. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  37725. if (this._redrawId !== redrawId) {
  37726. return;
  37727. }
  37728. paintAll = paintAll || false;
  37729. this._updateLayerStatus(list);
  37730. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  37731. if (this._needsManuallyCompositing) {
  37732. this._compositeManually();
  37733. }
  37734. if (needsRefreshHover) {
  37735. this._paintHoverList(list);
  37736. }
  37737. if (!finished) {
  37738. var self_1 = this;
  37739. requestAnimationFrame$1(function () {
  37740. self_1._paintList(list, prevList, paintAll, redrawId);
  37741. });
  37742. }
  37743. else {
  37744. this.eachLayer(function (layer) {
  37745. layer.afterBrush && layer.afterBrush();
  37746. });
  37747. }
  37748. };
  37749. CanvasPainter.prototype._compositeManually = function () {
  37750. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  37751. var width = this._domRoot.width;
  37752. var height = this._domRoot.height;
  37753. ctx.clearRect(0, 0, width, height);
  37754. this.eachBuiltinLayer(function (layer) {
  37755. if (layer.virtual) {
  37756. ctx.drawImage(layer.dom, 0, 0, width, height);
  37757. }
  37758. });
  37759. };
  37760. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  37761. var _this = this;
  37762. var layerList = [];
  37763. var useDirtyRect = this._opts.useDirtyRect;
  37764. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  37765. var zlevel = this._zlevelList[zi];
  37766. var layer = this._layers[zlevel];
  37767. if (layer.__builtin__
  37768. && layer !== this._hoverlayer
  37769. && (layer.__dirty || paintAll)) {
  37770. layerList.push(layer);
  37771. }
  37772. }
  37773. var finished = true;
  37774. var needsRefreshHover = false;
  37775. var _loop_1 = function (k) {
  37776. var layer = layerList[k];
  37777. var ctx = layer.ctx;
  37778. var repaintRects = useDirtyRect
  37779. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  37780. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  37781. var useTimer = !paintAll && layer.incremental && Date.now;
  37782. var startTime = useTimer && Date.now();
  37783. var clearColor = layer.zlevel === this_1._zlevelList[0]
  37784. ? this_1._backgroundColor : null;
  37785. if (layer.__startIndex === layer.__endIndex) {
  37786. layer.clear(false, clearColor, repaintRects);
  37787. }
  37788. else if (start === layer.__startIndex) {
  37789. var firstEl = list[start];
  37790. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  37791. layer.clear(false, clearColor, repaintRects);
  37792. }
  37793. }
  37794. if (start === -1) {
  37795. console.error('For some unknown reason. drawIndex is -1');
  37796. start = layer.__startIndex;
  37797. }
  37798. var i;
  37799. var repaint = function (repaintRect) {
  37800. var scope = {
  37801. inHover: false,
  37802. allClipped: false,
  37803. prevEl: null,
  37804. viewWidth: _this._width,
  37805. viewHeight: _this._height
  37806. };
  37807. for (i = start; i < layer.__endIndex; i++) {
  37808. var el = list[i];
  37809. if (el.__inHover) {
  37810. needsRefreshHover = true;
  37811. }
  37812. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  37813. if (useTimer) {
  37814. var dTime = Date.now() - startTime;
  37815. if (dTime > 15) {
  37816. break;
  37817. }
  37818. }
  37819. }
  37820. if (scope.prevElClipPaths) {
  37821. ctx.restore();
  37822. }
  37823. };
  37824. if (repaintRects) {
  37825. if (repaintRects.length === 0) {
  37826. i = layer.__endIndex;
  37827. }
  37828. else {
  37829. var dpr = this_1.dpr;
  37830. for (var r = 0; r < repaintRects.length; ++r) {
  37831. var rect = repaintRects[r];
  37832. ctx.save();
  37833. ctx.beginPath();
  37834. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  37835. ctx.clip();
  37836. repaint(rect);
  37837. ctx.restore();
  37838. }
  37839. }
  37840. }
  37841. else {
  37842. ctx.save();
  37843. repaint();
  37844. ctx.restore();
  37845. }
  37846. layer.__drawIndex = i;
  37847. if (layer.__drawIndex < layer.__endIndex) {
  37848. finished = false;
  37849. }
  37850. };
  37851. var this_1 = this;
  37852. for (var k = 0; k < layerList.length; k++) {
  37853. _loop_1(k);
  37854. }
  37855. if (env.wxa) {
  37856. each(this._layers, function (layer) {
  37857. if (layer && layer.ctx && layer.ctx.draw) {
  37858. layer.ctx.draw();
  37859. }
  37860. });
  37861. }
  37862. return {
  37863. finished: finished,
  37864. needsRefreshHover: needsRefreshHover
  37865. };
  37866. };
  37867. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  37868. var ctx = currentLayer.ctx;
  37869. if (useDirtyRect) {
  37870. var paintRect = el.getPaintRect();
  37871. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  37872. brush(ctx, el, scope, isLast);
  37873. el.setPrevPaintRect(paintRect);
  37874. }
  37875. }
  37876. else {
  37877. brush(ctx, el, scope, isLast);
  37878. }
  37879. };
  37880. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  37881. if (this._singleCanvas && !this._needsManuallyCompositing) {
  37882. zlevel = CANVAS_ZLEVEL;
  37883. }
  37884. var layer = this._layers[zlevel];
  37885. if (!layer) {
  37886. layer = new Layer('zr_' + zlevel, this, this.dpr);
  37887. layer.zlevel = zlevel;
  37888. layer.__builtin__ = true;
  37889. if (this._layerConfig[zlevel]) {
  37890. merge(layer, this._layerConfig[zlevel], true);
  37891. }
  37892. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  37893. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  37894. }
  37895. if (virtual) {
  37896. layer.virtual = virtual;
  37897. }
  37898. this.insertLayer(zlevel, layer);
  37899. layer.initContext();
  37900. }
  37901. return layer;
  37902. };
  37903. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  37904. var layersMap = this._layers;
  37905. var zlevelList = this._zlevelList;
  37906. var len = zlevelList.length;
  37907. var domRoot = this._domRoot;
  37908. var prevLayer = null;
  37909. var i = -1;
  37910. if (layersMap[zlevel]) {
  37911. if ("development" !== 'production') {
  37912. logError('ZLevel ' + zlevel + ' has been used already');
  37913. }
  37914. return;
  37915. }
  37916. if (!isLayerValid(layer)) {
  37917. if ("development" !== 'production') {
  37918. logError('Layer of zlevel ' + zlevel + ' is not valid');
  37919. }
  37920. return;
  37921. }
  37922. if (len > 0 && zlevel > zlevelList[0]) {
  37923. for (i = 0; i < len - 1; i++) {
  37924. if (zlevelList[i] < zlevel
  37925. && zlevelList[i + 1] > zlevel) {
  37926. break;
  37927. }
  37928. }
  37929. prevLayer = layersMap[zlevelList[i]];
  37930. }
  37931. zlevelList.splice(i + 1, 0, zlevel);
  37932. layersMap[zlevel] = layer;
  37933. if (!layer.virtual) {
  37934. if (prevLayer) {
  37935. var prevDom = prevLayer.dom;
  37936. if (prevDom.nextSibling) {
  37937. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  37938. }
  37939. else {
  37940. domRoot.appendChild(layer.dom);
  37941. }
  37942. }
  37943. else {
  37944. if (domRoot.firstChild) {
  37945. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  37946. }
  37947. else {
  37948. domRoot.appendChild(layer.dom);
  37949. }
  37950. }
  37951. }
  37952. layer.painter || (layer.painter = this);
  37953. };
  37954. CanvasPainter.prototype.eachLayer = function (cb, context) {
  37955. var zlevelList = this._zlevelList;
  37956. for (var i = 0; i < zlevelList.length; i++) {
  37957. var z = zlevelList[i];
  37958. cb.call(context, this._layers[z], z);
  37959. }
  37960. };
  37961. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  37962. var zlevelList = this._zlevelList;
  37963. for (var i = 0; i < zlevelList.length; i++) {
  37964. var z = zlevelList[i];
  37965. var layer = this._layers[z];
  37966. if (layer.__builtin__) {
  37967. cb.call(context, layer, z);
  37968. }
  37969. }
  37970. };
  37971. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  37972. var zlevelList = this._zlevelList;
  37973. for (var i = 0; i < zlevelList.length; i++) {
  37974. var z = zlevelList[i];
  37975. var layer = this._layers[z];
  37976. if (!layer.__builtin__) {
  37977. cb.call(context, layer, z);
  37978. }
  37979. }
  37980. };
  37981. CanvasPainter.prototype.getLayers = function () {
  37982. return this._layers;
  37983. };
  37984. CanvasPainter.prototype._updateLayerStatus = function (list) {
  37985. this.eachBuiltinLayer(function (layer, z) {
  37986. layer.__dirty = layer.__used = false;
  37987. });
  37988. function updatePrevLayer(idx) {
  37989. if (prevLayer) {
  37990. if (prevLayer.__endIndex !== idx) {
  37991. prevLayer.__dirty = true;
  37992. }
  37993. prevLayer.__endIndex = idx;
  37994. }
  37995. }
  37996. if (this._singleCanvas) {
  37997. for (var i_1 = 1; i_1 < list.length; i_1++) {
  37998. var el = list[i_1];
  37999. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  38000. this._needsManuallyCompositing = true;
  38001. break;
  38002. }
  38003. }
  38004. }
  38005. var prevLayer = null;
  38006. var incrementalLayerCount = 0;
  38007. var prevZlevel;
  38008. var i;
  38009. for (i = 0; i < list.length; i++) {
  38010. var el = list[i];
  38011. var zlevel = el.zlevel;
  38012. var layer = void 0;
  38013. if (prevZlevel !== zlevel) {
  38014. prevZlevel = zlevel;
  38015. incrementalLayerCount = 0;
  38016. }
  38017. if (el.incremental) {
  38018. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  38019. layer.incremental = true;
  38020. incrementalLayerCount = 1;
  38021. }
  38022. else {
  38023. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  38024. }
  38025. if (!layer.__builtin__) {
  38026. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  38027. }
  38028. if (layer !== prevLayer) {
  38029. layer.__used = true;
  38030. if (layer.__startIndex !== i) {
  38031. layer.__dirty = true;
  38032. }
  38033. layer.__startIndex = i;
  38034. if (!layer.incremental) {
  38035. layer.__drawIndex = i;
  38036. }
  38037. else {
  38038. layer.__drawIndex = -1;
  38039. }
  38040. updatePrevLayer(i);
  38041. prevLayer = layer;
  38042. }
  38043. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  38044. layer.__dirty = true;
  38045. if (layer.incremental && layer.__drawIndex < 0) {
  38046. layer.__drawIndex = i;
  38047. }
  38048. }
  38049. }
  38050. updatePrevLayer(i);
  38051. this.eachBuiltinLayer(function (layer, z) {
  38052. if (!layer.__used && layer.getElementCount() > 0) {
  38053. layer.__dirty = true;
  38054. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  38055. }
  38056. if (layer.__dirty && layer.__drawIndex < 0) {
  38057. layer.__drawIndex = layer.__startIndex;
  38058. }
  38059. });
  38060. };
  38061. CanvasPainter.prototype.clear = function () {
  38062. this.eachBuiltinLayer(this._clearLayer);
  38063. return this;
  38064. };
  38065. CanvasPainter.prototype._clearLayer = function (layer) {
  38066. layer.clear();
  38067. };
  38068. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  38069. this._backgroundColor = backgroundColor;
  38070. each(this._layers, function (layer) {
  38071. layer.setUnpainted();
  38072. });
  38073. };
  38074. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  38075. if (config) {
  38076. var layerConfig = this._layerConfig;
  38077. if (!layerConfig[zlevel]) {
  38078. layerConfig[zlevel] = config;
  38079. }
  38080. else {
  38081. merge(layerConfig[zlevel], config, true);
  38082. }
  38083. for (var i = 0; i < this._zlevelList.length; i++) {
  38084. var _zlevel = this._zlevelList[i];
  38085. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  38086. var layer = this._layers[_zlevel];
  38087. merge(layer, layerConfig[zlevel], true);
  38088. }
  38089. }
  38090. }
  38091. };
  38092. CanvasPainter.prototype.delLayer = function (zlevel) {
  38093. var layers = this._layers;
  38094. var zlevelList = this._zlevelList;
  38095. var layer = layers[zlevel];
  38096. if (!layer) {
  38097. return;
  38098. }
  38099. layer.dom.parentNode.removeChild(layer.dom);
  38100. delete layers[zlevel];
  38101. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  38102. };
  38103. CanvasPainter.prototype.resize = function (width, height) {
  38104. if (!this._domRoot.style) {
  38105. if (width == null || height == null) {
  38106. return;
  38107. }
  38108. this._width = width;
  38109. this._height = height;
  38110. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  38111. }
  38112. else {
  38113. var domRoot = this._domRoot;
  38114. domRoot.style.display = 'none';
  38115. var opts = this._opts;
  38116. var root = this.root;
  38117. width != null && (opts.width = width);
  38118. height != null && (opts.height = height);
  38119. width = getSize(root, 0, opts);
  38120. height = getSize(root, 1, opts);
  38121. domRoot.style.display = '';
  38122. if (this._width !== width || height !== this._height) {
  38123. domRoot.style.width = width + 'px';
  38124. domRoot.style.height = height + 'px';
  38125. for (var id in this._layers) {
  38126. if (this._layers.hasOwnProperty(id)) {
  38127. this._layers[id].resize(width, height);
  38128. }
  38129. }
  38130. this.refresh(true);
  38131. }
  38132. this._width = width;
  38133. this._height = height;
  38134. }
  38135. return this;
  38136. };
  38137. CanvasPainter.prototype.clearLayer = function (zlevel) {
  38138. var layer = this._layers[zlevel];
  38139. if (layer) {
  38140. layer.clear();
  38141. }
  38142. };
  38143. CanvasPainter.prototype.dispose = function () {
  38144. this.root.innerHTML = '';
  38145. this.root =
  38146. this.storage =
  38147. this._domRoot =
  38148. this._layers = null;
  38149. };
  38150. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  38151. opts = opts || {};
  38152. if (this._singleCanvas && !this._compositeManually) {
  38153. return this._layers[CANVAS_ZLEVEL].dom;
  38154. }
  38155. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  38156. imageLayer.initContext();
  38157. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  38158. var ctx = imageLayer.ctx;
  38159. if (opts.pixelRatio <= this.dpr) {
  38160. this.refresh();
  38161. var width_1 = imageLayer.dom.width;
  38162. var height_1 = imageLayer.dom.height;
  38163. this.eachLayer(function (layer) {
  38164. if (layer.__builtin__) {
  38165. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  38166. }
  38167. else if (layer.renderToCanvas) {
  38168. ctx.save();
  38169. layer.renderToCanvas(ctx);
  38170. ctx.restore();
  38171. }
  38172. });
  38173. }
  38174. else {
  38175. var scope = {
  38176. inHover: false,
  38177. viewWidth: this._width,
  38178. viewHeight: this._height
  38179. };
  38180. var displayList = this.storage.getDisplayList(true);
  38181. for (var i = 0, len = displayList.length; i < len; i++) {
  38182. var el = displayList[i];
  38183. brush(ctx, el, scope, i === len - 1);
  38184. }
  38185. }
  38186. return imageLayer.dom;
  38187. };
  38188. CanvasPainter.prototype.getWidth = function () {
  38189. return this._width;
  38190. };
  38191. CanvasPainter.prototype.getHeight = function () {
  38192. return this._height;
  38193. };
  38194. return CanvasPainter;
  38195. }());
  38196. function install$1(registers) {
  38197. registers.registerPainter('canvas', CanvasPainter);
  38198. }
  38199. var LineSeriesModel = /** @class */function (_super) {
  38200. __extends(LineSeriesModel, _super);
  38201. function LineSeriesModel() {
  38202. var _this = _super !== null && _super.apply(this, arguments) || this;
  38203. _this.type = LineSeriesModel.type;
  38204. _this.hasSymbolVisual = true;
  38205. return _this;
  38206. }
  38207. LineSeriesModel.prototype.getInitialData = function (option) {
  38208. if ("development" !== 'production') {
  38209. var coordSys = option.coordinateSystem;
  38210. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  38211. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  38212. }
  38213. }
  38214. return createSeriesData(null, this, {
  38215. useEncodeDefaulter: true
  38216. });
  38217. };
  38218. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  38219. var group = new Group();
  38220. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  38221. group.add(line);
  38222. line.setStyle(opt.lineStyle);
  38223. var visualType = this.getData().getVisual('symbol');
  38224. var visualRotate = this.getData().getVisual('symbolRotate');
  38225. var symbolType = visualType === 'none' ? 'circle' : visualType;
  38226. // Symbol size is 80% when there is a line
  38227. var size = opt.itemHeight * 0.8;
  38228. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  38229. group.add(symbol);
  38230. symbol.setStyle(opt.itemStyle);
  38231. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  38232. symbol.rotation = symbolRotate * Math.PI / 180;
  38233. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  38234. if (symbolType.indexOf('empty') > -1) {
  38235. symbol.style.stroke = symbol.style.fill;
  38236. symbol.style.fill = tokens.color.neutral00;
  38237. symbol.style.lineWidth = 2;
  38238. }
  38239. return group;
  38240. };
  38241. LineSeriesModel.type = 'series.line';
  38242. LineSeriesModel.dependencies = ['grid', 'polar'];
  38243. LineSeriesModel.defaultOption = {
  38244. // zlevel: 0,
  38245. z: 3,
  38246. coordinateSystem: 'cartesian2d',
  38247. legendHoverLink: true,
  38248. clip: true,
  38249. label: {
  38250. position: 'top'
  38251. },
  38252. // itemStyle: {
  38253. // },
  38254. endLabel: {
  38255. show: false,
  38256. valueAnimation: true,
  38257. distance: 8
  38258. },
  38259. lineStyle: {
  38260. width: 2,
  38261. type: 'solid'
  38262. },
  38263. emphasis: {
  38264. scale: true
  38265. },
  38266. // areaStyle: {
  38267. // origin of areaStyle. Valid values:
  38268. // `'auto'/null/undefined`: from axisLine to data
  38269. // `'start'`: from min to data
  38270. // `'end'`: from data to max
  38271. // origin: 'auto'
  38272. // },
  38273. // false, 'start', 'end', 'middle'
  38274. step: false,
  38275. // Disabled if step is true
  38276. smooth: false,
  38277. smoothMonotone: null,
  38278. symbol: 'emptyCircle',
  38279. symbolSize: 6,
  38280. symbolRotate: null,
  38281. showSymbol: true,
  38282. // `false`: follow the label interval strategy.
  38283. // `true`: show all symbols.
  38284. // `'auto'`: If possible, show all symbols, otherwise
  38285. // follow the label interval strategy.
  38286. showAllSymbol: 'auto',
  38287. // Whether to connect break point.
  38288. connectNulls: false,
  38289. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  38290. sampling: 'none',
  38291. animationEasing: 'linear',
  38292. // Disable progressive
  38293. progressive: 0,
  38294. hoverLayerThreshold: Infinity,
  38295. universalTransition: {
  38296. divideShape: 'clone'
  38297. },
  38298. triggerLineEvent: false
  38299. };
  38300. return LineSeriesModel;
  38301. }(SeriesModel);
  38302. /**
  38303. * @return label string. Not null/undefined
  38304. */
  38305. function getDefaultLabel(data, dataIndex) {
  38306. var labelDims = data.mapDimensionsAll('defaultedLabel');
  38307. var len = labelDims.length;
  38308. // Simple optimization (in lots of cases, label dims length is 1)
  38309. if (len === 1) {
  38310. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  38311. return rawVal != null ? rawVal + '' : null;
  38312. } else if (len) {
  38313. var vals = [];
  38314. for (var i = 0; i < labelDims.length; i++) {
  38315. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  38316. }
  38317. return vals.join(' ');
  38318. }
  38319. }
  38320. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  38321. var labelDims = data.mapDimensionsAll('defaultedLabel');
  38322. if (!isArray(interpolatedValue)) {
  38323. return interpolatedValue + '';
  38324. }
  38325. var vals = [];
  38326. for (var i = 0; i < labelDims.length; i++) {
  38327. var dimIndex = data.getDimensionIndex(labelDims[i]);
  38328. if (dimIndex >= 0) {
  38329. vals.push(interpolatedValue[dimIndex]);
  38330. }
  38331. }
  38332. return vals.join(' ');
  38333. }
  38334. var Symbol = /** @class */function (_super) {
  38335. __extends(Symbol, _super);
  38336. function Symbol(data, idx, seriesScope, opts) {
  38337. var _this = _super.call(this) || this;
  38338. _this.updateData(data, idx, seriesScope, opts);
  38339. return _this;
  38340. }
  38341. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, z2, keepAspect) {
  38342. // Remove paths created before
  38343. this.removeAll();
  38344. // let symbolPath = createSymbol(
  38345. // symbolType, -0.5, -0.5, 1, 1, color
  38346. // );
  38347. // If width/height are set too small (e.g., set to 1) on ios10
  38348. // and macOS Sierra, a circle stroke become a rect, no matter what
  38349. // the scale is set. So we set width/height as 2. See #4150.
  38350. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  38351. symbolPath.attr({
  38352. z2: retrieve2(z2, 100),
  38353. culling: true,
  38354. scaleX: symbolSize[0] / 2,
  38355. scaleY: symbolSize[1] / 2
  38356. });
  38357. // Rewrite drift method
  38358. symbolPath.drift = driftSymbol;
  38359. this._symbolType = symbolType;
  38360. this.add(symbolPath);
  38361. };
  38362. /**
  38363. * Stop animation
  38364. * @param {boolean} toLastFrame
  38365. */
  38366. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  38367. this.childAt(0).stopAnimation(null, toLastFrame);
  38368. };
  38369. Symbol.prototype.getSymbolType = function () {
  38370. return this._symbolType;
  38371. };
  38372. /**
  38373. * FIXME:
  38374. * Caution: This method breaks the encapsulation of this module,
  38375. * but it indeed brings convenience. So do not use the method
  38376. * unless you detailedly know all the implements of `Symbol`,
  38377. * especially animation.
  38378. *
  38379. * Get symbol path element.
  38380. */
  38381. Symbol.prototype.getSymbolPath = function () {
  38382. return this.childAt(0);
  38383. };
  38384. /**
  38385. * Highlight symbol
  38386. */
  38387. Symbol.prototype.highlight = function () {
  38388. enterEmphasis(this.childAt(0));
  38389. };
  38390. /**
  38391. * Downplay symbol
  38392. */
  38393. Symbol.prototype.downplay = function () {
  38394. leaveEmphasis(this.childAt(0));
  38395. };
  38396. /**
  38397. * @param {number} zlevel
  38398. * @param {number} z
  38399. */
  38400. Symbol.prototype.setZ = function (zlevel, z) {
  38401. var symbolPath = this.childAt(0);
  38402. symbolPath.zlevel = zlevel;
  38403. symbolPath.z = z;
  38404. };
  38405. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  38406. var symbolPath = this.childAt(0);
  38407. symbolPath.draggable = draggable;
  38408. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  38409. };
  38410. /**
  38411. * Update symbol properties
  38412. */
  38413. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  38414. this.silent = false;
  38415. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  38416. var seriesModel = data.hostModel;
  38417. var symbolSize = Symbol.getSymbolSize(data, idx);
  38418. var z2 = Symbol.getSymbolZ2(data, idx);
  38419. var isInit = symbolType !== this._symbolType;
  38420. var disableAnimation = opts && opts.disableAnimation;
  38421. if (isInit) {
  38422. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  38423. this._createSymbol(symbolType, data, idx, symbolSize, z2, keepAspect);
  38424. } else {
  38425. var symbolPath = this.childAt(0);
  38426. symbolPath.silent = false;
  38427. var target = {
  38428. scaleX: symbolSize[0] / 2,
  38429. scaleY: symbolSize[1] / 2
  38430. };
  38431. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  38432. saveOldStyle(symbolPath);
  38433. }
  38434. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  38435. if (isInit) {
  38436. var symbolPath = this.childAt(0);
  38437. if (!disableAnimation) {
  38438. var target = {
  38439. scaleX: this._sizeX,
  38440. scaleY: this._sizeY,
  38441. style: {
  38442. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  38443. opacity: symbolPath.style.opacity
  38444. }
  38445. };
  38446. symbolPath.scaleX = symbolPath.scaleY = 0;
  38447. symbolPath.style.opacity = 0;
  38448. initProps(symbolPath, target, seriesModel, idx);
  38449. }
  38450. }
  38451. if (disableAnimation) {
  38452. // Must stop leave transition manually if don't call initProps or updateProps.
  38453. this.childAt(0).stopAnimation('leave');
  38454. }
  38455. };
  38456. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  38457. var symbolPath = this.childAt(0);
  38458. var seriesModel = data.hostModel;
  38459. var emphasisItemStyle;
  38460. var blurItemStyle;
  38461. var selectItemStyle;
  38462. var focus;
  38463. var blurScope;
  38464. var emphasisDisabled;
  38465. var labelStatesModels;
  38466. var hoverScale;
  38467. var cursorStyle;
  38468. if (seriesScope) {
  38469. emphasisItemStyle = seriesScope.emphasisItemStyle;
  38470. blurItemStyle = seriesScope.blurItemStyle;
  38471. selectItemStyle = seriesScope.selectItemStyle;
  38472. focus = seriesScope.focus;
  38473. blurScope = seriesScope.blurScope;
  38474. labelStatesModels = seriesScope.labelStatesModels;
  38475. hoverScale = seriesScope.hoverScale;
  38476. cursorStyle = seriesScope.cursorStyle;
  38477. emphasisDisabled = seriesScope.emphasisDisabled;
  38478. }
  38479. if (!seriesScope || data.hasItemOption) {
  38480. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  38481. var emphasisModel = itemModel.getModel('emphasis');
  38482. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  38483. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  38484. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  38485. focus = emphasisModel.get('focus');
  38486. blurScope = emphasisModel.get('blurScope');
  38487. emphasisDisabled = emphasisModel.get('disabled');
  38488. labelStatesModels = getLabelStatesModels(itemModel);
  38489. hoverScale = emphasisModel.getShallow('scale');
  38490. cursorStyle = itemModel.getShallow('cursor');
  38491. }
  38492. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  38493. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  38494. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  38495. if (symbolOffset) {
  38496. symbolPath.x = symbolOffset[0];
  38497. symbolPath.y = symbolOffset[1];
  38498. }
  38499. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  38500. var symbolStyle = data.getItemVisual(idx, 'style');
  38501. var visualColor = symbolStyle.fill;
  38502. if (symbolPath instanceof ZRImage) {
  38503. var pathStyle = symbolPath.style;
  38504. symbolPath.useStyle(extend({
  38505. // TODO other properties like x, y ?
  38506. image: pathStyle.image,
  38507. x: pathStyle.x,
  38508. y: pathStyle.y,
  38509. width: pathStyle.width,
  38510. height: pathStyle.height
  38511. }, symbolStyle));
  38512. } else {
  38513. if (symbolPath.__isEmptyBrush) {
  38514. // fill and stroke will be swapped if it's empty.
  38515. // So we cloned a new style to avoid it affecting the original style in visual storage.
  38516. // TODO Better implementation. No empty logic!
  38517. symbolPath.useStyle(extend({}, symbolStyle));
  38518. } else {
  38519. symbolPath.useStyle(symbolStyle);
  38520. }
  38521. // Disable decal because symbol scale will been applied on the decal.
  38522. symbolPath.style.decal = null;
  38523. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  38524. symbolPath.style.strokeNoScale = true;
  38525. }
  38526. var liftZ = data.getItemVisual(idx, 'liftZ');
  38527. var z2Origin = this._z2;
  38528. if (liftZ != null) {
  38529. if (z2Origin == null) {
  38530. this._z2 = symbolPath.z2;
  38531. symbolPath.z2 += liftZ;
  38532. }
  38533. } else if (z2Origin != null) {
  38534. symbolPath.z2 = z2Origin;
  38535. this._z2 = null;
  38536. }
  38537. var useNameLabel = opts && opts.useNameLabel;
  38538. setLabelStyle(symbolPath, labelStatesModels, {
  38539. labelFetcher: seriesModel,
  38540. labelDataIndex: idx,
  38541. defaultText: getLabelDefaultText,
  38542. inheritColor: visualColor,
  38543. defaultOpacity: symbolStyle.opacity
  38544. });
  38545. // Do not execute util needed.
  38546. function getLabelDefaultText(idx) {
  38547. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  38548. }
  38549. this._sizeX = symbolSize[0] / 2;
  38550. this._sizeY = symbolSize[1] / 2;
  38551. var emphasisState = symbolPath.ensureState('emphasis');
  38552. emphasisState.style = emphasisItemStyle;
  38553. symbolPath.ensureState('select').style = selectItemStyle;
  38554. symbolPath.ensureState('blur').style = blurItemStyle;
  38555. // null / undefined / true means to use default strategy.
  38556. // 0 / false / negative number / NaN / Infinity means no scale.
  38557. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY)
  38558. // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  38559. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1;
  38560. // always set scale to allow resetting
  38561. emphasisState.scaleX = this._sizeX * scaleRatio;
  38562. emphasisState.scaleY = this._sizeY * scaleRatio;
  38563. this.setSymbolScale(1);
  38564. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  38565. };
  38566. Symbol.prototype.setSymbolScale = function (scale) {
  38567. this.scaleX = this.scaleY = scale;
  38568. };
  38569. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  38570. var symbolPath = this.childAt(0);
  38571. var dataIndex = getECData(this).dataIndex;
  38572. var animationOpt = opt && opt.animation;
  38573. // Avoid mistaken hover when fading out
  38574. this.silent = symbolPath.silent = true;
  38575. // Not show text when animating
  38576. if (opt && opt.fadeLabel) {
  38577. var textContent = symbolPath.getTextContent();
  38578. if (textContent) {
  38579. removeElement(textContent, {
  38580. style: {
  38581. opacity: 0
  38582. }
  38583. }, seriesModel, {
  38584. dataIndex: dataIndex,
  38585. removeOpt: animationOpt,
  38586. cb: function () {
  38587. symbolPath.removeTextContent();
  38588. }
  38589. });
  38590. }
  38591. } else {
  38592. symbolPath.removeTextContent();
  38593. }
  38594. removeElement(symbolPath, {
  38595. style: {
  38596. opacity: 0
  38597. },
  38598. scaleX: 0,
  38599. scaleY: 0
  38600. }, seriesModel, {
  38601. dataIndex: dataIndex,
  38602. cb: cb,
  38603. removeOpt: animationOpt
  38604. });
  38605. };
  38606. Symbol.getSymbolSize = function (data, idx) {
  38607. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  38608. };
  38609. Symbol.getSymbolZ2 = function (data, idx) {
  38610. return data.getItemVisual(idx, 'z2');
  38611. };
  38612. return Symbol;
  38613. }(Group);
  38614. function driftSymbol(dx, dy) {
  38615. this.parent.drift(dx, dy);
  38616. }
  38617. function symbolNeedsDraw(data, point, idx, opt) {
  38618. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx))
  38619. // We do not set clipShape on group, because it will cut part of
  38620. // the symbol element shape. We use the same clip shape here as
  38621. // the line clip.
  38622. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  38623. }
  38624. function normalizeUpdateOpt(opt) {
  38625. if (opt != null && !isObject(opt)) {
  38626. opt = {
  38627. isIgnore: opt
  38628. };
  38629. }
  38630. return opt || {};
  38631. }
  38632. function makeSeriesScope(data) {
  38633. var seriesModel = data.hostModel;
  38634. var emphasisModel = seriesModel.getModel('emphasis');
  38635. return {
  38636. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  38637. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  38638. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  38639. focus: emphasisModel.get('focus'),
  38640. blurScope: emphasisModel.get('blurScope'),
  38641. emphasisDisabled: emphasisModel.get('disabled'),
  38642. hoverScale: emphasisModel.get('scale'),
  38643. labelStatesModels: getLabelStatesModels(seriesModel),
  38644. cursorStyle: seriesModel.get('cursor')
  38645. };
  38646. }
  38647. var SymbolDraw = /** @class */function () {
  38648. function SymbolDraw(SymbolCtor) {
  38649. this.group = new Group();
  38650. this._SymbolCtor = SymbolCtor || Symbol;
  38651. }
  38652. /**
  38653. * Update symbols draw by new data
  38654. */
  38655. SymbolDraw.prototype.updateData = function (data, opt) {
  38656. // Remove progressive els.
  38657. this._progressiveEls = null;
  38658. opt = normalizeUpdateOpt(opt);
  38659. var group = this.group;
  38660. var seriesModel = data.hostModel;
  38661. var oldData = this._data;
  38662. var SymbolCtor = this._SymbolCtor;
  38663. var disableAnimation = opt.disableAnimation;
  38664. var seriesScope = makeSeriesScope(data);
  38665. var symbolUpdateOpt = {
  38666. disableAnimation: disableAnimation
  38667. };
  38668. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  38669. return data.getItemLayout(idx);
  38670. };
  38671. // There is no oldLineData only when first rendering or switching from
  38672. // stream mode to normal mode, where previous elements should be removed.
  38673. if (!oldData) {
  38674. group.removeAll();
  38675. }
  38676. data.diff(oldData).add(function (newIdx) {
  38677. var point = getSymbolPoint(newIdx);
  38678. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  38679. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  38680. symbolEl.setPosition(point);
  38681. data.setItemGraphicEl(newIdx, symbolEl);
  38682. group.add(symbolEl);
  38683. }
  38684. }).update(function (newIdx, oldIdx) {
  38685. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  38686. var point = getSymbolPoint(newIdx);
  38687. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  38688. group.remove(symbolEl);
  38689. return;
  38690. }
  38691. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  38692. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  38693. if (!symbolEl
  38694. // Create a new if symbol type changed.
  38695. || oldSymbolType && oldSymbolType !== newSymbolType) {
  38696. group.remove(symbolEl);
  38697. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  38698. symbolEl.setPosition(point);
  38699. } else {
  38700. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  38701. var target = {
  38702. x: point[0],
  38703. y: point[1]
  38704. };
  38705. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  38706. }
  38707. // Add back
  38708. group.add(symbolEl);
  38709. data.setItemGraphicEl(newIdx, symbolEl);
  38710. }).remove(function (oldIdx) {
  38711. var el = oldData.getItemGraphicEl(oldIdx);
  38712. el && el.fadeOut(function () {
  38713. group.remove(el);
  38714. }, seriesModel);
  38715. }).execute();
  38716. this._getSymbolPoint = getSymbolPoint;
  38717. this._data = data;
  38718. };
  38719. SymbolDraw.prototype.updateLayout = function () {
  38720. var _this = this;
  38721. var data = this._data;
  38722. if (data) {
  38723. // Not use animation
  38724. data.eachItemGraphicEl(function (el, idx) {
  38725. var point = _this._getSymbolPoint(idx);
  38726. el.setPosition(point);
  38727. el.markRedraw();
  38728. });
  38729. }
  38730. };
  38731. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  38732. this._seriesScope = makeSeriesScope(data);
  38733. this._data = null;
  38734. this.group.removeAll();
  38735. };
  38736. /**
  38737. * Update symbols draw by new data
  38738. */
  38739. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  38740. // Clear
  38741. this._progressiveEls = [];
  38742. opt = normalizeUpdateOpt(opt);
  38743. function updateIncrementalAndHover(el) {
  38744. if (!el.isGroup) {
  38745. el.incremental = true;
  38746. el.ensureState('emphasis').hoverLayer = true;
  38747. }
  38748. }
  38749. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  38750. var point = data.getItemLayout(idx);
  38751. if (symbolNeedsDraw(data, point, idx, opt)) {
  38752. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  38753. el.traverse(updateIncrementalAndHover);
  38754. el.setPosition(point);
  38755. this.group.add(el);
  38756. data.setItemGraphicEl(idx, el);
  38757. this._progressiveEls.push(el);
  38758. }
  38759. }
  38760. };
  38761. SymbolDraw.prototype.eachRendered = function (cb) {
  38762. traverseElements(this._progressiveEls || this.group, cb);
  38763. };
  38764. SymbolDraw.prototype.remove = function (enableAnimation) {
  38765. var group = this.group;
  38766. var data = this._data;
  38767. // Incremental model do not have this._data.
  38768. if (data && enableAnimation) {
  38769. data.eachItemGraphicEl(function (el) {
  38770. el.fadeOut(function () {
  38771. group.remove(el);
  38772. }, data.hostModel);
  38773. });
  38774. } else {
  38775. group.removeAll();
  38776. }
  38777. };
  38778. return SymbolDraw;
  38779. }();
  38780. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  38781. var baseAxis = coordSys.getBaseAxis();
  38782. var valueAxis = coordSys.getOtherAxis(baseAxis);
  38783. var valueStart = getValueStart(valueAxis, valueOrigin);
  38784. var baseAxisDim = baseAxis.dim;
  38785. var valueAxisDim = valueAxis.dim;
  38786. var valueDim = data.mapDimension(valueAxisDim);
  38787. var baseDim = data.mapDimension(baseAxisDim);
  38788. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  38789. var dims = map(coordSys.dimensions, function (coordDim) {
  38790. return data.mapDimension(coordDim);
  38791. });
  38792. var stacked = false;
  38793. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  38794. if (isDimensionStacked(data, dims[0] /* , dims[1] */)) {
  38795. // jshint ignore:line
  38796. stacked = true;
  38797. dims[0] = stackResultDim;
  38798. }
  38799. if (isDimensionStacked(data, dims[1] /* , dims[0] */)) {
  38800. // jshint ignore:line
  38801. stacked = true;
  38802. dims[1] = stackResultDim;
  38803. }
  38804. return {
  38805. dataDimsForPoint: dims,
  38806. valueStart: valueStart,
  38807. valueAxisDim: valueAxisDim,
  38808. baseAxisDim: baseAxisDim,
  38809. stacked: !!stacked,
  38810. valueDim: valueDim,
  38811. baseDim: baseDim,
  38812. baseDataOffset: baseDataOffset,
  38813. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  38814. };
  38815. }
  38816. function getValueStart(valueAxis, valueOrigin) {
  38817. var valueStart = 0;
  38818. var extent = valueAxis.scale.getExtent();
  38819. if (valueOrigin === 'start') {
  38820. valueStart = extent[0];
  38821. } else if (valueOrigin === 'end') {
  38822. valueStart = extent[1];
  38823. }
  38824. // If origin is specified as a number, use it as
  38825. // valueStart directly
  38826. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  38827. valueStart = valueOrigin;
  38828. }
  38829. // auto
  38830. else {
  38831. // Both positive
  38832. if (extent[0] > 0) {
  38833. valueStart = extent[0];
  38834. }
  38835. // Both negative
  38836. else if (extent[1] < 0) {
  38837. valueStart = extent[1];
  38838. }
  38839. // If is one positive, and one negative, onZero shall be true
  38840. }
  38841. return valueStart;
  38842. }
  38843. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  38844. var value = NaN;
  38845. if (dataCoordInfo.stacked) {
  38846. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  38847. }
  38848. if (isNaN(value)) {
  38849. value = dataCoordInfo.valueStart;
  38850. }
  38851. var baseDataOffset = dataCoordInfo.baseDataOffset;
  38852. var stackedData = [];
  38853. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  38854. stackedData[1 - baseDataOffset] = value;
  38855. return coordSys.dataToPoint(stackedData);
  38856. }
  38857. function diffData(oldData, newData) {
  38858. var diffResult = [];
  38859. newData.diff(oldData).add(function (idx) {
  38860. diffResult.push({
  38861. cmd: '+',
  38862. idx: idx
  38863. });
  38864. }).update(function (newIdx, oldIdx) {
  38865. diffResult.push({
  38866. cmd: '=',
  38867. idx: oldIdx,
  38868. idx1: newIdx
  38869. });
  38870. }).remove(function (idx) {
  38871. diffResult.push({
  38872. cmd: '-',
  38873. idx: idx
  38874. });
  38875. }).execute();
  38876. return diffResult;
  38877. }
  38878. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  38879. var diff = diffData(oldData, newData);
  38880. // let newIdList = newData.mapArray(newData.getId);
  38881. // let oldIdList = oldData.mapArray(oldData.getId);
  38882. // convertToIntId(newIdList, oldIdList);
  38883. // // FIXME One data ?
  38884. // diff = arrayDiff(oldIdList, newIdList);
  38885. var currPoints = [];
  38886. var nextPoints = [];
  38887. // Points for stacking base line
  38888. var currStackedPoints = [];
  38889. var nextStackedPoints = [];
  38890. var status = [];
  38891. var sortedIndices = [];
  38892. var rawIndices = [];
  38893. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  38894. // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  38895. var oldPoints = oldData.getLayout('points') || [];
  38896. var newPoints = newData.getLayout('points') || [];
  38897. for (var i = 0; i < diff.length; i++) {
  38898. var diffItem = diff[i];
  38899. var pointAdded = true;
  38900. var oldIdx2 = void 0;
  38901. var newIdx2 = void 0;
  38902. // FIXME, animation is not so perfect when dataZoom window moves fast
  38903. // Which is in case remvoing or add more than one data in the tail or head
  38904. switch (diffItem.cmd) {
  38905. case '=':
  38906. oldIdx2 = diffItem.idx * 2;
  38907. newIdx2 = diffItem.idx1 * 2;
  38908. var currentX = oldPoints[oldIdx2];
  38909. var currentY = oldPoints[oldIdx2 + 1];
  38910. var nextX = newPoints[newIdx2];
  38911. var nextY = newPoints[newIdx2 + 1];
  38912. // If previous data is NaN, use next point directly
  38913. if (isNaN(currentX) || isNaN(currentY)) {
  38914. currentX = nextX;
  38915. currentY = nextY;
  38916. }
  38917. currPoints.push(currentX, currentY);
  38918. nextPoints.push(nextX, nextY);
  38919. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  38920. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  38921. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  38922. break;
  38923. case '+':
  38924. var newIdx = diffItem.idx;
  38925. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  38926. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  38927. newIdx2 = newIdx * 2;
  38928. currPoints.push(oldPt[0], oldPt[1]);
  38929. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  38930. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  38931. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  38932. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  38933. rawIndices.push(newData.getRawIndex(newIdx));
  38934. break;
  38935. case '-':
  38936. pointAdded = false;
  38937. }
  38938. // Original indices
  38939. if (pointAdded) {
  38940. status.push(diffItem);
  38941. sortedIndices.push(sortedIndices.length);
  38942. }
  38943. }
  38944. // Diff result may be crossed if all items are changed
  38945. // Sort by data index
  38946. sortedIndices.sort(function (a, b) {
  38947. return rawIndices[a] - rawIndices[b];
  38948. });
  38949. var len = currPoints.length;
  38950. var sortedCurrPoints = createFloat32Array(len);
  38951. var sortedNextPoints = createFloat32Array(len);
  38952. var sortedCurrStackedPoints = createFloat32Array(len);
  38953. var sortedNextStackedPoints = createFloat32Array(len);
  38954. var sortedStatus = [];
  38955. for (var i = 0; i < sortedIndices.length; i++) {
  38956. var idx = sortedIndices[i];
  38957. var i2 = i * 2;
  38958. var idx2 = idx * 2;
  38959. sortedCurrPoints[i2] = currPoints[idx2];
  38960. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  38961. sortedNextPoints[i2] = nextPoints[idx2];
  38962. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  38963. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  38964. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  38965. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  38966. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  38967. sortedStatus[i] = status[idx];
  38968. }
  38969. return {
  38970. current: sortedCurrPoints,
  38971. next: sortedNextPoints,
  38972. stackedOnCurrent: sortedCurrStackedPoints,
  38973. stackedOnNext: sortedNextStackedPoints,
  38974. status: sortedStatus
  38975. };
  38976. }
  38977. var mathMin$6 = Math.min;
  38978. var mathMax$6 = Math.max;
  38979. function isPointNull(x, y) {
  38980. return isNaN(x) || isNaN(y);
  38981. }
  38982. /**
  38983. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  38984. * situations. This should be used when points are non-monotone neither in x or
  38985. * y dimension.
  38986. */
  38987. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  38988. var prevX;
  38989. var prevY;
  38990. var cpx0;
  38991. var cpy0;
  38992. var cpx1;
  38993. var cpy1;
  38994. var idx = start;
  38995. var k = 0;
  38996. for (; k < segLen; k++) {
  38997. var x = points[idx * 2];
  38998. var y = points[idx * 2 + 1];
  38999. if (idx >= allLen || idx < 0) {
  39000. break;
  39001. }
  39002. if (isPointNull(x, y)) {
  39003. if (connectNulls) {
  39004. idx += dir;
  39005. continue;
  39006. }
  39007. break;
  39008. }
  39009. if (idx === start) {
  39010. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  39011. cpx0 = x;
  39012. cpy0 = y;
  39013. } else {
  39014. var dx = x - prevX;
  39015. var dy = y - prevY;
  39016. // Ignore tiny segment.
  39017. if (dx * dx + dy * dy < 0.5) {
  39018. idx += dir;
  39019. continue;
  39020. }
  39021. if (smooth > 0) {
  39022. var nextIdx = idx + dir;
  39023. var nextX = points[nextIdx * 2];
  39024. var nextY = points[nextIdx * 2 + 1];
  39025. // Ignore duplicate point
  39026. while (nextX === x && nextY === y && k < segLen) {
  39027. k++;
  39028. nextIdx += dir;
  39029. idx += dir;
  39030. nextX = points[nextIdx * 2];
  39031. nextY = points[nextIdx * 2 + 1];
  39032. x = points[idx * 2];
  39033. y = points[idx * 2 + 1];
  39034. dx = x - prevX;
  39035. dy = y - prevY;
  39036. }
  39037. var tmpK = k + 1;
  39038. if (connectNulls) {
  39039. // Find next point not null
  39040. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  39041. tmpK++;
  39042. nextIdx += dir;
  39043. nextX = points[nextIdx * 2];
  39044. nextY = points[nextIdx * 2 + 1];
  39045. }
  39046. }
  39047. var ratioNextSeg = 0.5;
  39048. var vx = 0;
  39049. var vy = 0;
  39050. var nextCpx0 = void 0;
  39051. var nextCpy0 = void 0;
  39052. // Is last point
  39053. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  39054. cpx1 = x;
  39055. cpy1 = y;
  39056. } else {
  39057. vx = nextX - prevX;
  39058. vy = nextY - prevY;
  39059. var dx0 = x - prevX;
  39060. var dx1 = nextX - x;
  39061. var dy0 = y - prevY;
  39062. var dy1 = nextY - y;
  39063. var lenPrevSeg = void 0;
  39064. var lenNextSeg = void 0;
  39065. if (smoothMonotone === 'x') {
  39066. lenPrevSeg = Math.abs(dx0);
  39067. lenNextSeg = Math.abs(dx1);
  39068. var dir_1 = vx > 0 ? 1 : -1;
  39069. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  39070. cpy1 = y;
  39071. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  39072. nextCpy0 = y;
  39073. } else if (smoothMonotone === 'y') {
  39074. lenPrevSeg = Math.abs(dy0);
  39075. lenNextSeg = Math.abs(dy1);
  39076. var dir_2 = vy > 0 ? 1 : -1;
  39077. cpx1 = x;
  39078. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  39079. nextCpx0 = x;
  39080. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  39081. } else {
  39082. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  39083. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  39084. // Use ratio of seg length
  39085. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  39086. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  39087. cpy1 = y - vy * smooth * (1 - ratioNextSeg);
  39088. // cp0 of next segment
  39089. nextCpx0 = x + vx * smooth * ratioNextSeg;
  39090. nextCpy0 = y + vy * smooth * ratioNextSeg;
  39091. // Smooth constraint between point and next point.
  39092. // Avoid exceeding extreme after smoothing.
  39093. nextCpx0 = mathMin$6(nextCpx0, mathMax$6(nextX, x));
  39094. nextCpy0 = mathMin$6(nextCpy0, mathMax$6(nextY, y));
  39095. nextCpx0 = mathMax$6(nextCpx0, mathMin$6(nextX, x));
  39096. nextCpy0 = mathMax$6(nextCpy0, mathMin$6(nextY, y));
  39097. // Reclaculate cp1 based on the adjusted cp0 of next seg.
  39098. vx = nextCpx0 - x;
  39099. vy = nextCpy0 - y;
  39100. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  39101. cpy1 = y - vy * lenPrevSeg / lenNextSeg;
  39102. // Smooth constraint between point and prev point.
  39103. // Avoid exceeding extreme after smoothing.
  39104. cpx1 = mathMin$6(cpx1, mathMax$6(prevX, x));
  39105. cpy1 = mathMin$6(cpy1, mathMax$6(prevY, y));
  39106. cpx1 = mathMax$6(cpx1, mathMin$6(prevX, x));
  39107. cpy1 = mathMax$6(cpy1, mathMin$6(prevY, y));
  39108. // Adjust next cp0 again.
  39109. vx = x - cpx1;
  39110. vy = y - cpy1;
  39111. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  39112. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  39113. }
  39114. }
  39115. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  39116. cpx0 = nextCpx0;
  39117. cpy0 = nextCpy0;
  39118. } else {
  39119. ctx.lineTo(x, y);
  39120. }
  39121. }
  39122. prevX = x;
  39123. prevY = y;
  39124. idx += dir;
  39125. }
  39126. return k;
  39127. }
  39128. var ECPolylineShape = /** @class */function () {
  39129. function ECPolylineShape() {
  39130. this.smooth = 0;
  39131. this.smoothConstraint = true;
  39132. }
  39133. return ECPolylineShape;
  39134. }();
  39135. var ECPolyline = /** @class */function (_super) {
  39136. __extends(ECPolyline, _super);
  39137. function ECPolyline(opts) {
  39138. var _this = _super.call(this, opts) || this;
  39139. _this.type = 'ec-polyline';
  39140. return _this;
  39141. }
  39142. ECPolyline.prototype.getDefaultStyle = function () {
  39143. return {
  39144. stroke: tokens.color.neutral99,
  39145. fill: null
  39146. };
  39147. };
  39148. ECPolyline.prototype.getDefaultShape = function () {
  39149. return new ECPolylineShape();
  39150. };
  39151. ECPolyline.prototype.buildPath = function (ctx, shape) {
  39152. var points = shape.points;
  39153. var i = 0;
  39154. var len = points.length / 2;
  39155. // const result = getBoundingBox(points, shape.smoothConstraint);
  39156. if (shape.connectNulls) {
  39157. // Must remove first and last null values avoid draw error in polygon
  39158. for (; len > 0; len--) {
  39159. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  39160. break;
  39161. }
  39162. }
  39163. for (; i < len; i++) {
  39164. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  39165. break;
  39166. }
  39167. }
  39168. }
  39169. while (i < len) {
  39170. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  39171. }
  39172. };
  39173. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  39174. if (!this.path) {
  39175. this.createPathProxy();
  39176. this.buildPath(this.path, this.shape);
  39177. }
  39178. var path = this.path;
  39179. var data = path.data;
  39180. var CMD = PathProxy.CMD;
  39181. var x0;
  39182. var y0;
  39183. var isDimX = dim === 'x';
  39184. var roots = [];
  39185. for (var i = 0; i < data.length;) {
  39186. var cmd = data[i++];
  39187. var x = void 0;
  39188. var y = void 0;
  39189. var x2 = void 0;
  39190. var y2 = void 0;
  39191. var x3 = void 0;
  39192. var y3 = void 0;
  39193. var t = void 0;
  39194. switch (cmd) {
  39195. case CMD.M:
  39196. x0 = data[i++];
  39197. y0 = data[i++];
  39198. break;
  39199. case CMD.L:
  39200. x = data[i++];
  39201. y = data[i++];
  39202. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  39203. if (t <= 1 && t >= 0) {
  39204. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  39205. return isDimX ? [xOrY, val] : [val, xOrY];
  39206. }
  39207. x0 = x;
  39208. y0 = y;
  39209. break;
  39210. case CMD.C:
  39211. x = data[i++];
  39212. y = data[i++];
  39213. x2 = data[i++];
  39214. y2 = data[i++];
  39215. x3 = data[i++];
  39216. y3 = data[i++];
  39217. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  39218. if (nRoot > 0) {
  39219. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  39220. var t_1 = roots[i_1];
  39221. if (t_1 <= 1 && t_1 >= 0) {
  39222. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  39223. return isDimX ? [xOrY, val] : [val, xOrY];
  39224. }
  39225. }
  39226. }
  39227. x0 = x3;
  39228. y0 = y3;
  39229. break;
  39230. }
  39231. }
  39232. };
  39233. return ECPolyline;
  39234. }(Path);
  39235. var ECPolygonShape = /** @class */function (_super) {
  39236. __extends(ECPolygonShape, _super);
  39237. function ECPolygonShape() {
  39238. return _super !== null && _super.apply(this, arguments) || this;
  39239. }
  39240. return ECPolygonShape;
  39241. }(ECPolylineShape);
  39242. var ECPolygon = /** @class */function (_super) {
  39243. __extends(ECPolygon, _super);
  39244. function ECPolygon(opts) {
  39245. var _this = _super.call(this, opts) || this;
  39246. _this.type = 'ec-polygon';
  39247. return _this;
  39248. }
  39249. ECPolygon.prototype.getDefaultShape = function () {
  39250. return new ECPolygonShape();
  39251. };
  39252. ECPolygon.prototype.buildPath = function (ctx, shape) {
  39253. var points = shape.points;
  39254. var stackedOnPoints = shape.stackedOnPoints;
  39255. var i = 0;
  39256. var len = points.length / 2;
  39257. var smoothMonotone = shape.smoothMonotone;
  39258. if (shape.connectNulls) {
  39259. // Must remove first and last null values avoid draw error in polygon
  39260. for (; len > 0; len--) {
  39261. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  39262. break;
  39263. }
  39264. }
  39265. for (; i < len; i++) {
  39266. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  39267. break;
  39268. }
  39269. }
  39270. }
  39271. while (i < len) {
  39272. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  39273. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  39274. i += k + 1;
  39275. ctx.closePath();
  39276. }
  39277. };
  39278. return ECPolygon;
  39279. }(Path);
  39280. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  39281. var rect = cartesian.getArea();
  39282. var x = rect.x;
  39283. var y = rect.y;
  39284. var width = rect.width;
  39285. var height = rect.height;
  39286. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 0;
  39287. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  39288. x -= lineWidth / 2;
  39289. y -= lineWidth / 2;
  39290. width += lineWidth;
  39291. height += lineWidth;
  39292. // fix: https://github.com/apache/incubator-echarts/issues/11369
  39293. width = Math.ceil(width);
  39294. if (x !== Math.floor(x)) {
  39295. x = Math.floor(x);
  39296. // if no extra 1px on `width`, it will still be clipped since `x` is floored
  39297. width++;
  39298. }
  39299. var clipPath = new Rect({
  39300. shape: {
  39301. x: x,
  39302. y: y,
  39303. width: width,
  39304. height: height
  39305. }
  39306. });
  39307. if (hasAnimation) {
  39308. var baseAxis = cartesian.getBaseAxis();
  39309. var isHorizontal = baseAxis.isHorizontal();
  39310. var isAxisInversed = baseAxis.inverse;
  39311. if (isHorizontal) {
  39312. if (isAxisInversed) {
  39313. clipPath.shape.x += width;
  39314. }
  39315. clipPath.shape.width = 0;
  39316. } else {
  39317. if (!isAxisInversed) {
  39318. clipPath.shape.y += height;
  39319. }
  39320. clipPath.shape.height = 0;
  39321. }
  39322. var duringCb = isFunction(during) ? function (percent) {
  39323. during(percent, clipPath);
  39324. } : null;
  39325. initProps(clipPath, {
  39326. shape: {
  39327. width: width,
  39328. height: height,
  39329. x: x,
  39330. y: y
  39331. }
  39332. }, seriesModel, null, done, duringCb);
  39333. }
  39334. return clipPath;
  39335. }
  39336. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  39337. var sectorArea = polar.getArea();
  39338. // Avoid float number rounding error for symbol on the edge of axis extent.
  39339. var r0 = round(sectorArea.r0, 1);
  39340. var r = round(sectorArea.r, 1);
  39341. var clipPath = new Sector({
  39342. shape: {
  39343. cx: round(polar.cx, 1),
  39344. cy: round(polar.cy, 1),
  39345. r0: r0,
  39346. r: r,
  39347. startAngle: sectorArea.startAngle,
  39348. endAngle: sectorArea.endAngle,
  39349. clockwise: sectorArea.clockwise
  39350. }
  39351. });
  39352. if (hasAnimation) {
  39353. var isRadial = polar.getBaseAxis().dim === 'angle';
  39354. if (isRadial) {
  39355. clipPath.shape.endAngle = sectorArea.startAngle;
  39356. } else {
  39357. clipPath.shape.r = r0;
  39358. }
  39359. initProps(clipPath, {
  39360. shape: {
  39361. endAngle: sectorArea.endAngle,
  39362. r: r
  39363. }
  39364. }, seriesModel);
  39365. }
  39366. return clipPath;
  39367. }
  39368. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  39369. if (!coordSys) {
  39370. return null;
  39371. } else if (coordSys.type === 'polar') {
  39372. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  39373. } else if (coordSys.type === 'cartesian2d') {
  39374. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  39375. }
  39376. return null;
  39377. }
  39378. /*
  39379. * Licensed to the Apache Software Foundation (ASF) under one
  39380. * or more contributor license agreements. See the NOTICE file
  39381. * distributed with this work for additional information
  39382. * regarding copyright ownership. The ASF licenses this file
  39383. * to you under the Apache License, Version 2.0 (the
  39384. * "License"); you may not use this file except in compliance
  39385. * with the License. You may obtain a copy of the License at
  39386. *
  39387. * http://www.apache.org/licenses/LICENSE-2.0
  39388. *
  39389. * Unless required by applicable law or agreed to in writing,
  39390. * software distributed under the License is distributed on an
  39391. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39392. * KIND, either express or implied. See the License for the
  39393. * specific language governing permissions and limitations
  39394. * under the License.
  39395. */
  39396. /**
  39397. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39398. */
  39399. /*
  39400. * Licensed to the Apache Software Foundation (ASF) under one
  39401. * or more contributor license agreements. See the NOTICE file
  39402. * distributed with this work for additional information
  39403. * regarding copyright ownership. The ASF licenses this file
  39404. * to you under the Apache License, Version 2.0 (the
  39405. * "License"); you may not use this file except in compliance
  39406. * with the License. You may obtain a copy of the License at
  39407. *
  39408. * http://www.apache.org/licenses/LICENSE-2.0
  39409. *
  39410. * Unless required by applicable law or agreed to in writing,
  39411. * software distributed under the License is distributed on an
  39412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39413. * KIND, either express or implied. See the License for the
  39414. * specific language governing permissions and limitations
  39415. * under the License.
  39416. */
  39417. function isCoordinateSystemType(coordSys, type) {
  39418. return coordSys.type === type;
  39419. }
  39420. function isPointsSame(points1, points2) {
  39421. if (points1.length !== points2.length) {
  39422. return;
  39423. }
  39424. for (var i = 0; i < points1.length; i++) {
  39425. if (points1[i] !== points2[i]) {
  39426. return;
  39427. }
  39428. }
  39429. return true;
  39430. }
  39431. function bboxFromPoints(points) {
  39432. var minX = Infinity;
  39433. var minY = Infinity;
  39434. var maxX = -Infinity;
  39435. var maxY = -Infinity;
  39436. for (var i = 0; i < points.length;) {
  39437. var x = points[i++];
  39438. var y = points[i++];
  39439. if (!isNaN(x)) {
  39440. minX = Math.min(x, minX);
  39441. maxX = Math.max(x, maxX);
  39442. }
  39443. if (!isNaN(y)) {
  39444. minY = Math.min(y, minY);
  39445. maxY = Math.max(y, maxY);
  39446. }
  39447. }
  39448. return [[minX, minY], [maxX, maxY]];
  39449. }
  39450. function getBoundingDiff(points1, points2) {
  39451. var _a = bboxFromPoints(points1),
  39452. min1 = _a[0],
  39453. max1 = _a[1];
  39454. var _b = bboxFromPoints(points2),
  39455. min2 = _b[0],
  39456. max2 = _b[1];
  39457. // Get a max value from each corner of two boundings.
  39458. 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]));
  39459. }
  39460. function getSmooth(smooth) {
  39461. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  39462. }
  39463. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  39464. if (!dataCoordInfo.valueDim) {
  39465. return [];
  39466. }
  39467. var len = data.count();
  39468. var points = createFloat32Array(len * 2);
  39469. for (var idx = 0; idx < len; idx++) {
  39470. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  39471. points[idx * 2] = pt[0];
  39472. points[idx * 2 + 1] = pt[1];
  39473. }
  39474. return points;
  39475. }
  39476. /**
  39477. * Filter the null data and extend data for step considering `stepTurnAt`
  39478. *
  39479. * @param points data to convert, that may containing null
  39480. * @param basePoints base data to reference, used only for areaStyle points
  39481. * @param coordSys coordinate system
  39482. * @param stepTurnAt 'start' | 'end' | 'middle' | true
  39483. * @param connectNulls whether to connect nulls
  39484. * @returns converted point positions
  39485. */
  39486. function turnPointsIntoStep(points, basePoints, coordSys, stepTurnAt, connectNulls) {
  39487. var baseAxis = coordSys.getBaseAxis();
  39488. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  39489. var stepPoints = [];
  39490. var i = 0;
  39491. var stepPt = [];
  39492. var pt = [];
  39493. var nextPt = [];
  39494. var filteredPoints = [];
  39495. if (connectNulls) {
  39496. for (i = 0; i < points.length; i += 2) {
  39497. /**
  39498. * For areaStyle of stepped lines, `stackedOnPoints` should be
  39499. * filtered the same as `points` so that the base axis values
  39500. * should stay the same as the lines above. See #20021
  39501. */
  39502. var reference = basePoints || points;
  39503. if (!isNaN(reference[i]) && !isNaN(reference[i + 1])) {
  39504. filteredPoints.push(points[i], points[i + 1]);
  39505. }
  39506. }
  39507. points = filteredPoints;
  39508. }
  39509. for (i = 0; i < points.length - 2; i += 2) {
  39510. nextPt[0] = points[i + 2];
  39511. nextPt[1] = points[i + 3];
  39512. pt[0] = points[i];
  39513. pt[1] = points[i + 1];
  39514. stepPoints.push(pt[0], pt[1]);
  39515. switch (stepTurnAt) {
  39516. case 'end':
  39517. stepPt[baseIndex] = nextPt[baseIndex];
  39518. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  39519. stepPoints.push(stepPt[0], stepPt[1]);
  39520. break;
  39521. case 'middle':
  39522. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  39523. var stepPt2 = [];
  39524. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  39525. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  39526. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  39527. stepPoints.push(stepPt[0], stepPt[1]);
  39528. stepPoints.push(stepPt2[0], stepPt2[1]);
  39529. break;
  39530. default:
  39531. // default is start
  39532. stepPt[baseIndex] = pt[baseIndex];
  39533. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  39534. stepPoints.push(stepPt[0], stepPt[1]);
  39535. }
  39536. }
  39537. // Last points
  39538. stepPoints.push(points[i++], points[i++]);
  39539. return stepPoints;
  39540. }
  39541. /**
  39542. * Clip color stops to edge. Avoid creating too large gradients.
  39543. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  39544. *
  39545. * The stops has been sorted from small to large.
  39546. */
  39547. function clipColorStops(colorStops, maxSize) {
  39548. var newColorStops = [];
  39549. var len = colorStops.length;
  39550. // coord will always < 0 in prevOutOfRangeColorStop.
  39551. var prevOutOfRangeColorStop;
  39552. var prevInRangeColorStop;
  39553. function lerpStop(stop0, stop1, clippedCoord) {
  39554. var coord0 = stop0.coord;
  39555. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  39556. var color = lerp$1(p, [stop0.color, stop1.color]);
  39557. return {
  39558. coord: clippedCoord,
  39559. color: color
  39560. };
  39561. }
  39562. for (var i = 0; i < len; i++) {
  39563. var stop_1 = colorStops[i];
  39564. var coord = stop_1.coord;
  39565. if (coord < 0) {
  39566. prevOutOfRangeColorStop = stop_1;
  39567. } else if (coord > maxSize) {
  39568. if (prevInRangeColorStop) {
  39569. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  39570. } else if (prevOutOfRangeColorStop) {
  39571. // If there are two stops and coord range is between these two stops
  39572. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  39573. }
  39574. // All following stop will be out of range. So just ignore them.
  39575. break;
  39576. } else {
  39577. if (prevOutOfRangeColorStop) {
  39578. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0));
  39579. // Reset
  39580. prevOutOfRangeColorStop = null;
  39581. }
  39582. newColorStops.push(stop_1);
  39583. prevInRangeColorStop = stop_1;
  39584. }
  39585. }
  39586. return newColorStops;
  39587. }
  39588. function getVisualGradient(data, coordSys, api) {
  39589. var visualMetaList = data.getVisual('visualMeta');
  39590. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  39591. // When data.count() is 0, gradient range can not be calculated.
  39592. return;
  39593. }
  39594. if (coordSys.type !== 'cartesian2d') {
  39595. if ("development" !== 'production') {
  39596. console.warn('Visual map on line style is only supported on cartesian2d.');
  39597. }
  39598. return;
  39599. }
  39600. var coordDim;
  39601. var visualMeta;
  39602. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  39603. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  39604. coordDim = dimInfo && dimInfo.coordDim;
  39605. // Can only be x or y
  39606. if (coordDim === 'x' || coordDim === 'y') {
  39607. visualMeta = visualMetaList[i];
  39608. break;
  39609. }
  39610. }
  39611. if (!visualMeta) {
  39612. if ("development" !== 'production') {
  39613. console.warn('Visual map on line style only support x or y dimension.');
  39614. }
  39615. return;
  39616. }
  39617. // If the area to be rendered is bigger than area defined by LinearGradient,
  39618. // the canvas spec prescribes that the color of the first stop and the last
  39619. // stop should be used. But if two stops are added at offset 0, in effect
  39620. // browsers use the color of the second stop to render area outside
  39621. // LinearGradient. So we can only infinitesimally extend area defined in
  39622. // LinearGradient to render `outerColors`.
  39623. var axis = coordSys.getAxis(coordDim);
  39624. // dataToCoord mapping may not be linear, but must be monotonic.
  39625. var colorStops = map(visualMeta.stops, function (stop) {
  39626. // offset will be calculated later.
  39627. return {
  39628. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  39629. color: stop.color
  39630. };
  39631. });
  39632. var stopLen = colorStops.length;
  39633. var outerColors = visualMeta.outerColors.slice();
  39634. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  39635. colorStops.reverse();
  39636. outerColors.reverse();
  39637. }
  39638. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  39639. var inRangeStopLen = colorStopsInRange.length;
  39640. if (!inRangeStopLen && stopLen) {
  39641. // All stops are out of range. All will be the same color.
  39642. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  39643. }
  39644. var tinyExtent = 10; // Arbitrary value: 10px
  39645. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  39646. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  39647. var coordSpan = maxCoord - minCoord;
  39648. if (coordSpan < 1e-3) {
  39649. return 'transparent';
  39650. }
  39651. each(colorStopsInRange, function (stop) {
  39652. stop.offset = (stop.coord - minCoord) / coordSpan;
  39653. });
  39654. colorStopsInRange.push({
  39655. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  39656. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  39657. color: outerColors[1] || 'transparent'
  39658. });
  39659. colorStopsInRange.unshift({
  39660. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  39661. color: outerColors[0] || 'transparent'
  39662. });
  39663. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  39664. gradient[coordDim] = minCoord;
  39665. gradient[coordDim + '2'] = maxCoord;
  39666. return gradient;
  39667. }
  39668. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  39669. var showAllSymbol = seriesModel.get('showAllSymbol');
  39670. var isAuto = showAllSymbol === 'auto';
  39671. if (showAllSymbol && !isAuto) {
  39672. return;
  39673. }
  39674. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  39675. if (!categoryAxis) {
  39676. return;
  39677. }
  39678. // Note that category label interval strategy might bring some weird effect
  39679. // in some scenario: users may wonder why some of the symbols are not
  39680. // displayed. So we show all symbols as possible as we can.
  39681. if (isAuto
  39682. // Simplify the logic, do not determine label overlap here.
  39683. && canShowAllSymbolForCategory(categoryAxis, data)) {
  39684. return;
  39685. }
  39686. // Otherwise follow the label interval strategy on category axis.
  39687. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  39688. var labelMap = {};
  39689. each(categoryAxis.getViewLabels(), function (labelItem) {
  39690. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  39691. labelMap[ordinalNumber] = 1;
  39692. });
  39693. return function (dataIndex) {
  39694. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  39695. };
  39696. }
  39697. function canShowAllSymbolForCategory(categoryAxis, data) {
  39698. // In most cases, line is monotonous on category axis, and the label size
  39699. // is close with each other. So we check the symbol size and some of the
  39700. // label size alone with the category axis to estimate whether all symbol
  39701. // can be shown without overlap.
  39702. var axisExtent = categoryAxis.getExtent();
  39703. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  39704. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  39705. // Sampling some points, max 5.
  39706. var dataLen = data.count();
  39707. var step = Math.max(1, Math.round(dataLen / 5));
  39708. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  39709. if (Symbol.getSymbolSize(data, dataIndex
  39710. // Only for cartesian, where `isHorizontal` exists.
  39711. )[categoryAxis.isHorizontal() ? 1 : 0]
  39712. // Empirical number
  39713. * 1.5 > availSize) {
  39714. return false;
  39715. }
  39716. }
  39717. return true;
  39718. }
  39719. function isPointNull$1(x, y) {
  39720. return isNaN(x) || isNaN(y);
  39721. }
  39722. function getLastIndexNotNull(points) {
  39723. var len = points.length / 2;
  39724. for (; len > 0; len--) {
  39725. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  39726. break;
  39727. }
  39728. }
  39729. return len - 1;
  39730. }
  39731. function getPointAtIndex(points, idx) {
  39732. return [points[idx * 2], points[idx * 2 + 1]];
  39733. }
  39734. function getIndexRange(points, xOrY, dim) {
  39735. var len = points.length / 2;
  39736. var dimIdx = dim === 'x' ? 0 : 1;
  39737. var a;
  39738. var b;
  39739. var prevIndex = 0;
  39740. var nextIndex = -1;
  39741. for (var i = 0; i < len; i++) {
  39742. b = points[i * 2 + dimIdx];
  39743. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  39744. continue;
  39745. }
  39746. if (i === 0) {
  39747. a = b;
  39748. continue;
  39749. }
  39750. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  39751. nextIndex = i;
  39752. break;
  39753. }
  39754. prevIndex = i;
  39755. a = b;
  39756. }
  39757. return {
  39758. range: [prevIndex, nextIndex],
  39759. t: (xOrY - a) / (b - a)
  39760. };
  39761. }
  39762. function anyStateShowEndLabel(seriesModel) {
  39763. if (seriesModel.get(['endLabel', 'show'])) {
  39764. return true;
  39765. }
  39766. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  39767. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  39768. return true;
  39769. }
  39770. }
  39771. return false;
  39772. }
  39773. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  39774. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  39775. var endLabelModel_1 = seriesModel.getModel('endLabel');
  39776. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  39777. var data_1 = seriesModel.getData();
  39778. var labelAnimationRecord_1 = {
  39779. lastFrameIndex: 0
  39780. };
  39781. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  39782. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  39783. } : null;
  39784. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  39785. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  39786. var endLabel = lineView._endLabel;
  39787. if (endLabel && hasAnimation) {
  39788. if (labelAnimationRecord_1.originalX != null) {
  39789. endLabel.attr({
  39790. x: labelAnimationRecord_1.originalX,
  39791. y: labelAnimationRecord_1.originalY
  39792. });
  39793. }
  39794. }
  39795. }, during);
  39796. // Expand clip shape to avoid clipping when line value exceeds axis
  39797. if (!seriesModel.get('clip', true)) {
  39798. var rectShape = clipPath.shape;
  39799. var expandSize = Math.max(rectShape.width, rectShape.height);
  39800. if (isHorizontal) {
  39801. rectShape.y -= expandSize;
  39802. rectShape.height += expandSize * 2;
  39803. } else {
  39804. rectShape.x -= expandSize;
  39805. rectShape.width += expandSize * 2;
  39806. }
  39807. }
  39808. // Set to the final frame. To make sure label layout is right.
  39809. if (during) {
  39810. during(1, clipPath);
  39811. }
  39812. return clipPath;
  39813. } else {
  39814. if ("development" !== 'production') {
  39815. if (seriesModel.get(['endLabel', 'show'])) {
  39816. console.warn('endLabel is not supported for lines in polar systems.');
  39817. }
  39818. }
  39819. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  39820. }
  39821. }
  39822. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  39823. var baseAxis = coordSys.getBaseAxis();
  39824. var isHorizontal = baseAxis.isHorizontal();
  39825. var isBaseInversed = baseAxis.inverse;
  39826. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  39827. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  39828. return {
  39829. normal: {
  39830. align: endLabelModel.get('align') || align,
  39831. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  39832. }
  39833. };
  39834. }
  39835. var LineView = /** @class */function (_super) {
  39836. __extends(LineView, _super);
  39837. function LineView() {
  39838. return _super !== null && _super.apply(this, arguments) || this;
  39839. }
  39840. LineView.prototype.init = function () {
  39841. var lineGroup = new Group();
  39842. var symbolDraw = new SymbolDraw();
  39843. this.group.add(symbolDraw.group);
  39844. this._symbolDraw = symbolDraw;
  39845. this._lineGroup = lineGroup;
  39846. this._changePolyState = bind(this._changePolyState, this);
  39847. };
  39848. LineView.prototype.render = function (seriesModel, ecModel, api) {
  39849. var coordSys = seriesModel.coordinateSystem;
  39850. var group = this.group;
  39851. var data = seriesModel.getData();
  39852. var lineStyleModel = seriesModel.getModel('lineStyle');
  39853. var areaStyleModel = seriesModel.getModel('areaStyle');
  39854. var points = data.getLayout('points') || [];
  39855. var isCoordSysPolar = coordSys.type === 'polar';
  39856. var prevCoordSys = this._coordSys;
  39857. var symbolDraw = this._symbolDraw;
  39858. var polyline = this._polyline;
  39859. var polygon = this._polygon;
  39860. var lineGroup = this._lineGroup;
  39861. var hasAnimation = !ecModel.ssr && seriesModel.get('animation');
  39862. var isAreaChart = !areaStyleModel.isEmpty();
  39863. var valueOrigin = areaStyleModel.get('origin');
  39864. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  39865. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  39866. var showSymbol = seriesModel.get('showSymbol');
  39867. var connectNulls = seriesModel.get('connectNulls');
  39868. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys);
  39869. // Remove temporary symbols
  39870. var oldData = this._data;
  39871. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  39872. if (el.__temp) {
  39873. group.remove(el);
  39874. oldData.setItemGraphicEl(idx, null);
  39875. }
  39876. });
  39877. // Remove previous created symbols if showSymbol changed to false
  39878. if (!showSymbol) {
  39879. symbolDraw.remove();
  39880. }
  39881. group.add(lineGroup);
  39882. // FIXME step not support polar
  39883. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  39884. var clipShapeForSymbol;
  39885. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  39886. clipShapeForSymbol = coordSys.getArea();
  39887. // Avoid float number rounding error for symbol on the edge of axis extent.
  39888. // See #7913 and `test/dataZoom-clip.html`.
  39889. if (clipShapeForSymbol.width != null) {
  39890. clipShapeForSymbol.x -= 0.1;
  39891. clipShapeForSymbol.y -= 0.1;
  39892. clipShapeForSymbol.width += 0.2;
  39893. clipShapeForSymbol.height += 0.2;
  39894. } else if (clipShapeForSymbol.r0) {
  39895. clipShapeForSymbol.r0 -= 0.5;
  39896. clipShapeForSymbol.r += 0.5;
  39897. }
  39898. }
  39899. this._clipShapeForSymbol = clipShapeForSymbol;
  39900. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')];
  39901. // Initialization animation or coordinate system changed
  39902. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  39903. showSymbol && symbolDraw.updateData(data, {
  39904. isIgnore: isIgnoreFunc,
  39905. clipShape: clipShapeForSymbol,
  39906. disableAnimation: true,
  39907. getSymbolPoint: function (idx) {
  39908. return [points[idx * 2], points[idx * 2 + 1]];
  39909. }
  39910. });
  39911. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  39912. if (step) {
  39913. if (stackedOnPoints) {
  39914. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, points, coordSys, step, connectNulls);
  39915. }
  39916. // TODO If stacked series is not step
  39917. points = turnPointsIntoStep(points, null, coordSys, step, connectNulls);
  39918. }
  39919. polyline = this._newPolyline(points);
  39920. if (isAreaChart) {
  39921. polygon = this._newPolygon(points, stackedOnPoints);
  39922. } // If areaStyle is removed
  39923. else if (polygon) {
  39924. lineGroup.remove(polygon);
  39925. polygon = this._polygon = null;
  39926. }
  39927. // NOTE: Must update _endLabel before setClipPath.
  39928. if (!isCoordSysPolar) {
  39929. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  39930. }
  39931. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  39932. } else {
  39933. if (isAreaChart && !polygon) {
  39934. // If areaStyle is added
  39935. polygon = this._newPolygon(points, stackedOnPoints);
  39936. } else if (polygon && !isAreaChart) {
  39937. // If areaStyle is removed
  39938. lineGroup.remove(polygon);
  39939. polygon = this._polygon = null;
  39940. }
  39941. // NOTE: Must update _endLabel before setClipPath.
  39942. if (!isCoordSysPolar) {
  39943. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  39944. }
  39945. // Update clipPath
  39946. var oldClipPath = lineGroup.getClipPath();
  39947. if (oldClipPath) {
  39948. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  39949. initProps(oldClipPath, {
  39950. shape: newClipPath.shape
  39951. }, seriesModel);
  39952. } else {
  39953. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  39954. }
  39955. // Always update, or it is wrong in the case turning on legend
  39956. // because points are not changed.
  39957. showSymbol && symbolDraw.updateData(data, {
  39958. isIgnore: isIgnoreFunc,
  39959. clipShape: clipShapeForSymbol,
  39960. disableAnimation: true,
  39961. getSymbolPoint: function (idx) {
  39962. return [points[idx * 2], points[idx * 2 + 1]];
  39963. }
  39964. });
  39965. // In the case data zoom triggered refreshing frequently
  39966. // Data may not change if line has a category axis. So it should animate nothing.
  39967. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  39968. if (hasAnimation) {
  39969. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  39970. } else {
  39971. // Not do it in update with animation
  39972. if (step) {
  39973. if (stackedOnPoints) {
  39974. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, points, coordSys, step, connectNulls);
  39975. }
  39976. // TODO If stacked series is not step
  39977. points = turnPointsIntoStep(points, null, coordSys, step, connectNulls);
  39978. }
  39979. polyline.setShape({
  39980. points: points
  39981. });
  39982. polygon && polygon.setShape({
  39983. points: points,
  39984. stackedOnPoints: stackedOnPoints
  39985. });
  39986. }
  39987. }
  39988. }
  39989. var emphasisModel = seriesModel.getModel('emphasis');
  39990. var focus = emphasisModel.get('focus');
  39991. var blurScope = emphasisModel.get('blurScope');
  39992. var emphasisDisabled = emphasisModel.get('disabled');
  39993. polyline.useStyle(defaults(
  39994. // Use color in lineStyle first
  39995. lineStyleModel.getLineStyle(), {
  39996. fill: 'none',
  39997. stroke: visualColor,
  39998. lineJoin: 'bevel'
  39999. }));
  40000. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  40001. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  40002. var emphasisLineStyle = polyline.getState('emphasis').style;
  40003. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  40004. }
  40005. // Needs seriesIndex for focus
  40006. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  40007. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  40008. var smooth = getSmooth(seriesModel.get('smooth'));
  40009. var smoothMonotone = seriesModel.get('smoothMonotone');
  40010. polyline.setShape({
  40011. smooth: smooth,
  40012. smoothMonotone: smoothMonotone,
  40013. connectNulls: connectNulls
  40014. });
  40015. if (polygon) {
  40016. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  40017. var stackedOnSmooth = 0;
  40018. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  40019. fill: visualColor,
  40020. opacity: 0.7,
  40021. lineJoin: 'bevel',
  40022. decal: data.getVisual('style').decal
  40023. }));
  40024. if (stackedOnSeries) {
  40025. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  40026. }
  40027. polygon.setShape({
  40028. smooth: smooth,
  40029. stackedOnSmooth: stackedOnSmooth,
  40030. smoothMonotone: smoothMonotone,
  40031. connectNulls: connectNulls
  40032. });
  40033. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle');
  40034. // Needs seriesIndex for focus
  40035. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  40036. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  40037. }
  40038. var changePolyState = this._changePolyState;
  40039. data.eachItemGraphicEl(function (el) {
  40040. // Switch polyline / polygon state if element changed its state.
  40041. el && (el.onHoverStateChange = changePolyState);
  40042. });
  40043. this._polyline.onHoverStateChange = changePolyState;
  40044. this._data = data;
  40045. // Save the coordinate system for transition animation when data changed
  40046. this._coordSys = coordSys;
  40047. this._stackedOnPoints = stackedOnPoints;
  40048. this._points = points;
  40049. this._step = step;
  40050. this._valueOrigin = valueOrigin;
  40051. if (seriesModel.get('triggerLineEvent')) {
  40052. this.packEventData(seriesModel, polyline);
  40053. polygon && this.packEventData(seriesModel, polygon);
  40054. }
  40055. };
  40056. LineView.prototype.packEventData = function (seriesModel, el) {
  40057. getECData(el).eventData = {
  40058. componentType: 'series',
  40059. componentSubType: 'line',
  40060. componentIndex: seriesModel.componentIndex,
  40061. seriesIndex: seriesModel.seriesIndex,
  40062. seriesName: seriesModel.name,
  40063. seriesType: 'line'
  40064. };
  40065. };
  40066. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  40067. var data = seriesModel.getData();
  40068. var dataIndex = queryDataIndex(data, payload);
  40069. this._changePolyState('emphasis');
  40070. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  40071. var points = data.getLayout('points');
  40072. var symbol = data.getItemGraphicEl(dataIndex);
  40073. if (!symbol) {
  40074. // Create a temporary symbol if it is not exists
  40075. var x = points[dataIndex * 2];
  40076. var y = points[dataIndex * 2 + 1];
  40077. if (isNaN(x) || isNaN(y)) {
  40078. // Null data
  40079. return;
  40080. }
  40081. // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  40082. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  40083. return;
  40084. }
  40085. var zlevel = seriesModel.get('zlevel') || 0;
  40086. var z = seriesModel.get('z') || 0;
  40087. symbol = new Symbol(data, dataIndex);
  40088. symbol.x = x;
  40089. symbol.y = y;
  40090. symbol.setZ(zlevel, z);
  40091. // ensure label text of the temporary symbol is in front of line and area polygon
  40092. var symbolLabel = symbol.getSymbolPath().getTextContent();
  40093. if (symbolLabel) {
  40094. symbolLabel.zlevel = zlevel;
  40095. symbolLabel.z = z;
  40096. symbolLabel.z2 = this._polyline.z2 + 1;
  40097. }
  40098. symbol.__temp = true;
  40099. data.setItemGraphicEl(dataIndex, symbol);
  40100. // Stop scale animation
  40101. symbol.stopSymbolAnimation(true);
  40102. this.group.add(symbol);
  40103. }
  40104. symbol.highlight();
  40105. } else {
  40106. // Highlight whole series
  40107. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  40108. }
  40109. };
  40110. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  40111. var data = seriesModel.getData();
  40112. var dataIndex = queryDataIndex(data, payload);
  40113. this._changePolyState('normal');
  40114. if (dataIndex != null && dataIndex >= 0) {
  40115. var symbol = data.getItemGraphicEl(dataIndex);
  40116. if (symbol) {
  40117. if (symbol.__temp) {
  40118. data.setItemGraphicEl(dataIndex, null);
  40119. this.group.remove(symbol);
  40120. } else {
  40121. symbol.downplay();
  40122. }
  40123. }
  40124. } else {
  40125. // FIXME
  40126. // can not downplay completely.
  40127. // Downplay whole series
  40128. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  40129. }
  40130. };
  40131. LineView.prototype._changePolyState = function (toState) {
  40132. var polygon = this._polygon;
  40133. setStatesFlag(this._polyline, toState);
  40134. polygon && setStatesFlag(polygon, toState);
  40135. };
  40136. LineView.prototype._newPolyline = function (points) {
  40137. var polyline = this._polyline;
  40138. // Remove previous created polyline
  40139. if (polyline) {
  40140. this._lineGroup.remove(polyline);
  40141. }
  40142. polyline = new ECPolyline({
  40143. shape: {
  40144. points: points
  40145. },
  40146. segmentIgnoreThreshold: 2,
  40147. z2: 10
  40148. });
  40149. this._lineGroup.add(polyline);
  40150. this._polyline = polyline;
  40151. return polyline;
  40152. };
  40153. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  40154. var polygon = this._polygon;
  40155. // Remove previous created polygon
  40156. if (polygon) {
  40157. this._lineGroup.remove(polygon);
  40158. }
  40159. polygon = new ECPolygon({
  40160. shape: {
  40161. points: points,
  40162. stackedOnPoints: stackedOnPoints
  40163. },
  40164. segmentIgnoreThreshold: 2
  40165. });
  40166. this._lineGroup.add(polygon);
  40167. this._polygon = polygon;
  40168. return polygon;
  40169. };
  40170. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  40171. var isHorizontalOrRadial;
  40172. var isCoordSysPolar;
  40173. var baseAxis = coordSys.getBaseAxis();
  40174. var isAxisInverse = baseAxis.inverse;
  40175. if (coordSys.type === 'cartesian2d') {
  40176. isHorizontalOrRadial = baseAxis.isHorizontal();
  40177. isCoordSysPolar = false;
  40178. } else if (coordSys.type === 'polar') {
  40179. isHorizontalOrRadial = baseAxis.dim === 'angle';
  40180. isCoordSysPolar = true;
  40181. }
  40182. var seriesModel = data.hostModel;
  40183. var seriesDuration = seriesModel.get('animationDuration');
  40184. if (isFunction(seriesDuration)) {
  40185. seriesDuration = seriesDuration(null);
  40186. }
  40187. var seriesDelay = seriesModel.get('animationDelay') || 0;
  40188. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  40189. data.eachItemGraphicEl(function (symbol, idx) {
  40190. var el = symbol;
  40191. if (el) {
  40192. var point = [symbol.x, symbol.y];
  40193. var start = void 0;
  40194. var end = void 0;
  40195. var current = void 0;
  40196. if (clipShape) {
  40197. if (isCoordSysPolar) {
  40198. var polarClip = clipShape;
  40199. var coord = coordSys.pointToCoord(point);
  40200. if (isHorizontalOrRadial) {
  40201. start = polarClip.startAngle;
  40202. end = polarClip.endAngle;
  40203. current = -coord[1] / 180 * Math.PI;
  40204. } else {
  40205. start = polarClip.r0;
  40206. end = polarClip.r;
  40207. current = coord[0];
  40208. }
  40209. } else {
  40210. var gridClip = clipShape;
  40211. if (isHorizontalOrRadial) {
  40212. start = gridClip.x;
  40213. end = gridClip.x + gridClip.width;
  40214. current = symbol.x;
  40215. } else {
  40216. start = gridClip.y + gridClip.height;
  40217. end = gridClip.y;
  40218. current = symbol.y;
  40219. }
  40220. }
  40221. }
  40222. var ratio = end === start ? 0 : (current - start) / (end - start);
  40223. if (isAxisInverse) {
  40224. ratio = 1 - ratio;
  40225. }
  40226. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  40227. var symbolPath = el.getSymbolPath();
  40228. var text = symbolPath.getTextContent();
  40229. el.attr({
  40230. scaleX: 0,
  40231. scaleY: 0
  40232. });
  40233. el.animateTo({
  40234. scaleX: 1,
  40235. scaleY: 1
  40236. }, {
  40237. duration: 200,
  40238. setToFinal: true,
  40239. delay: delay
  40240. });
  40241. if (text) {
  40242. text.animateFrom({
  40243. style: {
  40244. opacity: 0
  40245. }
  40246. }, {
  40247. duration: 300,
  40248. delay: delay
  40249. });
  40250. }
  40251. symbolPath.disableLabelAnimation = true;
  40252. }
  40253. });
  40254. };
  40255. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  40256. var endLabelModel = seriesModel.getModel('endLabel');
  40257. if (anyStateShowEndLabel(seriesModel)) {
  40258. var data_2 = seriesModel.getData();
  40259. var polyline = this._polyline;
  40260. // series may be filtered.
  40261. var points = data_2.getLayout('points');
  40262. if (!points) {
  40263. polyline.removeTextContent();
  40264. this._endLabel = null;
  40265. return;
  40266. }
  40267. var endLabel = this._endLabel;
  40268. if (!endLabel) {
  40269. endLabel = this._endLabel = new ZRText({
  40270. z2: 200 // should be higher than item symbol
  40271. });
  40272. endLabel.ignoreClip = true;
  40273. polyline.setTextContent(this._endLabel);
  40274. polyline.disableLabelAnimation = true;
  40275. }
  40276. // Find last non-NaN data to display data
  40277. var dataIndex = getLastIndexNotNull(points);
  40278. if (dataIndex >= 0) {
  40279. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  40280. inheritColor: inheritColor,
  40281. labelFetcher: seriesModel,
  40282. labelDataIndex: dataIndex,
  40283. defaultText: function (dataIndex, opt, interpolatedValue) {
  40284. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  40285. },
  40286. enableTextSetter: true
  40287. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  40288. polyline.textConfig.position = null;
  40289. }
  40290. } else if (this._endLabel) {
  40291. this._polyline.removeTextContent();
  40292. this._endLabel = null;
  40293. }
  40294. };
  40295. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  40296. var endLabel = this._endLabel;
  40297. var polyline = this._polyline;
  40298. if (endLabel) {
  40299. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  40300. // The label is not prepared at this time.
  40301. if (percent < 1 && animationRecord.originalX == null) {
  40302. animationRecord.originalX = endLabel.x;
  40303. animationRecord.originalY = endLabel.y;
  40304. }
  40305. var points = data.getLayout('points');
  40306. var seriesModel = data.hostModel;
  40307. var connectNulls = seriesModel.get('connectNulls');
  40308. var precision = endLabelModel.get('precision');
  40309. var distance = endLabelModel.get('distance') || 0;
  40310. var baseAxis = coordSys.getBaseAxis();
  40311. var isHorizontal = baseAxis.isHorizontal();
  40312. var isBaseInversed = baseAxis.inverse;
  40313. var clipShape = clipRect.shape;
  40314. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  40315. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  40316. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  40317. var dim = isHorizontal ? 'x' : 'y';
  40318. var dataIndexRange = getIndexRange(points, xOrY, dim);
  40319. var indices = dataIndexRange.range;
  40320. var diff = indices[1] - indices[0];
  40321. var value = void 0;
  40322. if (diff >= 1) {
  40323. // diff > 1 && connectNulls, which is on the null data.
  40324. if (diff > 1 && !connectNulls) {
  40325. var pt = getPointAtIndex(points, indices[0]);
  40326. endLabel.attr({
  40327. x: pt[0] + distanceX,
  40328. y: pt[1] + distanceY
  40329. });
  40330. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  40331. } else {
  40332. var pt = polyline.getPointOn(xOrY, dim);
  40333. pt && endLabel.attr({
  40334. x: pt[0] + distanceX,
  40335. y: pt[1] + distanceY
  40336. });
  40337. var startValue = seriesModel.getRawValue(indices[0]);
  40338. var endValue = seriesModel.getRawValue(indices[1]);
  40339. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  40340. }
  40341. animationRecord.lastFrameIndex = indices[0];
  40342. } else {
  40343. // If diff <= 0, which is the range is not found(Include NaN)
  40344. // Choose the first point or last point.
  40345. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  40346. var pt = getPointAtIndex(points, idx);
  40347. valueAnimation && (value = seriesModel.getRawValue(idx));
  40348. endLabel.attr({
  40349. x: pt[0] + distanceX,
  40350. y: pt[1] + distanceY
  40351. });
  40352. }
  40353. if (valueAnimation) {
  40354. var inner = labelInner(endLabel);
  40355. if (typeof inner.setLabelText === 'function') {
  40356. inner.setLabelText(value);
  40357. }
  40358. }
  40359. }
  40360. };
  40361. /**
  40362. * @private
  40363. */
  40364. // FIXME Two value axis
  40365. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  40366. var polyline = this._polyline;
  40367. var polygon = this._polygon;
  40368. var seriesModel = data.hostModel;
  40369. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  40370. var current = diff.current;
  40371. var stackedOnCurrent = diff.stackedOnCurrent;
  40372. var next = diff.next;
  40373. var stackedOnNext = diff.stackedOnNext;
  40374. if (step) {
  40375. // TODO If stacked series is not step
  40376. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, diff.current, coordSys, step, connectNulls);
  40377. current = turnPointsIntoStep(diff.current, null, coordSys, step, connectNulls);
  40378. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, diff.next, coordSys, step, connectNulls);
  40379. next = turnPointsIntoStep(diff.next, null, coordSys, step, connectNulls);
  40380. }
  40381. // Don't apply animation if diff is large.
  40382. // For better result and avoid memory explosion problems like
  40383. // https://github.com/apache/incubator-echarts/issues/12229
  40384. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  40385. polyline.stopAnimation();
  40386. polyline.setShape({
  40387. points: next
  40388. });
  40389. if (polygon) {
  40390. polygon.stopAnimation();
  40391. polygon.setShape({
  40392. points: next,
  40393. stackedOnPoints: stackedOnNext
  40394. });
  40395. }
  40396. return;
  40397. }
  40398. polyline.shape.__points = diff.current;
  40399. polyline.shape.points = current;
  40400. var target = {
  40401. shape: {
  40402. points: next
  40403. }
  40404. };
  40405. // Also animate the original points.
  40406. // If points reference is changed when turning into step line.
  40407. if (diff.current !== current) {
  40408. target.shape.__points = diff.next;
  40409. }
  40410. // Stop previous animation.
  40411. polyline.stopAnimation();
  40412. updateProps(polyline, target, seriesModel);
  40413. if (polygon) {
  40414. polygon.setShape({
  40415. // Reuse the points with polyline.
  40416. points: current,
  40417. stackedOnPoints: stackedOnCurrent
  40418. });
  40419. polygon.stopAnimation();
  40420. updateProps(polygon, {
  40421. shape: {
  40422. stackedOnPoints: stackedOnNext
  40423. }
  40424. }, seriesModel);
  40425. // If use attr directly in updateProps.
  40426. if (polyline.shape.points !== polygon.shape.points) {
  40427. polygon.shape.points = polyline.shape.points;
  40428. }
  40429. }
  40430. var updatedDataInfo = [];
  40431. var diffStatus = diff.status;
  40432. for (var i = 0; i < diffStatus.length; i++) {
  40433. var cmd = diffStatus[i].cmd;
  40434. if (cmd === '=') {
  40435. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  40436. if (el) {
  40437. updatedDataInfo.push({
  40438. el: el,
  40439. ptIdx: i // Index of points
  40440. });
  40441. }
  40442. }
  40443. }
  40444. if (polyline.animators && polyline.animators.length) {
  40445. polyline.animators[0].during(function () {
  40446. polygon && polygon.dirtyShape();
  40447. var points = polyline.shape.__points;
  40448. for (var i = 0; i < updatedDataInfo.length; i++) {
  40449. var el = updatedDataInfo[i].el;
  40450. var offset = updatedDataInfo[i].ptIdx * 2;
  40451. el.x = points[offset];
  40452. el.y = points[offset + 1];
  40453. el.markRedraw();
  40454. }
  40455. });
  40456. }
  40457. };
  40458. LineView.prototype.remove = function (ecModel) {
  40459. var group = this.group;
  40460. var oldData = this._data;
  40461. this._lineGroup.removeAll();
  40462. this._symbolDraw.remove(true);
  40463. // Remove temporary created elements when highlighting
  40464. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  40465. if (el.__temp) {
  40466. group.remove(el);
  40467. oldData.setItemGraphicEl(idx, null);
  40468. }
  40469. });
  40470. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  40471. };
  40472. LineView.type = 'line';
  40473. return LineView;
  40474. }(ChartView);
  40475. function pointsLayout(seriesType, forceStoreInTypedArray) {
  40476. return {
  40477. seriesType: seriesType,
  40478. plan: createRenderPlanner(),
  40479. reset: function (seriesModel) {
  40480. var data = seriesModel.getData();
  40481. var coordSys = seriesModel.coordinateSystem;
  40482. var pipelineContext = seriesModel.pipelineContext;
  40483. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  40484. if (!coordSys) {
  40485. return;
  40486. }
  40487. var dims = map(coordSys.dimensions, function (dim) {
  40488. return data.mapDimension(dim);
  40489. }).slice(0, 2);
  40490. var dimLen = dims.length;
  40491. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  40492. if (isDimensionStacked(data, dims[0])) {
  40493. dims[0] = stackResultDim;
  40494. }
  40495. if (isDimensionStacked(data, dims[1])) {
  40496. dims[1] = stackResultDim;
  40497. }
  40498. var store = data.getStore();
  40499. var dimIdx0 = data.getDimensionIndex(dims[0]);
  40500. var dimIdx1 = data.getDimensionIndex(dims[1]);
  40501. return dimLen && {
  40502. progress: function (params, data) {
  40503. var segCount = params.end - params.start;
  40504. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  40505. var tmpIn = [];
  40506. var tmpOut = [];
  40507. for (var i = params.start, offset = 0; i < params.end; i++) {
  40508. var point = void 0;
  40509. if (dimLen === 1) {
  40510. var x = store.get(dimIdx0, i);
  40511. // NOTE: Make sure the second parameter is null to use default strategy.
  40512. point = coordSys.dataToPoint(x, null, tmpOut);
  40513. } else {
  40514. tmpIn[0] = store.get(dimIdx0, i);
  40515. tmpIn[1] = store.get(dimIdx1, i);
  40516. // Let coordinate system to handle the NaN data.
  40517. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  40518. }
  40519. if (useTypedArray) {
  40520. points[offset++] = point[0];
  40521. points[offset++] = point[1];
  40522. } else {
  40523. data.setItemLayout(i, point.slice());
  40524. }
  40525. }
  40526. useTypedArray && data.setLayout('points', points);
  40527. }
  40528. };
  40529. }
  40530. };
  40531. }
  40532. var samplers = {
  40533. average: function (frame) {
  40534. var sum = 0;
  40535. var count = 0;
  40536. for (var i = 0; i < frame.length; i++) {
  40537. if (!isNaN(frame[i])) {
  40538. sum += frame[i];
  40539. count++;
  40540. }
  40541. }
  40542. // Return NaN if count is 0
  40543. return count === 0 ? NaN : sum / count;
  40544. },
  40545. sum: function (frame) {
  40546. var sum = 0;
  40547. for (var i = 0; i < frame.length; i++) {
  40548. // Ignore NaN
  40549. sum += frame[i] || 0;
  40550. }
  40551. return sum;
  40552. },
  40553. max: function (frame) {
  40554. var max = -Infinity;
  40555. for (var i = 0; i < frame.length; i++) {
  40556. frame[i] > max && (max = frame[i]);
  40557. }
  40558. // NaN will cause illegal axis extent.
  40559. return isFinite(max) ? max : NaN;
  40560. },
  40561. min: function (frame) {
  40562. var min = Infinity;
  40563. for (var i = 0; i < frame.length; i++) {
  40564. frame[i] < min && (min = frame[i]);
  40565. }
  40566. // NaN will cause illegal axis extent.
  40567. return isFinite(min) ? min : NaN;
  40568. },
  40569. // TODO
  40570. // Median
  40571. nearest: function (frame) {
  40572. return frame[0];
  40573. }
  40574. };
  40575. var indexSampler = function (frame) {
  40576. return Math.round(frame.length / 2);
  40577. };
  40578. function dataSample(seriesType) {
  40579. return {
  40580. seriesType: seriesType,
  40581. // FIXME:TS never used, so comment it
  40582. // modifyOutputEnd: true,
  40583. reset: function (seriesModel, ecModel, api) {
  40584. var data = seriesModel.getData();
  40585. var sampling = seriesModel.get('sampling');
  40586. var coordSys = seriesModel.coordinateSystem;
  40587. var count = data.count();
  40588. // Only cartesian2d support down sampling. Disable it when there is few data.
  40589. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  40590. var baseAxis = coordSys.getBaseAxis();
  40591. var valueAxis = coordSys.getOtherAxis(baseAxis);
  40592. var extent = baseAxis.getExtent();
  40593. var dpr = api.getDevicePixelRatio();
  40594. // Coordinste system has been resized
  40595. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  40596. var rate = Math.round(count / size);
  40597. if (isFinite(rate) && rate > 1) {
  40598. if (sampling === 'lttb') {
  40599. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  40600. } else if (sampling === 'minmax') {
  40601. seriesModel.setData(data.minmaxDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  40602. }
  40603. var sampler = void 0;
  40604. if (isString(sampling)) {
  40605. sampler = samplers[sampling];
  40606. } else if (isFunction(sampling)) {
  40607. sampler = sampling;
  40608. }
  40609. if (sampler) {
  40610. // Only support sample the first dim mapped from value axis.
  40611. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  40612. }
  40613. }
  40614. }
  40615. }
  40616. };
  40617. }
  40618. function install$2(registers) {
  40619. registers.registerChartView(LineView);
  40620. registers.registerSeriesModel(LineSeriesModel);
  40621. registers.registerLayout(pointsLayout('line', true));
  40622. registers.registerVisual({
  40623. seriesType: 'line',
  40624. reset: function (seriesModel) {
  40625. var data = seriesModel.getData();
  40626. // Visual coding for legend
  40627. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  40628. if (lineStyle && !lineStyle.stroke) {
  40629. // Fill in visual should be palette color if
  40630. // has color callback
  40631. lineStyle.stroke = data.getVisual('style').fill;
  40632. }
  40633. data.setVisual('legendLineStyle', lineStyle);
  40634. }
  40635. });
  40636. // Down sample after filter
  40637. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  40638. }
  40639. var BaseBarSeriesModel = /** @class */function (_super) {
  40640. __extends(BaseBarSeriesModel, _super);
  40641. function BaseBarSeriesModel() {
  40642. var _this = _super !== null && _super.apply(this, arguments) || this;
  40643. _this.type = BaseBarSeriesModel.type;
  40644. return _this;
  40645. }
  40646. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  40647. return createSeriesData(null, this, {
  40648. useEncodeDefaulter: true
  40649. });
  40650. };
  40651. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  40652. var coordSys = this.coordinateSystem;
  40653. if (coordSys && coordSys.clampData) {
  40654. // PENDING if clamp ?
  40655. var clampData_1 = coordSys.clampData(value);
  40656. var pt_1 = coordSys.dataToPoint(clampData_1);
  40657. if (startingAtTick) {
  40658. each(coordSys.getAxes(), function (axis, idx) {
  40659. // If axis type is category, use tick coords instead
  40660. if (axis.type === 'category' && dims != null) {
  40661. var tickCoords = axis.getTicksCoords();
  40662. var alignTicksWithLabel = axis.getTickModel().get('alignWithLabel');
  40663. var targetTickId = clampData_1[idx];
  40664. // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  40665. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  40666. if (isEnd && !alignTicksWithLabel) {
  40667. targetTickId += 1;
  40668. }
  40669. // The only contains one tick, tickCoords is
  40670. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  40671. // to the length should always be larger than 1
  40672. if (tickCoords.length < 2) {
  40673. return;
  40674. } else if (tickCoords.length === 2) {
  40675. // The left value and right value of the axis are
  40676. // the same. coord is 0 in both items. Use the max
  40677. // value of the axis as the coord
  40678. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  40679. return;
  40680. }
  40681. var leftCoord = void 0;
  40682. var coord = void 0;
  40683. var stepTickValue = 1;
  40684. for (var i = 0; i < tickCoords.length; i++) {
  40685. var tickCoord = tickCoords[i].coord;
  40686. // The last item of tickCoords doesn't contain
  40687. // tickValue
  40688. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  40689. if (tickValue === targetTickId) {
  40690. coord = tickCoord;
  40691. break;
  40692. } else if (tickValue < targetTickId) {
  40693. leftCoord = tickCoord;
  40694. } else if (leftCoord != null && tickValue > targetTickId) {
  40695. coord = (tickCoord + leftCoord) / 2;
  40696. break;
  40697. }
  40698. if (i === 1) {
  40699. // Here we assume the step of category axes is
  40700. // the same
  40701. stepTickValue = tickValue - tickCoords[0].tickValue;
  40702. }
  40703. }
  40704. if (coord == null) {
  40705. if (!leftCoord) {
  40706. // targetTickId is smaller than all tick ids in the
  40707. // visible area, use the leftmost tick coord
  40708. coord = tickCoords[0].coord;
  40709. } else if (leftCoord) {
  40710. // targetTickId is larger than all tick ids in the
  40711. // visible area, use the rightmost tick coord
  40712. coord = tickCoords[tickCoords.length - 1].coord;
  40713. }
  40714. }
  40715. pt_1[idx] = axis.toGlobalCoord(coord);
  40716. }
  40717. });
  40718. } else {
  40719. var data = this.getData();
  40720. var offset = data.getLayout('offset');
  40721. var size = data.getLayout('size');
  40722. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  40723. pt_1[offsetIndex] += offset + size / 2;
  40724. }
  40725. return pt_1;
  40726. }
  40727. return [NaN, NaN];
  40728. };
  40729. BaseBarSeriesModel.type = 'series.__base_bar__';
  40730. BaseBarSeriesModel.defaultOption = {
  40731. // zlevel: 0,
  40732. z: 2,
  40733. coordinateSystem: 'cartesian2d',
  40734. legendHoverLink: true,
  40735. // stack: null
  40736. // Cartesian coordinate system
  40737. // xAxisIndex: 0,
  40738. // yAxisIndex: 0,
  40739. barMinHeight: 0,
  40740. barMinAngle: 0,
  40741. // cursor: null,
  40742. large: false,
  40743. largeThreshold: 400,
  40744. progressive: 3e3,
  40745. progressiveChunkMode: 'mod',
  40746. defaultBarGap: '10%'
  40747. };
  40748. return BaseBarSeriesModel;
  40749. }(SeriesModel);
  40750. SeriesModel.registerClass(BaseBarSeriesModel);
  40751. var BarSeriesModel = /** @class */function (_super) {
  40752. __extends(BarSeriesModel, _super);
  40753. function BarSeriesModel() {
  40754. var _this = _super !== null && _super.apply(this, arguments) || this;
  40755. _this.type = BarSeriesModel.type;
  40756. return _this;
  40757. }
  40758. BarSeriesModel.prototype.getInitialData = function () {
  40759. return createSeriesData(null, this, {
  40760. useEncodeDefaulter: true,
  40761. createInvertedIndices: !!this.get('realtimeSort', true) || null
  40762. });
  40763. };
  40764. /**
  40765. * @override
  40766. */
  40767. BarSeriesModel.prototype.getProgressive = function () {
  40768. // Do not support progressive in normal mode.
  40769. return this.get('large') ? this.get('progressive') : false;
  40770. };
  40771. /**
  40772. * @override
  40773. */
  40774. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  40775. // Do not support progressive in normal mode.
  40776. var progressiveThreshold = this.get('progressiveThreshold');
  40777. var largeThreshold = this.get('largeThreshold');
  40778. if (largeThreshold > progressiveThreshold) {
  40779. progressiveThreshold = largeThreshold;
  40780. }
  40781. return progressiveThreshold;
  40782. };
  40783. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  40784. return selectors.rect(data.getItemLayout(dataIndex));
  40785. };
  40786. BarSeriesModel.type = 'series.bar';
  40787. BarSeriesModel.dependencies = ['grid', 'polar'];
  40788. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  40789. // If clipped
  40790. // Only available on cartesian2d
  40791. clip: true,
  40792. roundCap: false,
  40793. showBackground: false,
  40794. backgroundStyle: {
  40795. color: 'rgba(180, 180, 180, 0.2)',
  40796. borderColor: null,
  40797. borderWidth: 0,
  40798. borderType: 'solid',
  40799. borderRadius: 0,
  40800. shadowBlur: 0,
  40801. shadowColor: null,
  40802. shadowOffsetX: 0,
  40803. shadowOffsetY: 0,
  40804. opacity: 1
  40805. },
  40806. select: {
  40807. itemStyle: {
  40808. borderColor: tokens.color.primary,
  40809. borderWidth: 2
  40810. }
  40811. },
  40812. realtimeSort: false
  40813. });
  40814. return BarSeriesModel;
  40815. }(BaseBarSeriesModel);
  40816. /**
  40817. * Sausage: similar to sector, but have half circle on both sides
  40818. */
  40819. var SausageShape = /** @class */function () {
  40820. function SausageShape() {
  40821. this.cx = 0;
  40822. this.cy = 0;
  40823. this.r0 = 0;
  40824. this.r = 0;
  40825. this.startAngle = 0;
  40826. this.endAngle = Math.PI * 2;
  40827. this.clockwise = true;
  40828. }
  40829. return SausageShape;
  40830. }();
  40831. var SausagePath = /** @class */function (_super) {
  40832. __extends(SausagePath, _super);
  40833. function SausagePath(opts) {
  40834. var _this = _super.call(this, opts) || this;
  40835. _this.type = 'sausage';
  40836. return _this;
  40837. }
  40838. SausagePath.prototype.getDefaultShape = function () {
  40839. return new SausageShape();
  40840. };
  40841. SausagePath.prototype.buildPath = function (ctx, shape) {
  40842. var cx = shape.cx;
  40843. var cy = shape.cy;
  40844. var r0 = Math.max(shape.r0 || 0, 0);
  40845. var r = Math.max(shape.r, 0);
  40846. var dr = (r - r0) * 0.5;
  40847. var rCenter = r0 + dr;
  40848. var startAngle = shape.startAngle;
  40849. var endAngle = shape.endAngle;
  40850. var clockwise = shape.clockwise;
  40851. var PI2 = Math.PI * 2;
  40852. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  40853. if (!lessThanCircle) {
  40854. // Normalize angles
  40855. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  40856. }
  40857. var unitStartX = Math.cos(startAngle);
  40858. var unitStartY = Math.sin(startAngle);
  40859. var unitEndX = Math.cos(endAngle);
  40860. var unitEndY = Math.sin(endAngle);
  40861. if (lessThanCircle) {
  40862. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  40863. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  40864. } else {
  40865. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  40866. }
  40867. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  40868. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  40869. if (r0 !== 0) {
  40870. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  40871. }
  40872. // ctx.closePath();
  40873. };
  40874. return SausagePath;
  40875. }(Path);
  40876. function createSectorCalculateTextPosition(positionMapping, opts) {
  40877. opts = opts || {};
  40878. var isRoundCap = opts.isRoundCap;
  40879. return function (out, opts, boundingRect) {
  40880. var textPosition = opts.position;
  40881. if (!textPosition || textPosition instanceof Array) {
  40882. return calculateTextPosition(out, opts, boundingRect);
  40883. }
  40884. var mappedSectorPosition = positionMapping(textPosition);
  40885. var distance = opts.distance != null ? opts.distance : 5;
  40886. var sector = this.shape;
  40887. var cx = sector.cx;
  40888. var cy = sector.cy;
  40889. var r = sector.r;
  40890. var r0 = sector.r0;
  40891. var middleR = (r + r0) / 2;
  40892. var startAngle = sector.startAngle;
  40893. var endAngle = sector.endAngle;
  40894. var middleAngle = (startAngle + endAngle) / 2;
  40895. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  40896. var mathCos = Math.cos;
  40897. var mathSin = Math.sin;
  40898. // base position: top-left
  40899. var x = cx + r * mathCos(startAngle);
  40900. var y = cy + r * mathSin(startAngle);
  40901. var textAlign = 'left';
  40902. var textVerticalAlign = 'top';
  40903. switch (mappedSectorPosition) {
  40904. case 'startArc':
  40905. x = cx + (r0 - distance) * mathCos(middleAngle);
  40906. y = cy + (r0 - distance) * mathSin(middleAngle);
  40907. textAlign = 'center';
  40908. textVerticalAlign = 'top';
  40909. break;
  40910. case 'insideStartArc':
  40911. x = cx + (r0 + distance) * mathCos(middleAngle);
  40912. y = cy + (r0 + distance) * mathSin(middleAngle);
  40913. textAlign = 'center';
  40914. textVerticalAlign = 'bottom';
  40915. break;
  40916. case 'startAngle':
  40917. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  40918. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  40919. textAlign = 'right';
  40920. textVerticalAlign = 'middle';
  40921. break;
  40922. case 'insideStartAngle':
  40923. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  40924. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  40925. textAlign = 'left';
  40926. textVerticalAlign = 'middle';
  40927. break;
  40928. case 'middle':
  40929. x = cx + middleR * mathCos(middleAngle);
  40930. y = cy + middleR * mathSin(middleAngle);
  40931. textAlign = 'center';
  40932. textVerticalAlign = 'middle';
  40933. break;
  40934. case 'endArc':
  40935. x = cx + (r + distance) * mathCos(middleAngle);
  40936. y = cy + (r + distance) * mathSin(middleAngle);
  40937. textAlign = 'center';
  40938. textVerticalAlign = 'bottom';
  40939. break;
  40940. case 'insideEndArc':
  40941. x = cx + (r - distance) * mathCos(middleAngle);
  40942. y = cy + (r - distance) * mathSin(middleAngle);
  40943. textAlign = 'center';
  40944. textVerticalAlign = 'top';
  40945. break;
  40946. case 'endAngle':
  40947. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  40948. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  40949. textAlign = 'left';
  40950. textVerticalAlign = 'middle';
  40951. break;
  40952. case 'insideEndAngle':
  40953. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  40954. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  40955. textAlign = 'right';
  40956. textVerticalAlign = 'middle';
  40957. break;
  40958. default:
  40959. return calculateTextPosition(out, opts, boundingRect);
  40960. }
  40961. out = out || {};
  40962. out.x = x;
  40963. out.y = y;
  40964. out.align = textAlign;
  40965. out.verticalAlign = textVerticalAlign;
  40966. return out;
  40967. };
  40968. }
  40969. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  40970. if (isNumber(rotateType)) {
  40971. // user-set rotation
  40972. sector.setTextConfig({
  40973. rotation: rotateType
  40974. });
  40975. return;
  40976. } else if (isArray(textPosition)) {
  40977. // user-set position, use 0 as auto rotation
  40978. sector.setTextConfig({
  40979. rotation: 0
  40980. });
  40981. return;
  40982. }
  40983. var shape = sector.shape;
  40984. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  40985. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  40986. var middleAngle = (startAngle + endAngle) / 2;
  40987. var anchorAngle;
  40988. var mappedSectorPosition = positionMapping(textPosition);
  40989. switch (mappedSectorPosition) {
  40990. case 'startArc':
  40991. case 'insideStartArc':
  40992. case 'middle':
  40993. case 'insideEndArc':
  40994. case 'endArc':
  40995. anchorAngle = middleAngle;
  40996. break;
  40997. case 'startAngle':
  40998. case 'insideStartAngle':
  40999. anchorAngle = startAngle;
  41000. break;
  41001. case 'endAngle':
  41002. case 'insideEndAngle':
  41003. anchorAngle = endAngle;
  41004. break;
  41005. default:
  41006. sector.setTextConfig({
  41007. rotation: 0
  41008. });
  41009. return;
  41010. }
  41011. var rotate = Math.PI * 1.5 - anchorAngle;
  41012. /**
  41013. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  41014. * half round flipped to increase readability. However, only middle
  41015. * position supports this for now, because in other positions, the
  41016. * anchor point is not at the center of the text, so the positions
  41017. * after rotating is not as expected.
  41018. */
  41019. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  41020. rotate -= Math.PI;
  41021. }
  41022. sector.setTextConfig({
  41023. rotation: rotate
  41024. });
  41025. }
  41026. function adjustAngleDistanceX(angle, distance, isEnd) {
  41027. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  41028. }
  41029. function adjustAngleDistanceY(angle, distance, isEnd) {
  41030. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  41031. }
  41032. function getSectorCornerRadius(model, shape, zeroIfNull) {
  41033. var cornerRadius = model.get('borderRadius');
  41034. if (cornerRadius == null) {
  41035. return zeroIfNull ? {
  41036. cornerRadius: 0
  41037. } : null;
  41038. }
  41039. if (!isArray(cornerRadius)) {
  41040. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  41041. }
  41042. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  41043. return {
  41044. cornerRadius: map(cornerRadius, function (cr) {
  41045. return parsePercent(cr, dr);
  41046. })
  41047. };
  41048. }
  41049. var mathMax$7 = Math.max;
  41050. var mathMin$7 = Math.min;
  41051. function getClipArea(coord, data) {
  41052. var coordSysClipArea = coord.getArea && coord.getArea();
  41053. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  41054. var baseAxis = coord.getBaseAxis();
  41055. // When boundaryGap is false or using time axis. bar may exceed the grid.
  41056. // We should not clip this part.
  41057. // See test/bar2.html
  41058. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  41059. var expandWidth = data.getLayout('bandWidth');
  41060. if (baseAxis.isHorizontal()) {
  41061. coordSysClipArea.x -= expandWidth;
  41062. coordSysClipArea.width += expandWidth * 2;
  41063. } else {
  41064. coordSysClipArea.y -= expandWidth;
  41065. coordSysClipArea.height += expandWidth * 2;
  41066. }
  41067. }
  41068. }
  41069. return coordSysClipArea;
  41070. }
  41071. var BarView = /** @class */function (_super) {
  41072. __extends(BarView, _super);
  41073. function BarView() {
  41074. var _this = _super.call(this) || this;
  41075. _this.type = BarView.type;
  41076. _this._isFirstFrame = true;
  41077. return _this;
  41078. }
  41079. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  41080. this._model = seriesModel;
  41081. this._removeOnRenderedListener(api);
  41082. this._updateDrawMode(seriesModel);
  41083. var coordinateSystemType = seriesModel.get('coordinateSystem');
  41084. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  41085. // Clear previously rendered progressive elements.
  41086. this._progressiveEls = null;
  41087. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  41088. } else if ("development" !== 'production') {
  41089. warn('Only cartesian2d and polar supported for bar.');
  41090. }
  41091. };
  41092. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  41093. this._clear();
  41094. this._updateDrawMode(seriesModel);
  41095. // incremental also need to clip, otherwise might be overlow.
  41096. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  41097. this._updateLargeClip(seriesModel);
  41098. };
  41099. BarView.prototype.incrementalRender = function (params, seriesModel) {
  41100. // Reset
  41101. this._progressiveEls = [];
  41102. // Do not support progressive in normal mode.
  41103. this._incrementalRenderLarge(params, seriesModel);
  41104. };
  41105. BarView.prototype.eachRendered = function (cb) {
  41106. traverseElements(this._progressiveEls || this.group, cb);
  41107. };
  41108. BarView.prototype._updateDrawMode = function (seriesModel) {
  41109. var isLargeDraw = seriesModel.pipelineContext.large;
  41110. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  41111. this._isLargeDraw = isLargeDraw;
  41112. this._clear();
  41113. }
  41114. };
  41115. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  41116. var group = this.group;
  41117. var data = seriesModel.getData();
  41118. var oldData = this._data;
  41119. var coord = seriesModel.coordinateSystem;
  41120. var baseAxis = coord.getBaseAxis();
  41121. var isHorizontalOrRadial;
  41122. if (coord.type === 'cartesian2d') {
  41123. isHorizontalOrRadial = baseAxis.isHorizontal();
  41124. } else if (coord.type === 'polar') {
  41125. isHorizontalOrRadial = baseAxis.dim === 'angle';
  41126. }
  41127. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  41128. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  41129. if (realtimeSortCfg) {
  41130. this._enableRealtimeSort(realtimeSortCfg, data, api);
  41131. }
  41132. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  41133. var coordSysClipArea = getClipArea(coord, data);
  41134. // If there is clipPath created in large mode. Remove it.
  41135. group.removeClipPath();
  41136. // We don't use clipPath in normal mode because we needs a perfect animation
  41137. // And don't want the label are clipped.
  41138. var roundCap = seriesModel.get('roundCap', true);
  41139. var drawBackground = seriesModel.get('showBackground', true);
  41140. var backgroundModel = seriesModel.getModel('backgroundStyle');
  41141. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  41142. var bgEls = [];
  41143. var oldBgEls = this._backgroundEls;
  41144. var isInitSort = payload && payload.isInitSort;
  41145. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  41146. function createBackground(dataIndex) {
  41147. var bgLayout = getLayout[coord.type](data, dataIndex);
  41148. if (!bgLayout) {
  41149. return null;
  41150. }
  41151. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  41152. bgEl.useStyle(backgroundModel.getItemStyle());
  41153. // Only cartesian2d support borderRadius.
  41154. if (coord.type === 'cartesian2d') {
  41155. bgEl.setShape('r', barBorderRadius);
  41156. } else {
  41157. bgEl.setShape('cornerRadius', barBorderRadius);
  41158. }
  41159. bgEls[dataIndex] = bgEl;
  41160. return bgEl;
  41161. }
  41162. data.diff(oldData).add(function (dataIndex) {
  41163. var itemModel = data.getItemModel(dataIndex);
  41164. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  41165. if (!layout) {
  41166. return;
  41167. }
  41168. if (drawBackground) {
  41169. createBackground(dataIndex);
  41170. }
  41171. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  41172. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  41173. return;
  41174. }
  41175. var isClipped = false;
  41176. if (needsClip) {
  41177. // Clip will modify the layout params.
  41178. // And return a boolean to determine if the shape are fully clipped.
  41179. isClipped = clip[coord.type](coordSysClipArea, layout);
  41180. }
  41181. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  41182. if (realtimeSortCfg) {
  41183. /**
  41184. * Force label animation because even if the element is
  41185. * ignored because it's clipped, it may not be clipped after
  41186. * changing order. Then, if not using forceLabelAnimation,
  41187. * the label animation was never started, in which case,
  41188. * the label will be the final value and doesn't have label
  41189. * animation.
  41190. */
  41191. el.forceLabelAnimation = true;
  41192. }
  41193. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  41194. if (isInitSort) {
  41195. el.attr({
  41196. shape: layout
  41197. });
  41198. } else if (realtimeSortCfg) {
  41199. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  41200. } else {
  41201. initProps(el, {
  41202. shape: layout
  41203. }, seriesModel, dataIndex);
  41204. }
  41205. data.setItemGraphicEl(dataIndex, el);
  41206. group.add(el);
  41207. el.ignore = isClipped;
  41208. }).update(function (newIndex, oldIndex) {
  41209. var itemModel = data.getItemModel(newIndex);
  41210. var layout = getLayout[coord.type](data, newIndex, itemModel);
  41211. if (!layout) {
  41212. return;
  41213. }
  41214. if (drawBackground) {
  41215. var bgEl = void 0;
  41216. if (oldBgEls.length === 0) {
  41217. bgEl = createBackground(oldIndex);
  41218. } else {
  41219. bgEl = oldBgEls[oldIndex];
  41220. bgEl.useStyle(backgroundModel.getItemStyle());
  41221. // Only cartesian2d support borderRadius.
  41222. if (coord.type === 'cartesian2d') {
  41223. bgEl.setShape('r', barBorderRadius);
  41224. } else {
  41225. bgEl.setShape('cornerRadius', barBorderRadius);
  41226. }
  41227. bgEls[newIndex] = bgEl;
  41228. }
  41229. var bgLayout = getLayout[coord.type](data, newIndex);
  41230. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  41231. updateProps(bgEl, {
  41232. shape: shape
  41233. }, animationModel, newIndex);
  41234. }
  41235. var el = oldData.getItemGraphicEl(oldIndex);
  41236. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  41237. group.remove(el);
  41238. return;
  41239. }
  41240. var isClipped = false;
  41241. if (needsClip) {
  41242. isClipped = clip[coord.type](coordSysClipArea, layout);
  41243. if (isClipped) {
  41244. group.remove(el);
  41245. }
  41246. }
  41247. var roundCapChanged = el && (el.type === 'sector' && roundCap || el.type === 'sausage' && !roundCap);
  41248. if (roundCapChanged) {
  41249. // roundCap changed, there is no way to use animation from a `sector` to a `sausage` shape,
  41250. // so remove the old one and create a new shape
  41251. el && removeElementWithFadeOut(el, seriesModel, oldIndex);
  41252. el = null;
  41253. }
  41254. if (!el) {
  41255. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, true, roundCap);
  41256. } else {
  41257. saveOldStyle(el);
  41258. }
  41259. if (realtimeSortCfg) {
  41260. el.forceLabelAnimation = true;
  41261. }
  41262. if (isChangeOrder) {
  41263. var textEl = el.getTextContent();
  41264. if (textEl) {
  41265. var labelInnerStore = labelInner(textEl);
  41266. if (labelInnerStore.prevValue != null) {
  41267. /**
  41268. * Set preValue to be value so that no new label
  41269. * should be started, otherwise, it will take a full
  41270. * `animationDurationUpdate` time to finish the
  41271. * animation, which is not expected.
  41272. */
  41273. labelInnerStore.prevValue = labelInnerStore.value;
  41274. }
  41275. }
  41276. }
  41277. // Not change anything if only order changed.
  41278. // Especially not change label.
  41279. else {
  41280. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  41281. }
  41282. if (isInitSort) {
  41283. el.attr({
  41284. shape: layout
  41285. });
  41286. } else if (realtimeSortCfg) {
  41287. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  41288. } else {
  41289. updateProps(el, {
  41290. shape: layout
  41291. }, seriesModel, newIndex, null);
  41292. }
  41293. data.setItemGraphicEl(newIndex, el);
  41294. el.ignore = isClipped;
  41295. group.add(el);
  41296. }).remove(function (dataIndex) {
  41297. var el = oldData.getItemGraphicEl(dataIndex);
  41298. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  41299. }).execute();
  41300. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  41301. bgGroup.removeAll();
  41302. for (var i = 0; i < bgEls.length; ++i) {
  41303. bgGroup.add(bgEls[i]);
  41304. }
  41305. group.add(bgGroup);
  41306. this._backgroundEls = bgEls;
  41307. this._data = data;
  41308. };
  41309. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  41310. this._clear();
  41311. createLarge(seriesModel, this.group);
  41312. this._updateLargeClip(seriesModel);
  41313. };
  41314. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  41315. this._removeBackground();
  41316. createLarge(seriesModel, this.group, this._progressiveEls, true);
  41317. };
  41318. BarView.prototype._updateLargeClip = function (seriesModel) {
  41319. // Use clipPath in large mode.
  41320. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  41321. var group = this.group;
  41322. if (clipPath) {
  41323. group.setClipPath(clipPath);
  41324. } else {
  41325. group.removeClipPath();
  41326. }
  41327. };
  41328. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  41329. var _this = this;
  41330. // If no data in the first frame, wait for data to initSort
  41331. if (!data.count()) {
  41332. return;
  41333. }
  41334. var baseAxis = realtimeSortCfg.baseAxis;
  41335. if (this._isFirstFrame) {
  41336. this._dispatchInitSort(data, realtimeSortCfg, api);
  41337. this._isFirstFrame = false;
  41338. } else {
  41339. var orderMapping_1 = function (idx) {
  41340. var el = data.getItemGraphicEl(idx);
  41341. var shape = el && el.shape;
  41342. return shape &&
  41343. // The result should be consistent with the initial sort by data value.
  41344. // Do not support the case that both positive and negative exist.
  41345. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width)
  41346. // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  41347. || 0;
  41348. };
  41349. this._onRendered = function () {
  41350. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  41351. };
  41352. api.getZr().on('rendered', this._onRendered);
  41353. }
  41354. };
  41355. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  41356. var info = [];
  41357. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  41358. var mappedValue = orderMapping(dataIdx);
  41359. mappedValue = mappedValue == null ? NaN : mappedValue;
  41360. info.push({
  41361. dataIndex: dataIdx,
  41362. mappedValue: mappedValue,
  41363. ordinalNumber: ordinalNumber
  41364. });
  41365. });
  41366. info.sort(function (a, b) {
  41367. // If NaN, it will be treated as min val.
  41368. return b.mappedValue - a.mappedValue;
  41369. });
  41370. return {
  41371. ordinalNumbers: map(info, function (item) {
  41372. return item.ordinalNumber;
  41373. })
  41374. };
  41375. };
  41376. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  41377. var scale = baseAxis.scale;
  41378. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  41379. var lastValue = Number.MAX_VALUE;
  41380. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  41381. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  41382. var value = rawIdx < 0
  41383. // If some tick have no bar, the tick will be treated as min.
  41384. ? Number.MIN_VALUE
  41385. // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  41386. : orderMapping(data.indexOfRawIndex(rawIdx));
  41387. if (value > lastValue) {
  41388. return true;
  41389. }
  41390. lastValue = value;
  41391. }
  41392. return false;
  41393. };
  41394. /*
  41395. * Consider the case when A and B changed order, whose representing
  41396. * bars are both out of sight, we don't wish to trigger reorder action
  41397. * as long as the order in the view doesn't change.
  41398. */
  41399. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  41400. var scale = baseAxis.scale;
  41401. var extent = scale.getExtent();
  41402. var tickNum = Math.max(0, extent[0]);
  41403. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  41404. for (; tickNum <= tickMax; ++tickNum) {
  41405. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  41406. return true;
  41407. }
  41408. }
  41409. };
  41410. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  41411. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  41412. return;
  41413. }
  41414. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  41415. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  41416. this._removeOnRenderedListener(api);
  41417. api.dispatchAction({
  41418. type: 'changeAxisOrder',
  41419. componentType: baseAxis.dim + 'Axis',
  41420. axisId: baseAxis.index,
  41421. sortInfo: sortInfo
  41422. });
  41423. }
  41424. };
  41425. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  41426. var baseAxis = realtimeSortCfg.baseAxis;
  41427. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  41428. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  41429. });
  41430. api.dispatchAction({
  41431. type: 'changeAxisOrder',
  41432. componentType: baseAxis.dim + 'Axis',
  41433. isInitSort: true,
  41434. axisId: baseAxis.index,
  41435. sortInfo: sortResult
  41436. });
  41437. };
  41438. BarView.prototype.remove = function (ecModel, api) {
  41439. this._clear(this._model);
  41440. this._removeOnRenderedListener(api);
  41441. };
  41442. BarView.prototype.dispose = function (ecModel, api) {
  41443. this._removeOnRenderedListener(api);
  41444. };
  41445. BarView.prototype._removeOnRenderedListener = function (api) {
  41446. if (this._onRendered) {
  41447. api.getZr().off('rendered', this._onRendered);
  41448. this._onRendered = null;
  41449. }
  41450. };
  41451. BarView.prototype._clear = function (model) {
  41452. var group = this.group;
  41453. var data = this._data;
  41454. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  41455. this._removeBackground();
  41456. this._backgroundEls = [];
  41457. data.eachItemGraphicEl(function (el) {
  41458. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  41459. });
  41460. } else {
  41461. group.removeAll();
  41462. }
  41463. this._data = null;
  41464. this._isFirstFrame = true;
  41465. };
  41466. BarView.prototype._removeBackground = function () {
  41467. this.group.remove(this._backgroundGroup);
  41468. this._backgroundGroup = null;
  41469. };
  41470. BarView.type = 'bar';
  41471. return BarView;
  41472. }(ChartView);
  41473. var clip = {
  41474. cartesian2d: function (coordSysBoundingRect, layout) {
  41475. var signWidth = layout.width < 0 ? -1 : 1;
  41476. var signHeight = layout.height < 0 ? -1 : 1;
  41477. // Needs positive width and height
  41478. if (signWidth < 0) {
  41479. layout.x += layout.width;
  41480. layout.width = -layout.width;
  41481. }
  41482. if (signHeight < 0) {
  41483. layout.y += layout.height;
  41484. layout.height = -layout.height;
  41485. }
  41486. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  41487. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  41488. var x = mathMax$7(layout.x, coordSysBoundingRect.x);
  41489. var x2 = mathMin$7(layout.x + layout.width, coordSysX2);
  41490. var y = mathMax$7(layout.y, coordSysBoundingRect.y);
  41491. var y2 = mathMin$7(layout.y + layout.height, coordSysY2);
  41492. var xClipped = x2 < x;
  41493. var yClipped = y2 < y;
  41494. // When xClipped or yClipped, the element will be marked as `ignore`.
  41495. // But we should also place the element at the edge of the coord sys bounding rect.
  41496. // Because if data changed and the bar shows again, its transition animation
  41497. // will begin at this place.
  41498. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  41499. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  41500. layout.width = xClipped ? 0 : x2 - x;
  41501. layout.height = yClipped ? 0 : y2 - y;
  41502. // Reverse back
  41503. if (signWidth < 0) {
  41504. layout.x += layout.width;
  41505. layout.width = -layout.width;
  41506. }
  41507. if (signHeight < 0) {
  41508. layout.y += layout.height;
  41509. layout.height = -layout.height;
  41510. }
  41511. return xClipped || yClipped;
  41512. },
  41513. polar: function (coordSysClipArea, layout) {
  41514. var signR = layout.r0 <= layout.r ? 1 : -1;
  41515. // Make sure r is larger than r0
  41516. if (signR < 0) {
  41517. var tmp = layout.r;
  41518. layout.r = layout.r0;
  41519. layout.r0 = tmp;
  41520. }
  41521. var r = mathMin$7(layout.r, coordSysClipArea.r);
  41522. var r0 = mathMax$7(layout.r0, coordSysClipArea.r0);
  41523. layout.r = r;
  41524. layout.r0 = r0;
  41525. var clipped = r - r0 < 0;
  41526. // Reverse back
  41527. if (signR < 0) {
  41528. var tmp = layout.r;
  41529. layout.r = layout.r0;
  41530. layout.r0 = tmp;
  41531. }
  41532. return clipped;
  41533. }
  41534. };
  41535. var elementCreator = {
  41536. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  41537. var rect = new Rect({
  41538. shape: extend({}, layout),
  41539. z2: 1
  41540. });
  41541. rect.__dataIndex = newIndex;
  41542. rect.name = 'item';
  41543. if (animationModel) {
  41544. var rectShape = rect.shape;
  41545. var animateProperty = isHorizontal ? 'height' : 'width';
  41546. rectShape[animateProperty] = 0;
  41547. }
  41548. return rect;
  41549. },
  41550. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  41551. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  41552. var sector = new ShapeClass({
  41553. shape: layout,
  41554. z2: 1
  41555. });
  41556. sector.name = 'item';
  41557. var positionMap = createPolarPositionMapping(isRadial);
  41558. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  41559. isRoundCap: ShapeClass === SausagePath
  41560. });
  41561. // Animation
  41562. if (animationModel) {
  41563. var sectorShape = sector.shape;
  41564. var animateProperty = isRadial ? 'r' : 'endAngle';
  41565. var animateTarget = {};
  41566. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  41567. animateTarget[animateProperty] = layout[animateProperty];
  41568. (isUpdate ? updateProps : initProps)(sector, {
  41569. shape: animateTarget
  41570. // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  41571. }, animationModel);
  41572. }
  41573. return sector;
  41574. }
  41575. };
  41576. function shouldRealtimeSort(seriesModel, coordSys) {
  41577. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  41578. var baseAxis = coordSys.getBaseAxis();
  41579. if ("development" !== 'production') {
  41580. if (realtimeSortOption) {
  41581. if (baseAxis.type !== 'category') {
  41582. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  41583. }
  41584. if (coordSys.type !== 'cartesian2d') {
  41585. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  41586. }
  41587. }
  41588. }
  41589. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  41590. return {
  41591. baseAxis: baseAxis,
  41592. otherAxis: coordSys.getOtherAxis(baseAxis)
  41593. };
  41594. }
  41595. }
  41596. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  41597. var seriesTarget;
  41598. var axisTarget;
  41599. if (isHorizontal) {
  41600. axisTarget = {
  41601. x: layout.x,
  41602. width: layout.width
  41603. };
  41604. seriesTarget = {
  41605. y: layout.y,
  41606. height: layout.height
  41607. };
  41608. } else {
  41609. axisTarget = {
  41610. y: layout.y,
  41611. height: layout.height
  41612. };
  41613. seriesTarget = {
  41614. x: layout.x,
  41615. width: layout.width
  41616. };
  41617. }
  41618. if (!isChangeOrder) {
  41619. // Keep the original growth animation if only axis order changed.
  41620. // Not start a new animation.
  41621. (isUpdate ? updateProps : initProps)(el, {
  41622. shape: seriesTarget
  41623. }, seriesAnimationModel, newIndex, null);
  41624. }
  41625. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  41626. (isUpdate ? updateProps : initProps)(el, {
  41627. shape: axisTarget
  41628. }, axisAnimationModel, newIndex);
  41629. }
  41630. function checkPropertiesNotValid(obj, props) {
  41631. for (var i = 0; i < props.length; i++) {
  41632. if (!isFinite(obj[props[i]])) {
  41633. return true;
  41634. }
  41635. }
  41636. return false;
  41637. }
  41638. var rectPropties = ['x', 'y', 'width', 'height'];
  41639. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  41640. var isValidLayout = {
  41641. cartesian2d: function (layout) {
  41642. return !checkPropertiesNotValid(layout, rectPropties);
  41643. },
  41644. polar: function (layout) {
  41645. return !checkPropertiesNotValid(layout, polarPropties);
  41646. }
  41647. };
  41648. var getLayout = {
  41649. // itemModel is only used to get borderWidth, which is not needed
  41650. // when calculating bar background layout.
  41651. cartesian2d: function (data, dataIndex, itemModel) {
  41652. var layout = data.getItemLayout(dataIndex);
  41653. if (!layout) {
  41654. return null;
  41655. }
  41656. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  41657. // fix layout with lineWidth
  41658. var signX = layout.width > 0 ? 1 : -1;
  41659. var signY = layout.height > 0 ? 1 : -1;
  41660. return {
  41661. x: layout.x + signX * fixedLineWidth / 2,
  41662. y: layout.y + signY * fixedLineWidth / 2,
  41663. width: layout.width - signX * fixedLineWidth,
  41664. height: layout.height - signY * fixedLineWidth
  41665. };
  41666. },
  41667. polar: function (data, dataIndex, itemModel) {
  41668. var layout = data.getItemLayout(dataIndex);
  41669. return {
  41670. cx: layout.cx,
  41671. cy: layout.cy,
  41672. r0: layout.r0,
  41673. r: layout.r,
  41674. startAngle: layout.startAngle,
  41675. endAngle: layout.endAngle,
  41676. clockwise: layout.clockwise
  41677. };
  41678. }
  41679. };
  41680. function isZeroOnPolar(layout) {
  41681. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  41682. }
  41683. function createPolarPositionMapping(isRadial) {
  41684. return function (isRadial) {
  41685. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  41686. return function (position) {
  41687. switch (position) {
  41688. case 'start':
  41689. case 'insideStart':
  41690. case 'end':
  41691. case 'insideEnd':
  41692. return position + arcOrAngle;
  41693. default:
  41694. return position;
  41695. }
  41696. };
  41697. }(isRadial);
  41698. }
  41699. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  41700. var style = data.getItemVisual(dataIndex, 'style');
  41701. if (!isPolar) {
  41702. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  41703. el.setShape('r', borderRadius);
  41704. } else if (!seriesModel.get('roundCap')) {
  41705. var sectorShape = el.shape;
  41706. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  41707. extend(sectorShape, cornerRadius);
  41708. el.setShape(sectorShape);
  41709. }
  41710. el.useStyle(style);
  41711. var cursorStyle = itemModel.getShallow('cursor');
  41712. cursorStyle && el.attr('cursor', cursorStyle);
  41713. 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';
  41714. var labelStatesModels = getLabelStatesModels(itemModel);
  41715. setLabelStyle(el, labelStatesModels, {
  41716. labelFetcher: seriesModel,
  41717. labelDataIndex: dataIndex,
  41718. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  41719. inheritColor: style.fill,
  41720. defaultOpacity: style.opacity,
  41721. defaultOutsidePosition: labelPositionOutside
  41722. });
  41723. var label = el.getTextContent();
  41724. if (isPolar && label) {
  41725. var position = itemModel.get(['label', 'position']);
  41726. el.textConfig.inside = position === 'middle' ? true : null;
  41727. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  41728. }
  41729. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  41730. return getDefaultInterpolatedLabel(data, value);
  41731. });
  41732. var emphasisModel = itemModel.getModel(['emphasis']);
  41733. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  41734. setStatesStylesFromModel(el, itemModel);
  41735. if (isZeroOnPolar(layout)) {
  41736. el.style.fill = 'none';
  41737. el.style.stroke = 'none';
  41738. each(el.states, function (state) {
  41739. if (state.style) {
  41740. state.style.fill = state.style.stroke = 'none';
  41741. }
  41742. });
  41743. }
  41744. }
  41745. // In case width or height are too small.
  41746. function getLineWidth(itemModel, rawLayout) {
  41747. // Has no border.
  41748. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  41749. if (!borderColor || borderColor === 'none') {
  41750. return 0;
  41751. }
  41752. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0;
  41753. // width or height may be NaN for empty data
  41754. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  41755. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  41756. return Math.min(lineWidth, width, height);
  41757. }
  41758. var LagePathShape = /** @class */function () {
  41759. function LagePathShape() {}
  41760. return LagePathShape;
  41761. }();
  41762. var LargePath = /** @class */function (_super) {
  41763. __extends(LargePath, _super);
  41764. function LargePath(opts) {
  41765. var _this = _super.call(this, opts) || this;
  41766. _this.type = 'largeBar';
  41767. return _this;
  41768. }
  41769. LargePath.prototype.getDefaultShape = function () {
  41770. return new LagePathShape();
  41771. };
  41772. LargePath.prototype.buildPath = function (ctx, shape) {
  41773. // Drawing lines is more efficient than drawing
  41774. // a whole line or drawing rects.
  41775. var points = shape.points;
  41776. var baseDimIdx = this.baseDimIdx;
  41777. var valueDimIdx = 1 - this.baseDimIdx;
  41778. var startPoint = [];
  41779. var size = [];
  41780. var barWidth = this.barWidth;
  41781. for (var i = 0; i < points.length; i += 3) {
  41782. size[baseDimIdx] = barWidth;
  41783. size[valueDimIdx] = points[i + 2];
  41784. startPoint[baseDimIdx] = points[i + baseDimIdx];
  41785. startPoint[valueDimIdx] = points[i + valueDimIdx];
  41786. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  41787. }
  41788. };
  41789. return LargePath;
  41790. }(Path);
  41791. function createLarge(seriesModel, group, progressiveEls, incremental) {
  41792. // TODO support polar
  41793. var data = seriesModel.getData();
  41794. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  41795. var largeDataIndices = data.getLayout('largeDataIndices');
  41796. var barWidth = data.getLayout('size');
  41797. var backgroundModel = seriesModel.getModel('backgroundStyle');
  41798. var bgPoints = data.getLayout('largeBackgroundPoints');
  41799. if (bgPoints) {
  41800. var bgEl = new LargePath({
  41801. shape: {
  41802. points: bgPoints
  41803. },
  41804. incremental: !!incremental,
  41805. silent: true,
  41806. z2: 0
  41807. });
  41808. bgEl.baseDimIdx = baseDimIdx;
  41809. bgEl.largeDataIndices = largeDataIndices;
  41810. bgEl.barWidth = barWidth;
  41811. bgEl.useStyle(backgroundModel.getItemStyle());
  41812. group.add(bgEl);
  41813. progressiveEls && progressiveEls.push(bgEl);
  41814. }
  41815. var el = new LargePath({
  41816. shape: {
  41817. points: data.getLayout('largePoints')
  41818. },
  41819. incremental: !!incremental,
  41820. ignoreCoarsePointer: true,
  41821. z2: 1
  41822. });
  41823. el.baseDimIdx = baseDimIdx;
  41824. el.largeDataIndices = largeDataIndices;
  41825. el.barWidth = barWidth;
  41826. group.add(el);
  41827. el.useStyle(data.getVisual('style'));
  41828. // Stroke is rendered first to avoid overlapping with fill
  41829. el.style.stroke = null;
  41830. // Enable tooltip and user mouse/touch event handlers.
  41831. getECData(el).seriesIndex = seriesModel.seriesIndex;
  41832. if (!seriesModel.get('silent')) {
  41833. el.on('mousedown', largePathUpdateDataIndex);
  41834. el.on('mousemove', largePathUpdateDataIndex);
  41835. }
  41836. progressiveEls && progressiveEls.push(el);
  41837. }
  41838. // Use throttle to avoid frequently traverse to find dataIndex.
  41839. var largePathUpdateDataIndex = throttle(function (event) {
  41840. var largePath = this;
  41841. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  41842. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  41843. }, 30, false);
  41844. function largePathFindDataIndex(largePath, x, y) {
  41845. var baseDimIdx = largePath.baseDimIdx;
  41846. var valueDimIdx = 1 - baseDimIdx;
  41847. var points = largePath.shape.points;
  41848. var largeDataIndices = largePath.largeDataIndices;
  41849. var startPoint = [];
  41850. var size = [];
  41851. var barWidth = largePath.barWidth;
  41852. for (var i = 0, len = points.length / 3; i < len; i++) {
  41853. var ii = i * 3;
  41854. size[baseDimIdx] = barWidth;
  41855. size[valueDimIdx] = points[ii + 2];
  41856. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  41857. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  41858. if (size[valueDimIdx] < 0) {
  41859. startPoint[valueDimIdx] += size[valueDimIdx];
  41860. size[valueDimIdx] = -size[valueDimIdx];
  41861. }
  41862. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  41863. return largeDataIndices[i];
  41864. }
  41865. }
  41866. return -1;
  41867. }
  41868. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  41869. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  41870. var rectShape = layout;
  41871. var coordLayout = coord.getArea();
  41872. return {
  41873. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  41874. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  41875. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  41876. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  41877. };
  41878. } else {
  41879. var coordLayout = coord.getArea();
  41880. var sectorShape = layout;
  41881. return {
  41882. cx: coordLayout.cx,
  41883. cy: coordLayout.cy,
  41884. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  41885. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  41886. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  41887. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  41888. };
  41889. }
  41890. }
  41891. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  41892. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  41893. return new ElementClz({
  41894. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  41895. silent: true,
  41896. z2: 0
  41897. });
  41898. }
  41899. function install$3(registers) {
  41900. registers.registerChartView(BarView);
  41901. registers.registerSeriesModel(BarSeriesModel);
  41902. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  41903. // Do layout after other overall layout, which can prepare some information.
  41904. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar'));
  41905. // Down sample after filter
  41906. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  41907. /**
  41908. * @payload
  41909. * @property {string} [componentType=series]
  41910. * @property {number} [dx]
  41911. * @property {number} [dy]
  41912. * @property {number} [zoom]
  41913. * @property {number} [originX]
  41914. * @property {number} [originY]
  41915. */
  41916. registers.registerAction({
  41917. type: 'changeAxisOrder',
  41918. event: 'changeAxisOrder',
  41919. update: 'update'
  41920. }, function (payload, ecModel) {
  41921. var componentType = payload.componentType || 'series';
  41922. ecModel.eachComponent({
  41923. mainType: componentType,
  41924. query: payload
  41925. }, function (componentModel) {
  41926. if (payload.sortInfo) {
  41927. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  41928. }
  41929. });
  41930. });
  41931. }
  41932. var PI2$7 = Math.PI * 2;
  41933. var RADIAN = Math.PI / 180;
  41934. function pieLayout(seriesType, ecModel, api) {
  41935. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  41936. var data = seriesModel.getData();
  41937. var valueDim = data.mapDimension('value');
  41938. var _a = getCircleLayout(seriesModel, api),
  41939. cx = _a.cx,
  41940. cy = _a.cy,
  41941. r = _a.r,
  41942. r0 = _a.r0,
  41943. viewRect = _a.viewRect;
  41944. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  41945. var endAngle = seriesModel.get('endAngle');
  41946. var padAngle = seriesModel.get('padAngle') * RADIAN;
  41947. endAngle = endAngle === 'auto' ? startAngle - PI2$7 : -endAngle * RADIAN;
  41948. var minAngle = seriesModel.get('minAngle') * RADIAN;
  41949. var minAndPadAngle = minAngle + padAngle;
  41950. var validDataCount = 0;
  41951. data.each(valueDim, function (value) {
  41952. !isNaN(value) && validDataCount++;
  41953. });
  41954. var sum = data.getSum(valueDim);
  41955. // Sum may be 0
  41956. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  41957. var clockwise = seriesModel.get('clockwise');
  41958. var roseType = seriesModel.get('roseType');
  41959. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  41960. // [0...max]
  41961. var extent = data.getDataExtent(valueDim);
  41962. extent[0] = 0;
  41963. var dir = clockwise ? 1 : -1;
  41964. var angles = [startAngle, endAngle];
  41965. var halfPadAngle = dir * padAngle / 2;
  41966. normalizeArcAngles(angles, !clockwise);
  41967. startAngle = angles[0], endAngle = angles[1];
  41968. var layoutData = getSeriesLayoutData(seriesModel);
  41969. layoutData.startAngle = startAngle;
  41970. layoutData.endAngle = endAngle;
  41971. layoutData.clockwise = clockwise;
  41972. layoutData.cx = cx;
  41973. layoutData.cy = cy;
  41974. layoutData.r = r;
  41975. layoutData.r0 = r0;
  41976. var angleRange = Math.abs(endAngle - startAngle);
  41977. // In the case some sector angle is smaller than minAngle
  41978. var restAngle = angleRange;
  41979. var valueSumLargerThanMinAngle = 0;
  41980. var currentAngle = startAngle;
  41981. // Requird by `pieLabelLayout`.
  41982. data.setLayout({
  41983. viewRect: viewRect,
  41984. r: r
  41985. });
  41986. data.each(valueDim, function (value, idx) {
  41987. var angle;
  41988. if (isNaN(value)) {
  41989. data.setItemLayout(idx, {
  41990. angle: NaN,
  41991. startAngle: NaN,
  41992. endAngle: NaN,
  41993. clockwise: clockwise,
  41994. cx: cx,
  41995. cy: cy,
  41996. r0: r0,
  41997. r: roseType ? NaN : r
  41998. });
  41999. return;
  42000. }
  42001. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  42002. if (roseType !== 'area') {
  42003. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  42004. } else {
  42005. angle = angleRange / validDataCount;
  42006. }
  42007. if (angle < minAndPadAngle) {
  42008. angle = minAndPadAngle;
  42009. restAngle -= minAndPadAngle;
  42010. } else {
  42011. valueSumLargerThanMinAngle += value;
  42012. }
  42013. var endAngle = currentAngle + dir * angle;
  42014. // calculate display angle
  42015. var actualStartAngle = 0;
  42016. var actualEndAngle = 0;
  42017. if (padAngle > angle) {
  42018. actualStartAngle = currentAngle + dir * angle / 2;
  42019. actualEndAngle = actualStartAngle;
  42020. } else {
  42021. actualStartAngle = currentAngle + halfPadAngle;
  42022. actualEndAngle = endAngle - halfPadAngle;
  42023. }
  42024. data.setItemLayout(idx, {
  42025. angle: angle,
  42026. startAngle: actualStartAngle,
  42027. endAngle: actualEndAngle,
  42028. clockwise: clockwise,
  42029. cx: cx,
  42030. cy: cy,
  42031. r0: r0,
  42032. r: roseType ? linearMap(value, extent, [r0, r]) : r
  42033. });
  42034. currentAngle = endAngle;
  42035. });
  42036. // Some sector is constrained by minAngle and padAngle
  42037. // Rest sectors needs recalculate angle
  42038. if (restAngle < PI2$7 && validDataCount) {
  42039. // Average the angle if rest angle is not enough after all angles is
  42040. // Constrained by minAngle and padAngle
  42041. if (restAngle <= 1e-3) {
  42042. var angle_1 = angleRange / validDataCount;
  42043. data.each(valueDim, function (value, idx) {
  42044. if (!isNaN(value)) {
  42045. var layout = data.getItemLayout(idx);
  42046. layout.angle = angle_1;
  42047. var actualStartAngle = 0;
  42048. var actualEndAngle = 0;
  42049. if (angle_1 < padAngle) {
  42050. actualStartAngle = startAngle + dir * (idx + 1 / 2) * angle_1;
  42051. actualEndAngle = actualStartAngle;
  42052. } else {
  42053. actualStartAngle = startAngle + dir * idx * angle_1 + halfPadAngle;
  42054. actualEndAngle = startAngle + dir * (idx + 1) * angle_1 - halfPadAngle;
  42055. }
  42056. layout.startAngle = actualStartAngle;
  42057. layout.endAngle = actualEndAngle;
  42058. }
  42059. });
  42060. } else {
  42061. unitRadian = restAngle / valueSumLargerThanMinAngle;
  42062. currentAngle = startAngle;
  42063. data.each(valueDim, function (value, idx) {
  42064. if (!isNaN(value)) {
  42065. var layout = data.getItemLayout(idx);
  42066. var angle = layout.angle === minAndPadAngle ? minAndPadAngle : value * unitRadian;
  42067. var actualStartAngle = 0;
  42068. var actualEndAngle = 0;
  42069. if (angle < padAngle) {
  42070. actualStartAngle = currentAngle + dir * angle / 2;
  42071. actualEndAngle = actualStartAngle;
  42072. } else {
  42073. actualStartAngle = currentAngle + halfPadAngle;
  42074. actualEndAngle = currentAngle + dir * angle - halfPadAngle;
  42075. }
  42076. layout.startAngle = actualStartAngle;
  42077. layout.endAngle = actualEndAngle;
  42078. currentAngle += dir * angle;
  42079. }
  42080. });
  42081. }
  42082. }
  42083. });
  42084. }
  42085. var getSeriesLayoutData = makeInner();
  42086. /*
  42087. * Licensed to the Apache Software Foundation (ASF) under one
  42088. * or more contributor license agreements. See the NOTICE file
  42089. * distributed with this work for additional information
  42090. * regarding copyright ownership. The ASF licenses this file
  42091. * to you under the Apache License, Version 2.0 (the
  42092. * "License"); you may not use this file except in compliance
  42093. * with the License. You may obtain a copy of the License at
  42094. *
  42095. * http://www.apache.org/licenses/LICENSE-2.0
  42096. *
  42097. * Unless required by applicable law or agreed to in writing,
  42098. * software distributed under the License is distributed on an
  42099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42100. * KIND, either express or implied. See the License for the
  42101. * specific language governing permissions and limitations
  42102. * under the License.
  42103. */
  42104. /**
  42105. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42106. */
  42107. /*
  42108. * Licensed to the Apache Software Foundation (ASF) under one
  42109. * or more contributor license agreements. See the NOTICE file
  42110. * distributed with this work for additional information
  42111. * regarding copyright ownership. The ASF licenses this file
  42112. * to you under the Apache License, Version 2.0 (the
  42113. * "License"); you may not use this file except in compliance
  42114. * with the License. You may obtain a copy of the License at
  42115. *
  42116. * http://www.apache.org/licenses/LICENSE-2.0
  42117. *
  42118. * Unless required by applicable law or agreed to in writing,
  42119. * software distributed under the License is distributed on an
  42120. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42121. * KIND, either express or implied. See the License for the
  42122. * specific language governing permissions and limitations
  42123. * under the License.
  42124. */
  42125. function dataFilter(seriesType) {
  42126. return {
  42127. seriesType: seriesType,
  42128. reset: function (seriesModel, ecModel) {
  42129. var legendModels = ecModel.findComponents({
  42130. mainType: 'legend'
  42131. });
  42132. if (!legendModels || !legendModels.length) {
  42133. return;
  42134. }
  42135. var data = seriesModel.getData();
  42136. data.filterSelf(function (idx) {
  42137. var name = data.getName(idx);
  42138. // If in any legend component the status is not selected.
  42139. for (var i = 0; i < legendModels.length; i++) {
  42140. // @ts-ignore FIXME: LegendModel
  42141. if (!legendModels[i].isSelected(name)) {
  42142. return false;
  42143. }
  42144. }
  42145. return true;
  42146. });
  42147. }
  42148. };
  42149. }
  42150. var RADIAN$1 = Math.PI / 180;
  42151. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  42152. if (list.length < 2) {
  42153. return;
  42154. }
  42155. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  42156. var rB = semi.rB;
  42157. var rB2 = rB * rB;
  42158. for (var i = 0; i < semi.list.length; i++) {
  42159. var item = semi.list[i];
  42160. var dy = Math.abs(item.label.y - cy);
  42161. // horizontal r is always same with original r because x is not changed.
  42162. var rA = r + item.len;
  42163. var rA2 = rA * rA;
  42164. // Use ellipse implicit function to calculate x
  42165. var dx = Math.sqrt(Math.abs((1 - dy * dy / rB2) * rA2));
  42166. var newX = cx + (dx + item.len2) * dir;
  42167. var deltaX = newX - item.label.x;
  42168. var newTargetWidth = item.targetTextWidth - deltaX * dir;
  42169. // text x is changed, so need to recalculate width.
  42170. constrainTextWidth(item, newTargetWidth, true);
  42171. item.label.x = newX;
  42172. }
  42173. }
  42174. // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  42175. function recalculateX(items) {
  42176. // Extremes of
  42177. var topSemi = {
  42178. list: [],
  42179. maxY: 0
  42180. };
  42181. var bottomSemi = {
  42182. list: [],
  42183. maxY: 0
  42184. };
  42185. for (var i = 0; i < items.length; i++) {
  42186. if (items[i].labelAlignTo !== 'none') {
  42187. continue;
  42188. }
  42189. var item = items[i];
  42190. var semi = item.label.y > cy ? bottomSemi : topSemi;
  42191. var dy = Math.abs(item.label.y - cy);
  42192. if (dy >= semi.maxY) {
  42193. var dx = item.label.x - cx - item.len2 * dir;
  42194. // horizontal r is always same with original r because x is not changed.
  42195. var rA = r + item.len;
  42196. // Canculate rB based on the topest / bottemest label.
  42197. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  42198. semi.rB = rB;
  42199. semi.maxY = dy;
  42200. }
  42201. semi.list.push(item);
  42202. }
  42203. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  42204. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  42205. }
  42206. var len = list.length;
  42207. for (var i = 0; i < len; i++) {
  42208. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  42209. var dx = list[i].label.x - farthestX;
  42210. list[i].linePoints[1][0] += dx;
  42211. list[i].label.x = farthestX;
  42212. }
  42213. }
  42214. if (shiftLayoutOnXY(list, 1, viewTop, viewTop + viewHeight)) {
  42215. recalculateX(list);
  42216. }
  42217. }
  42218. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  42219. var leftList = [];
  42220. var rightList = [];
  42221. var leftmostX = Number.MAX_VALUE;
  42222. var rightmostX = -Number.MAX_VALUE;
  42223. for (var i = 0; i < labelLayoutList.length; i++) {
  42224. var label = labelLayoutList[i].label;
  42225. if (isPositionCenter(labelLayoutList[i])) {
  42226. continue;
  42227. }
  42228. if (label.x < cx) {
  42229. leftmostX = Math.min(leftmostX, label.x);
  42230. leftList.push(labelLayoutList[i]);
  42231. } else {
  42232. rightmostX = Math.max(rightmostX, label.x);
  42233. rightList.push(labelLayoutList[i]);
  42234. }
  42235. }
  42236. for (var i = 0; i < labelLayoutList.length; i++) {
  42237. var layout = labelLayoutList[i];
  42238. if (!isPositionCenter(layout) && layout.linePoints) {
  42239. if (layout.labelStyleWidth != null) {
  42240. continue;
  42241. }
  42242. var label = layout.label;
  42243. var linePoints = layout.linePoints;
  42244. var targetTextWidth = void 0;
  42245. if (layout.labelAlignTo === 'edge') {
  42246. if (label.x < cx) {
  42247. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  42248. } else {
  42249. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  42250. }
  42251. } else if (layout.labelAlignTo === 'labelLine') {
  42252. if (label.x < cx) {
  42253. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  42254. } else {
  42255. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  42256. }
  42257. } else {
  42258. if (label.x < cx) {
  42259. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  42260. } else {
  42261. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  42262. }
  42263. }
  42264. layout.targetTextWidth = targetTextWidth;
  42265. constrainTextWidth(layout, targetTextWidth, false);
  42266. }
  42267. }
  42268. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  42269. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  42270. for (var i = 0; i < labelLayoutList.length; i++) {
  42271. var layout = labelLayoutList[i];
  42272. if (!isPositionCenter(layout) && layout.linePoints) {
  42273. var label = layout.label;
  42274. var linePoints = layout.linePoints;
  42275. var isAlignToEdge = layout.labelAlignTo === 'edge';
  42276. var padding = label.style.padding;
  42277. var paddingH = padding ? padding[1] + padding[3] : 0;
  42278. // textRect.width already contains paddingH if bgColor is set
  42279. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  42280. var realTextWidth = layout.rect.width + extraPaddingH;
  42281. var dist = linePoints[1][0] - linePoints[2][0];
  42282. if (isAlignToEdge) {
  42283. if (label.x < cx) {
  42284. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  42285. } else {
  42286. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  42287. }
  42288. } else {
  42289. if (label.x < cx) {
  42290. linePoints[2][0] = label.x + layout.labelDistance;
  42291. } else {
  42292. linePoints[2][0] = label.x - layout.labelDistance;
  42293. }
  42294. linePoints[1][0] = linePoints[2][0] + dist;
  42295. }
  42296. linePoints[1][1] = linePoints[2][1] = label.y;
  42297. }
  42298. }
  42299. }
  42300. /**
  42301. * Set max width of each label, and then wrap each label to the max width.
  42302. *
  42303. * @param layout label layout
  42304. * @param availableWidth max width for the label to display
  42305. * @param forceRecalculate recaculate the text layout even if the current width
  42306. * is smaller than `availableWidth`. This is useful when the text was previously
  42307. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  42308. * which case, previous wrapping should be redo.
  42309. */
  42310. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  42311. if (layout.labelStyleWidth != null) {
  42312. // User-defined style.width has the highest priority.
  42313. return;
  42314. }
  42315. var label = layout.label;
  42316. var style = label.style;
  42317. var textRect = layout.rect;
  42318. var bgColor = style.backgroundColor;
  42319. var padding = style.padding;
  42320. var paddingH = padding ? padding[1] + padding[3] : 0;
  42321. var overflow = style.overflow;
  42322. // textRect.width already contains paddingH if bgColor is set
  42323. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  42324. if (availableWidth < oldOuterWidth || forceRecalculate) {
  42325. if (overflow && overflow.match('break')) {
  42326. // Temporarily set background to be null to calculate
  42327. // the bounding box without background.
  42328. label.setStyle('backgroundColor', null);
  42329. // Set constraining width
  42330. label.setStyle('width', availableWidth - paddingH);
  42331. // This is the real bounding box of the text without padding.
  42332. var innerRect = label.getBoundingRect();
  42333. label.setStyle('width', Math.ceil(innerRect.width));
  42334. label.setStyle('backgroundColor', bgColor);
  42335. } else {
  42336. var availableInnerWidth = availableWidth - paddingH;
  42337. var newWidth = availableWidth < oldOuterWidth
  42338. // Current text is too wide, use `availableWidth` as max width.
  42339. ? availableInnerWidth :
  42340. // Current available width is enough, but the text may have
  42341. // already been wrapped with a smaller available width.
  42342. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth
  42343. // Current available is larger than text width,
  42344. // so don't constrain width (otherwise it may have
  42345. // empty space in the background).
  42346. ? null
  42347. // Current available is smaller than text width, so
  42348. // use the current available width as constraining
  42349. // width.
  42350. : availableInnerWidth
  42351. // Current available width is enough, so no need to
  42352. // constrain.
  42353. : null;
  42354. label.setStyle('width', newWidth);
  42355. }
  42356. computeLabelGlobalRect(textRect, label);
  42357. }
  42358. }
  42359. function computeLabelGlobalRect(out, label) {
  42360. _tmpLabelGeometry.rect = out;
  42361. computeLabelGeometry(_tmpLabelGeometry, label, _computeLabelGeometryOpt);
  42362. }
  42363. var _computeLabelGeometryOpt = {
  42364. minMarginForce: [null, 0, null, 0],
  42365. marginDefault: [1, 0, 1, 0]
  42366. };
  42367. var _tmpLabelGeometry = {};
  42368. function isPositionCenter(sectorShape) {
  42369. // Not change x for center label
  42370. return sectorShape.position === 'center';
  42371. }
  42372. function pieLabelLayout(seriesModel) {
  42373. var data = seriesModel.getData();
  42374. var labelLayoutList = [];
  42375. var cx;
  42376. var cy;
  42377. var hasLabelRotate = false;
  42378. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  42379. var viewRect = data.getLayout('viewRect');
  42380. var r = data.getLayout('r');
  42381. var viewWidth = viewRect.width;
  42382. var viewLeft = viewRect.x;
  42383. var viewTop = viewRect.y;
  42384. var viewHeight = viewRect.height;
  42385. function setNotShow(el) {
  42386. el.ignore = true;
  42387. }
  42388. function isLabelShown(label) {
  42389. if (!label.ignore) {
  42390. return true;
  42391. }
  42392. for (var key in label.states) {
  42393. if (label.states[key].ignore === false) {
  42394. return true;
  42395. }
  42396. }
  42397. return false;
  42398. }
  42399. data.each(function (idx) {
  42400. var sector = data.getItemGraphicEl(idx);
  42401. var sectorShape = sector.shape;
  42402. var label = sector.getTextContent();
  42403. var labelLine = sector.getTextGuideLine();
  42404. var itemModel = data.getItemModel(idx);
  42405. var labelModel = itemModel.getModel('label');
  42406. // Use position in normal or emphasis
  42407. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  42408. var labelDistance = labelModel.get('distanceToLabelLine');
  42409. var labelAlignTo = labelModel.get('alignTo');
  42410. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  42411. var bleedMargin = labelModel.get('bleedMargin');
  42412. if (bleedMargin == null) {
  42413. // An arbitrary strategy for small viewRect - especial pie is layout in calendar or matrix coord sys.
  42414. bleedMargin = Math.min(viewWidth, viewHeight) > 200 ? 10 : 2;
  42415. }
  42416. var labelLineModel = itemModel.getModel('labelLine');
  42417. var labelLineLen = labelLineModel.get('length');
  42418. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  42419. var labelLineLen2 = labelLineModel.get('length2');
  42420. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  42421. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  42422. each(label.states, setNotShow);
  42423. label.ignore = true;
  42424. if (labelLine) {
  42425. each(labelLine.states, setNotShow);
  42426. labelLine.ignore = true;
  42427. }
  42428. return;
  42429. }
  42430. if (!isLabelShown(label)) {
  42431. return;
  42432. }
  42433. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  42434. var nx = Math.cos(midAngle);
  42435. var ny = Math.sin(midAngle);
  42436. var textX;
  42437. var textY;
  42438. var linePoints;
  42439. var textAlign;
  42440. cx = sectorShape.cx;
  42441. cy = sectorShape.cy;
  42442. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  42443. if (labelPosition === 'center') {
  42444. textX = sectorShape.cx;
  42445. textY = sectorShape.cy;
  42446. textAlign = 'center';
  42447. } else {
  42448. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  42449. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  42450. textX = x1 + nx * 3;
  42451. textY = y1 + ny * 3;
  42452. if (!isLabelInside) {
  42453. // For roseType
  42454. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  42455. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  42456. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  42457. var y3 = y2;
  42458. if (labelAlignTo === 'edge') {
  42459. // Adjust textX because text align of edge is opposite
  42460. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  42461. } else {
  42462. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  42463. }
  42464. textY = y3;
  42465. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  42466. }
  42467. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  42468. }
  42469. var PI = Math.PI;
  42470. var labelRotate = 0;
  42471. var rotate = labelModel.get('rotate');
  42472. if (isNumber(rotate)) {
  42473. labelRotate = rotate * (PI / 180);
  42474. } else if (labelPosition === 'center') {
  42475. labelRotate = 0;
  42476. } else if (rotate === 'radial' || rotate === true) {
  42477. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  42478. labelRotate = radialAngle;
  42479. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  42480. var rad = Math.atan2(nx, ny);
  42481. if (rad < 0) {
  42482. rad = PI * 2 + rad;
  42483. }
  42484. var isDown = ny > 0;
  42485. if (isDown) {
  42486. rad = PI + rad;
  42487. }
  42488. labelRotate = rad - PI;
  42489. }
  42490. hasLabelRotate = !!labelRotate;
  42491. label.x = textX;
  42492. label.y = textY;
  42493. label.rotation = labelRotate;
  42494. label.setStyle({
  42495. verticalAlign: 'middle'
  42496. });
  42497. // Not sectorShape the inside label
  42498. if (!isLabelInside) {
  42499. var textRect = new BoundingRect(0, 0, 0, 0);
  42500. computeLabelGlobalRect(textRect, label);
  42501. labelLayoutList.push({
  42502. label: label,
  42503. labelLine: labelLine,
  42504. position: labelPosition,
  42505. len: labelLineLen,
  42506. len2: labelLineLen2,
  42507. minTurnAngle: labelLineModel.get('minTurnAngle'),
  42508. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  42509. surfaceNormal: new Point(nx, ny),
  42510. linePoints: linePoints,
  42511. textAlign: textAlign,
  42512. labelDistance: labelDistance,
  42513. labelAlignTo: labelAlignTo,
  42514. edgeDistance: edgeDistance,
  42515. bleedMargin: bleedMargin,
  42516. rect: textRect,
  42517. unconstrainedWidth: textRect.width,
  42518. labelStyleWidth: label.style.width
  42519. });
  42520. } else {
  42521. label.setStyle({
  42522. align: textAlign
  42523. });
  42524. var selectState = label.states.select;
  42525. if (selectState) {
  42526. selectState.x += label.x;
  42527. selectState.y += label.y;
  42528. }
  42529. }
  42530. sector.setTextConfig({
  42531. inside: isLabelInside
  42532. });
  42533. });
  42534. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  42535. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  42536. }
  42537. for (var i = 0; i < labelLayoutList.length; i++) {
  42538. var layout = labelLayoutList[i];
  42539. var label = layout.label;
  42540. var labelLine = layout.labelLine;
  42541. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  42542. if (label) {
  42543. label.setStyle({
  42544. align: layout.textAlign
  42545. });
  42546. if (notShowLabel) {
  42547. each(label.states, setNotShow);
  42548. label.ignore = true;
  42549. }
  42550. var selectState = label.states.select;
  42551. if (selectState) {
  42552. selectState.x += label.x;
  42553. selectState.y += label.y;
  42554. }
  42555. }
  42556. if (labelLine) {
  42557. var linePoints = layout.linePoints;
  42558. if (notShowLabel || !linePoints) {
  42559. each(labelLine.states, setNotShow);
  42560. labelLine.ignore = true;
  42561. } else {
  42562. limitTurnAngle(linePoints, layout.minTurnAngle);
  42563. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  42564. labelLine.setShape({
  42565. points: linePoints
  42566. });
  42567. // Set the anchor to the midpoint of sector
  42568. label.__hostTarget.textGuideLineConfig = {
  42569. anchor: new Point(linePoints[0][0], linePoints[0][1])
  42570. };
  42571. }
  42572. }
  42573. }
  42574. }
  42575. /**
  42576. * Piece of pie including Sector, Label, LabelLine
  42577. */
  42578. var PiePiece = /** @class */function (_super) {
  42579. __extends(PiePiece, _super);
  42580. function PiePiece(data, idx, startAngle) {
  42581. var _this = _super.call(this) || this;
  42582. _this.z2 = 2;
  42583. var text = new ZRText();
  42584. _this.setTextContent(text);
  42585. _this.updateData(data, idx, startAngle, true);
  42586. return _this;
  42587. }
  42588. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  42589. var sector = this;
  42590. var seriesModel = data.hostModel;
  42591. var itemModel = data.getItemModel(idx);
  42592. var emphasisModel = itemModel.getModel('emphasis');
  42593. var layout = data.getItemLayout(idx);
  42594. // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  42595. // see `setItemLayout` in `pieLayout.ts`.
  42596. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout);
  42597. // Ignore NaN data.
  42598. if (isNaN(sectorShape.startAngle)) {
  42599. // Use NaN shape to avoid drawing shape.
  42600. sector.setShape(sectorShape);
  42601. return;
  42602. }
  42603. if (firstCreate) {
  42604. sector.setShape(sectorShape);
  42605. var animationType = seriesModel.getShallow('animationType');
  42606. if (seriesModel.ecModel.ssr) {
  42607. // Use scale animation in SSR mode(opacity?)
  42608. // Because CSS SVG animation doesn't support very customized shape animation.
  42609. initProps(sector, {
  42610. scaleX: 0,
  42611. scaleY: 0
  42612. }, seriesModel, {
  42613. dataIndex: idx,
  42614. isFrom: true
  42615. });
  42616. sector.originX = sectorShape.cx;
  42617. sector.originY = sectorShape.cy;
  42618. } else if (animationType === 'scale') {
  42619. sector.shape.r = layout.r0;
  42620. initProps(sector, {
  42621. shape: {
  42622. r: layout.r
  42623. }
  42624. }, seriesModel, idx);
  42625. }
  42626. // Expansion
  42627. else {
  42628. if (startAngle != null) {
  42629. sector.setShape({
  42630. startAngle: startAngle,
  42631. endAngle: startAngle
  42632. });
  42633. initProps(sector, {
  42634. shape: {
  42635. startAngle: layout.startAngle,
  42636. endAngle: layout.endAngle
  42637. }
  42638. }, seriesModel, idx);
  42639. } else {
  42640. sector.shape.endAngle = layout.startAngle;
  42641. updateProps(sector, {
  42642. shape: {
  42643. endAngle: layout.endAngle
  42644. }
  42645. }, seriesModel, idx);
  42646. }
  42647. }
  42648. } else {
  42649. saveOldStyle(sector);
  42650. // Transition animation from the old shape
  42651. updateProps(sector, {
  42652. shape: sectorShape
  42653. }, seriesModel, idx);
  42654. }
  42655. sector.useStyle(data.getItemVisual(idx, 'style'));
  42656. setStatesStylesFromModel(sector, itemModel);
  42657. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  42658. var offset = seriesModel.get('selectedOffset');
  42659. var dx = Math.cos(midAngle) * offset;
  42660. var dy = Math.sin(midAngle) * offset;
  42661. var cursorStyle = itemModel.getShallow('cursor');
  42662. cursorStyle && sector.attr('cursor', cursorStyle);
  42663. this._updateLabel(seriesModel, data, idx);
  42664. sector.ensureState('emphasis').shape = extend({
  42665. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  42666. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  42667. extend(sector.ensureState('select'), {
  42668. x: dx,
  42669. y: dy,
  42670. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  42671. });
  42672. extend(sector.ensureState('blur'), {
  42673. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  42674. });
  42675. var labelLine = sector.getTextGuideLine();
  42676. var labelText = sector.getTextContent();
  42677. labelLine && extend(labelLine.ensureState('select'), {
  42678. x: dx,
  42679. y: dy
  42680. });
  42681. // TODO: needs dx, dy in zrender?
  42682. extend(labelText.ensureState('select'), {
  42683. x: dx,
  42684. y: dy
  42685. });
  42686. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  42687. };
  42688. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  42689. var sector = this;
  42690. var itemModel = data.getItemModel(idx);
  42691. var labelLineModel = itemModel.getModel('labelLine');
  42692. var style = data.getItemVisual(idx, 'style');
  42693. var visualColor = style && style.fill;
  42694. var visualOpacity = style && style.opacity;
  42695. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  42696. labelFetcher: data.hostModel,
  42697. labelDataIndex: idx,
  42698. inheritColor: visualColor,
  42699. defaultOpacity: visualOpacity,
  42700. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  42701. });
  42702. var labelText = sector.getTextContent();
  42703. // Set textConfig on sector.
  42704. sector.setTextConfig({
  42705. // reset position, rotation
  42706. position: null,
  42707. rotation: null
  42708. });
  42709. // Make sure update style on labelText after setLabelStyle.
  42710. // Because setLabelStyle will replace a new style on it.
  42711. labelText.attr({
  42712. z2: 10
  42713. });
  42714. var labelPosition = itemModel.get(['label', 'position']);
  42715. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  42716. sector.removeTextGuideLine();
  42717. } else {
  42718. var polyline = this.getTextGuideLine();
  42719. if (!polyline) {
  42720. polyline = new Polyline();
  42721. this.setTextGuideLine(polyline);
  42722. }
  42723. // Default use item visual color
  42724. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  42725. stroke: visualColor,
  42726. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  42727. });
  42728. }
  42729. };
  42730. return PiePiece;
  42731. }(Sector);
  42732. // Pie view
  42733. var PieView = /** @class */function (_super) {
  42734. __extends(PieView, _super);
  42735. function PieView() {
  42736. var _this = _super !== null && _super.apply(this, arguments) || this;
  42737. _this.ignoreLabelLineUpdate = true;
  42738. return _this;
  42739. }
  42740. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  42741. var data = seriesModel.getData();
  42742. var oldData = this._data;
  42743. var group = this.group;
  42744. var startAngle;
  42745. // First render
  42746. if (!oldData && data.count() > 0) {
  42747. var shape = data.getItemLayout(0);
  42748. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  42749. shape = data.getItemLayout(s);
  42750. }
  42751. if (shape) {
  42752. startAngle = shape.startAngle;
  42753. }
  42754. }
  42755. // remove empty-circle if it exists
  42756. if (this._emptyCircleSector) {
  42757. group.remove(this._emptyCircleSector);
  42758. }
  42759. // when all data are filtered, show lightgray empty circle
  42760. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  42761. var layoutData = getSeriesLayoutData(seriesModel);
  42762. var sector = new Sector({
  42763. shape: clone(layoutData)
  42764. });
  42765. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  42766. this._emptyCircleSector = sector;
  42767. group.add(sector);
  42768. }
  42769. data.diff(oldData).add(function (idx) {
  42770. var piePiece = new PiePiece(data, idx, startAngle);
  42771. data.setItemGraphicEl(idx, piePiece);
  42772. group.add(piePiece);
  42773. }).update(function (newIdx, oldIdx) {
  42774. var piePiece = oldData.getItemGraphicEl(oldIdx);
  42775. piePiece.updateData(data, newIdx, startAngle);
  42776. piePiece.off('click');
  42777. group.add(piePiece);
  42778. data.setItemGraphicEl(newIdx, piePiece);
  42779. }).remove(function (idx) {
  42780. var piePiece = oldData.getItemGraphicEl(idx);
  42781. removeElementWithFadeOut(piePiece, seriesModel, idx);
  42782. }).execute();
  42783. pieLabelLayout(seriesModel);
  42784. // Always use initial animation.
  42785. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  42786. this._data = data;
  42787. }
  42788. };
  42789. PieView.prototype.dispose = function () {};
  42790. PieView.prototype.containPoint = function (point, seriesModel) {
  42791. var data = seriesModel.getData();
  42792. var itemLayout = data.getItemLayout(0);
  42793. if (itemLayout) {
  42794. var dx = point[0] - itemLayout.cx;
  42795. var dy = point[1] - itemLayout.cy;
  42796. var radius = Math.sqrt(dx * dx + dy * dy);
  42797. return radius <= itemLayout.r && radius >= itemLayout.r0;
  42798. }
  42799. };
  42800. PieView.type = 'pie';
  42801. return PieView;
  42802. }(ChartView);
  42803. /**
  42804. * [Usage]:
  42805. * (1)
  42806. * createListSimply(seriesModel, ['value']);
  42807. * (2)
  42808. * createListSimply(seriesModel, {
  42809. * coordDimensions: ['value'],
  42810. * dimensionsCount: 5
  42811. * });
  42812. */
  42813. function createSeriesDataSimply(seriesModel, opt, nameList) {
  42814. opt = isArray(opt) && {
  42815. coordDimensions: opt
  42816. } || extend({
  42817. encodeDefine: seriesModel.getEncode()
  42818. }, opt);
  42819. var source = seriesModel.getSource();
  42820. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  42821. var list = new SeriesData(dimensions, seriesModel);
  42822. list.initData(source, nameList);
  42823. return list;
  42824. }
  42825. /*
  42826. * Licensed to the Apache Software Foundation (ASF) under one
  42827. * or more contributor license agreements. See the NOTICE file
  42828. * distributed with this work for additional information
  42829. * regarding copyright ownership. The ASF licenses this file
  42830. * to you under the Apache License, Version 2.0 (the
  42831. * "License"); you may not use this file except in compliance
  42832. * with the License. You may obtain a copy of the License at
  42833. *
  42834. * http://www.apache.org/licenses/LICENSE-2.0
  42835. *
  42836. * Unless required by applicable law or agreed to in writing,
  42837. * software distributed under the License is distributed on an
  42838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42839. * KIND, either express or implied. See the License for the
  42840. * specific language governing permissions and limitations
  42841. * under the License.
  42842. */
  42843. /**
  42844. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42845. */
  42846. /*
  42847. * Licensed to the Apache Software Foundation (ASF) under one
  42848. * or more contributor license agreements. See the NOTICE file
  42849. * distributed with this work for additional information
  42850. * regarding copyright ownership. The ASF licenses this file
  42851. * to you under the Apache License, Version 2.0 (the
  42852. * "License"); you may not use this file except in compliance
  42853. * with the License. You may obtain a copy of the License at
  42854. *
  42855. * http://www.apache.org/licenses/LICENSE-2.0
  42856. *
  42857. * Unless required by applicable law or agreed to in writing,
  42858. * software distributed under the License is distributed on an
  42859. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42860. * KIND, either express or implied. See the License for the
  42861. * specific language governing permissions and limitations
  42862. * under the License.
  42863. */
  42864. /**
  42865. * LegendVisualProvider is an bridge that pick encoded color from data and
  42866. * provide to the legend component.
  42867. */
  42868. var LegendVisualProvider = /** @class */function () {
  42869. function LegendVisualProvider(
  42870. // Function to get data after filtered. It stores all the encoding info
  42871. getDataWithEncodedVisual,
  42872. // Function to get raw data before filtered.
  42873. getRawData) {
  42874. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  42875. this._getRawData = getRawData;
  42876. }
  42877. LegendVisualProvider.prototype.getAllNames = function () {
  42878. var rawData = this._getRawData();
  42879. // We find the name from the raw data. In case it's filtered by the legend component.
  42880. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  42881. return rawData.mapArray(rawData.getName);
  42882. };
  42883. LegendVisualProvider.prototype.containName = function (name) {
  42884. var rawData = this._getRawData();
  42885. return rawData.indexOfName(name) >= 0;
  42886. };
  42887. LegendVisualProvider.prototype.indexOfName = function (name) {
  42888. // Only get data when necessary.
  42889. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  42890. // Invoking Series#getData immediately will throw an error.
  42891. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  42892. return dataWithEncodedVisual.indexOfName(name);
  42893. };
  42894. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  42895. // Get encoded visual properties from final filtered data.
  42896. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  42897. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  42898. };
  42899. return LegendVisualProvider;
  42900. }();
  42901. var innerData = makeInner();
  42902. var PieSeriesModel = /** @class */function (_super) {
  42903. __extends(PieSeriesModel, _super);
  42904. function PieSeriesModel() {
  42905. return _super !== null && _super.apply(this, arguments) || this;
  42906. }
  42907. /**
  42908. * @overwrite
  42909. */
  42910. PieSeriesModel.prototype.init = function (option) {
  42911. _super.prototype.init.apply(this, arguments);
  42912. // Enable legend selection for each data item
  42913. // Use a function instead of direct access because data reference may changed
  42914. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  42915. this._defaultLabelLine(option);
  42916. };
  42917. /**
  42918. * @overwrite
  42919. */
  42920. PieSeriesModel.prototype.mergeOption = function () {
  42921. _super.prototype.mergeOption.apply(this, arguments);
  42922. };
  42923. /**
  42924. * @overwrite
  42925. */
  42926. PieSeriesModel.prototype.getInitialData = function () {
  42927. return createSeriesDataSimply(this, {
  42928. coordDimensions: ['value'],
  42929. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  42930. });
  42931. };
  42932. /**
  42933. * @overwrite
  42934. */
  42935. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  42936. var data = this.getData();
  42937. // update seats when data is changed
  42938. var dataInner = innerData(data);
  42939. var seats = dataInner.seats;
  42940. if (!seats) {
  42941. var valueList_1 = [];
  42942. data.each(data.mapDimension('value'), function (value) {
  42943. valueList_1.push(value);
  42944. });
  42945. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  42946. }
  42947. var params = _super.prototype.getDataParams.call(this, dataIndex);
  42948. // seats may be empty when sum is 0
  42949. params.percent = seats[dataIndex] || 0;
  42950. params.$vars.push('percent');
  42951. return params;
  42952. };
  42953. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  42954. // Extend labelLine emphasis
  42955. defaultEmphasis(option, 'labelLine', ['show']);
  42956. var labelLineNormalOpt = option.labelLine;
  42957. var labelLineEmphasisOpt = option.emphasis.labelLine;
  42958. // Not show label line if `label.normal.show = false`
  42959. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  42960. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  42961. };
  42962. PieSeriesModel.type = 'series.pie';
  42963. PieSeriesModel.defaultOption = {
  42964. // zlevel: 0,
  42965. z: 2,
  42966. legendHoverLink: true,
  42967. colorBy: 'data',
  42968. // 默认全局居中
  42969. center: ['50%', '50%'],
  42970. radius: [0, '50%'],
  42971. // 默认顺时针
  42972. clockwise: true,
  42973. startAngle: 90,
  42974. endAngle: 'auto',
  42975. padAngle: 0,
  42976. // 最小角度改为0
  42977. minAngle: 0,
  42978. // If the angle of a sector less than `minShowLabelAngle`,
  42979. // the label will not be displayed.
  42980. minShowLabelAngle: 0,
  42981. // 选中时扇区偏移量
  42982. selectedOffset: 10,
  42983. // 选择模式,默认关闭,可选single,multiple
  42984. // selectedMode: false,
  42985. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  42986. // roseType: null,
  42987. percentPrecision: 2,
  42988. // If still show when all data zero.
  42989. stillShowZeroSum: true,
  42990. // cursor: null,
  42991. coordinateSystemUsage: 'box',
  42992. left: 0,
  42993. top: 0,
  42994. right: 0,
  42995. bottom: 0,
  42996. width: null,
  42997. height: null,
  42998. label: {
  42999. // color: 'inherit',
  43000. // If rotate around circle
  43001. rotate: 0,
  43002. show: true,
  43003. overflow: 'truncate',
  43004. // 'outer', 'inside', 'center'
  43005. position: 'outer',
  43006. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  43007. alignTo: 'none',
  43008. // Closest distance between label and chart edge.
  43009. // Works only position is 'outer' and alignTo is 'edge'.
  43010. edgeDistance: '25%',
  43011. // Works only position is 'outer' and alignTo is not 'edge'.
  43012. // The default `bleedMargin` is auto determined according to view rect size.
  43013. // bleedMargin: 10,
  43014. // Distance between text and label line.
  43015. distanceToLabelLine: 5
  43016. // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  43017. // 默认使用全局文本样式,详见 textStyle
  43018. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  43019. },
  43020. // Enabled when label.normal.position is 'outer'
  43021. labelLine: {
  43022. show: true,
  43023. // 引导线两段中的第一段长度
  43024. length: 15,
  43025. // 引导线两段中的第二段长度
  43026. length2: 30,
  43027. smooth: false,
  43028. minTurnAngle: 90,
  43029. maxSurfaceAngle: 90,
  43030. lineStyle: {
  43031. // color: 各异,
  43032. width: 1,
  43033. type: 'solid'
  43034. }
  43035. },
  43036. itemStyle: {
  43037. borderWidth: 1,
  43038. borderJoin: 'round'
  43039. },
  43040. showEmptyCircle: true,
  43041. emptyCircleStyle: {
  43042. color: 'lightgray',
  43043. opacity: 1
  43044. },
  43045. labelLayout: {
  43046. // Hide the overlapped label.
  43047. hideOverlap: true
  43048. },
  43049. emphasis: {
  43050. scale: true,
  43051. scaleSize: 5
  43052. },
  43053. // If use strategy to avoid label overlapping
  43054. avoidLabelOverlap: true,
  43055. // Animation type. Valid values: expansion, scale
  43056. animationType: 'expansion',
  43057. animationDuration: 1000,
  43058. // Animation type when update. Valid values: transition, expansion
  43059. animationTypeUpdate: 'transition',
  43060. animationEasingUpdate: 'cubicInOut',
  43061. animationDurationUpdate: 500,
  43062. animationEasing: 'cubicInOut'
  43063. };
  43064. return PieSeriesModel;
  43065. }(SeriesModel);
  43066. registerLayOutOnCoordSysUsage({
  43067. fullType: PieSeriesModel.type,
  43068. getCoord2: function (model) {
  43069. // Not able to validate `center` type here.
  43070. // But percentage center, such as '12%', is not allowed in this case.
  43071. return model.getShallow('center');
  43072. }
  43073. });
  43074. function negativeDataFilter(seriesType) {
  43075. return {
  43076. seriesType: seriesType,
  43077. reset: function (seriesModel, ecModel) {
  43078. var data = seriesModel.getData();
  43079. data.filterSelf(function (idx) {
  43080. // handle negative value condition
  43081. var valueDim = data.mapDimension('value');
  43082. var curValue = data.get(valueDim, idx);
  43083. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  43084. return false;
  43085. }
  43086. return true;
  43087. });
  43088. }
  43089. };
  43090. }
  43091. function install$4(registers) {
  43092. registers.registerChartView(PieView);
  43093. registers.registerSeriesModel(PieSeriesModel);
  43094. createLegacyDataSelectAction('pie', registers.registerAction);
  43095. registers.registerLayout(curry(pieLayout, 'pie'));
  43096. registers.registerProcessor(dataFilter('pie'));
  43097. registers.registerProcessor(negativeDataFilter('pie'));
  43098. }
  43099. var ScatterSeriesModel = /** @class */function (_super) {
  43100. __extends(ScatterSeriesModel, _super);
  43101. function ScatterSeriesModel() {
  43102. var _this = _super !== null && _super.apply(this, arguments) || this;
  43103. _this.type = ScatterSeriesModel.type;
  43104. _this.hasSymbolVisual = true;
  43105. return _this;
  43106. }
  43107. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  43108. return createSeriesData(null, this, {
  43109. useEncodeDefaulter: true
  43110. });
  43111. };
  43112. ScatterSeriesModel.prototype.getProgressive = function () {
  43113. var progressive = this.option.progressive;
  43114. if (progressive == null) {
  43115. // PENDING
  43116. return this.option.large ? 5e3 : this.get('progressive');
  43117. }
  43118. return progressive;
  43119. };
  43120. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  43121. var progressiveThreshold = this.option.progressiveThreshold;
  43122. if (progressiveThreshold == null) {
  43123. // PENDING
  43124. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  43125. }
  43126. return progressiveThreshold;
  43127. };
  43128. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  43129. return selectors.point(data.getItemLayout(dataIndex));
  43130. };
  43131. ScatterSeriesModel.prototype.getZLevelKey = function () {
  43132. // Each progressive series has individual key.
  43133. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  43134. };
  43135. ScatterSeriesModel.type = 'series.scatter';
  43136. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar', 'matrix'];
  43137. ScatterSeriesModel.defaultOption = {
  43138. coordinateSystem: 'cartesian2d',
  43139. // zlevel: 0,
  43140. z: 2,
  43141. legendHoverLink: true,
  43142. symbolSize: 10,
  43143. // symbolRotate: null, // 图形旋转控制
  43144. large: false,
  43145. // Available when large is true
  43146. largeThreshold: 2000,
  43147. // cursor: null,
  43148. itemStyle: {
  43149. opacity: 0.8
  43150. // color: 各异
  43151. },
  43152. emphasis: {
  43153. scale: true
  43154. },
  43155. // If clip the overflow graphics
  43156. // Works on cartesian / polar series
  43157. clip: true,
  43158. select: {
  43159. itemStyle: {
  43160. borderColor: tokens.color.primary
  43161. }
  43162. },
  43163. universalTransition: {
  43164. divideShape: 'clone'
  43165. }
  43166. // progressive: null
  43167. };
  43168. return ScatterSeriesModel;
  43169. }(SeriesModel);
  43170. var BOOST_SIZE_THRESHOLD = 4;
  43171. var LargeSymbolPathShape = /** @class */function () {
  43172. function LargeSymbolPathShape() {}
  43173. return LargeSymbolPathShape;
  43174. }();
  43175. var LargeSymbolPath = /** @class */function (_super) {
  43176. __extends(LargeSymbolPath, _super);
  43177. function LargeSymbolPath(opts) {
  43178. var _this = _super.call(this, opts) || this;
  43179. _this._off = 0;
  43180. _this.hoverDataIdx = -1;
  43181. return _this;
  43182. }
  43183. LargeSymbolPath.prototype.getDefaultShape = function () {
  43184. return new LargeSymbolPathShape();
  43185. };
  43186. LargeSymbolPath.prototype.reset = function () {
  43187. this.notClear = false;
  43188. this._off = 0;
  43189. };
  43190. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  43191. var points = shape.points;
  43192. var size = shape.size;
  43193. var symbolProxy = this.symbolProxy;
  43194. var symbolProxyShape = symbolProxy.shape;
  43195. var ctx = path.getContext ? path.getContext() : path;
  43196. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  43197. var softClipShape = this.softClipShape;
  43198. var i;
  43199. // Do draw in afterBrush.
  43200. if (canBoost) {
  43201. this._ctx = ctx;
  43202. return;
  43203. }
  43204. this._ctx = null;
  43205. for (i = this._off; i < points.length;) {
  43206. var x = points[i++];
  43207. var y = points[i++];
  43208. if (isNaN(x) || isNaN(y)) {
  43209. continue;
  43210. }
  43211. if (softClipShape && !softClipShape.contain(x, y)) {
  43212. continue;
  43213. }
  43214. symbolProxyShape.x = x - size[0] / 2;
  43215. symbolProxyShape.y = y - size[1] / 2;
  43216. symbolProxyShape.width = size[0];
  43217. symbolProxyShape.height = size[1];
  43218. symbolProxy.buildPath(path, symbolProxyShape, true);
  43219. }
  43220. if (this.incremental) {
  43221. this._off = i;
  43222. this.notClear = true;
  43223. }
  43224. };
  43225. LargeSymbolPath.prototype.afterBrush = function () {
  43226. var shape = this.shape;
  43227. var points = shape.points;
  43228. var size = shape.size;
  43229. var ctx = this._ctx;
  43230. var softClipShape = this.softClipShape;
  43231. var i;
  43232. if (!ctx) {
  43233. return;
  43234. }
  43235. // PENDING If style or other canvas status changed?
  43236. for (i = this._off; i < points.length;) {
  43237. var x = points[i++];
  43238. var y = points[i++];
  43239. if (isNaN(x) || isNaN(y)) {
  43240. continue;
  43241. }
  43242. if (softClipShape && !softClipShape.contain(x, y)) {
  43243. continue;
  43244. }
  43245. // fillRect is faster than building a rect path and draw.
  43246. // And it support light globalCompositeOperation.
  43247. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  43248. }
  43249. if (this.incremental) {
  43250. this._off = i;
  43251. this.notClear = true;
  43252. }
  43253. };
  43254. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  43255. // TODO ???
  43256. // Consider transform
  43257. var shape = this.shape;
  43258. var points = shape.points;
  43259. var size = shape.size;
  43260. var w = Math.max(size[0], 4);
  43261. var h = Math.max(size[1], 4);
  43262. // Not consider transform
  43263. // Treat each element as a rect
  43264. // top down traverse
  43265. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  43266. var i = idx * 2;
  43267. var x0 = points[i] - w / 2;
  43268. var y0 = points[i + 1] - h / 2;
  43269. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  43270. return idx;
  43271. }
  43272. }
  43273. return -1;
  43274. };
  43275. LargeSymbolPath.prototype.contain = function (x, y) {
  43276. var localPos = this.transformCoordToLocal(x, y);
  43277. var rect = this.getBoundingRect();
  43278. x = localPos[0];
  43279. y = localPos[1];
  43280. if (rect.contain(x, y)) {
  43281. // Cache found data index.
  43282. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  43283. return dataIdx >= 0;
  43284. }
  43285. this.hoverDataIdx = -1;
  43286. return false;
  43287. };
  43288. LargeSymbolPath.prototype.getBoundingRect = function () {
  43289. // Ignore stroke for large symbol draw.
  43290. var rect = this._rect;
  43291. if (!rect) {
  43292. var shape = this.shape;
  43293. var points = shape.points;
  43294. var size = shape.size;
  43295. var w = size[0];
  43296. var h = size[1];
  43297. var minX = Infinity;
  43298. var minY = Infinity;
  43299. var maxX = -Infinity;
  43300. var maxY = -Infinity;
  43301. for (var i = 0; i < points.length;) {
  43302. var x = points[i++];
  43303. var y = points[i++];
  43304. minX = Math.min(x, minX);
  43305. maxX = Math.max(x, maxX);
  43306. minY = Math.min(y, minY);
  43307. maxY = Math.max(y, maxY);
  43308. }
  43309. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  43310. }
  43311. return rect;
  43312. };
  43313. return LargeSymbolPath;
  43314. }(Path);
  43315. var LargeSymbolDraw = /** @class */function () {
  43316. function LargeSymbolDraw() {
  43317. this.group = new Group();
  43318. }
  43319. /**
  43320. * Update symbols draw by new data
  43321. */
  43322. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  43323. this._clear();
  43324. var symbolEl = this._create();
  43325. symbolEl.setShape({
  43326. points: data.getLayout('points')
  43327. });
  43328. this._setCommon(symbolEl, data, opt);
  43329. };
  43330. LargeSymbolDraw.prototype.updateLayout = function (data) {
  43331. var points = data.getLayout('points');
  43332. this.group.eachChild(function (child) {
  43333. if (child.startIndex != null) {
  43334. var len = (child.endIndex - child.startIndex) * 2;
  43335. var byteOffset = child.startIndex * 4 * 2;
  43336. points = new Float32Array(points.buffer, byteOffset, len);
  43337. }
  43338. child.setShape('points', points);
  43339. // Reset draw cursor.
  43340. child.reset();
  43341. });
  43342. };
  43343. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  43344. this._clear();
  43345. };
  43346. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  43347. var lastAdded = this._newAdded[0];
  43348. var points = data.getLayout('points');
  43349. var oldPoints = lastAdded && lastAdded.shape.points;
  43350. // Merging the exists. Each element has 1e4 points.
  43351. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  43352. if (oldPoints && oldPoints.length < 2e4) {
  43353. var oldLen = oldPoints.length;
  43354. var newPoints = new Float32Array(oldLen + points.length);
  43355. // Concat two array
  43356. newPoints.set(oldPoints);
  43357. newPoints.set(points, oldLen);
  43358. // Update endIndex
  43359. lastAdded.endIndex = taskParams.end;
  43360. lastAdded.setShape({
  43361. points: newPoints
  43362. });
  43363. } else {
  43364. // Clear
  43365. this._newAdded = [];
  43366. var symbolEl = this._create();
  43367. symbolEl.startIndex = taskParams.start;
  43368. symbolEl.endIndex = taskParams.end;
  43369. symbolEl.incremental = true;
  43370. symbolEl.setShape({
  43371. points: points
  43372. });
  43373. this._setCommon(symbolEl, data, opt);
  43374. }
  43375. };
  43376. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  43377. this._newAdded[0] && cb(this._newAdded[0]);
  43378. };
  43379. LargeSymbolDraw.prototype._create = function () {
  43380. var symbolEl = new LargeSymbolPath({
  43381. cursor: 'default'
  43382. });
  43383. symbolEl.ignoreCoarsePointer = true;
  43384. this.group.add(symbolEl);
  43385. this._newAdded.push(symbolEl);
  43386. return symbolEl;
  43387. };
  43388. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  43389. var hostModel = data.hostModel;
  43390. opt = opt || {};
  43391. var size = data.getVisual('symbolSize');
  43392. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  43393. symbolEl.softClipShape = opt.clipShape || null;
  43394. // Create symbolProxy to build path for each data
  43395. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0);
  43396. // Use symbolProxy setColor method
  43397. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  43398. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  43399. symbolEl.useStyle(
  43400. // Draw shadow when doing fillRect is extremely slow.
  43401. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  43402. var globalStyle = data.getVisual('style');
  43403. var visualColor = globalStyle && globalStyle.fill;
  43404. if (visualColor) {
  43405. symbolEl.setColor(visualColor);
  43406. }
  43407. var ecData = getECData(symbolEl);
  43408. // Enable tooltip
  43409. // PENDING May have performance issue when path is extremely large
  43410. ecData.seriesIndex = hostModel.seriesIndex;
  43411. symbolEl.on('mousemove', function (e) {
  43412. ecData.dataIndex = null;
  43413. var dataIndex = symbolEl.hoverDataIdx;
  43414. if (dataIndex >= 0) {
  43415. // Provide dataIndex for tooltip
  43416. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  43417. }
  43418. });
  43419. };
  43420. LargeSymbolDraw.prototype.remove = function () {
  43421. this._clear();
  43422. };
  43423. LargeSymbolDraw.prototype._clear = function () {
  43424. this._newAdded = [];
  43425. this.group.removeAll();
  43426. };
  43427. return LargeSymbolDraw;
  43428. }();
  43429. var ScatterView = /** @class */function (_super) {
  43430. __extends(ScatterView, _super);
  43431. function ScatterView() {
  43432. var _this = _super !== null && _super.apply(this, arguments) || this;
  43433. _this.type = ScatterView.type;
  43434. return _this;
  43435. }
  43436. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  43437. var data = seriesModel.getData();
  43438. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  43439. symbolDraw.updateData(data, {
  43440. // TODO
  43441. // If this parameter should be a shape or a bounding volume
  43442. // shape will be more general.
  43443. // But bounding volume like bounding rect will be much faster in the contain calculation
  43444. clipShape: this._getClipShape(seriesModel)
  43445. });
  43446. this._finished = true;
  43447. };
  43448. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  43449. var data = seriesModel.getData();
  43450. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  43451. symbolDraw.incrementalPrepareUpdate(data);
  43452. this._finished = false;
  43453. };
  43454. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  43455. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  43456. clipShape: this._getClipShape(seriesModel)
  43457. });
  43458. this._finished = taskParams.end === seriesModel.getData().count();
  43459. };
  43460. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  43461. var data = seriesModel.getData();
  43462. // Must mark group dirty and make sure the incremental layer will be cleared
  43463. // PENDING
  43464. this.group.dirty();
  43465. if (!this._finished || data.count() > 1e4) {
  43466. return {
  43467. update: true
  43468. };
  43469. } else {
  43470. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  43471. if (res.progress) {
  43472. res.progress({
  43473. start: 0,
  43474. end: data.count(),
  43475. count: data.count()
  43476. }, data);
  43477. }
  43478. this._symbolDraw.updateLayout(data);
  43479. }
  43480. };
  43481. ScatterView.prototype.eachRendered = function (cb) {
  43482. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  43483. };
  43484. ScatterView.prototype._getClipShape = function (seriesModel) {
  43485. if (!seriesModel.get('clip', true)) {
  43486. return;
  43487. }
  43488. var coordSys = seriesModel.coordinateSystem;
  43489. // PENDING make `0.1` configurable, for example, `clipTolerance`?
  43490. return coordSys && coordSys.getArea && coordSys.getArea(.1);
  43491. };
  43492. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  43493. var symbolDraw = this._symbolDraw;
  43494. var pipelineContext = seriesModel.pipelineContext;
  43495. var isLargeDraw = pipelineContext.large;
  43496. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  43497. symbolDraw && symbolDraw.remove();
  43498. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  43499. this._isLargeDraw = isLargeDraw;
  43500. this.group.removeAll();
  43501. }
  43502. this.group.add(symbolDraw.group);
  43503. return symbolDraw;
  43504. };
  43505. ScatterView.prototype.remove = function (ecModel, api) {
  43506. this._symbolDraw && this._symbolDraw.remove(true);
  43507. this._symbolDraw = null;
  43508. };
  43509. ScatterView.prototype.dispose = function () {};
  43510. ScatterView.type = 'scatter';
  43511. return ScatterView;
  43512. }(ChartView);
  43513. // For backward compatibility, do not use a margin. Although the labels might touch the edge of
  43514. // the canvas, the chart canvas probably does not have an border or a different background color within a page.
  43515. var OUTER_BOUNDS_DEFAULT = {
  43516. left: 0,
  43517. right: 0,
  43518. top: 0,
  43519. bottom: 0
  43520. };
  43521. var OUTER_BOUNDS_CLAMP_DEFAULT = ['25%', '25%'];
  43522. var GridModel = /** @class */function (_super) {
  43523. __extends(GridModel, _super);
  43524. function GridModel() {
  43525. return _super !== null && _super.apply(this, arguments) || this;
  43526. }
  43527. GridModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  43528. var outerBoundsCp = getLayoutParams(option.outerBounds);
  43529. _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
  43530. if (outerBoundsCp && option.outerBounds) {
  43531. mergeLayoutParam(option.outerBounds, outerBoundsCp);
  43532. }
  43533. };
  43534. GridModel.prototype.mergeOption = function (newOption, ecModel) {
  43535. _super.prototype.mergeOption.apply(this, arguments);
  43536. if (this.option.outerBounds && newOption.outerBounds) {
  43537. mergeLayoutParam(this.option.outerBounds, newOption.outerBounds);
  43538. }
  43539. };
  43540. GridModel.type = 'grid';
  43541. GridModel.dependencies = ['xAxis', 'yAxis'];
  43542. GridModel.layoutMode = 'box';
  43543. GridModel.defaultOption = {
  43544. show: false,
  43545. // zlevel: 0,
  43546. z: 0,
  43547. left: '15%',
  43548. top: 65,
  43549. right: '10%',
  43550. bottom: 80,
  43551. // If grid size contain label
  43552. containLabel: false,
  43553. outerBoundsMode: 'auto',
  43554. outerBounds: OUTER_BOUNDS_DEFAULT,
  43555. outerBoundsContain: 'all',
  43556. outerBoundsClampWidth: OUTER_BOUNDS_CLAMP_DEFAULT[0],
  43557. outerBoundsClampHeight: OUTER_BOUNDS_CLAMP_DEFAULT[1],
  43558. // width: {totalWidth} - left - right,
  43559. // height: {totalHeight} - top - bottom,
  43560. backgroundColor: tokens.color.transparent,
  43561. borderWidth: 1,
  43562. borderColor: tokens.color.neutral30
  43563. };
  43564. return GridModel;
  43565. }(ComponentModel);
  43566. var CartesianAxisModel = /** @class */function (_super) {
  43567. __extends(CartesianAxisModel, _super);
  43568. function CartesianAxisModel() {
  43569. return _super !== null && _super.apply(this, arguments) || this;
  43570. }
  43571. CartesianAxisModel.prototype.getCoordSysModel = function () {
  43572. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  43573. };
  43574. CartesianAxisModel.type = 'cartesian2dAxis';
  43575. return CartesianAxisModel;
  43576. }(ComponentModel);
  43577. mixin(CartesianAxisModel, AxisModelCommonMixin);
  43578. var defaultOption = {
  43579. show: true,
  43580. // zlevel: 0,
  43581. z: 0,
  43582. // Inverse the axis.
  43583. inverse: false,
  43584. // Axis name displayed.
  43585. name: '',
  43586. // 'start' | 'middle' | 'end'
  43587. nameLocation: 'end',
  43588. // By degree. By default auto rotate by nameLocation.
  43589. nameRotate: null,
  43590. nameTruncate: {
  43591. maxWidth: null,
  43592. ellipsis: '...',
  43593. placeholder: '.'
  43594. },
  43595. // Use global text style by default.
  43596. nameTextStyle: {
  43597. // textMargin: never, // The default value will be specified based on `nameLocation`.
  43598. },
  43599. // The gap between axisName and axisLine.
  43600. nameGap: 15,
  43601. // Default `false` to support tooltip.
  43602. silent: false,
  43603. // Default `false` to avoid legacy user event listener fail.
  43604. triggerEvent: false,
  43605. tooltip: {
  43606. show: false
  43607. },
  43608. axisPointer: {},
  43609. axisLine: {
  43610. show: true,
  43611. onZero: true,
  43612. onZeroAxisIndex: null,
  43613. lineStyle: {
  43614. color: tokens.color.axisLine,
  43615. width: 1,
  43616. type: 'solid'
  43617. },
  43618. // The arrow at both ends the the axis.
  43619. symbol: ['none', 'none'],
  43620. symbolSize: [10, 15],
  43621. breakLine: true
  43622. },
  43623. axisTick: {
  43624. show: true,
  43625. // Whether axisTick is inside the grid or outside the grid.
  43626. inside: false,
  43627. // The length of axisTick.
  43628. length: 5,
  43629. lineStyle: {
  43630. width: 1
  43631. }
  43632. },
  43633. axisLabel: {
  43634. show: true,
  43635. // Whether axisLabel is inside the grid or outside the grid.
  43636. inside: false,
  43637. rotate: 0,
  43638. // true | false | null/undefined (auto)
  43639. showMinLabel: null,
  43640. // true | false | null/undefined (auto)
  43641. showMaxLabel: null,
  43642. margin: 8,
  43643. // formatter: null,
  43644. fontSize: 12,
  43645. color: tokens.color.axisLabel,
  43646. // In scenarios like axis labels, when labels text's progression direction matches the label
  43647. // layout direction (e.g., when all letters are in a single line), extra start/end margin is
  43648. // needed to prevent the text from appearing visually joined. In the other case, when lables
  43649. // are stacked (e.g., having rotation or horizontal labels on yAxis), the layout needs to be
  43650. // compact, so NO extra top/bottom margin should be applied.
  43651. textMargin: [0, 3]
  43652. },
  43653. splitLine: {
  43654. show: true,
  43655. showMinLine: true,
  43656. showMaxLine: true,
  43657. lineStyle: {
  43658. color: tokens.color.axisSplitLine,
  43659. width: 1,
  43660. type: 'solid'
  43661. }
  43662. },
  43663. splitArea: {
  43664. show: false,
  43665. areaStyle: {
  43666. color: [tokens.color.backgroundTint, tokens.color.backgroundTransparent]
  43667. }
  43668. },
  43669. breakArea: {
  43670. show: true,
  43671. itemStyle: {
  43672. color: tokens.color.neutral00,
  43673. // Break border color should be darker than the splitLine
  43674. // because it has opacity and should be more prominent
  43675. borderColor: tokens.color.border,
  43676. borderWidth: 1,
  43677. borderType: [3, 3],
  43678. opacity: 0.6
  43679. },
  43680. zigzagAmplitude: 4,
  43681. zigzagMinSpan: 4,
  43682. zigzagMaxSpan: 20,
  43683. zigzagZ: 100,
  43684. expandOnClick: true
  43685. },
  43686. breakLabelLayout: {
  43687. moveOverlap: 'auto'
  43688. }
  43689. };
  43690. var categoryAxis = merge({
  43691. // The gap at both ends of the axis. For categoryAxis, boolean.
  43692. boundaryGap: true,
  43693. // Set false to faster category collection.
  43694. deduplication: null,
  43695. jitter: 0,
  43696. jitterOverlap: true,
  43697. jitterMargin: 2,
  43698. // splitArea: {
  43699. // show: false
  43700. // },
  43701. splitLine: {
  43702. show: false
  43703. },
  43704. axisTick: {
  43705. // If tick is align with label when boundaryGap is true
  43706. alignWithLabel: false,
  43707. interval: 'auto',
  43708. show: 'auto'
  43709. },
  43710. axisLabel: {
  43711. interval: 'auto'
  43712. }
  43713. }, defaultOption);
  43714. var valueAxis = merge({
  43715. boundaryGap: [0, 0],
  43716. axisLine: {
  43717. // Not shown when other axis is categoryAxis in cartesian
  43718. show: 'auto'
  43719. },
  43720. axisTick: {
  43721. // Not shown when other axis is categoryAxis in cartesian
  43722. show: 'auto'
  43723. },
  43724. // TODO
  43725. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  43726. splitNumber: 5,
  43727. minorTick: {
  43728. // Minor tick, not available for cateogry axis.
  43729. show: false,
  43730. // Split number of minor ticks. The value should be in range of (0, 100)
  43731. splitNumber: 5,
  43732. // Length of minor tick
  43733. length: 3,
  43734. // Line style
  43735. lineStyle: {
  43736. // Default to be same with axisTick
  43737. }
  43738. },
  43739. minorSplitLine: {
  43740. show: false,
  43741. lineStyle: {
  43742. color: tokens.color.axisMinorSplitLine,
  43743. width: 1
  43744. }
  43745. }
  43746. }, defaultOption);
  43747. var timeAxis = merge({
  43748. splitNumber: 6,
  43749. axisLabel: {
  43750. // To eliminate labels that are not nice
  43751. showMinLabel: false,
  43752. showMaxLabel: false,
  43753. rich: {
  43754. primary: {
  43755. fontWeight: 'bold'
  43756. }
  43757. }
  43758. },
  43759. splitLine: {
  43760. show: false
  43761. }
  43762. }, valueAxis);
  43763. var logAxis = defaults({
  43764. logBase: 10
  43765. }, valueAxis);
  43766. var axisDefault = {
  43767. category: categoryAxis,
  43768. value: valueAxis,
  43769. time: timeAxis,
  43770. log: logAxis
  43771. };
  43772. /*
  43773. * Licensed to the Apache Software Foundation (ASF) under one
  43774. * or more contributor license agreements. See the NOTICE file
  43775. * distributed with this work for additional information
  43776. * regarding copyright ownership. The ASF licenses this file
  43777. * to you under the Apache License, Version 2.0 (the
  43778. * "License"); you may not use this file except in compliance
  43779. * with the License. You may obtain a copy of the License at
  43780. *
  43781. * http://www.apache.org/licenses/LICENSE-2.0
  43782. *
  43783. * Unless required by applicable law or agreed to in writing,
  43784. * software distributed under the License is distributed on an
  43785. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43786. * KIND, either express or implied. See the License for the
  43787. * specific language governing permissions and limitations
  43788. * under the License.
  43789. */
  43790. /**
  43791. * AUTO-GENERATED FILE. DO NOT MODIFY.
  43792. */
  43793. /*
  43794. * Licensed to the Apache Software Foundation (ASF) under one
  43795. * or more contributor license agreements. See the NOTICE file
  43796. * distributed with this work for additional information
  43797. * regarding copyright ownership. The ASF licenses this file
  43798. * to you under the Apache License, Version 2.0 (the
  43799. * "License"); you may not use this file except in compliance
  43800. * with the License. You may obtain a copy of the License at
  43801. *
  43802. * http://www.apache.org/licenses/LICENSE-2.0
  43803. *
  43804. * Unless required by applicable law or agreed to in writing,
  43805. * software distributed under the License is distributed on an
  43806. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43807. * KIND, either express or implied. See the License for the
  43808. * specific language governing permissions and limitations
  43809. * under the License.
  43810. */
  43811. var AXIS_TYPES = {
  43812. value: 1,
  43813. category: 1,
  43814. time: 1,
  43815. log: 1
  43816. };
  43817. /*
  43818. * Licensed to the Apache Software Foundation (ASF) under one
  43819. * or more contributor license agreements. See the NOTICE file
  43820. * distributed with this work for additional information
  43821. * regarding copyright ownership. The ASF licenses this file
  43822. * to you under the Apache License, Version 2.0 (the
  43823. * "License"); you may not use this file except in compliance
  43824. * with the License. You may obtain a copy of the License at
  43825. *
  43826. * http://www.apache.org/licenses/LICENSE-2.0
  43827. *
  43828. * Unless required by applicable law or agreed to in writing,
  43829. * software distributed under the License is distributed on an
  43830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43831. * KIND, either express or implied. See the License for the
  43832. * specific language governing permissions and limitations
  43833. * under the License.
  43834. */
  43835. /**
  43836. * AUTO-GENERATED FILE. DO NOT MODIFY.
  43837. */
  43838. /*
  43839. * Licensed to the Apache Software Foundation (ASF) under one
  43840. * or more contributor license agreements. See the NOTICE file
  43841. * distributed with this work for additional information
  43842. * regarding copyright ownership. The ASF licenses this file
  43843. * to you under the Apache License, Version 2.0 (the
  43844. * "License"); you may not use this file except in compliance
  43845. * with the License. You may obtain a copy of the License at
  43846. *
  43847. * http://www.apache.org/licenses/LICENSE-2.0
  43848. *
  43849. * Unless required by applicable law or agreed to in writing,
  43850. * software distributed under the License is distributed on an
  43851. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43852. * KIND, either express or implied. See the License for the
  43853. * specific language governing permissions and limitations
  43854. * under the License.
  43855. */
  43856. var _impl$1 = null;
  43857. function registerAxisBreakHelperImpl(impl) {
  43858. if (!_impl$1) {
  43859. _impl$1 = impl;
  43860. }
  43861. }
  43862. function getAxisBreakHelper() {
  43863. return _impl$1;
  43864. }
  43865. /**
  43866. * Generate sub axis model class
  43867. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  43868. */
  43869. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  43870. each(AXIS_TYPES, function (v, axisType) {
  43871. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  43872. var AxisModel = /** @class */function (_super) {
  43873. __extends(AxisModel, _super);
  43874. function AxisModel() {
  43875. var _this = _super !== null && _super.apply(this, arguments) || this;
  43876. _this.type = axisName + 'Axis.' + axisType;
  43877. return _this;
  43878. }
  43879. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  43880. var layoutMode = fetchLayoutMode(this);
  43881. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  43882. var themeModel = ecModel.getTheme();
  43883. merge(option, themeModel.get(axisType + 'Axis'));
  43884. merge(option, this.getDefaultOption());
  43885. option.type = getAxisType(option);
  43886. if (layoutMode) {
  43887. mergeLayoutParam(option, inputPositionParams, layoutMode);
  43888. }
  43889. };
  43890. AxisModel.prototype.optionUpdated = function () {
  43891. var thisOption = this.option;
  43892. if (thisOption.type === 'category') {
  43893. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  43894. }
  43895. };
  43896. /**
  43897. * Should not be called before all of 'getInitailData' finished.
  43898. * Because categories are collected during initializing data.
  43899. */
  43900. AxisModel.prototype.getCategories = function (rawData) {
  43901. var option = this.option;
  43902. // FIXME
  43903. // warning if called before all of 'getInitailData' finished.
  43904. if (option.type === 'category') {
  43905. if (rawData) {
  43906. return option.data;
  43907. }
  43908. return this.__ordinalMeta.categories;
  43909. }
  43910. };
  43911. AxisModel.prototype.getOrdinalMeta = function () {
  43912. return this.__ordinalMeta;
  43913. };
  43914. AxisModel.prototype.updateAxisBreaks = function (payload) {
  43915. var axisBreakHelper = getAxisBreakHelper();
  43916. return axisBreakHelper ? axisBreakHelper.updateModelAxisBreak(this, payload) : {
  43917. breaks: []
  43918. };
  43919. };
  43920. AxisModel.type = axisName + 'Axis.' + axisType;
  43921. AxisModel.defaultOption = defaultOption;
  43922. return AxisModel;
  43923. }(BaseAxisModelClass);
  43924. registers.registerComponentModel(AxisModel);
  43925. });
  43926. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  43927. }
  43928. function getAxisType(option) {
  43929. // Default axis with data is category axis
  43930. return option.type || (option.data ? 'category' : 'value');
  43931. }
  43932. var Cartesian = /** @class */function () {
  43933. function Cartesian(name) {
  43934. this.type = 'cartesian';
  43935. this._dimList = [];
  43936. this._axes = {};
  43937. this.name = name || '';
  43938. }
  43939. Cartesian.prototype.getAxis = function (dim) {
  43940. return this._axes[dim];
  43941. };
  43942. Cartesian.prototype.getAxes = function () {
  43943. return map(this._dimList, function (dim) {
  43944. return this._axes[dim];
  43945. }, this);
  43946. };
  43947. Cartesian.prototype.getAxesByScale = function (scaleType) {
  43948. scaleType = scaleType.toLowerCase();
  43949. return filter(this.getAxes(), function (axis) {
  43950. return axis.scale.type === scaleType;
  43951. });
  43952. };
  43953. Cartesian.prototype.addAxis = function (axis) {
  43954. var dim = axis.dim;
  43955. this._axes[dim] = axis;
  43956. this._dimList.push(dim);
  43957. };
  43958. return Cartesian;
  43959. }();
  43960. var cartesian2DDimensions = ['x', 'y'];
  43961. function canCalculateAffineTransform(scale) {
  43962. return (scale.type === 'interval' || scale.type === 'time') && !scale.hasBreaks();
  43963. }
  43964. var Cartesian2D = /** @class */function (_super) {
  43965. __extends(Cartesian2D, _super);
  43966. function Cartesian2D() {
  43967. var _this = _super !== null && _super.apply(this, arguments) || this;
  43968. _this.type = 'cartesian2d';
  43969. _this.dimensions = cartesian2DDimensions;
  43970. return _this;
  43971. }
  43972. /**
  43973. * Calculate an affine transform matrix if two axes are time or value.
  43974. * It's mainly for accelartion on the large time series data.
  43975. */
  43976. Cartesian2D.prototype.calcAffineTransform = function () {
  43977. this._transform = this._invTransform = null;
  43978. var xAxisScale = this.getAxis('x').scale;
  43979. var yAxisScale = this.getAxis('y').scale;
  43980. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  43981. return;
  43982. }
  43983. var xScaleExtent = xAxisScale.getExtent();
  43984. var yScaleExtent = yAxisScale.getExtent();
  43985. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  43986. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  43987. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  43988. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  43989. if (!xScaleSpan || !yScaleSpan) {
  43990. return;
  43991. }
  43992. // Accelerate data to point calculation on the special large time series data.
  43993. var scaleX = (end[0] - start[0]) / xScaleSpan;
  43994. var scaleY = (end[1] - start[1]) / yScaleSpan;
  43995. var translateX = start[0] - xScaleExtent[0] * scaleX;
  43996. var translateY = start[1] - yScaleExtent[0] * scaleY;
  43997. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  43998. this._invTransform = invert([], m);
  43999. };
  44000. /**
  44001. * Base axis will be used on stacking.
  44002. */
  44003. Cartesian2D.prototype.getBaseAxis = function () {
  44004. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  44005. };
  44006. Cartesian2D.prototype.containPoint = function (point) {
  44007. var axisX = this.getAxis('x');
  44008. var axisY = this.getAxis('y');
  44009. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  44010. };
  44011. Cartesian2D.prototype.containData = function (data) {
  44012. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  44013. };
  44014. Cartesian2D.prototype.containZone = function (data1, data2) {
  44015. var zoneDiag1 = this.dataToPoint(data1);
  44016. var zoneDiag2 = this.dataToPoint(data2);
  44017. var area = this.getArea();
  44018. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  44019. return area.intersect(zone);
  44020. };
  44021. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  44022. out = out || [];
  44023. var xVal = data[0];
  44024. var yVal = data[1];
  44025. // [CAVEAT]: Do not add time consuming operation within and before fast path.
  44026. // Fast path.
  44027. if (this._transform
  44028. // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  44029. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  44030. return applyTransform(out, data, this._transform);
  44031. }
  44032. var xAxis = this.getAxis('x');
  44033. var yAxis = this.getAxis('y');
  44034. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  44035. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  44036. return out;
  44037. };
  44038. Cartesian2D.prototype.clampData = function (data, out) {
  44039. var xScale = this.getAxis('x').scale;
  44040. var yScale = this.getAxis('y').scale;
  44041. var xAxisExtent = xScale.getExtent();
  44042. var yAxisExtent = yScale.getExtent();
  44043. var x = xScale.parse(data[0]);
  44044. var y = yScale.parse(data[1]);
  44045. out = out || [];
  44046. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  44047. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  44048. return out;
  44049. };
  44050. Cartesian2D.prototype.pointToData = function (point, clamp, out) {
  44051. out = out || [];
  44052. if (this._invTransform) {
  44053. return applyTransform(out, point, this._invTransform);
  44054. }
  44055. var xAxis = this.getAxis('x');
  44056. var yAxis = this.getAxis('y');
  44057. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  44058. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  44059. return out;
  44060. };
  44061. Cartesian2D.prototype.getOtherAxis = function (axis) {
  44062. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  44063. };
  44064. /**
  44065. * Get rect area of cartesian.
  44066. * Area will have a contain function to determine if a point is in the coordinate system.
  44067. */
  44068. Cartesian2D.prototype.getArea = function (tolerance) {
  44069. tolerance = tolerance || 0;
  44070. var xExtent = this.getAxis('x').getGlobalExtent();
  44071. var yExtent = this.getAxis('y').getGlobalExtent();
  44072. var x = Math.min(xExtent[0], xExtent[1]) - tolerance;
  44073. var y = Math.min(yExtent[0], yExtent[1]) - tolerance;
  44074. var width = Math.max(xExtent[0], xExtent[1]) - x + tolerance;
  44075. var height = Math.max(yExtent[0], yExtent[1]) - y + tolerance;
  44076. return new BoundingRect(x, y, width, height);
  44077. };
  44078. return Cartesian2D;
  44079. }(Cartesian);
  44080. var Axis2D = /** @class */function (_super) {
  44081. __extends(Axis2D, _super);
  44082. function Axis2D(dim, scale, coordExtent, axisType, position) {
  44083. var _this = _super.call(this, dim, scale, coordExtent) || this;
  44084. /**
  44085. * Index of axis, can be used as key
  44086. * Injected outside.
  44087. */
  44088. _this.index = 0;
  44089. _this.type = axisType || 'value';
  44090. _this.position = position || 'bottom';
  44091. return _this;
  44092. }
  44093. Axis2D.prototype.isHorizontal = function () {
  44094. var position = this.position;
  44095. return position === 'top' || position === 'bottom';
  44096. };
  44097. /**
  44098. * Each item cooresponds to this.getExtent(), which
  44099. * means globalExtent[0] may greater than globalExtent[1],
  44100. * unless `asc` is input.
  44101. *
  44102. * @param {boolean} [asc]
  44103. * @return {Array.<number>}
  44104. */
  44105. Axis2D.prototype.getGlobalExtent = function (asc) {
  44106. var ret = this.getExtent();
  44107. ret[0] = this.toGlobalCoord(ret[0]);
  44108. ret[1] = this.toGlobalCoord(ret[1]);
  44109. asc && ret[0] > ret[1] && ret.reverse();
  44110. return ret;
  44111. };
  44112. Axis2D.prototype.pointToData = function (point, clamp) {
  44113. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  44114. };
  44115. /**
  44116. * Set ordinalSortInfo
  44117. * @param info new OrdinalSortInfo
  44118. */
  44119. Axis2D.prototype.setCategorySortInfo = function (info) {
  44120. if (this.type !== 'category') {
  44121. return false;
  44122. }
  44123. this.model.option.categorySortInfo = info;
  44124. this.scale.setSortInfo(info);
  44125. };
  44126. return Axis2D;
  44127. }(Axis);
  44128. var AXIS_BREAK_EXPAND_ACTION_TYPE = 'expandAxisBreak';
  44129. var AXIS_BREAK_COLLAPSE_ACTION_TYPE = 'collapseAxisBreak';
  44130. var AXIS_BREAK_TOGGLE_ACTION_TYPE = 'toggleAxisBreak';
  44131. var AXIS_BREAK_CHANGED_EVENT_TYPE = 'axisbreakchanged';
  44132. var expandAxisBreakActionInfo = {
  44133. type: AXIS_BREAK_EXPAND_ACTION_TYPE,
  44134. event: AXIS_BREAK_CHANGED_EVENT_TYPE,
  44135. update: 'update',
  44136. refineEvent: refineAxisBreakChangeEvent
  44137. };
  44138. var collapseAxisBreakActionInfo = {
  44139. type: AXIS_BREAK_COLLAPSE_ACTION_TYPE,
  44140. event: AXIS_BREAK_CHANGED_EVENT_TYPE,
  44141. update: 'update',
  44142. refineEvent: refineAxisBreakChangeEvent
  44143. };
  44144. var toggleAxisBreakActionInfo = {
  44145. type: AXIS_BREAK_TOGGLE_ACTION_TYPE,
  44146. event: AXIS_BREAK_CHANGED_EVENT_TYPE,
  44147. update: 'update',
  44148. refineEvent: refineAxisBreakChangeEvent
  44149. };
  44150. function refineAxisBreakChangeEvent(actionResultBatch, payload, ecModel, api) {
  44151. var breaks = [];
  44152. each(actionResultBatch, function (actionResult) {
  44153. breaks = breaks.concat(actionResult.eventBreaks);
  44154. });
  44155. return {
  44156. eventContent: {
  44157. breaks: breaks
  44158. }
  44159. };
  44160. }
  44161. function registerAction$1(registers) {
  44162. registers.registerAction(expandAxisBreakActionInfo, actionHandler);
  44163. registers.registerAction(collapseAxisBreakActionInfo, actionHandler);
  44164. registers.registerAction(toggleAxisBreakActionInfo, actionHandler);
  44165. function actionHandler(payload, ecModel) {
  44166. var eventBreaks = [];
  44167. var finderResult = parseFinder(ecModel, payload);
  44168. function dealUpdate(modelProp, indexProp) {
  44169. each(finderResult[modelProp], function (axisModel) {
  44170. var result = axisModel.updateAxisBreaks(payload);
  44171. each(result.breaks, function (item) {
  44172. var _a;
  44173. eventBreaks.push(defaults((_a = {}, _a[indexProp] = axisModel.componentIndex, _a), item));
  44174. });
  44175. });
  44176. }
  44177. dealUpdate('xAxisModels', 'xAxisIndex');
  44178. dealUpdate('yAxisModels', 'yAxisIndex');
  44179. dealUpdate('singleAxisModels', 'singleAxisIndex');
  44180. return {
  44181. eventBreaks: eventBreaks
  44182. };
  44183. }
  44184. }
  44185. var PI$5 = Math.PI;
  44186. var DEFAULT_CENTER_NAME_MARGIN_LEVELS = [[1, 2, 1, 2], [5, 3, 5, 3], [8, 3, 8, 3]];
  44187. var DEFAULT_ENDS_NAME_MARGIN_LEVELS = [[0, 1, 0, 1], [0, 3, 0, 3], [0, 3, 0, 3]];
  44188. var getLabelInner = makeInner();
  44189. var getTickInner = makeInner();
  44190. /**
  44191. * A context shared by difference axisBuilder instances.
  44192. * For cross-axes overlap resolving.
  44193. *
  44194. * Lifecycle constraint: should not over a pass of ec main process.
  44195. * If model is changed, the context must be disposed.
  44196. *
  44197. * @see AxisBuilderLocalContext
  44198. */
  44199. var AxisBuilderSharedContext = /** @class */function () {
  44200. function AxisBuilderSharedContext(resolveAxisNameOverlap) {
  44201. /**
  44202. * [CAUTION] Do not modify this data structure outside this class.
  44203. */
  44204. this.recordMap = {};
  44205. this.resolveAxisNameOverlap = resolveAxisNameOverlap;
  44206. }
  44207. AxisBuilderSharedContext.prototype.ensureRecord = function (axisModel) {
  44208. var dim = axisModel.axis.dim;
  44209. var idx = axisModel.componentIndex;
  44210. var recordMap = this.recordMap;
  44211. var records = recordMap[dim] || (recordMap[dim] = []);
  44212. return records[idx] || (records[idx] = {
  44213. ready: {}
  44214. });
  44215. };
  44216. return AxisBuilderSharedContext;
  44217. }();
  44218. /**
  44219. * [CAUTION]
  44220. * 1. The call of this function must be after axisLabel overlap handlings
  44221. * (such as `hideOverlap`, `fixMinMaxLabelShow`) and after transform calculating.
  44222. * 2. Can be called multiple times and should be idempotent.
  44223. */
  44224. function resetOverlapRecordToShared(cfg, shared, axisModel, labelLayoutList) {
  44225. var axis = axisModel.axis;
  44226. var record = shared.ensureRecord(axisModel);
  44227. var labelInfoList = [];
  44228. var stOccupiedRect;
  44229. var useStOccupiedRect = hasAxisName(cfg.axisName) && isNameLocationCenter(cfg.nameLocation);
  44230. each(labelLayoutList, function (layout) {
  44231. var layoutInfo = ensureLabelLayoutWithGeometry(layout);
  44232. if (!layoutInfo || layoutInfo.label.ignore) {
  44233. return;
  44234. }
  44235. labelInfoList.push(layoutInfo);
  44236. var transGroup = record.transGroup;
  44237. if (useStOccupiedRect) {
  44238. // Transform to "standard axis" for creating stOccupiedRect (the label rects union).
  44239. transGroup.transform ? invert(_stTransTmp, transGroup.transform) : identity(_stTransTmp);
  44240. if (layoutInfo.transform) {
  44241. mul$1(_stTransTmp, _stTransTmp, layoutInfo.transform);
  44242. }
  44243. BoundingRect.copy(_stLabelRectTmp, layoutInfo.localRect);
  44244. _stLabelRectTmp.applyTransform(_stTransTmp);
  44245. stOccupiedRect ? stOccupiedRect.union(_stLabelRectTmp) : BoundingRect.copy(stOccupiedRect = new BoundingRect(0, 0, 0, 0), _stLabelRectTmp);
  44246. }
  44247. });
  44248. var sortByDim = Math.abs(record.dirVec.x) > 0.1 ? 'x' : 'y';
  44249. var sortByValue = record.transGroup[sortByDim];
  44250. labelInfoList.sort(function (info1, info2) {
  44251. return Math.abs(info1.label[sortByDim] - sortByValue) - Math.abs(info2.label[sortByDim] - sortByValue);
  44252. });
  44253. if (useStOccupiedRect && stOccupiedRect) {
  44254. var extent = axis.getExtent();
  44255. var axisLineX = Math.min(extent[0], extent[1]);
  44256. var axisLineWidth = Math.max(extent[0], extent[1]) - axisLineX;
  44257. // If `nameLocation` is 'middle', enlarge axis labels boundingRect to axisLine to avoid bad
  44258. // case like that axis name is placed in the gap between axis labels and axis line.
  44259. // If only one label exists, the entire band should be occupied for
  44260. // visual consistency, so extent it to [0, canvas width].
  44261. stOccupiedRect.union(new BoundingRect(axisLineX, 0, axisLineWidth, 1));
  44262. }
  44263. record.stOccupiedRect = stOccupiedRect;
  44264. record.labelInfoList = labelInfoList;
  44265. }
  44266. var _stTransTmp = create$1();
  44267. var _stLabelRectTmp = new BoundingRect(0, 0, 0, 0);
  44268. /**
  44269. * The default resolver does not involve other axes within the same coordinate system.
  44270. */
  44271. var resolveAxisNameOverlapDefault = function (cfg, ctx, axisModel, nameLayoutInfo, nameMoveDirVec, thisRecord) {
  44272. if (isNameLocationCenter(cfg.nameLocation)) {
  44273. var stOccupiedRect = thisRecord.stOccupiedRect;
  44274. if (stOccupiedRect) {
  44275. moveIfOverlap(computeLabelGeometry2({}, stOccupiedRect, thisRecord.transGroup.transform), nameLayoutInfo, nameMoveDirVec);
  44276. }
  44277. } else {
  44278. moveIfOverlapByLinearLabels(thisRecord.labelInfoList, thisRecord.dirVec, nameLayoutInfo, nameMoveDirVec);
  44279. }
  44280. };
  44281. // [NOTICE] not consider ignore.
  44282. function moveIfOverlap(basedLayoutInfo, movableLayoutInfo, moveDirVec) {
  44283. var mtv = new Point();
  44284. if (labelIntersect(basedLayoutInfo, movableLayoutInfo, mtv, {
  44285. direction: Math.atan2(moveDirVec.y, moveDirVec.x),
  44286. bidirectional: false,
  44287. touchThreshold: 0.05
  44288. })) {
  44289. labelLayoutApplyTranslation(movableLayoutInfo, mtv);
  44290. }
  44291. }
  44292. function moveIfOverlapByLinearLabels(baseLayoutInfoList, baseDirVec, movableLayoutInfo, moveDirVec) {
  44293. // Detect and move from far to close.
  44294. var sameDir = Point.dot(moveDirVec, baseDirVec) >= 0;
  44295. for (var idx = 0, len = baseLayoutInfoList.length; idx < len; idx++) {
  44296. var labelInfo = baseLayoutInfoList[sameDir ? idx : len - 1 - idx];
  44297. if (!labelInfo.label.ignore) {
  44298. moveIfOverlap(labelInfo, movableLayoutInfo, moveDirVec);
  44299. }
  44300. }
  44301. }
  44302. /**
  44303. * @caution
  44304. * - Ensure it is called after the data processing stage finished.
  44305. * - It might be called before `CahrtView#render`, sush as called at `CoordinateSystem#update`,
  44306. * thus ensure the result the same whenever it is called.
  44307. *
  44308. * A builder for a straight-line axis.
  44309. *
  44310. * A final axis is translated and rotated from a "standard axis".
  44311. * So opt.position and opt.rotation is required.
  44312. *
  44313. * A "standard axis" is the axis [0,0]-->[abs(axisExtent[1]-axisExtent[0]),0]
  44314. * for example: [0,0]-->[50,0]
  44315. */
  44316. var AxisBuilder = /** @class */function () {
  44317. /**
  44318. * [CAUTION]: axisModel.axis.extent/scale must be ready to use.
  44319. */
  44320. function AxisBuilder(axisModel, api, opt, shared) {
  44321. this.group = new Group();
  44322. this._axisModel = axisModel;
  44323. this._api = api;
  44324. this._local = {};
  44325. this._shared = shared || new AxisBuilderSharedContext(resolveAxisNameOverlapDefault);
  44326. this._resetCfgDetermined(opt);
  44327. }
  44328. /**
  44329. * Regarding axis label related configurations, only the change of label.x/y is supported; other
  44330. * changes are not necessary and not performant. To be specific, only `axis.position`
  44331. * (and consequently `labelOffset`) and `axis.extent` can be changed, and assume everything in
  44332. * `axisModel` are not changed.
  44333. * Axis line related configurations can be changed since this method can only be called
  44334. * before they are created.
  44335. */
  44336. AxisBuilder.prototype.updateCfg = function (opt) {
  44337. if ("development" !== 'production') {
  44338. var ready = this._shared.ensureRecord(this._axisModel).ready;
  44339. // After that, changing cfg is not supported; avoid unnecessary complexity.
  44340. assert(!ready.axisLine && !ready.axisTickLabelDetermine);
  44341. // Have to be called again if cfg changed.
  44342. ready.axisName = ready.axisTickLabelEstimate = false;
  44343. }
  44344. var raw = this._cfg.raw;
  44345. raw.position = opt.position;
  44346. raw.labelOffset = opt.labelOffset;
  44347. this._resetCfgDetermined(raw);
  44348. };
  44349. /**
  44350. * [CAUTION] For debug usage. Never change it outside!
  44351. */
  44352. AxisBuilder.prototype.__getRawCfg = function () {
  44353. return this._cfg.raw;
  44354. };
  44355. AxisBuilder.prototype._resetCfgDetermined = function (raw) {
  44356. var axisModel = this._axisModel;
  44357. // FIXME:
  44358. // Currently there is no uniformed way to set default values if an option
  44359. // is specified null/undefined by user (intentionally or unintentionally),
  44360. // e.g. null/undefined is not a illegal value for `nameLocation`.
  44361. // Try to use `getDefaultOption` to address it. But radar has no `getDefaultOption`.
  44362. var axisModelDefaultOption = axisModel.getDefaultOption ? axisModel.getDefaultOption() : {};
  44363. // Default value
  44364. var axisName = retrieve2(raw.axisName, axisModel.get('name'));
  44365. var nameMoveOverlapOption = axisModel.get('nameMoveOverlap');
  44366. if (nameMoveOverlapOption == null || nameMoveOverlapOption === 'auto') {
  44367. nameMoveOverlapOption = retrieve2(raw.defaultNameMoveOverlap, true);
  44368. }
  44369. var cfg = {
  44370. raw: raw,
  44371. position: raw.position,
  44372. rotation: raw.rotation,
  44373. nameDirection: retrieve2(raw.nameDirection, 1),
  44374. tickDirection: retrieve2(raw.tickDirection, 1),
  44375. labelDirection: retrieve2(raw.labelDirection, 1),
  44376. labelOffset: retrieve2(raw.labelOffset, 0),
  44377. silent: retrieve2(raw.silent, true),
  44378. axisName: axisName,
  44379. nameLocation: retrieve3(axisModel.get('nameLocation'), axisModelDefaultOption.nameLocation, 'end'),
  44380. shouldNameMoveOverlap: hasAxisName(axisName) && nameMoveOverlapOption,
  44381. optionHideOverlap: axisModel.get(['axisLabel', 'hideOverlap']),
  44382. showMinorTicks: axisModel.get(['minorTick', 'show'])
  44383. };
  44384. if ("development" !== 'production') {
  44385. assert(cfg.position != null);
  44386. assert(cfg.rotation != null);
  44387. }
  44388. this._cfg = cfg;
  44389. // FIXME Not use a separate text group?
  44390. var transformGroup = new Group({
  44391. x: cfg.position[0],
  44392. y: cfg.position[1],
  44393. rotation: cfg.rotation
  44394. });
  44395. transformGroup.updateTransform();
  44396. this._transformGroup = transformGroup;
  44397. var record = this._shared.ensureRecord(axisModel);
  44398. record.transGroup = this._transformGroup;
  44399. record.dirVec = new Point(Math.cos(-cfg.rotation), Math.sin(-cfg.rotation));
  44400. };
  44401. AxisBuilder.prototype.build = function (axisPartNameMap, extraParams) {
  44402. var _this = this;
  44403. if (!axisPartNameMap) {
  44404. axisPartNameMap = {
  44405. axisLine: true,
  44406. axisTickLabelEstimate: false,
  44407. axisTickLabelDetermine: true,
  44408. axisName: true
  44409. };
  44410. }
  44411. each(AXIS_BUILDER_AXIS_PART_NAMES, function (partName) {
  44412. if (axisPartNameMap[partName]) {
  44413. builders[partName](_this._cfg, _this._local, _this._shared, _this._axisModel, _this.group, _this._transformGroup, _this._api, extraParams || {});
  44414. }
  44415. });
  44416. return this;
  44417. };
  44418. /**
  44419. * Currently only get text align/verticalAlign by rotation.
  44420. * NO `position` is involved, otherwise it have to be performed for each `updateAxisLabelChangableProps`.
  44421. */
  44422. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  44423. var rotationDiff = remRadian(textRotation - axisRotation);
  44424. var textAlign;
  44425. var textVerticalAlign;
  44426. if (isRadianAroundZero(rotationDiff)) {
  44427. // Label is parallel with axis line.
  44428. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  44429. textAlign = 'center';
  44430. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  44431. // Label is inverse parallel with axis line.
  44432. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  44433. textAlign = 'center';
  44434. } else {
  44435. textVerticalAlign = 'middle';
  44436. if (rotationDiff > 0 && rotationDiff < PI$5) {
  44437. textAlign = direction > 0 ? 'right' : 'left';
  44438. } else {
  44439. textAlign = direction > 0 ? 'left' : 'right';
  44440. }
  44441. }
  44442. return {
  44443. rotation: rotationDiff,
  44444. textAlign: textAlign,
  44445. textVerticalAlign: textVerticalAlign
  44446. };
  44447. };
  44448. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  44449. var eventData = {
  44450. componentType: axisModel.mainType,
  44451. componentIndex: axisModel.componentIndex
  44452. };
  44453. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  44454. return eventData;
  44455. };
  44456. AxisBuilder.isLabelSilent = function (axisModel) {
  44457. var tooltipOpt = axisModel.get('tooltip');
  44458. return axisModel.get('silent')
  44459. // Consider mouse cursor, add these restrictions.
  44460. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  44461. };
  44462. return AxisBuilder;
  44463. }();
  44464. // Sorted by dependency order.
  44465. var AXIS_BUILDER_AXIS_PART_NAMES = ['axisLine', 'axisTickLabelEstimate', 'axisTickLabelDetermine', 'axisName'];
  44466. var builders = {
  44467. axisLine: function (cfg, local, shared, axisModel, group, transformGroup, api) {
  44468. if ("development" !== 'production') {
  44469. var ready = shared.ensureRecord(axisModel).ready;
  44470. assert(!ready.axisLine);
  44471. ready.axisLine = true;
  44472. }
  44473. var shown = axisModel.get(['axisLine', 'show']);
  44474. if (shown === 'auto') {
  44475. shown = true;
  44476. if (cfg.raw.axisLineAutoShow != null) {
  44477. shown = !!cfg.raw.axisLineAutoShow;
  44478. }
  44479. }
  44480. if (!shown) {
  44481. return;
  44482. }
  44483. var extent = axisModel.axis.getExtent();
  44484. var matrix = transformGroup.transform;
  44485. var pt1 = [extent[0], 0];
  44486. var pt2 = [extent[1], 0];
  44487. var inverse = pt1[0] > pt2[0];
  44488. if (matrix) {
  44489. applyTransform(pt1, pt1, matrix);
  44490. applyTransform(pt2, pt2, matrix);
  44491. }
  44492. var lineStyle = extend({
  44493. lineCap: 'round'
  44494. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  44495. var pathBaseProp = {
  44496. strokeContainThreshold: cfg.raw.strokeContainThreshold || 5,
  44497. silent: true,
  44498. z2: 1,
  44499. style: lineStyle
  44500. };
  44501. if (axisModel.get(['axisLine', 'breakLine']) && axisModel.axis.scale.hasBreaks()) {
  44502. getAxisBreakHelper().buildAxisBreakLine(axisModel, group, transformGroup, pathBaseProp);
  44503. } else {
  44504. var line = new Line(extend({
  44505. shape: {
  44506. x1: pt1[0],
  44507. y1: pt1[1],
  44508. x2: pt2[0],
  44509. y2: pt2[1]
  44510. }
  44511. }, pathBaseProp));
  44512. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  44513. line.anid = 'line';
  44514. group.add(line);
  44515. }
  44516. var arrows = axisModel.get(['axisLine', 'symbol']);
  44517. if (arrows != null) {
  44518. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  44519. if (isString(arrows)) {
  44520. // Use the same arrow for start and end point
  44521. arrows = [arrows, arrows];
  44522. }
  44523. if (isString(arrowSize) || isNumber(arrowSize)) {
  44524. // Use the same size for width and height
  44525. arrowSize = [arrowSize, arrowSize];
  44526. }
  44527. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  44528. var symbolWidth_1 = arrowSize[0];
  44529. var symbolHeight_1 = arrowSize[1];
  44530. each([{
  44531. rotate: cfg.rotation + Math.PI / 2,
  44532. offset: arrowOffset[0],
  44533. r: 0
  44534. }, {
  44535. rotate: cfg.rotation - Math.PI / 2,
  44536. offset: arrowOffset[1],
  44537. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  44538. }], function (point, index) {
  44539. if (arrows[index] !== 'none' && arrows[index] != null) {
  44540. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true);
  44541. // Calculate arrow position with offset
  44542. var r = point.r + point.offset;
  44543. var pt = inverse ? pt2 : pt1;
  44544. symbol.attr({
  44545. rotation: point.rotate,
  44546. x: pt[0] + r * Math.cos(cfg.rotation),
  44547. y: pt[1] - r * Math.sin(cfg.rotation),
  44548. silent: true,
  44549. z2: 11
  44550. });
  44551. group.add(symbol);
  44552. }
  44553. });
  44554. }
  44555. },
  44556. /**
  44557. * [CAUTION] This method can be called multiple times, following the change due to `resetCfg` called
  44558. * in size measurement. Thus this method should be idempotent, and should be performant.
  44559. */
  44560. axisTickLabelEstimate: function (cfg, local, shared, axisModel, group, transformGroup, api, extraParams) {
  44561. if ("development" !== 'production') {
  44562. var ready = shared.ensureRecord(axisModel).ready;
  44563. assert(!ready.axisTickLabelDetermine);
  44564. ready.axisTickLabelEstimate = true;
  44565. }
  44566. var needCallLayout = dealLastTickLabelResultReusable(local, group, extraParams);
  44567. if (needCallLayout) {
  44568. layOutAxisTickLabel(cfg, local, shared, axisModel, group, transformGroup, api, AxisTickLabelComputingKind.estimate);
  44569. }
  44570. },
  44571. /**
  44572. * Finish axis tick label build.
  44573. * Can be only called once.
  44574. */
  44575. axisTickLabelDetermine: function (cfg, local, shared, axisModel, group, transformGroup, api, extraParams) {
  44576. if ("development" !== 'production') {
  44577. var ready = shared.ensureRecord(axisModel).ready;
  44578. ready.axisTickLabelDetermine = true;
  44579. }
  44580. var needCallLayout = dealLastTickLabelResultReusable(local, group, extraParams);
  44581. if (needCallLayout) {
  44582. layOutAxisTickLabel(cfg, local, shared, axisModel, group, transformGroup, api, AxisTickLabelComputingKind.determine);
  44583. }
  44584. var ticksEls = buildAxisMajorTicks(cfg, group, transformGroup, axisModel);
  44585. syncLabelIgnoreToMajorTicks(cfg, local.labelLayoutList, ticksEls);
  44586. buildAxisMinorTicks(cfg, group, transformGroup, axisModel, cfg.tickDirection);
  44587. },
  44588. /**
  44589. * [CAUTION] This method can be called multiple times, following the change due to `resetCfg` called
  44590. * in size measurement. Thus this method should be idempotent, and should be performant.
  44591. */
  44592. axisName: function (cfg, local, shared, axisModel, group, transformGroup, api, extraParams) {
  44593. var sharedRecord = shared.ensureRecord(axisModel);
  44594. if ("development" !== 'production') {
  44595. var ready = sharedRecord.ready;
  44596. assert(ready.axisTickLabelEstimate || ready.axisTickLabelDetermine);
  44597. ready.axisName = true;
  44598. }
  44599. // Remove the existing name result created in estimation phase.
  44600. if (local.nameEl) {
  44601. group.remove(local.nameEl);
  44602. local.nameEl = sharedRecord.nameLayout = sharedRecord.nameLocation = null;
  44603. }
  44604. var name = cfg.axisName;
  44605. if (!hasAxisName(name)) {
  44606. return;
  44607. }
  44608. var nameLocation = cfg.nameLocation;
  44609. var nameDirection = cfg.nameDirection;
  44610. var textStyleModel = axisModel.getModel('nameTextStyle');
  44611. var gap = axisModel.get('nameGap') || 0;
  44612. var extent = axisModel.axis.getExtent();
  44613. var gapStartEndSignal = axisModel.axis.inverse ? -1 : 1;
  44614. var pos = new Point(0, 0);
  44615. var nameMoveDirVec = new Point(0, 0);
  44616. if (nameLocation === 'start') {
  44617. pos.x = extent[0] - gapStartEndSignal * gap;
  44618. nameMoveDirVec.x = -gapStartEndSignal;
  44619. } else if (nameLocation === 'end') {
  44620. pos.x = extent[1] + gapStartEndSignal * gap;
  44621. nameMoveDirVec.x = gapStartEndSignal;
  44622. } else {
  44623. // 'middle' or 'center'
  44624. pos.x = (extent[0] + extent[1]) / 2;
  44625. pos.y = cfg.labelOffset + nameDirection * gap;
  44626. nameMoveDirVec.y = nameDirection;
  44627. }
  44628. var mt = create$1();
  44629. nameMoveDirVec.transform(rotate(mt, mt, cfg.rotation));
  44630. var nameRotation = axisModel.get('nameRotate');
  44631. if (nameRotation != null) {
  44632. nameRotation = nameRotation * PI$5 / 180; // To radian.
  44633. }
  44634. var labelLayout;
  44635. var axisNameAvailableWidth;
  44636. if (isNameLocationCenter(nameLocation)) {
  44637. labelLayout = AxisBuilder.innerTextLayout(cfg.rotation, nameRotation != null ? nameRotation : cfg.rotation,
  44638. // Adapt to axis.
  44639. nameDirection);
  44640. } else {
  44641. labelLayout = endTextLayout(cfg.rotation, nameLocation, nameRotation || 0, extent);
  44642. axisNameAvailableWidth = cfg.raw.axisNameAvailableWidth;
  44643. if (axisNameAvailableWidth != null) {
  44644. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  44645. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  44646. }
  44647. }
  44648. var textFont = textStyleModel.getFont();
  44649. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  44650. var ellipsis = truncateOpt.ellipsis;
  44651. var maxWidth = retrieve(cfg.raw.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  44652. var nameMarginLevel = extraParams.nameMarginLevel || 0;
  44653. var textEl = new ZRText({
  44654. x: pos.x,
  44655. y: pos.y,
  44656. rotation: labelLayout.rotation,
  44657. silent: AxisBuilder.isLabelSilent(axisModel),
  44658. style: createTextStyle(textStyleModel, {
  44659. text: name,
  44660. font: textFont,
  44661. overflow: 'truncate',
  44662. width: maxWidth,
  44663. ellipsis: ellipsis,
  44664. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  44665. align: textStyleModel.get('align') || labelLayout.textAlign,
  44666. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  44667. }),
  44668. z2: 1
  44669. });
  44670. setTooltipConfig({
  44671. el: textEl,
  44672. componentModel: axisModel,
  44673. itemName: name
  44674. });
  44675. textEl.__fullText = name;
  44676. // Id for animation
  44677. textEl.anid = 'name';
  44678. if (axisModel.get('triggerEvent')) {
  44679. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  44680. eventData.targetType = 'axisName';
  44681. eventData.name = name;
  44682. getECData(textEl).eventData = eventData;
  44683. }
  44684. transformGroup.add(textEl);
  44685. textEl.updateTransform();
  44686. local.nameEl = textEl;
  44687. var nameLayout = sharedRecord.nameLayout = ensureLabelLayoutWithGeometry({
  44688. label: textEl,
  44689. priority: textEl.z2,
  44690. defaultAttr: {
  44691. ignore: textEl.ignore
  44692. },
  44693. marginDefault: isNameLocationCenter(nameLocation)
  44694. // Make axis name visually far from axis labels.
  44695. // (but not too aggressive, consider multiple small charts)
  44696. ? DEFAULT_CENTER_NAME_MARGIN_LEVELS[nameMarginLevel]
  44697. // top/button margin is set to `0` to inserted the xAxis name into the indention
  44698. // above the axis labels to save space. (see example below.)
  44699. : DEFAULT_ENDS_NAME_MARGIN_LEVELS[nameMarginLevel]
  44700. });
  44701. sharedRecord.nameLocation = nameLocation;
  44702. group.add(textEl);
  44703. textEl.decomposeTransform();
  44704. if (cfg.shouldNameMoveOverlap && nameLayout) {
  44705. var record = shared.ensureRecord(axisModel);
  44706. if ("development" !== 'production') {
  44707. assert(record.labelInfoList);
  44708. }
  44709. shared.resolveAxisNameOverlap(cfg, shared, axisModel, nameLayout, nameMoveDirVec, record);
  44710. }
  44711. }
  44712. };
  44713. function layOutAxisTickLabel(cfg, local, shared, axisModel, group, transformGroup, api, kind) {
  44714. if (!axisLabelBuildResultExists(local)) {
  44715. buildAxisLabel(cfg, local, group, kind, axisModel, api);
  44716. }
  44717. var labelLayoutList = local.labelLayoutList;
  44718. updateAxisLabelChangableProps(cfg, axisModel, labelLayoutList, transformGroup);
  44719. adjustBreakLabels(axisModel, cfg.rotation, labelLayoutList);
  44720. var optionHideOverlap = cfg.optionHideOverlap;
  44721. fixMinMaxLabelShow(axisModel, labelLayoutList, optionHideOverlap);
  44722. if (optionHideOverlap) {
  44723. // This bit fixes the label overlap issue for the time chart.
  44724. // See https://github.com/apache/echarts/issues/14266 for more.
  44725. hideOverlap(
  44726. // Filter the already ignored labels by the previous overlap resolving methods.
  44727. filter(labelLayoutList, function (layout) {
  44728. return layout && !layout.label.ignore;
  44729. }));
  44730. }
  44731. // Always call it even this axis has no name, since it serves in overlapping detection
  44732. // and grid outerBounds on other axis.
  44733. resetOverlapRecordToShared(cfg, shared, axisModel, labelLayoutList);
  44734. }
  44735. function endTextLayout(rotation, textPosition, textRotate, extent) {
  44736. var rotationDiff = remRadian(textRotate - rotation);
  44737. var textAlign;
  44738. var textVerticalAlign;
  44739. var inverse = extent[0] > extent[1];
  44740. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  44741. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  44742. textVerticalAlign = onLeft ? 'bottom' : 'top';
  44743. textAlign = 'center';
  44744. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  44745. textVerticalAlign = onLeft ? 'top' : 'bottom';
  44746. textAlign = 'center';
  44747. } else {
  44748. textVerticalAlign = 'middle';
  44749. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  44750. textAlign = onLeft ? 'left' : 'right';
  44751. } else {
  44752. textAlign = onLeft ? 'right' : 'left';
  44753. }
  44754. }
  44755. return {
  44756. rotation: rotationDiff,
  44757. textAlign: textAlign,
  44758. textVerticalAlign: textVerticalAlign
  44759. };
  44760. }
  44761. /**
  44762. * Assume `labelLayoutList` has no `label.ignore: true`.
  44763. * Assume `labelLayoutList` have been sorted by value ascending order.
  44764. */
  44765. function fixMinMaxLabelShow(axisModel, labelLayoutList, optionHideOverlap) {
  44766. if (shouldShowAllLabels(axisModel.axis)) {
  44767. return;
  44768. }
  44769. // FIXME
  44770. // Have not consider onBand yet, where tick els is more than label els.
  44771. // Assert no ignore in labels.
  44772. function deal(showMinMaxLabel, outmostLabelIdx, innerLabelIdx) {
  44773. var outmostLabelLayout = ensureLabelLayoutWithGeometry(labelLayoutList[outmostLabelIdx]);
  44774. var innerLabelLayout = ensureLabelLayoutWithGeometry(labelLayoutList[innerLabelIdx]);
  44775. if (!outmostLabelLayout || !innerLabelLayout) {
  44776. return;
  44777. }
  44778. if (showMinMaxLabel === false || outmostLabelLayout.suggestIgnore) {
  44779. ignoreEl(outmostLabelLayout.label);
  44780. return;
  44781. }
  44782. if (innerLabelLayout.suggestIgnore) {
  44783. ignoreEl(innerLabelLayout.label);
  44784. return;
  44785. }
  44786. // PENDING: Originally we thought `optionHideOverlap === false` means do not hide anything,
  44787. // since currently the bounding rect of text might not accurate enough and might slightly bigger,
  44788. // which causes false positive. But `optionHideOverlap: null/undfined` is falsy and likely
  44789. // be treated as false.
  44790. // In most fonts the glyph does not reach the boundary of the bounding rect.
  44791. // This is needed to avoid too aggressive to hide two elements that meet at the edge
  44792. // due to compact layout by the same bounding rect or OBB.
  44793. var touchThreshold = 0.1;
  44794. // This treatment is for backward compatibility. And `!optionHideOverlap` implies that
  44795. // the user accepts the visual touch between adjacent labels, thus "hide min/max label"
  44796. // should be conservative, since the space might be sufficient in this case.
  44797. if (!optionHideOverlap) {
  44798. var marginForce = [0, 0, 0, 0];
  44799. // Make a copy to apply `ignoreMargin`.
  44800. outmostLabelLayout = newLabelLayoutWithGeometry({
  44801. marginForce: marginForce
  44802. }, outmostLabelLayout);
  44803. innerLabelLayout = newLabelLayoutWithGeometry({
  44804. marginForce: marginForce
  44805. }, innerLabelLayout);
  44806. }
  44807. if (labelIntersect(outmostLabelLayout, innerLabelLayout, null, {
  44808. touchThreshold: touchThreshold
  44809. })) {
  44810. if (showMinMaxLabel) {
  44811. ignoreEl(innerLabelLayout.label);
  44812. } else {
  44813. ignoreEl(outmostLabelLayout.label);
  44814. }
  44815. }
  44816. }
  44817. // If min or max are user set, we need to check
  44818. // If the tick on min(max) are overlap on their neighbour tick
  44819. // If they are overlapped, we need to hide the min(max) tick label
  44820. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  44821. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']);
  44822. var labelsLen = labelLayoutList.length;
  44823. deal(showMinLabel, 0, 1);
  44824. deal(showMaxLabel, labelsLen - 1, labelsLen - 2);
  44825. }
  44826. // PENDING: Is it necessary to display a tick while the corresponding label is ignored?
  44827. function syncLabelIgnoreToMajorTicks(cfg, labelLayoutList, tickEls) {
  44828. if (cfg.showMinorTicks) {
  44829. // It probably unreaasonable to hide major ticks when show minor ticks.
  44830. return;
  44831. }
  44832. each(labelLayoutList, function (labelLayout) {
  44833. if (labelLayout && labelLayout.label.ignore) {
  44834. for (var idx = 0; idx < tickEls.length; idx++) {
  44835. var tickEl = tickEls[idx];
  44836. // Assume small array, linear search is fine for performance.
  44837. // PENDING: measure?
  44838. var tickInner = getTickInner(tickEl);
  44839. var labelInner = getLabelInner(labelLayout.label);
  44840. if (tickInner.tickValue != null && !tickInner.onBand && tickInner.tickValue === labelInner.tickValue) {
  44841. ignoreEl(tickEl);
  44842. return;
  44843. }
  44844. }
  44845. }
  44846. });
  44847. }
  44848. function ignoreEl(el) {
  44849. el && (el.ignore = true);
  44850. }
  44851. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  44852. var tickEls = [];
  44853. var pt1 = [];
  44854. var pt2 = [];
  44855. for (var i = 0; i < ticksCoords.length; i++) {
  44856. var tickCoord = ticksCoords[i].coord;
  44857. pt1[0] = tickCoord;
  44858. pt1[1] = 0;
  44859. pt2[0] = tickCoord;
  44860. pt2[1] = tickEndCoord;
  44861. if (tickTransform) {
  44862. applyTransform(pt1, pt1, tickTransform);
  44863. applyTransform(pt2, pt2, tickTransform);
  44864. }
  44865. // Tick line, Not use group transform to have better line draw
  44866. var tickEl = new Line({
  44867. shape: {
  44868. x1: pt1[0],
  44869. y1: pt1[1],
  44870. x2: pt2[0],
  44871. y2: pt2[1]
  44872. },
  44873. style: tickLineStyle,
  44874. z2: 2,
  44875. autoBatch: true,
  44876. silent: true
  44877. });
  44878. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  44879. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  44880. tickEls.push(tickEl);
  44881. var inner = getTickInner(tickEl);
  44882. inner.onBand = !!ticksCoords[i].onBand;
  44883. inner.tickValue = ticksCoords[i].tickValue;
  44884. }
  44885. return tickEls;
  44886. }
  44887. function buildAxisMajorTicks(cfg, group, transformGroup, axisModel) {
  44888. var axis = axisModel.axis;
  44889. var tickModel = axisModel.getModel('axisTick');
  44890. var shown = tickModel.get('show');
  44891. if (shown === 'auto') {
  44892. shown = true;
  44893. if (cfg.raw.axisTickAutoShow != null) {
  44894. shown = !!cfg.raw.axisTickAutoShow;
  44895. }
  44896. }
  44897. if (!shown || axis.scale.isBlank()) {
  44898. return [];
  44899. }
  44900. var lineStyleModel = tickModel.getModel('lineStyle');
  44901. var tickEndCoord = cfg.tickDirection * tickModel.get('length');
  44902. var ticksCoords = axis.getTicksCoords();
  44903. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  44904. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  44905. }), 'ticks');
  44906. for (var i = 0; i < ticksEls.length; i++) {
  44907. group.add(ticksEls[i]);
  44908. }
  44909. return ticksEls;
  44910. }
  44911. function buildAxisMinorTicks(cfg, group, transformGroup, axisModel, tickDirection) {
  44912. var axis = axisModel.axis;
  44913. var minorTickModel = axisModel.getModel('minorTick');
  44914. if (!cfg.showMinorTicks || axis.scale.isBlank()) {
  44915. return;
  44916. }
  44917. var minorTicksCoords = axis.getMinorTicksCoords();
  44918. if (!minorTicksCoords.length) {
  44919. return;
  44920. }
  44921. var lineStyleModel = minorTickModel.getModel('lineStyle');
  44922. var tickEndCoord = tickDirection * minorTickModel.get('length');
  44923. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  44924. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  44925. }));
  44926. for (var i = 0; i < minorTicksCoords.length; i++) {
  44927. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  44928. for (var k = 0; k < minorTicksEls.length; k++) {
  44929. group.add(minorTicksEls[k]);
  44930. }
  44931. }
  44932. }
  44933. // Return whether need to call `layOutAxisTickLabel` again.
  44934. function dealLastTickLabelResultReusable(local, group, extraParams) {
  44935. if (axisLabelBuildResultExists(local)) {
  44936. var axisLabelsCreationContext = local.axisLabelsCreationContext;
  44937. if ("development" !== 'production') {
  44938. assert(local.labelGroup && axisLabelsCreationContext);
  44939. }
  44940. var noPxChangeTryDetermine = axisLabelsCreationContext.out.noPxChangeTryDetermine;
  44941. if (extraParams.noPxChange) {
  44942. var canDetermine = true;
  44943. for (var idx = 0; idx < noPxChangeTryDetermine.length; idx++) {
  44944. canDetermine = canDetermine && noPxChangeTryDetermine[idx]();
  44945. }
  44946. if (canDetermine) {
  44947. return false;
  44948. }
  44949. }
  44950. if (noPxChangeTryDetermine.length) {
  44951. // Remove the result of `buildAxisLabel`
  44952. group.remove(local.labelGroup);
  44953. axisLabelBuildResultSet(local, null, null, null);
  44954. }
  44955. }
  44956. return true;
  44957. }
  44958. function buildAxisLabel(cfg, local, group, kind, axisModel, api) {
  44959. var axis = axisModel.axis;
  44960. var show = retrieve(cfg.raw.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  44961. var labelGroup = new Group();
  44962. group.add(labelGroup);
  44963. var axisLabelCreationCtx = createAxisLabelsComputingContext(kind);
  44964. if (!show || axis.scale.isBlank()) {
  44965. axisLabelBuildResultSet(local, [], labelGroup, axisLabelCreationCtx);
  44966. return;
  44967. }
  44968. var labelModel = axisModel.getModel('axisLabel');
  44969. var labels = axis.getViewLabels(axisLabelCreationCtx);
  44970. // Special label rotate.
  44971. var labelRotation = (retrieve(cfg.raw.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  44972. var labelLayout = AxisBuilder.innerTextLayout(cfg.rotation, labelRotation, cfg.labelDirection);
  44973. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  44974. var labelEls = [];
  44975. var triggerEvent = axisModel.get('triggerEvent');
  44976. var z2Min = Infinity;
  44977. var z2Max = -Infinity;
  44978. each(labels, function (labelItem, index) {
  44979. var _a;
  44980. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  44981. var formattedLabel = labelItem.formattedLabel;
  44982. var rawLabel = labelItem.rawLabel;
  44983. var itemLabelModel = labelModel;
  44984. if (rawCategoryData && rawCategoryData[tickValue]) {
  44985. var rawCategoryItem = rawCategoryData[tickValue];
  44986. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  44987. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  44988. }
  44989. }
  44990. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  44991. var align = itemLabelModel.getShallow('align', true) || labelLayout.textAlign;
  44992. var alignMin = retrieve2(itemLabelModel.getShallow('alignMinLabel', true), align);
  44993. var alignMax = retrieve2(itemLabelModel.getShallow('alignMaxLabel', true), align);
  44994. var verticalAlign = itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign;
  44995. var verticalAlignMin = retrieve2(itemLabelModel.getShallow('verticalAlignMinLabel', true), verticalAlign);
  44996. var verticalAlignMax = retrieve2(itemLabelModel.getShallow('verticalAlignMaxLabel', true), verticalAlign);
  44997. var z2 = 10 + (((_a = labelItem.time) === null || _a === void 0 ? void 0 : _a.level) || 0);
  44998. z2Min = Math.min(z2Min, z2);
  44999. z2Max = Math.max(z2Max, z2);
  45000. var textEl = new ZRText({
  45001. // --- transform props start ---
  45002. // All of the transform props MUST not be set here, but should be set in
  45003. // `updateAxisLabelChangableProps`, because they may change in estimation,
  45004. // and need to calculate based on global coord sys by `decomposeTransform`.
  45005. x: 0,
  45006. y: 0,
  45007. rotation: 0,
  45008. // --- transform props end ---
  45009. silent: AxisBuilder.isLabelSilent(axisModel),
  45010. z2: z2,
  45011. style: createTextStyle(itemLabelModel, {
  45012. text: formattedLabel,
  45013. align: index === 0 ? alignMin : index === labels.length - 1 ? alignMax : align,
  45014. verticalAlign: index === 0 ? verticalAlignMin : index === labels.length - 1 ? verticalAlignMax : verticalAlign,
  45015. fill: isFunction(textColor) ? textColor(
  45016. // (1) In category axis with data zoom, tick is not the original
  45017. // index of axis.data. So tick should not be exposed to user
  45018. // in category axis.
  45019. // (2) Compatible with previous version, which always use formatted label as
  45020. // input. But in interval scale the formatted label is like '223,445', which
  45021. // maked user replace ','. So we modify it to return original val but remain
  45022. // it as 'string' to avoid error in replacing.
  45023. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  45024. })
  45025. });
  45026. textEl.anid = 'label_' + tickValue;
  45027. var inner = getLabelInner(textEl);
  45028. inner["break"] = labelItem["break"];
  45029. inner.tickValue = tickValue;
  45030. inner.layoutRotation = labelLayout.rotation;
  45031. setTooltipConfig({
  45032. el: textEl,
  45033. componentModel: axisModel,
  45034. itemName: formattedLabel,
  45035. formatterParamsExtra: {
  45036. isTruncated: function () {
  45037. return textEl.isTruncated;
  45038. },
  45039. value: rawLabel,
  45040. tickIndex: index
  45041. }
  45042. });
  45043. // Pack data for mouse event
  45044. if (triggerEvent) {
  45045. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  45046. eventData.targetType = 'axisLabel';
  45047. eventData.value = rawLabel;
  45048. eventData.tickIndex = index;
  45049. if (labelItem["break"]) {
  45050. eventData["break"] = {
  45051. // type: labelItem.break.type,
  45052. start: labelItem["break"].parsedBreak.vmin,
  45053. end: labelItem["break"].parsedBreak.vmax
  45054. };
  45055. }
  45056. if (axis.type === 'category') {
  45057. eventData.dataIndex = tickValue;
  45058. }
  45059. getECData(textEl).eventData = eventData;
  45060. if (labelItem["break"]) {
  45061. addBreakEventHandler(axisModel, api, textEl, labelItem["break"]);
  45062. }
  45063. }
  45064. labelEls.push(textEl);
  45065. labelGroup.add(textEl);
  45066. });
  45067. var labelLayoutList = map(labelEls, function (label) {
  45068. return {
  45069. label: label,
  45070. priority: getLabelInner(label)["break"] ? label.z2 + (z2Max - z2Min + 1) // Make break labels be highest priority.
  45071. : label.z2,
  45072. defaultAttr: {
  45073. ignore: label.ignore
  45074. }
  45075. };
  45076. });
  45077. axisLabelBuildResultSet(local, labelLayoutList, labelGroup, axisLabelCreationCtx);
  45078. }
  45079. // Indicate that `layOutAxisTickLabel` has been called.
  45080. function axisLabelBuildResultExists(local) {
  45081. return !!local.labelLayoutList;
  45082. }
  45083. function axisLabelBuildResultSet(local, labelLayoutList, labelGroup, axisLabelsCreationContext) {
  45084. // Ensure the same lifetime.
  45085. local.labelLayoutList = labelLayoutList;
  45086. local.labelGroup = labelGroup;
  45087. local.axisLabelsCreationContext = axisLabelsCreationContext;
  45088. }
  45089. function updateAxisLabelChangableProps(cfg, axisModel, labelLayoutList, transformGroup) {
  45090. var labelMargin = axisModel.get(['axisLabel', 'margin']);
  45091. each(labelLayoutList, function (layout, idx) {
  45092. var geometry = ensureLabelLayoutWithGeometry(layout);
  45093. if (!geometry) {
  45094. return;
  45095. }
  45096. var labelEl = geometry.label;
  45097. var inner = getLabelInner(labelEl);
  45098. // See the comment in `suggestIgnore`.
  45099. geometry.suggestIgnore = labelEl.ignore;
  45100. // Currently no `ignore:true` is set in `buildAxisLabel`
  45101. // But `ignore:true` may be set subsequently for overlap handling, thus reset it here.
  45102. labelEl.ignore = false;
  45103. copyTransform(_tmpLayoutEl, _tmpLayoutElReset);
  45104. _tmpLayoutEl.x = axisModel.axis.dataToCoord(inner.tickValue);
  45105. _tmpLayoutEl.y = cfg.labelOffset + cfg.labelDirection * labelMargin;
  45106. _tmpLayoutEl.rotation = inner.layoutRotation;
  45107. transformGroup.add(_tmpLayoutEl);
  45108. _tmpLayoutEl.updateTransform();
  45109. transformGroup.remove(_tmpLayoutEl);
  45110. _tmpLayoutEl.decomposeTransform();
  45111. copyTransform(labelEl, _tmpLayoutEl);
  45112. labelEl.markRedraw();
  45113. setLabelLayoutDirty(geometry, true);
  45114. ensureLabelLayoutWithGeometry(geometry);
  45115. });
  45116. }
  45117. var _tmpLayoutEl = new Rect();
  45118. var _tmpLayoutElReset = new Rect();
  45119. function hasAxisName(axisName) {
  45120. return !!axisName;
  45121. }
  45122. function addBreakEventHandler(axisModel, api, textEl, visualBreak) {
  45123. textEl.on('click', function (params) {
  45124. var payload = {
  45125. type: AXIS_BREAK_EXPAND_ACTION_TYPE,
  45126. breaks: [{
  45127. start: visualBreak.parsedBreak.breakOption.start,
  45128. end: visualBreak.parsedBreak.breakOption.end
  45129. }]
  45130. };
  45131. payload[axisModel.axis.dim + "AxisIndex"] = axisModel.componentIndex;
  45132. api.dispatchAction(payload);
  45133. });
  45134. }
  45135. function adjustBreakLabels(axisModel, axisRotation, labelLayoutList) {
  45136. var scaleBreakHelper = getScaleBreakHelper();
  45137. if (!scaleBreakHelper) {
  45138. return;
  45139. }
  45140. var breakLabelIndexPairs = scaleBreakHelper.retrieveAxisBreakPairs(labelLayoutList, function (layoutInfo) {
  45141. return layoutInfo && getLabelInner(layoutInfo.label)["break"];
  45142. }, true);
  45143. var moveOverlap = axisModel.get(['breakLabelLayout', 'moveOverlap'], true);
  45144. if (moveOverlap === true || moveOverlap === 'auto') {
  45145. each(breakLabelIndexPairs, function (idxPair) {
  45146. getAxisBreakHelper().adjustBreakLabelPair(axisModel.axis.inverse, axisRotation, [ensureLabelLayoutWithGeometry(labelLayoutList[idxPair[0]]), ensureLabelLayoutWithGeometry(labelLayoutList[idxPair[1]])]);
  45147. });
  45148. }
  45149. }
  45150. /**
  45151. * [__CAUTION__]
  45152. * MUST guarantee: if only the input `rect` and `axis.extent` changed,
  45153. * only `layout.position` changes.
  45154. * This character is replied on `grid.contain` calculation in `AxisBuilder`.
  45155. * @see updateCartesianAxisViewCommonPartBuilder
  45156. *
  45157. * Can only be called after coordinate system creation stage.
  45158. * (Can be called before coordinate system update stage).
  45159. */
  45160. function layout$1(rect, axisModel, opt) {
  45161. opt = opt || {};
  45162. var axis = axisModel.axis;
  45163. var layout = {};
  45164. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  45165. var rawAxisPosition = axis.position;
  45166. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  45167. var axisDim = axis.dim;
  45168. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  45169. var idx = {
  45170. left: 0,
  45171. right: 1,
  45172. top: 0,
  45173. bottom: 1,
  45174. onZero: 2
  45175. };
  45176. var axisOffset = axisModel.get('offset') || 0;
  45177. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  45178. if (otherAxisOnZeroOf) {
  45179. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  45180. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  45181. }
  45182. // Axis position
  45183. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]];
  45184. // Axis rotation
  45185. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  45186. // Tick and label direction, x y is axisDim
  45187. var dirMap = {
  45188. top: -1,
  45189. bottom: 1,
  45190. left: -1,
  45191. right: 1
  45192. };
  45193. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  45194. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  45195. if (axisModel.get(['axisTick', 'inside'])) {
  45196. layout.tickDirection = -layout.tickDirection;
  45197. }
  45198. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  45199. layout.labelDirection = -layout.labelDirection;
  45200. }
  45201. // Special label rotation
  45202. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  45203. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  45204. // Over splitLine and splitArea
  45205. layout.z2 = 1;
  45206. return layout;
  45207. }
  45208. /**
  45209. * Note: If pie (or other similar series) use cartesian2d, here
  45210. * option `seriesModel.get('coordinateSystem') === 'cartesian2d'`
  45211. * and `seriesModel.coordinateSystem !== cartesian2dCoordSysInstance`
  45212. * and `seriesModel.boxCoordinateSystem === cartesian2dCoordSysInstance`,
  45213. * the logic below is probably wrong, therefore skip it temporarily.
  45214. */
  45215. function isCartesian2DInjectedAsDataCoordSys(seriesModel) {
  45216. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  45217. }
  45218. function findAxisModels(seriesModel) {
  45219. var axisModelMap = {
  45220. xAxisModel: null,
  45221. yAxisModel: null
  45222. };
  45223. each(axisModelMap, function (v, key) {
  45224. var axisType = key.replace(/Model$/, '');
  45225. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  45226. if ("development" !== 'production') {
  45227. if (!axisModel) {
  45228. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  45229. }
  45230. }
  45231. axisModelMap[key] = axisModel;
  45232. });
  45233. return axisModelMap;
  45234. }
  45235. function createCartesianAxisViewCommonPartBuilder(gridRect, cartesians, axisModel, api, ctx, defaultNameMoveOverlap) {
  45236. var layoutResult = layout$1(gridRect, axisModel);
  45237. var axisLineAutoShow = false;
  45238. var axisTickAutoShow = false;
  45239. // Not show axisTick or axisLine if other axis is category / time
  45240. for (var i = 0; i < cartesians.length; i++) {
  45241. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  45242. // Still show axis tick or axisLine if other axis is value / log
  45243. axisLineAutoShow = axisTickAutoShow = true;
  45244. if (axisModel.axis.type === 'category' && axisModel.axis.onBand) {
  45245. axisTickAutoShow = false;
  45246. }
  45247. }
  45248. }
  45249. layoutResult.axisLineAutoShow = axisLineAutoShow;
  45250. layoutResult.axisTickAutoShow = axisTickAutoShow;
  45251. layoutResult.defaultNameMoveOverlap = defaultNameMoveOverlap;
  45252. return new AxisBuilder(axisModel, api, layoutResult, ctx);
  45253. }
  45254. function updateCartesianAxisViewCommonPartBuilder(axisBuilder, gridRect, axisModel) {
  45255. var newRaw = layout$1(gridRect, axisModel);
  45256. if ("development" !== 'production') {
  45257. var oldRaw_1 = axisBuilder.__getRawCfg();
  45258. each(keys(newRaw), function (prop) {
  45259. if (prop !== 'position' && prop !== 'labelOffset') {
  45260. assert(newRaw[prop] === oldRaw_1[prop]);
  45261. }
  45262. });
  45263. }
  45264. axisBuilder.updateCfg(newRaw);
  45265. }
  45266. function alignScaleTicks(scale, axisModel, alignToScale) {
  45267. var _a;
  45268. var intervalScaleProto = IntervalScale.prototype;
  45269. // NOTE: There is a precondition for log scale here:
  45270. // In log scale we store _interval and _extent of exponent value.
  45271. // So if we use the method of InternalScale to set/get these data.
  45272. // It process the exponent value, which is linear and what we want here.
  45273. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  45274. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, {
  45275. expandToNicedExtent: true
  45276. });
  45277. var alignToSplitNumber = alignToTicks.length - 1;
  45278. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  45279. var scaleExtent = getScaleExtent(scale, axisModel);
  45280. var rawExtent = scaleExtent.extent;
  45281. var isMinFixed = scaleExtent.fixMin;
  45282. var isMaxFixed = scaleExtent.fixMax;
  45283. if (scale.type === 'log') {
  45284. rawExtent = logTransform(scale.base, rawExtent, true);
  45285. }
  45286. scale.setBreaksFromOption(retrieveAxisBreaksOption(axisModel));
  45287. scale.setExtent(rawExtent[0], rawExtent[1]);
  45288. scale.calcNiceExtent({
  45289. splitNumber: alignToSplitNumber,
  45290. fixMin: isMinFixed,
  45291. fixMax: isMaxFixed
  45292. });
  45293. var extent = intervalScaleProto.getExtent.call(scale);
  45294. // Need to update the rawExtent.
  45295. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  45296. if (isMinFixed) {
  45297. rawExtent[0] = extent[0];
  45298. }
  45299. if (isMaxFixed) {
  45300. rawExtent[1] = extent[1];
  45301. }
  45302. var interval = intervalScaleProto.getInterval.call(scale);
  45303. var min = rawExtent[0];
  45304. var max = rawExtent[1];
  45305. if (isMinFixed && isMaxFixed) {
  45306. // User set min, max, divide to get new interval
  45307. interval = (max - min) / alignToSplitNumber;
  45308. } else if (isMinFixed) {
  45309. max = rawExtent[0] + interval * alignToSplitNumber;
  45310. // User set min, expand extent on the other side
  45311. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  45312. interval = increaseInterval(interval);
  45313. max = rawExtent[0] + interval * alignToSplitNumber;
  45314. }
  45315. } else if (isMaxFixed) {
  45316. // User set max, expand extent on the other side
  45317. min = rawExtent[1] - interval * alignToSplitNumber;
  45318. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  45319. interval = increaseInterval(interval);
  45320. min = rawExtent[1] - interval * alignToSplitNumber;
  45321. }
  45322. } else {
  45323. var nicedSplitNumber = scale.getTicks().length - 1;
  45324. if (nicedSplitNumber > alignToSplitNumber) {
  45325. interval = increaseInterval(interval);
  45326. }
  45327. var range = interval * alignToSplitNumber;
  45328. max = Math.ceil(rawExtent[1] / interval) * interval;
  45329. min = round(max - range);
  45330. // Not change the result that crossing zero.
  45331. if (min < 0 && rawExtent[0] >= 0) {
  45332. min = 0;
  45333. max = round(range);
  45334. } else if (max > 0 && rawExtent[1] <= 0) {
  45335. max = 0;
  45336. min = -round(range);
  45337. }
  45338. }
  45339. // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  45340. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  45341. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval;
  45342. // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  45343. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  45344. intervalScaleProto.setInterval.call(scale, interval);
  45345. if (t0 || t1) {
  45346. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  45347. }
  45348. if ("development" !== 'production') {
  45349. var ticks = intervalScaleProto.getTicks.call(scale);
  45350. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  45351. warn("The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + (" and alignTicks: true. (" + ((_a = axisModel.axis) === null || _a === void 0 ? void 0 : _a.dim) + "AxisIndex: " + axisModel.componentIndex + ")"), true);
  45352. }
  45353. }
  45354. }
  45355. // margin is [top, right, bottom, left]
  45356. var XY_TO_MARGIN_IDX = [[3, 1], [0, 2] // xyIdx 1 => 'y'
  45357. ];
  45358. var Grid = /** @class */function () {
  45359. function Grid(gridModel, ecModel, api) {
  45360. // FIXME:TS where used (different from registered type 'cartesian2d')?
  45361. this.type = 'grid';
  45362. this._coordsMap = {};
  45363. this._coordsList = [];
  45364. this._axesMap = {};
  45365. this._axesList = [];
  45366. this.axisPointerEnabled = true;
  45367. this.dimensions = cartesian2DDimensions;
  45368. this._initCartesian(gridModel, ecModel, api);
  45369. this.model = gridModel;
  45370. }
  45371. Grid.prototype.getRect = function () {
  45372. return this._rect;
  45373. };
  45374. Grid.prototype.update = function (ecModel, api) {
  45375. var axesMap = this._axesMap;
  45376. this._updateScale(ecModel, this.model);
  45377. function updateAxisTicks(axes) {
  45378. var alignTo;
  45379. // Axis is added in order of axisIndex.
  45380. var axesIndices = keys(axes);
  45381. var len = axesIndices.length;
  45382. if (!len) {
  45383. return;
  45384. }
  45385. var axisNeedsAlign = [];
  45386. // Process once and calculate the ticks for those don't use alignTicks.
  45387. for (var i = len - 1; i >= 0; i--) {
  45388. var idx = +axesIndices[i]; // Convert to number.
  45389. var axis = axes[idx];
  45390. var model = axis.model;
  45391. var scale = axis.scale;
  45392. if (
  45393. // Only value and log axis without interval support alignTicks.
  45394. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  45395. axisNeedsAlign.push(axis);
  45396. } else {
  45397. niceScaleExtent(scale, model);
  45398. if (isIntervalOrLogScale(scale)) {
  45399. // Can only align to interval or log axis.
  45400. alignTo = axis;
  45401. }
  45402. }
  45403. }
  45404. // All axes has set alignTicks. Pick the first one.
  45405. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  45406. if (axisNeedsAlign.length) {
  45407. if (!alignTo) {
  45408. alignTo = axisNeedsAlign.pop();
  45409. niceScaleExtent(alignTo.scale, alignTo.model);
  45410. }
  45411. each(axisNeedsAlign, function (axis) {
  45412. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  45413. });
  45414. }
  45415. }
  45416. updateAxisTicks(axesMap.x);
  45417. updateAxisTicks(axesMap.y);
  45418. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  45419. var onZeroRecords = {};
  45420. each(axesMap.x, function (xAxis) {
  45421. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  45422. });
  45423. each(axesMap.y, function (yAxis) {
  45424. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  45425. });
  45426. // Resize again if containLabel is enabled
  45427. // FIXME It may cause getting wrong grid size in data processing stage
  45428. this.resize(this.model, api);
  45429. };
  45430. /**
  45431. * Resize the grid.
  45432. *
  45433. * [NOTE]
  45434. * If both "grid.containLabel/grid.contain" and pixel-required-data-processing (such as, "dataSampling")
  45435. * exist, circular dependency occurs in logic.
  45436. * The final compromised sequence is:
  45437. * 1. Calculate "axis.extent" (pixel extent) and AffineTransform based on only "grid layout options".
  45438. * Not accurate if "grid.containLabel/grid.contain" is required, but it is a compromise to avoid
  45439. * circular dependency.
  45440. * 2. Perform "series data processing" (where "dataSampling" requires "axis.extent").
  45441. * 3. Calculate "scale.extent" (data extent) based on "processed series data".
  45442. * 4. Modify "axis.extent" for "grid.containLabel/grid.contain":
  45443. * 4.1. Calculate "axis labels" based on "scale.extent".
  45444. * 4.2. Modify "axis.extent" by the bounding rects of "axis labels and names".
  45445. */
  45446. Grid.prototype.resize = function (gridModel, api, beforeDataProcessing) {
  45447. var layoutRef = createBoxLayoutReference(gridModel, api);
  45448. var gridRect = this._rect = getLayoutRect(gridModel.getBoxLayoutParams(), layoutRef.refContainer);
  45449. // PENDING: whether to support that if the input `coord` is out of the base coord sys,
  45450. // do not render anything. At present, the behavior is undefined.
  45451. var axesMap = this._axesMap;
  45452. var coordsList = this._coordsList;
  45453. var optionContainLabel = gridModel.get('containLabel'); // No `.get(, true)` for backward compat.
  45454. updateAllAxisExtentTransByGridRect(axesMap, gridRect);
  45455. if (!beforeDataProcessing) {
  45456. var axisBuilderSharedCtx = createAxisBiulders(gridRect, coordsList, axesMap, optionContainLabel, api);
  45457. var noPxChange = void 0;
  45458. if (optionContainLabel) {
  45459. {
  45460. if ("development" !== 'production') {
  45461. log('Specified `grid.containLabel` but no `use(LegacyGridContainLabel)`;' + 'use `grid.outerBounds` instead.', true);
  45462. }
  45463. noPxChange = layOutGridByOuterBounds(gridRect.clone(), 'axisLabel', null, gridRect, axesMap, axisBuilderSharedCtx, layoutRef);
  45464. }
  45465. } else {
  45466. var _a = prepareOuterBounds(gridModel, gridRect, layoutRef),
  45467. outerBoundsRect = _a.outerBoundsRect,
  45468. parsedOuterBoundsContain = _a.parsedOuterBoundsContain,
  45469. outerBoundsClamp = _a.outerBoundsClamp;
  45470. if (outerBoundsRect) {
  45471. // console.time('layOutGridByOuterBounds');
  45472. noPxChange = layOutGridByOuterBounds(outerBoundsRect, parsedOuterBoundsContain, outerBoundsClamp, gridRect, axesMap, axisBuilderSharedCtx, layoutRef);
  45473. // console.timeEnd('layOutGridByOuterBounds');
  45474. }
  45475. }
  45476. // console.time('buildAxesView_determine');
  45477. createOrUpdateAxesView(gridRect, axesMap, AxisTickLabelComputingKind.determine, null, noPxChange, layoutRef);
  45478. // console.timeEnd('buildAxesView_determine');
  45479. } // End of beforeDataProcessing
  45480. each(this._coordsList, function (coord) {
  45481. // Calculate affine matrix to accelerate the data to point transform.
  45482. // If all the axes scales are time or value.
  45483. coord.calcAffineTransform();
  45484. });
  45485. };
  45486. Grid.prototype.getAxis = function (dim, axisIndex) {
  45487. var axesMapOnDim = this._axesMap[dim];
  45488. if (axesMapOnDim != null) {
  45489. return axesMapOnDim[axisIndex || 0];
  45490. }
  45491. };
  45492. Grid.prototype.getAxes = function () {
  45493. return this._axesList.slice();
  45494. };
  45495. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  45496. if (xAxisIndex != null && yAxisIndex != null) {
  45497. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  45498. return this._coordsMap[key];
  45499. }
  45500. if (isObject(xAxisIndex)) {
  45501. yAxisIndex = xAxisIndex.yAxisIndex;
  45502. xAxisIndex = xAxisIndex.xAxisIndex;
  45503. }
  45504. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  45505. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  45506. return coordList[i];
  45507. }
  45508. }
  45509. };
  45510. Grid.prototype.getCartesians = function () {
  45511. return this._coordsList.slice();
  45512. };
  45513. /**
  45514. * @implements
  45515. */
  45516. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  45517. var target = this._findConvertTarget(finder);
  45518. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  45519. };
  45520. /**
  45521. * @implements
  45522. */
  45523. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  45524. var target = this._findConvertTarget(finder);
  45525. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  45526. };
  45527. Grid.prototype._findConvertTarget = function (finder) {
  45528. var seriesModel = finder.seriesModel;
  45529. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  45530. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  45531. var gridModel = finder.gridModel;
  45532. var coordsList = this._coordsList;
  45533. var cartesian;
  45534. var axis;
  45535. if (seriesModel) {
  45536. cartesian = seriesModel.coordinateSystem;
  45537. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  45538. } else if (xAxisModel && yAxisModel) {
  45539. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  45540. } else if (xAxisModel) {
  45541. axis = this.getAxis('x', xAxisModel.componentIndex);
  45542. } else if (yAxisModel) {
  45543. axis = this.getAxis('y', yAxisModel.componentIndex);
  45544. }
  45545. // Lowest priority.
  45546. else if (gridModel) {
  45547. var grid = gridModel.coordinateSystem;
  45548. if (grid === this) {
  45549. cartesian = this._coordsList[0];
  45550. }
  45551. }
  45552. return {
  45553. cartesian: cartesian,
  45554. axis: axis
  45555. };
  45556. };
  45557. /**
  45558. * @implements
  45559. */
  45560. Grid.prototype.containPoint = function (point) {
  45561. var coord = this._coordsList[0];
  45562. if (coord) {
  45563. return coord.containPoint(point);
  45564. }
  45565. };
  45566. /**
  45567. * Initialize cartesian coordinate systems
  45568. */
  45569. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  45570. var _this = this;
  45571. var grid = this;
  45572. var axisPositionUsed = {
  45573. left: false,
  45574. right: false,
  45575. top: false,
  45576. bottom: false
  45577. };
  45578. var axesMap = {
  45579. x: {},
  45580. y: {}
  45581. };
  45582. var axesCount = {
  45583. x: 0,
  45584. y: 0
  45585. };
  45586. // Create axis
  45587. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  45588. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  45589. if (!axesCount.x || !axesCount.y) {
  45590. // Roll back when there no either x or y axis
  45591. this._axesMap = {};
  45592. this._axesList = [];
  45593. return;
  45594. }
  45595. this._axesMap = axesMap;
  45596. // Create cartesian2d
  45597. each(axesMap.x, function (xAxis, xAxisIndex) {
  45598. each(axesMap.y, function (yAxis, yAxisIndex) {
  45599. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  45600. var cartesian = new Cartesian2D(key);
  45601. cartesian.master = _this;
  45602. cartesian.model = gridModel;
  45603. _this._coordsMap[key] = cartesian;
  45604. _this._coordsList.push(cartesian);
  45605. cartesian.addAxis(xAxis);
  45606. cartesian.addAxis(yAxis);
  45607. });
  45608. });
  45609. function createAxisCreator(dimName) {
  45610. return function (axisModel, idx) {
  45611. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  45612. return;
  45613. }
  45614. var axisPosition = axisModel.get('position');
  45615. if (dimName === 'x') {
  45616. // Fix position
  45617. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  45618. // Default bottom of X
  45619. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  45620. }
  45621. } else {
  45622. // Fix position
  45623. if (axisPosition !== 'left' && axisPosition !== 'right') {
  45624. // Default left of Y
  45625. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  45626. }
  45627. }
  45628. axisPositionUsed[axisPosition] = true;
  45629. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  45630. var isCategory = axis.type === 'category';
  45631. axis.onBand = isCategory && axisModel.get('boundaryGap');
  45632. axis.inverse = axisModel.get('inverse');
  45633. // Inject axis into axisModel
  45634. axisModel.axis = axis;
  45635. // Inject axisModel into axis
  45636. axis.model = axisModel;
  45637. // Inject grid info axis
  45638. axis.grid = grid;
  45639. // Index of axis, can be used as key
  45640. axis.index = idx;
  45641. grid._axesList.push(axis);
  45642. axesMap[dimName][idx] = axis;
  45643. axesCount[dimName]++;
  45644. };
  45645. }
  45646. };
  45647. /**
  45648. * Update cartesian properties from series.
  45649. */
  45650. Grid.prototype._updateScale = function (ecModel, gridModel) {
  45651. // Reset scale
  45652. each(this._axesList, function (axis) {
  45653. axis.scale.setExtent(Infinity, -Infinity);
  45654. if (axis.type === 'category') {
  45655. var categorySortInfo = axis.model.get('categorySortInfo');
  45656. axis.scale.setSortInfo(categorySortInfo);
  45657. }
  45658. });
  45659. ecModel.eachSeries(function (seriesModel) {
  45660. // If pie (or other similar series) use cartesian2d, the unionExtent logic below is
  45661. // wrong, therefore skip it temporarily. See also in `defaultAxisExtentFromData.ts`.
  45662. // TODO: support union extent in this case.
  45663. if (isCartesian2DInjectedAsDataCoordSys(seriesModel)) {
  45664. var axesModelMap = findAxisModels(seriesModel);
  45665. var xAxisModel = axesModelMap.xAxisModel;
  45666. var yAxisModel = axesModelMap.yAxisModel;
  45667. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  45668. return;
  45669. }
  45670. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  45671. var data = seriesModel.getData();
  45672. var xAxis = cartesian.getAxis('x');
  45673. var yAxis = cartesian.getAxis('y');
  45674. unionExtent(data, xAxis);
  45675. unionExtent(data, yAxis);
  45676. }
  45677. }, this);
  45678. function unionExtent(data, axis) {
  45679. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  45680. axis.scale.unionExtentFromData(data, dim);
  45681. });
  45682. }
  45683. };
  45684. /**
  45685. * @param dim 'x' or 'y' or 'auto' or null/undefined
  45686. */
  45687. Grid.prototype.getTooltipAxes = function (dim) {
  45688. var baseAxes = [];
  45689. var otherAxes = [];
  45690. each(this.getCartesians(), function (cartesian) {
  45691. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  45692. var otherAxis = cartesian.getOtherAxis(baseAxis);
  45693. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  45694. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  45695. });
  45696. return {
  45697. baseAxes: baseAxes,
  45698. otherAxes: otherAxes
  45699. };
  45700. };
  45701. Grid.create = function (ecModel, api) {
  45702. var grids = [];
  45703. ecModel.eachComponent('grid', function (gridModel, idx) {
  45704. var grid = new Grid(gridModel, ecModel, api);
  45705. grid.name = 'grid_' + idx;
  45706. // dataSampling requires axis extent, so resize
  45707. // should be performed in create stage.
  45708. grid.resize(gridModel, api, true);
  45709. gridModel.coordinateSystem = grid;
  45710. grids.push(grid);
  45711. });
  45712. // Inject the coordinateSystems into seriesModel
  45713. ecModel.eachSeries(function (seriesModel) {
  45714. injectCoordSysByOption({
  45715. targetModel: seriesModel,
  45716. coordSysType: 'cartesian2d',
  45717. coordSysProvider: coordSysProvider
  45718. });
  45719. function coordSysProvider() {
  45720. var axesModelMap = findAxisModels(seriesModel);
  45721. var xAxisModel = axesModelMap.xAxisModel;
  45722. var yAxisModel = axesModelMap.yAxisModel;
  45723. var gridModel = xAxisModel.getCoordSysModel();
  45724. if ("development" !== 'production') {
  45725. if (!gridModel) {
  45726. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  45727. }
  45728. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  45729. throw new Error('xAxis and yAxis must use the same grid');
  45730. }
  45731. }
  45732. var grid = gridModel.coordinateSystem;
  45733. return grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  45734. }
  45735. });
  45736. return grids;
  45737. };
  45738. // For deciding which dimensions to use when creating list data
  45739. Grid.dimensions = cartesian2DDimensions;
  45740. return Grid;
  45741. }();
  45742. /**
  45743. * Check if the axis is used in the specified grid.
  45744. */
  45745. function isAxisUsedInTheGrid(axisModel, gridModel) {
  45746. return axisModel.getCoordSysModel() === gridModel;
  45747. }
  45748. function fixAxisOnZero(axesMap, otherAxisDim, axis,
  45749. // Key: see `getOnZeroRecordKey`
  45750. onZeroRecords) {
  45751. axis.getAxesOnZeroOf = function () {
  45752. // TODO: onZero of multiple axes.
  45753. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  45754. };
  45755. // onZero can not be enabled in these two situations:
  45756. // 1. When any other axis is a category axis.
  45757. // 2. When no axis is cross 0 point.
  45758. var otherAxes = axesMap[otherAxisDim];
  45759. var otherAxisOnZeroOf;
  45760. var axisModel = axis.model;
  45761. var onZero = axisModel.get(['axisLine', 'onZero']);
  45762. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  45763. if (!onZero) {
  45764. return;
  45765. }
  45766. // If target axis is specified.
  45767. if (onZeroAxisIndex != null) {
  45768. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  45769. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  45770. }
  45771. } else {
  45772. // Find the first available other axis.
  45773. for (var idx in otherAxes) {
  45774. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])
  45775. // Consider that two Y axes on one value axis,
  45776. // if both onZero, the two Y axes overlap.
  45777. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  45778. otherAxisOnZeroOf = otherAxes[idx];
  45779. break;
  45780. }
  45781. }
  45782. }
  45783. if (otherAxisOnZeroOf) {
  45784. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  45785. }
  45786. function getOnZeroRecordKey(axis) {
  45787. return axis.dim + '_' + axis.index;
  45788. }
  45789. }
  45790. function canOnZeroToAxis(axis) {
  45791. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  45792. }
  45793. function updateAxisTransform(axis, coordBase) {
  45794. var axisExtent = axis.getExtent();
  45795. var axisExtentSum = axisExtent[0] + axisExtent[1];
  45796. // Fast transform
  45797. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  45798. return coord + coordBase;
  45799. } : function (coord) {
  45800. return axisExtentSum - coord + coordBase;
  45801. };
  45802. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  45803. return coord - coordBase;
  45804. } : function (coord) {
  45805. return axisExtentSum - coord + coordBase;
  45806. };
  45807. }
  45808. function updateAllAxisExtentTransByGridRect(axesMap, gridRect) {
  45809. each(axesMap.x, function (axis) {
  45810. return updateAxisExtentTransByGridRect(axis, gridRect.x, gridRect.width);
  45811. });
  45812. each(axesMap.y, function (axis) {
  45813. return updateAxisExtentTransByGridRect(axis, gridRect.y, gridRect.height);
  45814. });
  45815. }
  45816. function updateAxisExtentTransByGridRect(axis, gridXY, gridWH) {
  45817. var extent = [0, gridWH];
  45818. var idx = axis.inverse ? 1 : 0;
  45819. axis.setExtent(extent[idx], extent[1 - idx]);
  45820. updateAxisTransform(axis, gridXY);
  45821. }
  45822. // Return noPxChange.
  45823. function layOutGridByOuterBounds(outerBoundsRect, outerBoundsContain, outerBoundsClamp, gridRect, axesMap, axisBuilderSharedCtx, layoutRef) {
  45824. if ("development" !== 'production') {
  45825. assert(outerBoundsContain === 'all' || outerBoundsContain === 'axisLabel');
  45826. }
  45827. // Assume `updateAllAxisExtentTransByGridRect` has been performed once before this call.
  45828. // [NOTE]:
  45829. // - The bounding rect of the axis elements might be sensitve to variations in `axis.extent` due to strategies
  45830. // like hideOverlap/moveOverlap. @see the comment in `LabelLayoutBase['suggestIgnore']`.
  45831. // - The final `gridRect` might be slightly smaller than the ideally expected result if labels are giant and
  45832. // get hidden due to overlapping. More iterations could improve precision, but not performant. We consider
  45833. // the current result acceptable, since no alignment among charts can be guaranteed when using this feature.
  45834. createOrUpdateAxesView(gridRect, axesMap, AxisTickLabelComputingKind.estimate, outerBoundsContain, false, layoutRef);
  45835. var margin = [0, 0, 0, 0];
  45836. fillLabelNameOverflowOnOneDimension(0);
  45837. fillLabelNameOverflowOnOneDimension(1);
  45838. // If axis is blank, no label can be used to detect overflow.
  45839. // gridRect itself should not overflow.
  45840. fillMarginOnOneDimension(gridRect, 0, NaN);
  45841. fillMarginOnOneDimension(gridRect, 1, NaN);
  45842. var noPxChange = find(margin, function (item) {
  45843. return item > 0;
  45844. }) == null;
  45845. expandOrShrinkRect(gridRect, margin, true, true, outerBoundsClamp);
  45846. updateAllAxisExtentTransByGridRect(axesMap, gridRect);
  45847. return noPxChange;
  45848. function fillLabelNameOverflowOnOneDimension(xyIdx) {
  45849. each(axesMap[XY$1[xyIdx]], function (axis) {
  45850. if (!shouldAxisShow(axis.model)) {
  45851. return;
  45852. }
  45853. // FIXME: zr Group.union may wrongly union (0, 0, 0, 0) and not performant.
  45854. // unionRect.union(axis.axisBuilder.group.getBoundingRect());
  45855. // If ussing Group.getBoundingRect to calculate shrink space, it is not strictly accurate when
  45856. // the outermost label is ignored and the secondary label is very long and contribute to the
  45857. // union extension:
  45858. // -|---|---|---|
  45859. // 1,000,000,000
  45860. // Therefore we calculate them one by one.
  45861. // Also considered axis may be blank or no labels.
  45862. var sharedRecord = axisBuilderSharedCtx.ensureRecord(axis.model);
  45863. var labelInfoList = sharedRecord.labelInfoList;
  45864. if (labelInfoList) {
  45865. for (var idx = 0; idx < labelInfoList.length; idx++) {
  45866. var labelInfo = labelInfoList[idx];
  45867. var proportion = axis.scale.normalize(getLabelInner(labelInfo.label).tickValue);
  45868. proportion = xyIdx === 1 ? 1 - proportion : proportion;
  45869. // xAxis use proportion on x, yAxis use proprotion on y, otherwise not.
  45870. fillMarginOnOneDimension(labelInfo.rect, xyIdx, proportion);
  45871. fillMarginOnOneDimension(labelInfo.rect, 1 - xyIdx, NaN);
  45872. }
  45873. }
  45874. var nameLayout = sharedRecord.nameLayout;
  45875. if (nameLayout) {
  45876. var proportion = isNameLocationCenter(sharedRecord.nameLocation) ? 0.5 : NaN;
  45877. fillMarginOnOneDimension(nameLayout.rect, xyIdx, proportion);
  45878. fillMarginOnOneDimension(nameLayout.rect, 1 - xyIdx, NaN);
  45879. }
  45880. });
  45881. }
  45882. function fillMarginOnOneDimension(itemRect, xyIdx, proportion // NaN mean no use proportion
  45883. ) {
  45884. var overflow1 = outerBoundsRect[XY$1[xyIdx]] - itemRect[XY$1[xyIdx]];
  45885. var overflow2 = itemRect[WH$1[xyIdx]] + itemRect[XY$1[xyIdx]] - (outerBoundsRect[WH$1[xyIdx]] + outerBoundsRect[XY$1[xyIdx]]);
  45886. overflow1 = applyProportion(overflow1, 1 - proportion);
  45887. overflow2 = applyProportion(overflow2, proportion);
  45888. var minIdx = XY_TO_MARGIN_IDX[xyIdx][0];
  45889. var maxIdx = XY_TO_MARGIN_IDX[xyIdx][1];
  45890. margin[minIdx] = mathMax$1(margin[minIdx], overflow1);
  45891. margin[maxIdx] = mathMax$1(margin[maxIdx], overflow2);
  45892. }
  45893. function applyProportion(overflow, proportion) {
  45894. // proportion is not likely to near zero. If so, give up shrink
  45895. if (overflow > 0 && !eqNaN(proportion) && proportion > 1e-4) {
  45896. overflow /= proportion;
  45897. }
  45898. return overflow;
  45899. }
  45900. }
  45901. function createAxisBiulders(gridRect, cartesians, axesMap, optionContainLabel, api) {
  45902. var axisBuilderSharedCtx = new AxisBuilderSharedContext(resolveAxisNameOverlapForGrid);
  45903. each(axesMap, function (axisList) {
  45904. return each(axisList, function (axis) {
  45905. if (shouldAxisShow(axis.model)) {
  45906. // See `AxisBaseOptionCommon['nameMoveOverlap']`.
  45907. var defaultNameMoveOverlap = !optionContainLabel;
  45908. axis.axisBuilder = createCartesianAxisViewCommonPartBuilder(gridRect, cartesians, axis.model, api, axisBuilderSharedCtx, defaultNameMoveOverlap);
  45909. }
  45910. });
  45911. });
  45912. return axisBuilderSharedCtx;
  45913. }
  45914. /**
  45915. * Promote the axis-elements-building from "view render" stage to "coordinate system resize" stage.
  45916. * This is aimed to resovle overlap across multiple axes, since currently it's hard to reconcile
  45917. * multiple axes in "view render" stage.
  45918. *
  45919. * [CAUTION] But this promotion assumes that the subsequent "visual mapping" stage does not affect
  45920. * this axis-elements-building; otherwise we have to refactor it again.
  45921. */
  45922. function createOrUpdateAxesView(gridRect, axesMap, kind, outerBoundsContain, noPxChange, layoutRef) {
  45923. var isDetermine = kind === AxisTickLabelComputingKind.determine;
  45924. each(axesMap, function (axisList) {
  45925. return each(axisList, function (axis) {
  45926. if (shouldAxisShow(axis.model)) {
  45927. updateCartesianAxisViewCommonPartBuilder(axis.axisBuilder, gridRect, axis.model);
  45928. axis.axisBuilder.build(isDetermine ? {
  45929. axisTickLabelDetermine: true
  45930. } : {
  45931. axisTickLabelEstimate: true
  45932. }, {
  45933. noPxChange: noPxChange
  45934. });
  45935. }
  45936. });
  45937. });
  45938. var nameMarginLevelMap = {
  45939. x: 0,
  45940. y: 0
  45941. };
  45942. calcNameMarginLevel(0);
  45943. calcNameMarginLevel(1);
  45944. function calcNameMarginLevel(xyIdx) {
  45945. nameMarginLevelMap[XY$1[1 - xyIdx]] = gridRect[WH$1[xyIdx]] <= layoutRef.refContainer[WH$1[xyIdx]] * 0.5 ? 0 : 1 - xyIdx === 1 ? 2 : 1;
  45946. }
  45947. each(axesMap, function (axisList, xy) {
  45948. return each(axisList, function (axis) {
  45949. if (shouldAxisShow(axis.model)) {
  45950. if (outerBoundsContain === 'all' || isDetermine) {
  45951. // To resolve overlap, `axisName` layout depends on `axisTickLabel` layout result
  45952. // (all of the axes of the same `grid`; consider multiple x or y axes).
  45953. axis.axisBuilder.build({
  45954. axisName: true
  45955. }, {
  45956. nameMarginLevel: nameMarginLevelMap[xy]
  45957. });
  45958. }
  45959. if (isDetermine) {
  45960. axis.axisBuilder.build({
  45961. axisLine: true
  45962. });
  45963. }
  45964. }
  45965. });
  45966. });
  45967. }
  45968. function prepareOuterBounds(gridModel, rawRridRect, layoutRef) {
  45969. var outerBoundsRect;
  45970. var optionOuterBoundsMode = gridModel.get('outerBoundsMode', true);
  45971. if (optionOuterBoundsMode === 'same') {
  45972. outerBoundsRect = rawRridRect.clone();
  45973. } else if (optionOuterBoundsMode == null || optionOuterBoundsMode === 'auto') {
  45974. outerBoundsRect = getLayoutRect(gridModel.get('outerBounds', true) || OUTER_BOUNDS_DEFAULT, layoutRef.refContainer);
  45975. } else if (optionOuterBoundsMode !== 'none') {
  45976. if ("development" !== 'production') {
  45977. error("Invalid grid[" + gridModel.componentIndex + "].outerBoundsMode.");
  45978. }
  45979. }
  45980. var optionOuterBoundsContain = gridModel.get('outerBoundsContain', true);
  45981. var parsedOuterBoundsContain;
  45982. if (optionOuterBoundsContain == null || optionOuterBoundsContain === 'auto') {
  45983. parsedOuterBoundsContain = 'all';
  45984. } else if (indexOf(['all', 'axisLabel'], optionOuterBoundsContain) < 0) {
  45985. if ("development" !== 'production') {
  45986. error("Invalid grid[" + gridModel.componentIndex + "].outerBoundsContain.");
  45987. }
  45988. parsedOuterBoundsContain = 'all';
  45989. } else {
  45990. parsedOuterBoundsContain = optionOuterBoundsContain;
  45991. }
  45992. var outerBoundsClamp = [parsePositionSizeOption(retrieve2(gridModel.get('outerBoundsClampWidth', true), OUTER_BOUNDS_CLAMP_DEFAULT[0]), rawRridRect.width), parsePositionSizeOption(retrieve2(gridModel.get('outerBoundsClampHeight', true), OUTER_BOUNDS_CLAMP_DEFAULT[1]), rawRridRect.height)];
  45993. return {
  45994. outerBoundsRect: outerBoundsRect,
  45995. parsedOuterBoundsContain: parsedOuterBoundsContain,
  45996. outerBoundsClamp: outerBoundsClamp
  45997. };
  45998. }
  45999. var resolveAxisNameOverlapForGrid = function (cfg, ctx, axisModel, nameLayoutInfo, nameMoveDirVec, thisRecord) {
  46000. var perpendicularDim = axisModel.axis.dim === 'x' ? 'y' : 'x';
  46001. resolveAxisNameOverlapDefault(cfg, ctx, axisModel, nameLayoutInfo, nameMoveDirVec, thisRecord);
  46002. // If nameLocation 'center', and there are multiple axes parallel to this axis, do not adjust by
  46003. // other axes, because the axis name should be close to its axis line as much as possible even
  46004. // if overlapping; otherwise it might cause misleading.
  46005. // If nameLocation 'center', do not adjust by perpendicular axes, since they are not likely to overlap.
  46006. // If nameLocation 'start'/'end', move name within the same direction to escape overlap with the
  46007. // perpendicular axes.
  46008. if (!isNameLocationCenter(cfg.nameLocation)) {
  46009. each(ctx.recordMap[perpendicularDim], function (perpenRecord) {
  46010. // perpendicular axis may be no name.
  46011. if (perpenRecord && perpenRecord.labelInfoList && perpenRecord.dirVec) {
  46012. moveIfOverlapByLinearLabels(perpenRecord.labelInfoList, perpenRecord.dirVec, nameLayoutInfo, nameMoveDirVec);
  46013. }
  46014. });
  46015. }
  46016. };
  46017. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  46018. // allAxesInfo should be updated when setOption performed.
  46019. function collect(ecModel, api) {
  46020. var result = {
  46021. /**
  46022. * key: makeKey(axis.model)
  46023. * value: {
  46024. * axis,
  46025. * coordSys,
  46026. * axisPointerModel,
  46027. * triggerTooltip,
  46028. * triggerEmphasis,
  46029. * involveSeries,
  46030. * snap,
  46031. * seriesModels,
  46032. * seriesDataCount
  46033. * }
  46034. */
  46035. axesInfo: {},
  46036. seriesInvolved: false,
  46037. /**
  46038. * key: makeKey(coordSys.model)
  46039. * value: Object: key makeKey(axis.model), value: axisInfo
  46040. */
  46041. coordSysAxesInfo: {},
  46042. coordSysMap: {}
  46043. };
  46044. collectAxesInfo(result, ecModel, api);
  46045. // Check seriesInvolved for performance, in case too many series in some chart.
  46046. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  46047. return result;
  46048. }
  46049. function collectAxesInfo(result, ecModel, api) {
  46050. var globalTooltipModel = ecModel.getComponent('tooltip');
  46051. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  46052. // links can only be set on global.
  46053. var linksOption = globalAxisPointerModel.get('link', true) || [];
  46054. var linkGroups = [];
  46055. // Collect axes info.
  46056. each(api.getCoordinateSystems(), function (coordSys) {
  46057. // Some coordinate system do not support axes, like geo.
  46058. if (!coordSys.axisPointerEnabled) {
  46059. return;
  46060. }
  46061. var coordSysKey = makeKey(coordSys.model);
  46062. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  46063. result.coordSysMap[coordSysKey] = coordSys;
  46064. // Set tooltip (like 'cross') is a convenient way to show axisPointer
  46065. // for user. So we enable setting tooltip on coordSys model.
  46066. var coordSysModel = coordSys.model;
  46067. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  46068. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null));
  46069. // If axis tooltip used, choose tooltip axis for each coordSys.
  46070. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  46071. if (coordSys.getTooltipAxes && globalTooltipModel
  46072. // If tooltip.showContent is set as false, tooltip will not
  46073. // show but axisPointer will show as normal.
  46074. && baseTooltipModel.get('show')) {
  46075. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  46076. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  46077. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  46078. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  46079. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  46080. if (triggerAxis || cross) {
  46081. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  46082. }
  46083. if (cross) {
  46084. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  46085. }
  46086. }
  46087. // fromTooltip: true | false | 'cross'
  46088. // triggerTooltip: true | false | null
  46089. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  46090. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  46091. var axisPointerShow = axisPointerModel.get('show');
  46092. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  46093. return;
  46094. }
  46095. if (triggerTooltip == null) {
  46096. triggerTooltip = axisPointerModel.get('triggerTooltip');
  46097. }
  46098. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  46099. var snap = axisPointerModel.get('snap');
  46100. var triggerEmphasis = axisPointerModel.get('triggerEmphasis');
  46101. var axisKey = makeKey(axis.model);
  46102. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  46103. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  46104. var axisInfo = result.axesInfo[axisKey] = {
  46105. key: axisKey,
  46106. axis: axis,
  46107. coordSys: coordSys,
  46108. axisPointerModel: axisPointerModel,
  46109. triggerTooltip: triggerTooltip,
  46110. triggerEmphasis: triggerEmphasis,
  46111. involveSeries: involveSeries,
  46112. snap: snap,
  46113. useHandle: isHandleTrigger(axisPointerModel),
  46114. seriesModels: [],
  46115. linkGroup: null
  46116. };
  46117. axesInfoInCoordSys[axisKey] = axisInfo;
  46118. result.seriesInvolved = result.seriesInvolved || involveSeries;
  46119. var groupIndex = getLinkGroupIndex(linksOption, axis);
  46120. if (groupIndex != null) {
  46121. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  46122. axesInfo: {}
  46123. });
  46124. linkGroup.axesInfo[axisKey] = axisInfo;
  46125. linkGroup.mapper = linksOption[groupIndex].mapper;
  46126. axisInfo.linkGroup = linkGroup;
  46127. }
  46128. }
  46129. });
  46130. }
  46131. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  46132. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  46133. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  46134. var volatileOption = {};
  46135. each(fields, function (field) {
  46136. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  46137. });
  46138. // category axis do not auto snap, otherwise some tick that do not
  46139. // has value can not be hovered. value/time/log axis default snap if
  46140. // triggered from tooltip and trigger tooltip.
  46141. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  46142. // Compatible with previous behavior, tooltip axis does not show label by default.
  46143. // Only these properties can be overridden from tooltip to axisPointer.
  46144. if (tooltipAxisPointerModel.get('type') === 'cross') {
  46145. volatileOption.type = 'line';
  46146. }
  46147. var labelOption = volatileOption.label || (volatileOption.label = {});
  46148. // Follow the convention, do not show label when triggered by tooltip by default.
  46149. labelOption.show == null && (labelOption.show = false);
  46150. if (fromTooltip === 'cross') {
  46151. // When 'cross', both axes show labels.
  46152. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  46153. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  46154. // If triggerTooltip, this is a base axis, which should better not use cross style
  46155. // (cross style is dashed by default)
  46156. if (!triggerTooltip) {
  46157. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  46158. crossStyle && defaults(labelOption, crossStyle.textStyle);
  46159. }
  46160. }
  46161. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  46162. }
  46163. function collectSeriesInfo(result, ecModel) {
  46164. // Prepare data for axis trigger
  46165. ecModel.eachSeries(function (seriesModel) {
  46166. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  46167. var coordSys = seriesModel.coordinateSystem;
  46168. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  46169. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  46170. if (!coordSys || !coordSys.model // PENDING: radar do not have a model.
  46171. || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  46172. return;
  46173. }
  46174. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  46175. var axis = axisInfo.axis;
  46176. if (coordSys.getAxis(axis.dim) === axis) {
  46177. axisInfo.seriesModels.push(seriesModel);
  46178. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  46179. axisInfo.seriesDataCount += seriesModel.getData().count();
  46180. }
  46181. });
  46182. });
  46183. }
  46184. /**
  46185. * For example:
  46186. * {
  46187. * axisPointer: {
  46188. * links: [{
  46189. * xAxisIndex: [2, 4],
  46190. * yAxisIndex: 'all'
  46191. * }, {
  46192. * xAxisId: ['a5', 'a7'],
  46193. * xAxisName: 'xxx'
  46194. * }]
  46195. * }
  46196. * }
  46197. */
  46198. function getLinkGroupIndex(linksOption, axis) {
  46199. var axisModel = axis.model;
  46200. var dim = axis.dim;
  46201. for (var i = 0; i < linksOption.length; i++) {
  46202. var linkOption = linksOption[i] || {};
  46203. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  46204. return i;
  46205. }
  46206. }
  46207. }
  46208. function checkPropInLink(linkPropValue, axisPropValue) {
  46209. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  46210. }
  46211. function fixValue(axisModel) {
  46212. var axisInfo = getAxisInfo(axisModel);
  46213. if (!axisInfo) {
  46214. return;
  46215. }
  46216. var axisPointerModel = axisInfo.axisPointerModel;
  46217. var scale = axisInfo.axis.scale;
  46218. var option = axisPointerModel.option;
  46219. var status = axisPointerModel.get('status');
  46220. var value = axisPointerModel.get('value');
  46221. // Parse init value for category and time axis.
  46222. if (value != null) {
  46223. value = scale.parse(value);
  46224. }
  46225. var useHandle = isHandleTrigger(axisPointerModel);
  46226. // If `handle` used, `axisPointer` will always be displayed, so value
  46227. // and status should be initialized.
  46228. if (status == null) {
  46229. option.status = useHandle ? 'show' : 'hide';
  46230. }
  46231. var extent = scale.getExtent().slice();
  46232. extent[0] > extent[1] && extent.reverse();
  46233. if (
  46234. // Pick a value on axis when initializing.
  46235. value == null
  46236. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  46237. // where we should re-pick a value to keep `handle` displaying normally.
  46238. || value > extent[1]) {
  46239. // Make handle displayed on the end of the axis when init, which looks better.
  46240. value = extent[1];
  46241. }
  46242. if (value < extent[0]) {
  46243. value = extent[0];
  46244. }
  46245. option.value = value;
  46246. if (useHandle) {
  46247. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  46248. }
  46249. }
  46250. function getAxisInfo(axisModel) {
  46251. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  46252. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  46253. }
  46254. function getAxisPointerModel(axisModel) {
  46255. var axisInfo = getAxisInfo(axisModel);
  46256. return axisInfo && axisInfo.axisPointerModel;
  46257. }
  46258. function isHandleTrigger(axisPointerModel) {
  46259. return !!axisPointerModel.get(['handle', 'show']);
  46260. }
  46261. /**
  46262. * @param {module:echarts/model/Model} model
  46263. * @return {string} unique key
  46264. */
  46265. function makeKey(model) {
  46266. return model.type + '||' + model.id;
  46267. }
  46268. var axisPointerClazz = {};
  46269. /**
  46270. * Base class of AxisView.
  46271. */
  46272. var AxisView = /** @class */function (_super) {
  46273. __extends(AxisView, _super);
  46274. function AxisView() {
  46275. var _this = _super !== null && _super.apply(this, arguments) || this;
  46276. _this.type = AxisView.type;
  46277. return _this;
  46278. }
  46279. /**
  46280. * @override
  46281. */
  46282. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  46283. // FIXME
  46284. // This process should proformed after coordinate systems updated
  46285. // (axis scale updated), and should be performed each time update.
  46286. // So put it here temporarily, although it is not appropriate to
  46287. // put a model-writing procedure in `view`.
  46288. this.axisPointerClass && fixValue(axisModel);
  46289. _super.prototype.render.apply(this, arguments);
  46290. this._doUpdateAxisPointerClass(axisModel, api, true);
  46291. };
  46292. /**
  46293. * Action handler.
  46294. */
  46295. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  46296. this._doUpdateAxisPointerClass(axisModel, api, false);
  46297. };
  46298. /**
  46299. * @override
  46300. */
  46301. AxisView.prototype.remove = function (ecModel, api) {
  46302. var axisPointer = this._axisPointer;
  46303. axisPointer && axisPointer.remove(api);
  46304. };
  46305. /**
  46306. * @override
  46307. */
  46308. AxisView.prototype.dispose = function (ecModel, api) {
  46309. this._disposeAxisPointer(api);
  46310. _super.prototype.dispose.apply(this, arguments);
  46311. };
  46312. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  46313. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  46314. if (!Clazz) {
  46315. return;
  46316. }
  46317. var axisPointerModel = getAxisPointerModel(axisModel);
  46318. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  46319. };
  46320. AxisView.prototype._disposeAxisPointer = function (api) {
  46321. this._axisPointer && this._axisPointer.dispose(api);
  46322. this._axisPointer = null;
  46323. };
  46324. AxisView.registerAxisPointerClass = function (type, clazz) {
  46325. if ("development" !== 'production') {
  46326. if (axisPointerClazz[type]) {
  46327. throw new Error('axisPointer ' + type + ' exists');
  46328. }
  46329. }
  46330. axisPointerClazz[type] = clazz;
  46331. };
  46332. AxisView.getAxisPointerClass = function (type) {
  46333. return type && axisPointerClazz[type];
  46334. };
  46335. AxisView.type = 'axis';
  46336. return AxisView;
  46337. }(ComponentView);
  46338. var inner$5 = makeInner();
  46339. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  46340. var axis = axisModel.axis;
  46341. if (axis.scale.isBlank()) {
  46342. return;
  46343. }
  46344. // TODO: TYPE
  46345. var splitAreaModel = axisModel.getModel('splitArea');
  46346. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  46347. var areaColors = areaStyleModel.get('color');
  46348. var gridRect = gridModel.coordinateSystem.getRect();
  46349. var ticksCoords = axis.getTicksCoords({
  46350. tickModel: splitAreaModel,
  46351. clamp: true,
  46352. breakTicks: 'none',
  46353. pruneByBreak: 'preserve_extent_bound'
  46354. });
  46355. if (!ticksCoords.length) {
  46356. return;
  46357. }
  46358. // For Making appropriate splitArea animation, the color and anid
  46359. // should be corresponding to previous one if possible.
  46360. var areaColorsLen = areaColors.length;
  46361. var lastSplitAreaColors = inner$5(axisView).splitAreaColors;
  46362. var newSplitAreaColors = createHashMap();
  46363. var colorIndex = 0;
  46364. if (lastSplitAreaColors) {
  46365. for (var i = 0; i < ticksCoords.length; i++) {
  46366. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  46367. if (cIndex != null) {
  46368. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  46369. break;
  46370. }
  46371. }
  46372. }
  46373. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  46374. var areaStyle = areaStyleModel.getAreaStyle();
  46375. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  46376. for (var i = 1; i < ticksCoords.length; i++) {
  46377. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  46378. var x = void 0;
  46379. var y = void 0;
  46380. var width = void 0;
  46381. var height = void 0;
  46382. if (axis.isHorizontal()) {
  46383. x = prev;
  46384. y = gridRect.y;
  46385. width = tickCoord - x;
  46386. height = gridRect.height;
  46387. prev = x + width;
  46388. } else {
  46389. x = gridRect.x;
  46390. y = prev;
  46391. width = gridRect.width;
  46392. height = tickCoord - y;
  46393. prev = y + height;
  46394. }
  46395. var tickValue = ticksCoords[i - 1].tickValue;
  46396. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  46397. axisGroup.add(new Rect({
  46398. anid: tickValue != null ? 'area_' + tickValue : null,
  46399. shape: {
  46400. x: x,
  46401. y: y,
  46402. width: width,
  46403. height: height
  46404. },
  46405. style: defaults({
  46406. fill: areaColors[colorIndex]
  46407. }, areaStyle),
  46408. autoBatch: true,
  46409. silent: true
  46410. }));
  46411. colorIndex = (colorIndex + 1) % areaColorsLen;
  46412. }
  46413. inner$5(axisView).splitAreaColors = newSplitAreaColors;
  46414. }
  46415. function rectCoordAxisHandleRemove(axisView) {
  46416. inner$5(axisView).splitAreaColors = null;
  46417. }
  46418. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine', 'breakArea'];
  46419. var CartesianAxisView = /** @class */function (_super) {
  46420. __extends(CartesianAxisView, _super);
  46421. function CartesianAxisView() {
  46422. var _this = _super !== null && _super.apply(this, arguments) || this;
  46423. _this.type = CartesianAxisView.type;
  46424. _this.axisPointerClass = 'CartesianAxisPointer';
  46425. return _this;
  46426. }
  46427. /**
  46428. * @override
  46429. */
  46430. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  46431. this.group.removeAll();
  46432. var oldAxisGroup = this._axisGroup;
  46433. this._axisGroup = new Group();
  46434. this.group.add(this._axisGroup);
  46435. if (!shouldAxisShow(axisModel)) {
  46436. return;
  46437. }
  46438. this._axisGroup.add(axisModel.axis.axisBuilder.group);
  46439. each(selfBuilderAttrs, function (name) {
  46440. if (axisModel.get([name, 'show'])) {
  46441. axisElementBuilders[name](this, this._axisGroup, axisModel, axisModel.getCoordSysModel(), api);
  46442. }
  46443. }, this);
  46444. // THIS is a special case for bar racing chart.
  46445. // Update the axis label from the natural initial layout to
  46446. // sorted layout should has no animation.
  46447. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  46448. if (!isInitialSortFromBarRacing) {
  46449. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  46450. }
  46451. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  46452. };
  46453. CartesianAxisView.prototype.remove = function () {
  46454. rectCoordAxisHandleRemove(this);
  46455. };
  46456. CartesianAxisView.type = 'cartesianAxis';
  46457. return CartesianAxisView;
  46458. }(AxisView);
  46459. var axisElementBuilders = {
  46460. splitLine: function (axisView, axisGroup, axisModel, gridModel, api) {
  46461. var axis = axisModel.axis;
  46462. if (axis.scale.isBlank()) {
  46463. return;
  46464. }
  46465. var splitLineModel = axisModel.getModel('splitLine');
  46466. var lineStyleModel = splitLineModel.getModel('lineStyle');
  46467. var lineColors = lineStyleModel.get('color');
  46468. var showMinLine = splitLineModel.get('showMinLine') !== false;
  46469. var showMaxLine = splitLineModel.get('showMaxLine') !== false;
  46470. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  46471. var gridRect = gridModel.coordinateSystem.getRect();
  46472. var isHorizontal = axis.isHorizontal();
  46473. var lineCount = 0;
  46474. var ticksCoords = axis.getTicksCoords({
  46475. tickModel: splitLineModel,
  46476. breakTicks: 'none',
  46477. pruneByBreak: 'preserve_extent_bound'
  46478. });
  46479. var p1 = [];
  46480. var p2 = [];
  46481. var lineStyle = lineStyleModel.getLineStyle();
  46482. for (var i = 0; i < ticksCoords.length; i++) {
  46483. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  46484. if (i === 0 && !showMinLine || i === ticksCoords.length - 1 && !showMaxLine) {
  46485. continue;
  46486. }
  46487. var tickValue = ticksCoords[i].tickValue;
  46488. if (isHorizontal) {
  46489. p1[0] = tickCoord;
  46490. p1[1] = gridRect.y;
  46491. p2[0] = tickCoord;
  46492. p2[1] = gridRect.y + gridRect.height;
  46493. } else {
  46494. p1[0] = gridRect.x;
  46495. p1[1] = tickCoord;
  46496. p2[0] = gridRect.x + gridRect.width;
  46497. p2[1] = tickCoord;
  46498. }
  46499. var colorIndex = lineCount++ % lineColors.length;
  46500. var line = new Line({
  46501. anid: tickValue != null ? 'line_' + tickValue : null,
  46502. autoBatch: true,
  46503. shape: {
  46504. x1: p1[0],
  46505. y1: p1[1],
  46506. x2: p2[0],
  46507. y2: p2[1]
  46508. },
  46509. style: defaults({
  46510. stroke: lineColors[colorIndex]
  46511. }, lineStyle),
  46512. silent: true
  46513. });
  46514. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  46515. axisGroup.add(line);
  46516. }
  46517. },
  46518. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel, api) {
  46519. var axis = axisModel.axis;
  46520. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  46521. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  46522. var gridRect = gridModel.coordinateSystem.getRect();
  46523. var isHorizontal = axis.isHorizontal();
  46524. var minorTicksCoords = axis.getMinorTicksCoords();
  46525. if (!minorTicksCoords.length) {
  46526. return;
  46527. }
  46528. var p1 = [];
  46529. var p2 = [];
  46530. var lineStyle = lineStyleModel.getLineStyle();
  46531. for (var i = 0; i < minorTicksCoords.length; i++) {
  46532. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  46533. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  46534. if (isHorizontal) {
  46535. p1[0] = tickCoord;
  46536. p1[1] = gridRect.y;
  46537. p2[0] = tickCoord;
  46538. p2[1] = gridRect.y + gridRect.height;
  46539. } else {
  46540. p1[0] = gridRect.x;
  46541. p1[1] = tickCoord;
  46542. p2[0] = gridRect.x + gridRect.width;
  46543. p2[1] = tickCoord;
  46544. }
  46545. var line = new Line({
  46546. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  46547. autoBatch: true,
  46548. shape: {
  46549. x1: p1[0],
  46550. y1: p1[1],
  46551. x2: p2[0],
  46552. y2: p2[1]
  46553. },
  46554. style: lineStyle,
  46555. silent: true
  46556. });
  46557. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  46558. axisGroup.add(line);
  46559. }
  46560. }
  46561. },
  46562. splitArea: function (axisView, axisGroup, axisModel, gridModel, api) {
  46563. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  46564. },
  46565. breakArea: function (axisView, axisGroup, axisModel, gridModel, api) {
  46566. var axisBreakHelper = getAxisBreakHelper();
  46567. var scale = axisModel.axis.scale;
  46568. if (axisBreakHelper && scale.type !== 'ordinal') {
  46569. axisBreakHelper.rectCoordBuildBreakAxis(axisGroup, axisView, axisModel, gridModel.coordinateSystem.getRect(), api);
  46570. }
  46571. }
  46572. };
  46573. var CartesianXAxisView = /** @class */function (_super) {
  46574. __extends(CartesianXAxisView, _super);
  46575. function CartesianXAxisView() {
  46576. var _this = _super !== null && _super.apply(this, arguments) || this;
  46577. _this.type = CartesianXAxisView.type;
  46578. return _this;
  46579. }
  46580. CartesianXAxisView.type = 'xAxis';
  46581. return CartesianXAxisView;
  46582. }(CartesianAxisView);
  46583. var CartesianYAxisView = /** @class */function (_super) {
  46584. __extends(CartesianYAxisView, _super);
  46585. function CartesianYAxisView() {
  46586. var _this = _super !== null && _super.apply(this, arguments) || this;
  46587. _this.type = CartesianXAxisView.type;
  46588. return _this;
  46589. }
  46590. CartesianYAxisView.type = 'yAxis';
  46591. return CartesianYAxisView;
  46592. }(CartesianAxisView);
  46593. // Grid view
  46594. var GridView = /** @class */function (_super) {
  46595. __extends(GridView, _super);
  46596. function GridView() {
  46597. var _this = _super !== null && _super.apply(this, arguments) || this;
  46598. _this.type = 'grid';
  46599. return _this;
  46600. }
  46601. GridView.prototype.render = function (gridModel, ecModel) {
  46602. this.group.removeAll();
  46603. if (gridModel.get('show')) {
  46604. this.group.add(new Rect({
  46605. shape: gridModel.coordinateSystem.getRect(),
  46606. style: defaults({
  46607. fill: gridModel.get('backgroundColor')
  46608. }, gridModel.getItemStyle()),
  46609. silent: true,
  46610. z2: -1
  46611. }));
  46612. }
  46613. };
  46614. GridView.type = 'grid';
  46615. return GridView;
  46616. }(ComponentView);
  46617. var extraOption = {
  46618. // gridIndex: 0,
  46619. // gridId: '',
  46620. offset: 0
  46621. };
  46622. function install$5(registers) {
  46623. registers.registerComponentView(GridView);
  46624. registers.registerComponentModel(GridModel);
  46625. registers.registerCoordinateSystem('cartesian2d', Grid);
  46626. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  46627. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  46628. registers.registerComponentView(CartesianXAxisView);
  46629. registers.registerComponentView(CartesianYAxisView);
  46630. registers.registerPreprocessor(function (option) {
  46631. // Only create grid when need
  46632. if (option.xAxis && option.yAxis && !option.grid) {
  46633. option.grid = {};
  46634. }
  46635. });
  46636. }
  46637. function install$6(registers) {
  46638. // In case developer forget to include grid component
  46639. use(install$5);
  46640. registers.registerSeriesModel(ScatterSeriesModel);
  46641. registers.registerChartView(ScatterView);
  46642. registers.registerLayout(pointsLayout('scatter'));
  46643. }
  46644. var inner$6 = makeInner();
  46645. var clone$3 = clone;
  46646. var bind$1 = bind;
  46647. /**
  46648. * Base axis pointer class in 2D.
  46649. */
  46650. var BaseAxisPointer = /** @class */function () {
  46651. function BaseAxisPointer() {
  46652. this._dragging = false;
  46653. /**
  46654. * In px, arbitrary value. Do not set too small,
  46655. * no animation is ok for most cases.
  46656. */
  46657. this.animationThreshold = 15;
  46658. }
  46659. /**
  46660. * @implement
  46661. */
  46662. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  46663. var value = axisPointerModel.get('value');
  46664. var status = axisPointerModel.get('status');
  46665. // Bind them to `this`, not in closure, otherwise they will not
  46666. // be replaced when user calling setOption in not merge mode.
  46667. this._axisModel = axisModel;
  46668. this._axisPointerModel = axisPointerModel;
  46669. this._api = api;
  46670. // Optimize: `render` will be called repeatedly during mouse move.
  46671. // So it is power consuming if performing `render` each time,
  46672. // especially on mobile device.
  46673. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  46674. return;
  46675. }
  46676. this._lastValue = value;
  46677. this._lastStatus = status;
  46678. var group = this._group;
  46679. var handle = this._handle;
  46680. if (!status || status === 'hide') {
  46681. // Do not clear here, for animation better.
  46682. group && group.hide();
  46683. handle && handle.hide();
  46684. return;
  46685. }
  46686. group && group.show();
  46687. handle && handle.show();
  46688. // Otherwise status is 'show'
  46689. var elOption = {};
  46690. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  46691. // Enable change axis pointer type.
  46692. var graphicKey = elOption.graphicKey;
  46693. if (graphicKey !== this._lastGraphicKey) {
  46694. this.clear(api);
  46695. }
  46696. this._lastGraphicKey = graphicKey;
  46697. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  46698. if (!group) {
  46699. group = this._group = new Group();
  46700. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  46701. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  46702. api.getZr().add(group);
  46703. } else {
  46704. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  46705. this.updatePointerEl(group, elOption, doUpdateProps);
  46706. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  46707. }
  46708. updateMandatoryProps(group, axisPointerModel, true);
  46709. this._renderHandle(value);
  46710. };
  46711. /**
  46712. * @implement
  46713. */
  46714. BaseAxisPointer.prototype.remove = function (api) {
  46715. this.clear(api);
  46716. };
  46717. /**
  46718. * @implement
  46719. */
  46720. BaseAxisPointer.prototype.dispose = function (api) {
  46721. this.clear(api);
  46722. };
  46723. /**
  46724. * @protected
  46725. */
  46726. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  46727. var animation = axisPointerModel.get('animation');
  46728. var axis = axisModel.axis;
  46729. var isCategoryAxis = axis.type === 'category';
  46730. var useSnap = axisPointerModel.get('snap');
  46731. // Value axis without snap always do not snap.
  46732. if (!useSnap && !isCategoryAxis) {
  46733. return false;
  46734. }
  46735. if (animation === 'auto' || animation == null) {
  46736. var animationThreshold = this.animationThreshold;
  46737. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  46738. return true;
  46739. }
  46740. // It is important to auto animation when snap used. Consider if there is
  46741. // a dataZoom, animation will be disabled when too many points exist, while
  46742. // it will be enabled for better visual effect when little points exist.
  46743. if (useSnap) {
  46744. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  46745. var axisExtent = axis.getExtent();
  46746. // Approximate band width
  46747. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  46748. }
  46749. return false;
  46750. }
  46751. return animation === true;
  46752. };
  46753. /**
  46754. * add {pointer, label, graphicKey} to elOption
  46755. * @protected
  46756. */
  46757. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  46758. // Should be implemenented by sub-class.
  46759. };
  46760. /**
  46761. * @protected
  46762. */
  46763. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  46764. var pointerOption = elOption.pointer;
  46765. if (pointerOption) {
  46766. var pointerEl = inner$6(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  46767. group.add(pointerEl);
  46768. }
  46769. };
  46770. /**
  46771. * @protected
  46772. */
  46773. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  46774. if (elOption.label) {
  46775. var labelEl = inner$6(group).labelEl = new ZRText(clone$3(elOption.label));
  46776. group.add(labelEl);
  46777. updateLabelShowHide(labelEl, axisPointerModel);
  46778. }
  46779. };
  46780. /**
  46781. * @protected
  46782. */
  46783. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  46784. var pointerEl = inner$6(group).pointerEl;
  46785. if (pointerEl && elOption.pointer) {
  46786. pointerEl.setStyle(elOption.pointer.style);
  46787. updateProps(pointerEl, {
  46788. shape: elOption.pointer.shape
  46789. });
  46790. }
  46791. };
  46792. /**
  46793. * @protected
  46794. */
  46795. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  46796. var labelEl = inner$6(group).labelEl;
  46797. if (labelEl) {
  46798. labelEl.setStyle(elOption.label.style);
  46799. updateProps(labelEl, {
  46800. // Consider text length change in vertical axis, animation should
  46801. // be used on shape, otherwise the effect will be weird.
  46802. // TODOTODO
  46803. // shape: elOption.label.shape,
  46804. x: elOption.label.x,
  46805. y: elOption.label.y
  46806. });
  46807. updateLabelShowHide(labelEl, axisPointerModel);
  46808. }
  46809. };
  46810. /**
  46811. * @private
  46812. */
  46813. BaseAxisPointer.prototype._renderHandle = function (value) {
  46814. if (this._dragging || !this.updateHandleTransform) {
  46815. return;
  46816. }
  46817. var axisPointerModel = this._axisPointerModel;
  46818. var zr = this._api.getZr();
  46819. var handle = this._handle;
  46820. var handleModel = axisPointerModel.getModel('handle');
  46821. var status = axisPointerModel.get('status');
  46822. if (!handleModel.get('show') || !status || status === 'hide') {
  46823. handle && zr.remove(handle);
  46824. this._handle = null;
  46825. return;
  46826. }
  46827. var isInit;
  46828. if (!this._handle) {
  46829. isInit = true;
  46830. handle = this._handle = createIcon(handleModel.get('icon'), {
  46831. cursor: 'move',
  46832. draggable: true,
  46833. onmousemove: function (e) {
  46834. // For mobile device, prevent screen slider on the button.
  46835. stop(e.event);
  46836. },
  46837. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  46838. drift: bind$1(this._onHandleDragMove, this),
  46839. ondragend: bind$1(this._onHandleDragEnd, this)
  46840. });
  46841. zr.add(handle);
  46842. }
  46843. updateMandatoryProps(handle, axisPointerModel, false);
  46844. // update style
  46845. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY']));
  46846. // update position
  46847. var handleSize = handleModel.get('size');
  46848. if (!isArray(handleSize)) {
  46849. handleSize = [handleSize, handleSize];
  46850. }
  46851. handle.scaleX = handleSize[0] / 2;
  46852. handle.scaleY = handleSize[1] / 2;
  46853. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  46854. this._moveHandleToValue(value, isInit);
  46855. };
  46856. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  46857. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  46858. };
  46859. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  46860. var handle = this._handle;
  46861. if (!handle) {
  46862. return;
  46863. }
  46864. this._dragging = true;
  46865. // Persistent for throttle.
  46866. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  46867. this._payloadInfo = trans;
  46868. handle.stopAnimation();
  46869. handle.attr(getHandleTransProps(trans));
  46870. inner$6(handle).lastProp = null;
  46871. this._doDispatchAxisPointer();
  46872. };
  46873. /**
  46874. * Throttled method.
  46875. */
  46876. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  46877. var handle = this._handle;
  46878. if (!handle) {
  46879. return;
  46880. }
  46881. var payloadInfo = this._payloadInfo;
  46882. var axisModel = this._axisModel;
  46883. this._api.dispatchAction({
  46884. type: 'updateAxisPointer',
  46885. x: payloadInfo.cursorPoint[0],
  46886. y: payloadInfo.cursorPoint[1],
  46887. tooltipOption: payloadInfo.tooltipOption,
  46888. axesInfo: [{
  46889. axisDim: axisModel.axis.dim,
  46890. axisIndex: axisModel.componentIndex
  46891. }]
  46892. });
  46893. };
  46894. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  46895. this._dragging = false;
  46896. var handle = this._handle;
  46897. if (!handle) {
  46898. return;
  46899. }
  46900. var value = this._axisPointerModel.get('value');
  46901. // Consider snap or categroy axis, handle may be not consistent with
  46902. // axisPointer. So move handle to align the exact value position when
  46903. // drag ended.
  46904. this._moveHandleToValue(value);
  46905. // For the effect: tooltip will be shown when finger holding on handle
  46906. // button, and will be hidden after finger left handle button.
  46907. this._api.dispatchAction({
  46908. type: 'hideTip'
  46909. });
  46910. };
  46911. /**
  46912. * @private
  46913. */
  46914. BaseAxisPointer.prototype.clear = function (api) {
  46915. this._lastValue = null;
  46916. this._lastStatus = null;
  46917. var zr = api.getZr();
  46918. var group = this._group;
  46919. var handle = this._handle;
  46920. if (zr && group) {
  46921. this._lastGraphicKey = null;
  46922. group && zr.remove(group);
  46923. handle && zr.remove(handle);
  46924. this._group = null;
  46925. this._handle = null;
  46926. this._payloadInfo = null;
  46927. }
  46928. clear(this, '_doDispatchAxisPointer');
  46929. };
  46930. /**
  46931. * @protected
  46932. */
  46933. BaseAxisPointer.prototype.doClear = function () {
  46934. // Implemented by sub-class if necessary.
  46935. };
  46936. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  46937. xDimIndex = xDimIndex || 0;
  46938. return {
  46939. x: xy[xDimIndex],
  46940. y: xy[1 - xDimIndex],
  46941. width: wh[xDimIndex],
  46942. height: wh[1 - xDimIndex]
  46943. };
  46944. };
  46945. return BaseAxisPointer;
  46946. }();
  46947. function updateProps$1(animationModel, moveAnimation, el, props) {
  46948. // Animation optimize.
  46949. if (!propsEqual(inner$6(el).lastProp, props)) {
  46950. inner$6(el).lastProp = props;
  46951. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  46952. }
  46953. }
  46954. function propsEqual(lastProps, newProps) {
  46955. if (isObject(lastProps) && isObject(newProps)) {
  46956. var equals_1 = true;
  46957. each(newProps, function (item, key) {
  46958. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  46959. });
  46960. return !!equals_1;
  46961. } else {
  46962. return lastProps === newProps;
  46963. }
  46964. }
  46965. function updateLabelShowHide(labelEl, axisPointerModel) {
  46966. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  46967. }
  46968. function getHandleTransProps(trans) {
  46969. return {
  46970. x: trans.x || 0,
  46971. y: trans.y || 0,
  46972. rotation: trans.rotation || 0
  46973. };
  46974. }
  46975. function updateMandatoryProps(group, axisPointerModel, silent) {
  46976. var z = axisPointerModel.get('z');
  46977. var zlevel = axisPointerModel.get('zlevel');
  46978. group && group.traverse(function (el) {
  46979. if (el.type !== 'group') {
  46980. z != null && (el.z = z);
  46981. zlevel != null && (el.zlevel = zlevel);
  46982. el.silent = silent;
  46983. }
  46984. });
  46985. }
  46986. function buildElStyle(axisPointerModel) {
  46987. var axisPointerType = axisPointerModel.get('type');
  46988. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  46989. var style;
  46990. if (axisPointerType === 'line') {
  46991. style = styleModel.getLineStyle();
  46992. style.fill = null;
  46993. } else if (axisPointerType === 'shadow') {
  46994. style = styleModel.getAreaStyle();
  46995. style.stroke = null;
  46996. }
  46997. return style;
  46998. }
  46999. /**
  47000. * @param {Function} labelPos {align, verticalAlign, position}
  47001. */
  47002. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  47003. var value = axisPointerModel.get('value');
  47004. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  47005. precision: axisPointerModel.get(['label', 'precision']),
  47006. formatter: axisPointerModel.get(['label', 'formatter'])
  47007. });
  47008. var labelModel = axisPointerModel.getModel('label');
  47009. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  47010. var font = labelModel.getFont();
  47011. var textRect = getBoundingRect(text, font);
  47012. var position = labelPos.position;
  47013. var width = textRect.width + paddings[1] + paddings[3];
  47014. var height = textRect.height + paddings[0] + paddings[2];
  47015. // Adjust by align.
  47016. var align = labelPos.align;
  47017. align === 'right' && (position[0] -= width);
  47018. align === 'center' && (position[0] -= width / 2);
  47019. var verticalAlign = labelPos.verticalAlign;
  47020. verticalAlign === 'bottom' && (position[1] -= height);
  47021. verticalAlign === 'middle' && (position[1] -= height / 2);
  47022. // Not overflow ec container
  47023. confineInContainer(position, width, height, api);
  47024. var bgColor = labelModel.get('backgroundColor');
  47025. if (!bgColor || bgColor === 'auto') {
  47026. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  47027. }
  47028. elOption.label = {
  47029. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  47030. x: position[0],
  47031. y: position[1],
  47032. style: createTextStyle(labelModel, {
  47033. text: text,
  47034. font: font,
  47035. fill: labelModel.getTextColor(),
  47036. padding: paddings,
  47037. backgroundColor: bgColor
  47038. }),
  47039. // Label should be over axisPointer.
  47040. z2: 10
  47041. };
  47042. }
  47043. // Do not overflow ec container
  47044. function confineInContainer(position, width, height, api) {
  47045. var viewWidth = api.getWidth();
  47046. var viewHeight = api.getHeight();
  47047. position[0] = Math.min(position[0] + width, viewWidth) - width;
  47048. position[1] = Math.min(position[1] + height, viewHeight) - height;
  47049. position[0] = Math.max(position[0], 0);
  47050. position[1] = Math.max(position[1], 0);
  47051. }
  47052. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  47053. value = axis.scale.parse(value);
  47054. var text = axis.scale.getLabel({
  47055. value: value
  47056. }, {
  47057. // If `precision` is set, width can be fixed (like '12.00500'), which
  47058. // helps to debounce when when moving label.
  47059. precision: opt.precision
  47060. });
  47061. var formatter = opt.formatter;
  47062. if (formatter) {
  47063. var params_1 = {
  47064. value: getAxisRawValue(axis, {
  47065. value: value
  47066. }),
  47067. axisDimension: axis.dim,
  47068. axisIndex: axis.index,
  47069. seriesData: []
  47070. };
  47071. each(seriesDataIndices, function (idxItem) {
  47072. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  47073. var dataIndex = idxItem.dataIndexInside;
  47074. var dataParams = series && series.getDataParams(dataIndex);
  47075. dataParams && params_1.seriesData.push(dataParams);
  47076. });
  47077. if (isString(formatter)) {
  47078. text = formatter.replace('{value}', text);
  47079. } else if (isFunction(formatter)) {
  47080. text = formatter(params_1);
  47081. }
  47082. }
  47083. return text;
  47084. }
  47085. function getTransformedPosition(axis, value, layoutInfo) {
  47086. var transform = create$1();
  47087. rotate(transform, transform, layoutInfo.rotation);
  47088. translate(transform, transform, layoutInfo.position);
  47089. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  47090. }
  47091. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  47092. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  47093. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  47094. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  47095. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  47096. align: textLayout.textAlign,
  47097. verticalAlign: textLayout.textVerticalAlign
  47098. });
  47099. }
  47100. function makeLineShape(p1, p2, xDimIndex) {
  47101. xDimIndex = xDimIndex || 0;
  47102. return {
  47103. x1: p1[xDimIndex],
  47104. y1: p1[1 - xDimIndex],
  47105. x2: p2[xDimIndex],
  47106. y2: p2[1 - xDimIndex]
  47107. };
  47108. }
  47109. function makeRectShape(xy, wh, xDimIndex) {
  47110. xDimIndex = xDimIndex || 0;
  47111. return {
  47112. x: xy[xDimIndex],
  47113. y: xy[1 - xDimIndex],
  47114. width: wh[xDimIndex],
  47115. height: wh[1 - xDimIndex]
  47116. };
  47117. }
  47118. var CartesianAxisPointer = /** @class */function (_super) {
  47119. __extends(CartesianAxisPointer, _super);
  47120. function CartesianAxisPointer() {
  47121. return _super !== null && _super.apply(this, arguments) || this;
  47122. }
  47123. /**
  47124. * @override
  47125. */
  47126. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  47127. var axis = axisModel.axis;
  47128. var grid = axis.grid;
  47129. var axisPointerType = axisPointerModel.get('type');
  47130. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  47131. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  47132. if (axisPointerType && axisPointerType !== 'none') {
  47133. var elStyle = buildElStyle(axisPointerModel);
  47134. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  47135. pointerOption.style = elStyle;
  47136. elOption.graphicKey = pointerOption.type;
  47137. elOption.pointer = pointerOption;
  47138. }
  47139. var layoutInfo = layout$1(grid.getRect(), axisModel);
  47140. buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  47141. };
  47142. /**
  47143. * @override
  47144. */
  47145. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  47146. var layoutInfo = layout$1(axisModel.axis.grid.getRect(), axisModel, {
  47147. labelInside: false
  47148. });
  47149. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  47150. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  47151. return {
  47152. x: pos[0],
  47153. y: pos[1],
  47154. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  47155. };
  47156. };
  47157. /**
  47158. * @override
  47159. */
  47160. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  47161. var axis = axisModel.axis;
  47162. var grid = axis.grid;
  47163. var axisExtent = axis.getGlobalExtent(true);
  47164. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  47165. var dimIndex = axis.dim === 'x' ? 0 : 1;
  47166. var currPosition = [transform.x, transform.y];
  47167. currPosition[dimIndex] += delta[dimIndex];
  47168. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  47169. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  47170. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  47171. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  47172. cursorPoint[dimIndex] = currPosition[dimIndex];
  47173. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  47174. var tooltipOptions = [{
  47175. verticalAlign: 'middle'
  47176. }, {
  47177. align: 'center'
  47178. }];
  47179. return {
  47180. x: currPosition[0],
  47181. y: currPosition[1],
  47182. rotation: transform.rotation,
  47183. cursorPoint: cursorPoint,
  47184. tooltipOption: tooltipOptions[dimIndex]
  47185. };
  47186. };
  47187. return CartesianAxisPointer;
  47188. }(BaseAxisPointer);
  47189. function getCartesian(grid, axis) {
  47190. var opt = {};
  47191. opt[axis.dim + 'AxisIndex'] = axis.index;
  47192. return grid.getCartesian(opt);
  47193. }
  47194. var pointerShapeBuilder = {
  47195. line: function (axis, pixelValue, otherExtent) {
  47196. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  47197. return {
  47198. type: 'Line',
  47199. subPixelOptimize: true,
  47200. shape: targetShape
  47201. };
  47202. },
  47203. shadow: function (axis, pixelValue, otherExtent) {
  47204. var bandWidth = Math.max(1, axis.getBandWidth());
  47205. var span = otherExtent[1] - otherExtent[0];
  47206. return {
  47207. type: 'Rect',
  47208. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  47209. };
  47210. }
  47211. };
  47212. function getAxisDimIndex(axis) {
  47213. return axis.dim === 'x' ? 0 : 1;
  47214. }
  47215. var AxisPointerModel = /** @class */function (_super) {
  47216. __extends(AxisPointerModel, _super);
  47217. function AxisPointerModel() {
  47218. var _this = _super !== null && _super.apply(this, arguments) || this;
  47219. _this.type = AxisPointerModel.type;
  47220. return _this;
  47221. }
  47222. AxisPointerModel.type = 'axisPointer';
  47223. AxisPointerModel.defaultOption = {
  47224. // 'auto' means that show when triggered by tooltip or handle.
  47225. show: 'auto',
  47226. // zlevel: 0,
  47227. z: 50,
  47228. type: 'line',
  47229. // axispointer triggered by tootip determine snap automatically,
  47230. // see `modelHelper`.
  47231. snap: false,
  47232. triggerTooltip: true,
  47233. triggerEmphasis: true,
  47234. value: null,
  47235. status: null,
  47236. link: [],
  47237. // Do not set 'auto' here, otherwise global animation: false
  47238. // will not effect at this axispointer.
  47239. animation: null,
  47240. animationDurationUpdate: 200,
  47241. lineStyle: {
  47242. color: tokens.color.border,
  47243. width: 1,
  47244. type: 'dashed'
  47245. },
  47246. shadowStyle: {
  47247. color: tokens.color.shadowTint
  47248. },
  47249. label: {
  47250. show: true,
  47251. formatter: null,
  47252. precision: 'auto',
  47253. margin: 3,
  47254. color: tokens.color.neutral00,
  47255. padding: [5, 7, 5, 7],
  47256. backgroundColor: tokens.color.accent60,
  47257. borderColor: null,
  47258. borderWidth: 0,
  47259. borderRadius: 3
  47260. },
  47261. handle: {
  47262. show: false,
  47263. // eslint-disable-next-line
  47264. 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',
  47265. size: 45,
  47266. // handle margin is from symbol center to axis, which is stable when circular move.
  47267. margin: 50,
  47268. // color: '#1b8bbd'
  47269. // color: '#2f4554'
  47270. color: tokens.color.accent40,
  47271. // For mobile performance
  47272. throttle: 40
  47273. }
  47274. };
  47275. return AxisPointerModel;
  47276. }(ComponentModel);
  47277. var inner$7 = makeInner();
  47278. var each$3 = each;
  47279. /**
  47280. * @param {string} key
  47281. * @param {module:echarts/ExtensionAPI} api
  47282. * @param {Function} handler
  47283. * param: {string} currTrigger
  47284. * param: {Array.<number>} point
  47285. */
  47286. function register(key, api, handler) {
  47287. if (env.node) {
  47288. return;
  47289. }
  47290. var zr = api.getZr();
  47291. inner$7(zr).records || (inner$7(zr).records = {});
  47292. initGlobalListeners(zr, api);
  47293. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  47294. record.handler = handler;
  47295. }
  47296. function initGlobalListeners(zr, api) {
  47297. if (inner$7(zr).initialized) {
  47298. return;
  47299. }
  47300. inner$7(zr).initialized = true;
  47301. useHandler('click', curry(doEnter, 'click'));
  47302. useHandler('mousemove', curry(doEnter, 'mousemove'));
  47303. // useHandler('mouseout', onLeave);
  47304. useHandler('globalout', onLeave);
  47305. function useHandler(eventType, cb) {
  47306. zr.on(eventType, function (e) {
  47307. var dis = makeDispatchAction(api);
  47308. each$3(inner$7(zr).records, function (record) {
  47309. record && cb(record, e, dis.dispatchAction);
  47310. });
  47311. dispatchTooltipFinally(dis.pendings, api);
  47312. });
  47313. }
  47314. }
  47315. function dispatchTooltipFinally(pendings, api) {
  47316. var showLen = pendings.showTip.length;
  47317. var hideLen = pendings.hideTip.length;
  47318. var actuallyPayload;
  47319. if (showLen) {
  47320. actuallyPayload = pendings.showTip[showLen - 1];
  47321. } else if (hideLen) {
  47322. actuallyPayload = pendings.hideTip[hideLen - 1];
  47323. }
  47324. if (actuallyPayload) {
  47325. actuallyPayload.dispatchAction = null;
  47326. api.dispatchAction(actuallyPayload);
  47327. }
  47328. }
  47329. function onLeave(record, e, dispatchAction) {
  47330. record.handler('leave', null, dispatchAction);
  47331. }
  47332. function doEnter(currTrigger, record, e, dispatchAction) {
  47333. record.handler(currTrigger, e, dispatchAction);
  47334. }
  47335. function makeDispatchAction(api) {
  47336. var pendings = {
  47337. showTip: [],
  47338. hideTip: []
  47339. };
  47340. // FIXME
  47341. // better approach?
  47342. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  47343. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  47344. // So we have to add "final stage" to merge those dispatched actions.
  47345. var dispatchAction = function (payload) {
  47346. var pendingList = pendings[payload.type];
  47347. if (pendingList) {
  47348. pendingList.push(payload);
  47349. } else {
  47350. payload.dispatchAction = dispatchAction;
  47351. api.dispatchAction(payload);
  47352. }
  47353. };
  47354. return {
  47355. dispatchAction: dispatchAction,
  47356. pendings: pendings
  47357. };
  47358. }
  47359. function unregister(key, api) {
  47360. if (env.node) {
  47361. return;
  47362. }
  47363. var zr = api.getZr();
  47364. var record = (inner$7(zr).records || {})[key];
  47365. if (record) {
  47366. inner$7(zr).records[key] = null;
  47367. }
  47368. }
  47369. var AxisPointerView = /** @class */function (_super) {
  47370. __extends(AxisPointerView, _super);
  47371. function AxisPointerView() {
  47372. var _this = _super !== null && _super.apply(this, arguments) || this;
  47373. _this.type = AxisPointerView.type;
  47374. return _this;
  47375. }
  47376. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  47377. var globalTooltipModel = ecModel.getComponent('tooltip');
  47378. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click';
  47379. // Register global listener in AxisPointerView to enable
  47380. // AxisPointerView to be independent to Tooltip.
  47381. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  47382. // If 'none', it is not controlled by mouse totally.
  47383. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  47384. dispatchAction({
  47385. type: 'updateAxisPointer',
  47386. currTrigger: currTrigger,
  47387. x: e && e.offsetX,
  47388. y: e && e.offsetY
  47389. });
  47390. }
  47391. });
  47392. };
  47393. AxisPointerView.prototype.remove = function (ecModel, api) {
  47394. unregister('axisPointer', api);
  47395. };
  47396. AxisPointerView.prototype.dispose = function (ecModel, api) {
  47397. unregister('axisPointer', api);
  47398. };
  47399. AxisPointerView.type = 'axisPointer';
  47400. return AxisPointerView;
  47401. }(ComponentView);
  47402. /**
  47403. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  47404. * @param ecModel
  47405. * @return {point: [x, y], el: ...} point Will not be null.
  47406. */
  47407. function findPointFromSeries(finder, ecModel) {
  47408. var point = [];
  47409. var seriesIndex = finder.seriesIndex;
  47410. var seriesModel;
  47411. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  47412. return {
  47413. point: []
  47414. };
  47415. }
  47416. var data = seriesModel.getData();
  47417. var dataIndex = queryDataIndex(data, finder);
  47418. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  47419. return {
  47420. point: []
  47421. };
  47422. }
  47423. var el = data.getItemGraphicEl(dataIndex);
  47424. var coordSys = seriesModel.coordinateSystem;
  47425. if (seriesModel.getTooltipPosition) {
  47426. point = seriesModel.getTooltipPosition(dataIndex) || [];
  47427. } else if (coordSys && coordSys.dataToPoint) {
  47428. if (finder.isStacked) {
  47429. var baseAxis = coordSys.getBaseAxis();
  47430. var valueAxis = coordSys.getOtherAxis(baseAxis);
  47431. var valueAxisDim = valueAxis.dim;
  47432. var baseAxisDim = baseAxis.dim;
  47433. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  47434. var baseDim = data.mapDimension(baseAxisDim);
  47435. var stackedData = [];
  47436. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  47437. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  47438. point = coordSys.dataToPoint(stackedData) || [];
  47439. } else {
  47440. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  47441. return data.mapDimension(dim);
  47442. }), dataIndex)) || [];
  47443. }
  47444. } else if (el) {
  47445. // Use graphic bounding rect
  47446. var rect = el.getBoundingRect().clone();
  47447. rect.applyTransform(el.transform);
  47448. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  47449. }
  47450. return {
  47451. point: point,
  47452. el: el
  47453. };
  47454. }
  47455. var inner$8 = makeInner();
  47456. /**
  47457. * Basic logic: check all axis, if they do not demand show/highlight,
  47458. * then hide/downplay them.
  47459. *
  47460. * @return content of event obj for echarts.connect.
  47461. */
  47462. function axisTrigger(payload, ecModel, api) {
  47463. var currTrigger = payload.currTrigger;
  47464. var point = [payload.x, payload.y];
  47465. var finder = payload;
  47466. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  47467. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  47468. // Pending
  47469. // See #6121. But we are not able to reproduce it yet.
  47470. if (!coordSysAxesInfo) {
  47471. return;
  47472. }
  47473. if (illegalPoint(point)) {
  47474. // Used in the default behavior of `connection`: use the sample seriesIndex
  47475. // and dataIndex. And also used in the tooltipView trigger.
  47476. point = findPointFromSeries({
  47477. seriesIndex: finder.seriesIndex,
  47478. // Do not use dataIndexInside from other ec instance.
  47479. // FIXME: auto detect it?
  47480. dataIndex: finder.dataIndex
  47481. }, ecModel).point;
  47482. }
  47483. var isIllegalPoint = illegalPoint(point);
  47484. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  47485. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  47486. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  47487. // and dataIndex.
  47488. var inputAxesInfo = finder.axesInfo;
  47489. var axesInfo = coordSysAxesInfo.axesInfo;
  47490. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  47491. var outputPayload = {};
  47492. var showValueMap = {};
  47493. var dataByCoordSys = {
  47494. list: [],
  47495. map: {}
  47496. };
  47497. var updaters = {
  47498. showPointer: curry(showPointer, showValueMap),
  47499. showTooltip: curry(showTooltip, dataByCoordSys)
  47500. };
  47501. // Process for triggered axes.
  47502. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  47503. // If a point given, it must be contained by the coordinate system.
  47504. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  47505. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  47506. var axis = axisInfo.axis;
  47507. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  47508. // If no inputAxesInfo, no axis is restricted.
  47509. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  47510. var val = inputAxisInfo && inputAxisInfo.value;
  47511. if (val == null && !isIllegalPoint) {
  47512. val = axis.pointToData(point);
  47513. }
  47514. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  47515. }
  47516. });
  47517. });
  47518. // Process for linked axes.
  47519. var linkTriggers = {};
  47520. each(axesInfo, function (tarAxisInfo, tarKey) {
  47521. var linkGroup = tarAxisInfo.linkGroup;
  47522. // If axis has been triggered in the previous stage, it should not be triggered by link.
  47523. if (linkGroup && !showValueMap[tarKey]) {
  47524. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  47525. var srcValItem = showValueMap[srcKey];
  47526. // If srcValItem exist, source axis is triggered, so link to target axis.
  47527. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  47528. var val = srcValItem.value;
  47529. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  47530. linkTriggers[tarAxisInfo.key] = val;
  47531. }
  47532. });
  47533. }
  47534. });
  47535. each(linkTriggers, function (val, tarKey) {
  47536. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  47537. });
  47538. updateModelActually(showValueMap, axesInfo, outputPayload);
  47539. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  47540. dispatchHighDownActually(axesInfo, dispatchAction, api);
  47541. return outputPayload;
  47542. }
  47543. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  47544. var axis = axisInfo.axis;
  47545. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  47546. return;
  47547. }
  47548. if (!axisInfo.involveSeries) {
  47549. updaters.showPointer(axisInfo, newValue);
  47550. return;
  47551. }
  47552. // Heavy calculation. So put it after axis.containData checking.
  47553. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  47554. var payloadBatch = payloadInfo.payloadBatch;
  47555. var snapToValue = payloadInfo.snapToValue;
  47556. // Fill content of event obj for echarts.connect.
  47557. // By default use the first involved series data as a sample to connect.
  47558. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  47559. extend(outputFinder, payloadBatch[0]);
  47560. }
  47561. // If no linkSource input, this process is for collecting link
  47562. // target, where snap should not be accepted.
  47563. if (!noSnap && axisInfo.snap) {
  47564. if (axis.containData(snapToValue) && snapToValue != null) {
  47565. newValue = snapToValue;
  47566. }
  47567. }
  47568. updaters.showPointer(axisInfo, newValue, payloadBatch);
  47569. // Tooltip should always be snapToValue, otherwise there will be
  47570. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  47571. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  47572. }
  47573. function buildPayloadsBySeries(value, axisInfo) {
  47574. var axis = axisInfo.axis;
  47575. var dim = axis.dim;
  47576. var snapToValue = value;
  47577. var payloadBatch = [];
  47578. var minDist = Number.MAX_VALUE;
  47579. var minDiff = -1;
  47580. each(axisInfo.seriesModels, function (series, idx) {
  47581. var dataDim = series.getData().mapDimensionsAll(dim);
  47582. var seriesNestestValue;
  47583. var dataIndices;
  47584. if (series.getAxisTooltipData) {
  47585. var result = series.getAxisTooltipData(dataDim, value, axis);
  47586. dataIndices = result.dataIndices;
  47587. seriesNestestValue = result.nestestValue;
  47588. } else {
  47589. dataIndices = series.indicesOfNearest(dim, dataDim[0], value,
  47590. // Add a threshold to avoid find the wrong dataIndex
  47591. // when data length is not same.
  47592. // false,
  47593. axis.type === 'category' ? 0.5 : null);
  47594. if (!dataIndices.length) {
  47595. return;
  47596. }
  47597. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  47598. }
  47599. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  47600. return;
  47601. }
  47602. var diff = value - seriesNestestValue;
  47603. var dist = Math.abs(diff);
  47604. // Consider category case
  47605. if (dist <= minDist) {
  47606. if (dist < minDist || diff >= 0 && minDiff < 0) {
  47607. minDist = dist;
  47608. minDiff = diff;
  47609. snapToValue = seriesNestestValue;
  47610. payloadBatch.length = 0;
  47611. }
  47612. each(dataIndices, function (dataIndex) {
  47613. payloadBatch.push({
  47614. seriesIndex: series.seriesIndex,
  47615. dataIndexInside: dataIndex,
  47616. dataIndex: series.getData().getRawIndex(dataIndex)
  47617. });
  47618. });
  47619. }
  47620. });
  47621. return {
  47622. payloadBatch: payloadBatch,
  47623. snapToValue: snapToValue
  47624. };
  47625. }
  47626. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  47627. showValueMap[axisInfo.key] = {
  47628. value: value,
  47629. payloadBatch: payloadBatch
  47630. };
  47631. }
  47632. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  47633. var payloadBatch = payloadInfo.payloadBatch;
  47634. var axis = axisInfo.axis;
  47635. var axisModel = axis.model;
  47636. var axisPointerModel = axisInfo.axisPointerModel;
  47637. // If no data, do not create anything in dataByCoordSys,
  47638. // whose length will be used to judge whether dispatch action.
  47639. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  47640. return;
  47641. }
  47642. var coordSysModel = axisInfo.coordSys.model;
  47643. var coordSysKey = makeKey(coordSysModel);
  47644. var coordSysItem = dataByCoordSys.map[coordSysKey];
  47645. if (!coordSysItem) {
  47646. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  47647. coordSysId: coordSysModel.id,
  47648. coordSysIndex: coordSysModel.componentIndex,
  47649. coordSysType: coordSysModel.type,
  47650. coordSysMainType: coordSysModel.mainType,
  47651. dataByAxis: []
  47652. };
  47653. dataByCoordSys.list.push(coordSysItem);
  47654. }
  47655. coordSysItem.dataByAxis.push({
  47656. axisDim: axis.dim,
  47657. axisIndex: axisModel.componentIndex,
  47658. axisType: axisModel.type,
  47659. axisId: axisModel.id,
  47660. value: value,
  47661. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  47662. // depends that all models have been updated. So it should not be performed
  47663. // here. Considering axisPointerModel used here is volatile, which is hard
  47664. // to be retrieve in TooltipView, we prepare parameters here.
  47665. valueLabelOpt: {
  47666. precision: axisPointerModel.get(['label', 'precision']),
  47667. formatter: axisPointerModel.get(['label', 'formatter'])
  47668. },
  47669. seriesDataIndices: payloadBatch.slice()
  47670. });
  47671. }
  47672. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  47673. var outputAxesInfo = outputPayload.axesInfo = [];
  47674. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  47675. each(axesInfo, function (axisInfo, key) {
  47676. var option = axisInfo.axisPointerModel.option;
  47677. var valItem = showValueMap[key];
  47678. if (valItem) {
  47679. !axisInfo.useHandle && (option.status = 'show');
  47680. option.value = valItem.value;
  47681. // For label formatter param and highlight.
  47682. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  47683. }
  47684. // When always show (e.g., handle used), remain
  47685. // original value and status.
  47686. else {
  47687. // If hide, value still need to be set, consider
  47688. // click legend to toggle axis blank.
  47689. !axisInfo.useHandle && (option.status = 'hide');
  47690. }
  47691. // If status is 'hide', should be no info in payload.
  47692. option.status === 'show' && outputAxesInfo.push({
  47693. axisDim: axisInfo.axis.dim,
  47694. axisIndex: axisInfo.axis.model.componentIndex,
  47695. value: option.value
  47696. });
  47697. });
  47698. }
  47699. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  47700. // Basic logic: If no showTip required, hideTip will be dispatched.
  47701. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  47702. dispatchAction({
  47703. type: 'hideTip'
  47704. });
  47705. return;
  47706. }
  47707. // In most case only one axis (or event one series is used). It is
  47708. // convenient to fetch payload.seriesIndex and payload.dataIndex
  47709. // directly. So put the first seriesIndex and dataIndex of the first
  47710. // axis on the payload.
  47711. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  47712. dispatchAction({
  47713. type: 'showTip',
  47714. escapeConnect: true,
  47715. x: point[0],
  47716. y: point[1],
  47717. tooltipOption: payload.tooltipOption,
  47718. position: payload.position,
  47719. dataIndexInside: sampleItem.dataIndexInside,
  47720. dataIndex: sampleItem.dataIndex,
  47721. seriesIndex: sampleItem.seriesIndex,
  47722. dataByCoordSys: dataByCoordSys.list
  47723. });
  47724. }
  47725. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  47726. // FIXME
  47727. // highlight status modification should be a stage of main process?
  47728. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  47729. var zr = api.getZr();
  47730. var highDownKey = 'axisPointerLastHighlights';
  47731. var lastHighlights = inner$8(zr)[highDownKey] || {};
  47732. var newHighlights = inner$8(zr)[highDownKey] = {};
  47733. // Update highlight/downplay status according to axisPointer model.
  47734. // Build hash map and remove duplicate incidentally.
  47735. each(axesInfo, function (axisInfo, key) {
  47736. var option = axisInfo.axisPointerModel.option;
  47737. option.status === 'show' && axisInfo.triggerEmphasis && each(option.seriesDataIndices, function (batchItem) {
  47738. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  47739. newHighlights[key] = batchItem;
  47740. });
  47741. });
  47742. // Diff.
  47743. var toHighlight = [];
  47744. var toDownplay = [];
  47745. each(lastHighlights, function (batchItem, key) {
  47746. !newHighlights[key] && toDownplay.push(batchItem);
  47747. });
  47748. each(newHighlights, function (batchItem, key) {
  47749. !lastHighlights[key] && toHighlight.push(batchItem);
  47750. });
  47751. toDownplay.length && api.dispatchAction({
  47752. type: 'downplay',
  47753. escapeConnect: true,
  47754. // Not blur others when highlight in axisPointer.
  47755. notBlur: true,
  47756. batch: toDownplay
  47757. });
  47758. toHighlight.length && api.dispatchAction({
  47759. type: 'highlight',
  47760. escapeConnect: true,
  47761. // Not blur others when highlight in axisPointer.
  47762. notBlur: true,
  47763. batch: toHighlight
  47764. });
  47765. }
  47766. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  47767. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  47768. var inputAxisInfo = inputAxesInfo[i];
  47769. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  47770. return inputAxisInfo;
  47771. }
  47772. }
  47773. }
  47774. function makeMapperParam(axisInfo) {
  47775. var axisModel = axisInfo.axis.model;
  47776. var item = {};
  47777. var dim = item.axisDim = axisInfo.axis.dim;
  47778. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  47779. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  47780. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  47781. return item;
  47782. }
  47783. function illegalPoint(point) {
  47784. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  47785. }
  47786. function install$7(registers) {
  47787. // CartesianAxisPointer is not supposed to be required here. But consider
  47788. // echarts.simple.js and online build tooltip, which only require gridSimple,
  47789. // CartesianAxisPointer should be able to required somewhere.
  47790. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  47791. registers.registerComponentModel(AxisPointerModel);
  47792. registers.registerComponentView(AxisPointerView);
  47793. registers.registerPreprocessor(function (option) {
  47794. // Always has a global axisPointerModel for default setting.
  47795. if (option) {
  47796. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  47797. var link = option.axisPointer.link;
  47798. // Normalize to array to avoid object mergin. But if link
  47799. // is not set, remain null/undefined, otherwise it will
  47800. // override existent link setting.
  47801. if (link && !isArray(link)) {
  47802. option.axisPointer.link = [link];
  47803. }
  47804. }
  47805. });
  47806. // This process should proformed after coordinate systems created
  47807. // and series data processed. So put it on statistic processing stage.
  47808. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  47809. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  47810. // allAxesInfo should be updated when setOption performed.
  47811. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  47812. });
  47813. // Broadcast to all views.
  47814. registers.registerAction({
  47815. type: 'updateAxisPointer',
  47816. event: 'updateAxisPointer',
  47817. update: ':updateAxisPointer'
  47818. }, axisTrigger);
  47819. }
  47820. function install$8(registers) {
  47821. use(install$5);
  47822. use(install$7);
  47823. }
  47824. function setKeyInfoToNewElOption(resultItem, newElOption) {
  47825. var existElOption = resultItem.existing;
  47826. // Set id and type after id assigned.
  47827. newElOption.id = resultItem.keyInfo.id;
  47828. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  47829. // Set parent id if not specified
  47830. if (newElOption.parentId == null) {
  47831. var newElParentOption = newElOption.parentOption;
  47832. if (newElParentOption) {
  47833. newElOption.parentId = newElParentOption.id;
  47834. } else if (existElOption) {
  47835. newElOption.parentId = existElOption.parentId;
  47836. }
  47837. }
  47838. // Clear
  47839. newElOption.parentOption = null;
  47840. }
  47841. function isSetLoc(obj, props) {
  47842. var isSet;
  47843. each(props, function (prop) {
  47844. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  47845. });
  47846. return isSet;
  47847. }
  47848. function mergeNewElOptionToExist(existList, index, newElOption) {
  47849. // Update existing options, for `getOption` feature.
  47850. var newElOptCopy = extend({}, newElOption);
  47851. var existElOption = existList[index];
  47852. var $action = newElOption.$action || 'merge';
  47853. if ($action === 'merge') {
  47854. if (existElOption) {
  47855. if ("development" !== 'production') {
  47856. var newType = newElOption.type;
  47857. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  47858. }
  47859. // We can ensure that newElOptCopy and existElOption are not
  47860. // the same object, so `merge` will not change newElOptCopy.
  47861. merge(existElOption, newElOptCopy, true);
  47862. // Rigid body, use ignoreSize.
  47863. mergeLayoutParam(existElOption, newElOptCopy, {
  47864. ignoreSize: true
  47865. });
  47866. // Will be used in render.
  47867. copyLayoutParams(newElOption, existElOption);
  47868. // Copy transition info to new option so it can be used in the transition.
  47869. // DO IT AFTER merge
  47870. copyTransitionInfo(newElOption, existElOption);
  47871. copyTransitionInfo(newElOption, existElOption, 'shape');
  47872. copyTransitionInfo(newElOption, existElOption, 'style');
  47873. copyTransitionInfo(newElOption, existElOption, 'extra');
  47874. // Copy clipPath
  47875. newElOption.clipPath = existElOption.clipPath;
  47876. } else {
  47877. existList[index] = newElOptCopy;
  47878. }
  47879. } else if ($action === 'replace') {
  47880. existList[index] = newElOptCopy;
  47881. } else if ($action === 'remove') {
  47882. // null will be cleaned later.
  47883. existElOption && (existList[index] = null);
  47884. }
  47885. }
  47886. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  47887. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  47888. function copyTransitionInfo(target, source, targetProp) {
  47889. if (targetProp) {
  47890. if (!target[targetProp] && source[targetProp]) {
  47891. // TODO avoid creating this empty object when there is no transition configuration.
  47892. target[targetProp] = {};
  47893. }
  47894. target = target[targetProp];
  47895. source = source[targetProp];
  47896. }
  47897. if (!target || !source) {
  47898. return;
  47899. }
  47900. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  47901. for (var i = 0; i < props.length; i++) {
  47902. var prop = props[i];
  47903. if (target[prop] == null && source[prop] != null) {
  47904. target[prop] = source[prop];
  47905. }
  47906. }
  47907. }
  47908. function setLayoutInfoToExist(existItem, newElOption) {
  47909. if (!existItem) {
  47910. return;
  47911. }
  47912. existItem.hv = newElOption.hv = [
  47913. // Rigid body, don't care about `width`.
  47914. isSetLoc(newElOption, ['left', 'right']),
  47915. // Rigid body, don't care about `height`.
  47916. isSetLoc(newElOption, ['top', 'bottom'])];
  47917. // Give default group size. Otherwise layout error may occur.
  47918. if (existItem.type === 'group') {
  47919. var existingGroupOpt = existItem;
  47920. var newGroupOpt = newElOption;
  47921. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  47922. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  47923. }
  47924. }
  47925. var GraphicComponentModel = /** @class */function (_super) {
  47926. __extends(GraphicComponentModel, _super);
  47927. function GraphicComponentModel() {
  47928. var _this = _super !== null && _super.apply(this, arguments) || this;
  47929. _this.type = GraphicComponentModel.type;
  47930. _this.preventAutoZ = true;
  47931. return _this;
  47932. }
  47933. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  47934. // Prevent default merge to elements
  47935. var elements = this.option.elements;
  47936. this.option.elements = null;
  47937. _super.prototype.mergeOption.call(this, option, ecModel);
  47938. this.option.elements = elements;
  47939. };
  47940. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  47941. var thisOption = this.option;
  47942. var newList = (isInit ? thisOption : newOption).elements;
  47943. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  47944. var flattenedList = [];
  47945. this._flatten(newList, flattenedList, null);
  47946. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge');
  47947. // Clear elOptionsToUpdate
  47948. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  47949. each(mappingResult, function (resultItem, index) {
  47950. var newElOption = resultItem.newOption;
  47951. if ("development" !== 'production') {
  47952. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  47953. }
  47954. if (!newElOption) {
  47955. return;
  47956. }
  47957. elOptionsToUpdate.push(newElOption);
  47958. setKeyInfoToNewElOption(resultItem, newElOption);
  47959. mergeNewElOptionToExist(existList, index, newElOption);
  47960. setLayoutInfoToExist(existList[index], newElOption);
  47961. }, this);
  47962. // Clean
  47963. thisOption.elements = filter(existList, function (item) {
  47964. // $action should be volatile, otherwise option gotten from
  47965. // `getOption` will contain unexpected $action.
  47966. item && delete item.$action;
  47967. return item != null;
  47968. });
  47969. };
  47970. /**
  47971. * Convert
  47972. * [{
  47973. * type: 'group',
  47974. * id: 'xx',
  47975. * children: [{type: 'circle'}, {type: 'polygon'}]
  47976. * }]
  47977. * to
  47978. * [
  47979. * {type: 'group', id: 'xx'},
  47980. * {type: 'circle', parentId: 'xx'},
  47981. * {type: 'polygon', parentId: 'xx'}
  47982. * ]
  47983. */
  47984. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  47985. each(optionList, function (option) {
  47986. if (!option) {
  47987. return;
  47988. }
  47989. if (parentOption) {
  47990. option.parentOption = parentOption;
  47991. }
  47992. result.push(option);
  47993. var children = option.children;
  47994. // here we don't judge if option.type is `group`
  47995. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  47996. if (children && children.length) {
  47997. this._flatten(children, result, option);
  47998. }
  47999. // Deleting for JSON output, and for not affecting group creation.
  48000. delete option.children;
  48001. }, this);
  48002. };
  48003. // FIXME
  48004. // Pass to view using payload? setOption has a payload?
  48005. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  48006. var els = this._elOptionsToUpdate;
  48007. // Clear to avoid render duplicately when zooming.
  48008. this._elOptionsToUpdate = null;
  48009. return els;
  48010. };
  48011. GraphicComponentModel.type = 'graphic';
  48012. GraphicComponentModel.defaultOption = {
  48013. elements: []
  48014. // parentId: null
  48015. };
  48016. return GraphicComponentModel;
  48017. }(ComponentModel);
  48018. /**
  48019. * Whether need to call `convertEC4CompatibleStyle`.
  48020. */
  48021. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  48022. // Since echarts5, `RectText` is separated from its host element and style.text
  48023. // does not exist any more. The compat work brings some extra burden on performance.
  48024. // So we provide:
  48025. // `legacy: true` force make compat.
  48026. // `legacy: false`, force do not compat.
  48027. // `legacy` not set: auto detect whether legacy.
  48028. // But in this case we do not compat (difficult to detect and rare case):
  48029. // Because custom series and graphic component support "merge", users may firstly
  48030. // only set `textStrokeWidth` style or secondly only set `text`.
  48031. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan'
  48032. // Difficult to detect whether legacy for a "text" el.
  48033. && (elType === 'text' || hasOwn(style, 'text')));
  48034. }
  48035. /**
  48036. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  48037. * @param hostStyle The properties might be modified.
  48038. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  48039. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  48040. * retried from the `hostStyle`.
  48041. */
  48042. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  48043. var srcStyle = hostStyle;
  48044. var textConfig;
  48045. var textContent;
  48046. var textContentStyle;
  48047. if (elType === 'text') {
  48048. textContentStyle = srcStyle;
  48049. } else {
  48050. textContentStyle = {};
  48051. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  48052. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  48053. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  48054. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  48055. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  48056. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  48057. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  48058. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  48059. textContent = {
  48060. type: 'text',
  48061. style: textContentStyle,
  48062. // ec4 does not support rectText trigger.
  48063. // And when text position is different in normal and emphasis
  48064. // => hover text trigger emphasis;
  48065. // => text position changed, leave mouse pointer immediately;
  48066. // That might cause incorrect state.
  48067. silent: true
  48068. };
  48069. textConfig = {};
  48070. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  48071. if (isNormal) {
  48072. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  48073. } else {
  48074. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  48075. }
  48076. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  48077. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  48078. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  48079. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  48080. }
  48081. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  48082. each(textContentStyle.rich, function (richItem) {
  48083. convertEC4CompatibleRichItem(richItem, richItem);
  48084. });
  48085. return {
  48086. textConfig: textConfig,
  48087. textContent: textContent
  48088. };
  48089. }
  48090. /**
  48091. * The result will be set to `out`.
  48092. */
  48093. function convertEC4CompatibleRichItem(out, richItem) {
  48094. if (!richItem) {
  48095. return;
  48096. }
  48097. // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  48098. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  48099. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  48100. // richText in ec5.
  48101. // (2) `out === richItem` if and only if `out` is text el or rich item.
  48102. // So we can overwrite existing props in `out` since textXXX has higher priority.
  48103. richItem.font = richItem.textFont || richItem.font;
  48104. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  48105. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  48106. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  48107. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  48108. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  48109. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  48110. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  48111. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  48112. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  48113. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  48114. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  48115. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  48116. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  48117. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  48118. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  48119. }
  48120. var LEGACY_TRANSFORM_PROPS_MAP = {
  48121. position: ['x', 'y'],
  48122. scale: ['scaleX', 'scaleY'],
  48123. origin: ['originX', 'originY']
  48124. };
  48125. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  48126. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  48127. obj[key] = 1;
  48128. return obj;
  48129. }, {});
  48130. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', ');
  48131. // '' means root
  48132. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  48133. var transitionInnerStore = makeInner();
  48134. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  48135. var animationProp = animationType + "Animation";
  48136. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  48137. var userDuring = transitionInnerStore(el).userDuring;
  48138. // Only set when duration is > 0 and it's need to be animated.
  48139. if (config.duration > 0) {
  48140. // For simplicity, if during not specified, the previous during will not work any more.
  48141. config.during = userDuring ? bind(duringCall, {
  48142. el: el,
  48143. userDuring: userDuring
  48144. }) : null;
  48145. config.setToFinal = true;
  48146. config.scope = animationType;
  48147. }
  48148. extend(config, elOption[animationProp]);
  48149. return config;
  48150. }
  48151. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  48152. opts = opts || {};
  48153. var dataIndex = opts.dataIndex,
  48154. isInit = opts.isInit,
  48155. clearStyle = opts.clearStyle;
  48156. var hasAnimation = animatableModel.isAnimationEnabled();
  48157. // Save the meta info for further morphing. Like apply on the sub morphing elements.
  48158. var store = transitionInnerStore(el);
  48159. var styleOpt = elOption.style;
  48160. store.userDuring = elOption.during;
  48161. var transFromProps = {};
  48162. var propsToSet = {};
  48163. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  48164. if (el.type === 'compound') {
  48165. /**
  48166. * We cannot directly clone shape for compoundPath,
  48167. * because it makes the path to be an object instead of a Path instance,
  48168. * and thus missing `buildPath` method.
  48169. */
  48170. var paths = el.shape.paths;
  48171. var optionPaths = elOption.shape.paths;
  48172. for (var i = 0; i < optionPaths.length; i++) {
  48173. var path = optionPaths[i];
  48174. prepareShapeOrExtraAllPropsFinal('shape', path, paths[i]);
  48175. }
  48176. } else {
  48177. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  48178. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  48179. }
  48180. if (!isInit && hasAnimation) {
  48181. prepareTransformTransitionFrom(el, elOption, transFromProps);
  48182. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  48183. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  48184. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  48185. }
  48186. propsToSet.style = styleOpt;
  48187. applyPropsDirectly(el, propsToSet, clearStyle);
  48188. applyMiscProps(el, elOption);
  48189. if (hasAnimation) {
  48190. if (isInit) {
  48191. var enterFromProps_1 = {};
  48192. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  48193. var prop = propName ? elOption[propName] : elOption;
  48194. if (prop && prop.enterFrom) {
  48195. if (propName) {
  48196. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  48197. }
  48198. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  48199. }
  48200. });
  48201. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  48202. if (config.duration > 0) {
  48203. el.animateFrom(enterFromProps_1, config);
  48204. }
  48205. } else {
  48206. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  48207. }
  48208. }
  48209. // Store leave to be used in leave transition.
  48210. updateLeaveTo(el, elOption);
  48211. styleOpt ? el.dirty() : el.markRedraw();
  48212. }
  48213. function updateLeaveTo(el, elOption) {
  48214. // Try merge to previous set leaveTo
  48215. var leaveToProps = transitionInnerStore(el).leaveToProps;
  48216. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  48217. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  48218. var prop = propName ? elOption[propName] : elOption;
  48219. if (prop && prop.leaveTo) {
  48220. if (!leaveToProps) {
  48221. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  48222. }
  48223. if (propName) {
  48224. leaveToProps[propName] = leaveToProps[propName] || {};
  48225. }
  48226. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  48227. }
  48228. }
  48229. }
  48230. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  48231. if (el) {
  48232. var parent_1 = el.parent;
  48233. var leaveToProps = transitionInnerStore(el).leaveToProps;
  48234. if (leaveToProps) {
  48235. // TODO TODO use leave after leaveAnimation in series is introduced
  48236. // TODO Data index?
  48237. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  48238. config.done = function () {
  48239. parent_1 && parent_1.remove(el);
  48240. onRemove && onRemove();
  48241. };
  48242. el.animateTo(leaveToProps, config);
  48243. } else {
  48244. parent_1 && parent_1.remove(el);
  48245. onRemove && onRemove();
  48246. }
  48247. }
  48248. }
  48249. function isTransitionAll(transition) {
  48250. return transition === 'all';
  48251. }
  48252. function applyPropsDirectly(el,
  48253. // Can be null/undefined
  48254. allPropsFinal, clearStyle) {
  48255. var styleOpt = allPropsFinal.style;
  48256. if (!el.isGroup && styleOpt) {
  48257. if (clearStyle) {
  48258. el.useStyle({});
  48259. // When style object changed, how to trade the existing animation?
  48260. // It is probably complicated and not needed to cover all the cases.
  48261. // But still need consider the case:
  48262. // (1) When using init animation on `style.opacity`, and before the animation
  48263. // ended users triggers an update by mousewhel. At that time the init
  48264. // animation should better be continued rather than terminated.
  48265. // So after `useStyle` called, we should change the animation target manually
  48266. // to continue the effect of the init animation.
  48267. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  48268. // to update the value to `val2` and no animation declared, should be terminate
  48269. // the previous animation or just modify the target of the animation?
  48270. // Therotically That will happen not only on `style` but also on `shape` and
  48271. // `transfrom` props. But we haven't handle this case at present yet.
  48272. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  48273. var animators = el.animators;
  48274. for (var i = 0; i < animators.length; i++) {
  48275. var animator = animators[i];
  48276. // targetName is the "topKey".
  48277. if (animator.targetName === 'style') {
  48278. animator.changeTarget(el.style);
  48279. }
  48280. }
  48281. }
  48282. el.setStyle(styleOpt);
  48283. }
  48284. if (allPropsFinal) {
  48285. // Not set style here.
  48286. allPropsFinal.style = null;
  48287. // Set el to the final state firstly.
  48288. allPropsFinal && el.attr(allPropsFinal);
  48289. allPropsFinal.style = styleOpt;
  48290. }
  48291. }
  48292. function applyPropsTransition(el, elOption, dataIndex, model,
  48293. // Can be null/undefined
  48294. transFromProps) {
  48295. if (transFromProps) {
  48296. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  48297. if (config.duration > 0) {
  48298. el.animateFrom(transFromProps, config);
  48299. }
  48300. }
  48301. }
  48302. function applyMiscProps(el, elOption) {
  48303. // Merge by default.
  48304. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  48305. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  48306. if (el instanceof Displayable) {
  48307. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  48308. }
  48309. if (el instanceof Path) {
  48310. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  48311. }
  48312. }
  48313. // Use it to avoid it be exposed to user.
  48314. var tmpDuringScope = {};
  48315. var transitionDuringAPI = {
  48316. // Usually other props do not need to be changed in animation during.
  48317. setTransform: function (key, val) {
  48318. if ("development" !== 'production') {
  48319. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  48320. }
  48321. tmpDuringScope.el[key] = val;
  48322. return this;
  48323. },
  48324. getTransform: function (key) {
  48325. if ("development" !== 'production') {
  48326. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  48327. }
  48328. return tmpDuringScope.el[key];
  48329. },
  48330. setShape: function (key, val) {
  48331. if ("development" !== 'production') {
  48332. assertNotReserved(key);
  48333. }
  48334. var el = tmpDuringScope.el;
  48335. var shape = el.shape || (el.shape = {});
  48336. shape[key] = val;
  48337. el.dirtyShape && el.dirtyShape();
  48338. return this;
  48339. },
  48340. getShape: function (key) {
  48341. if ("development" !== 'production') {
  48342. assertNotReserved(key);
  48343. }
  48344. var shape = tmpDuringScope.el.shape;
  48345. if (shape) {
  48346. return shape[key];
  48347. }
  48348. },
  48349. setStyle: function (key, val) {
  48350. if ("development" !== 'production') {
  48351. assertNotReserved(key);
  48352. }
  48353. var el = tmpDuringScope.el;
  48354. var style = el.style;
  48355. if (style) {
  48356. if ("development" !== 'production') {
  48357. if (eqNaN(val)) {
  48358. warn('style.' + key + ' must not be assigned with NaN.');
  48359. }
  48360. }
  48361. style[key] = val;
  48362. el.dirtyStyle && el.dirtyStyle();
  48363. }
  48364. return this;
  48365. },
  48366. getStyle: function (key) {
  48367. if ("development" !== 'production') {
  48368. assertNotReserved(key);
  48369. }
  48370. var style = tmpDuringScope.el.style;
  48371. if (style) {
  48372. return style[key];
  48373. }
  48374. },
  48375. setExtra: function (key, val) {
  48376. if ("development" !== 'production') {
  48377. assertNotReserved(key);
  48378. }
  48379. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  48380. extra[key] = val;
  48381. return this;
  48382. },
  48383. getExtra: function (key) {
  48384. if ("development" !== 'production') {
  48385. assertNotReserved(key);
  48386. }
  48387. var extra = tmpDuringScope.el.extra;
  48388. if (extra) {
  48389. return extra[key];
  48390. }
  48391. }
  48392. };
  48393. function assertNotReserved(key) {
  48394. if ("development" !== 'production') {
  48395. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  48396. throw new Error('key must not be "' + key + '"');
  48397. }
  48398. }
  48399. }
  48400. function duringCall() {
  48401. // Do not provide "percent" until some requirements come.
  48402. // Because consider thies case:
  48403. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  48404. // And enter duration is different from update duration.
  48405. // Thus it might be confused about the meaning of "percent" in during callback.
  48406. var scope = this;
  48407. var el = scope.el;
  48408. if (!el) {
  48409. return;
  48410. }
  48411. // If el is remove from zr by reason like legend, during still need to called,
  48412. // because el will be added back to zr and the prop value should not be incorrect.
  48413. var latestUserDuring = transitionInnerStore(el).userDuring;
  48414. var scopeUserDuring = scope.userDuring;
  48415. // Ensured a during is only called once in each animation frame.
  48416. // If a during is called multiple times in one frame, maybe some users' calculation logic
  48417. // might be wrong (not sure whether this usage exists).
  48418. // The case of a during might be called twice can be: by default there is a animator for
  48419. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  48420. // another animators for 'style'/'shape'/'extra'.
  48421. if (latestUserDuring !== scopeUserDuring) {
  48422. // release
  48423. scope.el = scope.userDuring = null;
  48424. return;
  48425. }
  48426. tmpDuringScope.el = el;
  48427. // Give no `this` to user in "during" calling.
  48428. scopeUserDuring(transitionDuringAPI);
  48429. // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  48430. // consider the issue that the prop might be incorrect when return to "normal" state.
  48431. }
  48432. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  48433. var attrOpt = elOption[mainAttr];
  48434. if (!attrOpt) {
  48435. return;
  48436. }
  48437. var elPropsInAttr = fromEl[mainAttr];
  48438. var transFromPropsInAttr;
  48439. if (elPropsInAttr) {
  48440. var transition = elOption.transition;
  48441. var attrTransition = attrOpt.transition;
  48442. if (attrTransition) {
  48443. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  48444. if (isTransitionAll(attrTransition)) {
  48445. extend(transFromPropsInAttr, elPropsInAttr);
  48446. } else {
  48447. var transitionKeys = normalizeToArray(attrTransition);
  48448. for (var i = 0; i < transitionKeys.length; i++) {
  48449. var key = transitionKeys[i];
  48450. var elVal = elPropsInAttr[key];
  48451. transFromPropsInAttr[key] = elVal;
  48452. }
  48453. }
  48454. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  48455. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  48456. var elPropsInAttrKeys = keys(elPropsInAttr);
  48457. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  48458. var key = elPropsInAttrKeys[i];
  48459. var elVal = elPropsInAttr[key];
  48460. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  48461. transFromPropsInAttr[key] = elVal;
  48462. }
  48463. }
  48464. }
  48465. }
  48466. }
  48467. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  48468. var attrOpt = elOption[mainAttr];
  48469. if (!attrOpt) {
  48470. return;
  48471. }
  48472. var allPropsInAttr = allProps[mainAttr] = {};
  48473. var keysInAttr = keys(attrOpt);
  48474. for (var i = 0; i < keysInAttr.length; i++) {
  48475. var key = keysInAttr[i];
  48476. // To avoid share one object with different element, and
  48477. // to avoid user modify the object inexpectedly, have to clone.
  48478. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  48479. }
  48480. }
  48481. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  48482. var transition = elOption.transition;
  48483. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  48484. for (var i = 0; i < transitionKeys.length; i++) {
  48485. var key = transitionKeys[i];
  48486. if (key === 'style' || key === 'shape' || key === 'extra') {
  48487. continue;
  48488. }
  48489. var elVal = el[key];
  48490. if ("development" !== 'production') {
  48491. checkTransformPropRefer(key, 'el.transition');
  48492. }
  48493. // Do not clone, animator will perform that clone.
  48494. transFromProps[key] = elVal;
  48495. }
  48496. }
  48497. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  48498. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  48499. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  48500. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  48501. var legacyArr = elOption[legacyName];
  48502. if (legacyArr) {
  48503. allProps[xyName[0]] = legacyArr[0];
  48504. allProps[xyName[1]] = legacyArr[1];
  48505. }
  48506. }
  48507. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  48508. var key = TRANSFORMABLE_PROPS[i];
  48509. if (elOption[key] != null) {
  48510. allProps[key] = elOption[key];
  48511. }
  48512. }
  48513. }
  48514. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  48515. if (!styleOpt) {
  48516. return;
  48517. }
  48518. var fromElStyle = fromEl.style;
  48519. var transFromStyleProps;
  48520. if (fromElStyle) {
  48521. var styleTransition = styleOpt.transition;
  48522. var elTransition = elOption.transition;
  48523. if (styleTransition && !isTransitionAll(styleTransition)) {
  48524. var transitionKeys = normalizeToArray(styleTransition);
  48525. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  48526. for (var i = 0; i < transitionKeys.length; i++) {
  48527. var key = transitionKeys[i];
  48528. var elVal = fromElStyle[key];
  48529. // Do not clone, see `checkNonStyleTansitionRefer`.
  48530. transFromStyleProps[key] = elVal;
  48531. }
  48532. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  48533. var animationProps = fromEl.getAnimationStyleProps();
  48534. var animationStyleProps = animationProps ? animationProps.style : null;
  48535. if (animationStyleProps) {
  48536. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  48537. var styleKeys = keys(styleOpt);
  48538. for (var i = 0; i < styleKeys.length; i++) {
  48539. var key = styleKeys[i];
  48540. if (animationStyleProps[key]) {
  48541. var elVal = fromElStyle[key];
  48542. transFromStyleProps[key] = elVal;
  48543. }
  48544. }
  48545. }
  48546. }
  48547. }
  48548. }
  48549. function isNonStyleTransitionEnabled(optVal, elVal) {
  48550. // The same as `checkNonStyleTansitionRefer`.
  48551. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  48552. }
  48553. var checkTransformPropRefer;
  48554. if ("development" !== 'production') {
  48555. checkTransformPropRefer = function (key, usedIn) {
  48556. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  48557. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  48558. }
  48559. };
  48560. }
  48561. var getStateToRestore = makeInner();
  48562. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  48563. /**
  48564. * Stop previous keyframe animation and restore the attributes.
  48565. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  48566. */
  48567. function stopPreviousKeyframeAnimationAndRestore(el) {
  48568. // Stop previous keyframe animation.
  48569. el.stopAnimation('keyframe');
  48570. // Restore
  48571. el.attr(getStateToRestore(el));
  48572. }
  48573. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  48574. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  48575. return;
  48576. }
  48577. if (isArray(animationOpts)) {
  48578. each(animationOpts, function (singleAnimationOpts) {
  48579. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  48580. });
  48581. return;
  48582. }
  48583. var keyframes = animationOpts.keyframes;
  48584. var duration = animationOpts.duration;
  48585. if (animatableModel && duration == null) {
  48586. // Default to use duration of config.
  48587. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  48588. var config = getAnimationConfig('enter', animatableModel, 0);
  48589. duration = config && config.duration;
  48590. }
  48591. if (!keyframes || !duration) {
  48592. return;
  48593. }
  48594. var stateToRestore = getStateToRestore(el);
  48595. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  48596. if (targetPropName && !el[targetPropName]) {
  48597. return;
  48598. }
  48599. var animator;
  48600. var endFrameIsSet = false;
  48601. // Sort keyframes by percent.
  48602. keyframes.sort(function (a, b) {
  48603. return a.percent - b.percent;
  48604. });
  48605. each(keyframes, function (kf) {
  48606. // Stop current animation.
  48607. var animators = el.animators;
  48608. var kfValues = targetPropName ? kf[targetPropName] : kf;
  48609. if ("development" !== 'production') {
  48610. if (kf.percent >= 1) {
  48611. endFrameIsSet = true;
  48612. }
  48613. }
  48614. if (!kfValues) {
  48615. return;
  48616. }
  48617. var propKeys = keys(kfValues);
  48618. if (!targetPropName) {
  48619. // PENDING performance?
  48620. propKeys = filter(propKeys, function (key) {
  48621. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  48622. });
  48623. }
  48624. if (!propKeys.length) {
  48625. return;
  48626. }
  48627. if (!animator) {
  48628. animator = el.animate(targetPropName, animationOpts.loop, true);
  48629. animator.scope = 'keyframe';
  48630. }
  48631. for (var i = 0; i < animators.length; i++) {
  48632. // Stop all other animation that is not keyframe.
  48633. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  48634. animators[i].stopTracks(propKeys);
  48635. }
  48636. }
  48637. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  48638. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  48639. each(propKeys, function (key) {
  48640. // Save original value.
  48641. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  48642. });
  48643. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  48644. });
  48645. if (!animator) {
  48646. return;
  48647. }
  48648. if ("development" !== 'production') {
  48649. if (!endFrameIsSet) {
  48650. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  48651. }
  48652. }
  48653. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  48654. });
  48655. }
  48656. var nonShapeGraphicElements = {
  48657. // Reserved but not supported in graphic component.
  48658. path: null,
  48659. compoundPath: null,
  48660. // Supported in graphic component.
  48661. group: Group,
  48662. image: ZRImage,
  48663. text: ZRText
  48664. };
  48665. var inner$9 = makeInner();
  48666. // ------------------------
  48667. // View
  48668. // ------------------------
  48669. var GraphicComponentView = /** @class */function (_super) {
  48670. __extends(GraphicComponentView, _super);
  48671. function GraphicComponentView() {
  48672. var _this = _super !== null && _super.apply(this, arguments) || this;
  48673. _this.type = GraphicComponentView.type;
  48674. return _this;
  48675. }
  48676. GraphicComponentView.prototype.init = function () {
  48677. this._elMap = createHashMap();
  48678. };
  48679. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  48680. // Having leveraged between use cases and algorithm complexity, a very
  48681. // simple layout mechanism is used:
  48682. // The size(width/height) can be determined by itself or its parent (not
  48683. // implemented yet), but can not by its children. (Top-down travel)
  48684. // The location(x/y) can be determined by the bounding rect of itself
  48685. // (can including its descendants or not) and the size of its parent.
  48686. // (Bottom-up travel)
  48687. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  48688. // view will be reused.
  48689. if (graphicModel !== this._lastGraphicModel) {
  48690. this._clear();
  48691. }
  48692. this._lastGraphicModel = graphicModel;
  48693. this._updateElements(graphicModel);
  48694. this._relocate(graphicModel, api);
  48695. };
  48696. /**
  48697. * Update graphic elements.
  48698. */
  48699. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  48700. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  48701. if (!elOptionsToUpdate) {
  48702. return;
  48703. }
  48704. var elMap = this._elMap;
  48705. var rootGroup = this.group;
  48706. var globalZ = graphicModel.get('z');
  48707. var globalZLevel = graphicModel.get('zlevel');
  48708. // Top-down tranverse to assign graphic settings to each elements.
  48709. each(elOptionsToUpdate, function (elOption) {
  48710. var id = convertOptionIdName(elOption.id, null);
  48711. var elExisting = id != null ? elMap.get(id) : null;
  48712. var parentId = convertOptionIdName(elOption.parentId, null);
  48713. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  48714. var elType = elOption.type;
  48715. var elOptionStyle = elOption.style;
  48716. if (elType === 'text' && elOptionStyle) {
  48717. // In top/bottom mode, textVerticalAlign should not be used, which cause
  48718. // inaccurately locating.
  48719. if (elOption.hv && elOption.hv[1]) {
  48720. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  48721. }
  48722. }
  48723. var textContentOption = elOption.textContent;
  48724. var textConfig = elOption.textConfig;
  48725. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  48726. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  48727. if (!textConfig && convertResult.textConfig) {
  48728. textConfig = elOption.textConfig = convertResult.textConfig;
  48729. }
  48730. if (!textContentOption && convertResult.textContent) {
  48731. textContentOption = convertResult.textContent;
  48732. }
  48733. }
  48734. // Remove unnecessary props to avoid potential problems.
  48735. var elOptionCleaned = getCleanedElOption(elOption);
  48736. // For simple, do not support parent change, otherwise reorder is needed.
  48737. if ("development" !== 'production') {
  48738. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  48739. }
  48740. var $action = elOption.$action || 'merge';
  48741. var isMerge = $action === 'merge';
  48742. var isReplace = $action === 'replace';
  48743. if (isMerge) {
  48744. var isInit = !elExisting;
  48745. var el_1 = elExisting;
  48746. if (isInit) {
  48747. el_1 = createEl(id, targetElParent, elOption.type, elMap);
  48748. } else {
  48749. el_1 && (inner$9(el_1).isNew = false);
  48750. // Stop and restore before update any other attributes.
  48751. stopPreviousKeyframeAnimationAndRestore(el_1);
  48752. }
  48753. if (el_1) {
  48754. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  48755. isInit: isInit
  48756. });
  48757. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  48758. }
  48759. } else if (isReplace) {
  48760. removeEl(elExisting, elOption, elMap, graphicModel);
  48761. var el_2 = createEl(id, targetElParent, elOption.type, elMap);
  48762. if (el_2) {
  48763. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  48764. isInit: true
  48765. });
  48766. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  48767. }
  48768. } else if ($action === 'remove') {
  48769. updateLeaveTo(elExisting, elOption);
  48770. removeEl(elExisting, elOption, elMap, graphicModel);
  48771. }
  48772. var el = elMap.get(id);
  48773. if (el && textContentOption) {
  48774. if (isMerge) {
  48775. var textContentExisting = el.getTextContent();
  48776. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  48777. } else if (isReplace) {
  48778. el.setTextContent(new ZRText(textContentOption));
  48779. }
  48780. }
  48781. if (el) {
  48782. var clipPathOption = elOption.clipPath;
  48783. if (clipPathOption) {
  48784. var clipPathType = clipPathOption.type;
  48785. var clipPath = void 0;
  48786. var isInit = false;
  48787. if (isMerge) {
  48788. var oldClipPath = el.getClipPath();
  48789. isInit = !oldClipPath || inner$9(oldClipPath).type !== clipPathType;
  48790. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  48791. } else if (isReplace) {
  48792. isInit = true;
  48793. clipPath = newEl(clipPathType);
  48794. }
  48795. el.setClipPath(clipPath);
  48796. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  48797. isInit: isInit
  48798. });
  48799. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  48800. }
  48801. var elInner = inner$9(el);
  48802. el.setTextConfig(textConfig);
  48803. elInner.option = elOption;
  48804. setEventData(el, graphicModel, elOption);
  48805. setTooltipConfig({
  48806. el: el,
  48807. componentModel: graphicModel,
  48808. itemName: el.name,
  48809. itemTooltipOption: elOption.tooltip
  48810. });
  48811. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  48812. }
  48813. });
  48814. };
  48815. /**
  48816. * Locate graphic elements.
  48817. */
  48818. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  48819. var elOptions = graphicModel.option.elements;
  48820. var rootGroup = this.group;
  48821. var elMap = this._elMap;
  48822. var apiWidth = api.getWidth();
  48823. var apiHeight = api.getHeight();
  48824. var xy = ['x', 'y'];
  48825. // Top-down to calculate percentage width/height of group
  48826. for (var i = 0; i < elOptions.length; i++) {
  48827. var elOption = elOptions[i];
  48828. var id = convertOptionIdName(elOption.id, null);
  48829. var el = id != null ? elMap.get(id) : null;
  48830. if (!el || !el.isGroup) {
  48831. continue;
  48832. }
  48833. var parentEl = el.parent;
  48834. var isParentRoot = parentEl === rootGroup;
  48835. // Like 'position:absolut' in css, default 0.
  48836. var elInner = inner$9(el);
  48837. var parentElInner = inner$9(parentEl);
  48838. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  48839. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  48840. }
  48841. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  48842. for (var i = elOptions.length - 1; i >= 0; i--) {
  48843. var elOption = elOptions[i];
  48844. var id = convertOptionIdName(elOption.id, null);
  48845. var el = id != null ? elMap.get(id) : null;
  48846. if (!el) {
  48847. continue;
  48848. }
  48849. var parentEl = el.parent;
  48850. var parentElInner = inner$9(parentEl);
  48851. var containerInfo = parentEl === rootGroup ? {
  48852. width: apiWidth,
  48853. height: apiHeight
  48854. } : {
  48855. width: parentElInner.width,
  48856. height: parentElInner.height
  48857. };
  48858. // PENDING
  48859. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  48860. // does not include the rect of [0, 0, group.width, group.height], which
  48861. // is probably weird for users. Should we make a break change for it?
  48862. var layoutPos = {};
  48863. var layouted = positionElement(el, elOption, containerInfo, null, {
  48864. hv: elOption.hv,
  48865. boundingMode: elOption.bounding
  48866. }, layoutPos);
  48867. if (!inner$9(el).isNew && layouted) {
  48868. var transition = elOption.transition;
  48869. var animatePos = {};
  48870. for (var k = 0; k < xy.length; k++) {
  48871. var key = xy[k];
  48872. var val = layoutPos[key];
  48873. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  48874. animatePos[key] = val;
  48875. } else {
  48876. el[key] = val;
  48877. }
  48878. }
  48879. updateProps(el, animatePos, graphicModel, 0);
  48880. } else {
  48881. el.attr(layoutPos);
  48882. }
  48883. }
  48884. };
  48885. /**
  48886. * Clear all elements.
  48887. */
  48888. GraphicComponentView.prototype._clear = function () {
  48889. var _this = this;
  48890. var elMap = this._elMap;
  48891. elMap.each(function (el) {
  48892. removeEl(el, inner$9(el).option, elMap, _this._lastGraphicModel);
  48893. });
  48894. this._elMap = createHashMap();
  48895. };
  48896. GraphicComponentView.prototype.dispose = function () {
  48897. this._clear();
  48898. };
  48899. GraphicComponentView.type = 'graphic';
  48900. return GraphicComponentView;
  48901. }(ComponentView);
  48902. function newEl(graphicType) {
  48903. if ("development" !== 'production') {
  48904. assert(graphicType, 'graphic type MUST be set');
  48905. }
  48906. var Clz = hasOwn(nonShapeGraphicElements, graphicType)
  48907. // Those graphic elements are not shapes. They should not be
  48908. // overwritten by users, so do them first.
  48909. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  48910. if ("development" !== 'production') {
  48911. assert(Clz, "graphic type " + graphicType + " can not be found");
  48912. }
  48913. var el = new Clz({});
  48914. inner$9(el).type = graphicType;
  48915. return el;
  48916. }
  48917. function createEl(id, targetElParent, graphicType, elMap) {
  48918. var el = newEl(graphicType);
  48919. targetElParent.add(el);
  48920. elMap.set(id, el);
  48921. inner$9(el).id = id;
  48922. inner$9(el).isNew = true;
  48923. return el;
  48924. }
  48925. function removeEl(elExisting, elOption, elMap, graphicModel) {
  48926. var existElParent = elExisting && elExisting.parent;
  48927. if (existElParent) {
  48928. elExisting.type === 'group' && elExisting.traverse(function (el) {
  48929. removeEl(el, elOption, elMap, graphicModel);
  48930. });
  48931. applyLeaveTransition(elExisting, elOption, graphicModel);
  48932. elMap.removeKey(inner$9(elExisting).id);
  48933. }
  48934. }
  48935. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  48936. if (!el.isGroup) {
  48937. each([['cursor', Displayable.prototype.cursor],
  48938. // We should not support configure z and zlevel in the element level.
  48939. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  48940. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0],
  48941. // z2 must not be null/undefined, otherwise sort error may occur.
  48942. ['z2', 0]], function (item) {
  48943. var prop = item[0];
  48944. if (hasOwn(elOption, prop)) {
  48945. el[prop] = retrieve2(elOption[prop], item[1]);
  48946. } else if (el[prop] == null) {
  48947. el[prop] = item[1];
  48948. }
  48949. });
  48950. }
  48951. each(keys(elOption), function (key) {
  48952. // Assign event handlers.
  48953. // PENDING: should enumerate all event names or use pattern matching?
  48954. if (key.indexOf('on') === 0) {
  48955. var val = elOption[key];
  48956. el[key] = isFunction(val) ? val : null;
  48957. }
  48958. });
  48959. if (hasOwn(elOption, 'draggable')) {
  48960. el.draggable = elOption.draggable;
  48961. }
  48962. // Other attributes
  48963. elOption.name != null && (el.name = elOption.name);
  48964. elOption.id != null && (el.id = elOption.id);
  48965. }
  48966. // Remove unnecessary props to avoid potential problems.
  48967. function getCleanedElOption(elOption) {
  48968. elOption = extend({}, elOption);
  48969. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  48970. delete elOption[name];
  48971. });
  48972. return elOption;
  48973. }
  48974. function setEventData(el, graphicModel, elOption) {
  48975. var eventData = getECData(el).eventData;
  48976. // Simple optimize for large amount of elements that no need event.
  48977. if (!el.silent && !el.ignore && !eventData) {
  48978. eventData = getECData(el).eventData = {
  48979. componentType: 'graphic',
  48980. componentIndex: graphicModel.componentIndex,
  48981. name: el.name
  48982. };
  48983. }
  48984. // `elOption.info` enables user to mount some info on
  48985. // elements and use them in event handlers.
  48986. if (eventData) {
  48987. eventData.info = elOption.info;
  48988. }
  48989. }
  48990. function install$9(registers) {
  48991. registers.registerComponentModel(GraphicComponentModel);
  48992. registers.registerComponentView(GraphicComponentView);
  48993. registers.registerPreprocessor(function (option) {
  48994. var graphicOption = option.graphic;
  48995. // Convert
  48996. // {graphic: [{left: 10, type: 'circle'}, ...]}
  48997. // or
  48998. // {graphic: {left: 10, type: 'circle'}}
  48999. // to
  49000. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  49001. if (isArray(graphicOption)) {
  49002. if (!graphicOption[0] || !graphicOption[0].elements) {
  49003. option.graphic = [{
  49004. elements: graphicOption
  49005. }];
  49006. } else {
  49007. // Only one graphic instance can be instantiated. (We don't
  49008. // want that too many views are created in echarts._viewMap.)
  49009. option.graphic = [option.graphic[0]];
  49010. }
  49011. } else if (graphicOption && !graphicOption.elements) {
  49012. option.graphic = [{
  49013. elements: [graphicOption]
  49014. }];
  49015. }
  49016. });
  49017. }
  49018. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single'];
  49019. // Supported coords.
  49020. // FIXME: polar has been broken (but rarely used).
  49021. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  49022. function isCoordSupported(seriesModel) {
  49023. var coordType = seriesModel.get('coordinateSystem');
  49024. return indexOf(SERIES_COORDS, coordType) >= 0;
  49025. }
  49026. function getAxisMainType(axisDim) {
  49027. if ("development" !== 'production') {
  49028. assert(axisDim);
  49029. }
  49030. return axisDim + 'Axis';
  49031. }
  49032. /**
  49033. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  49034. * This function finds all linked dataZoomModels start from the given payload.
  49035. */
  49036. function findEffectedDataZooms(ecModel, payload) {
  49037. // Key: `DataZoomAxisDimension`
  49038. var axisRecords = createHashMap();
  49039. var effectedModels = [];
  49040. // Key: uid of dataZoomModel
  49041. var effectedModelMap = createHashMap();
  49042. // Find the dataZooms specified by payload.
  49043. ecModel.eachComponent({
  49044. mainType: 'dataZoom',
  49045. query: payload
  49046. }, function (dataZoomModel) {
  49047. if (!effectedModelMap.get(dataZoomModel.uid)) {
  49048. addToEffected(dataZoomModel);
  49049. }
  49050. });
  49051. // Start from the given dataZoomModels, travel the graph to find
  49052. // all of the linked dataZoom models.
  49053. var foundNewLink;
  49054. do {
  49055. foundNewLink = false;
  49056. ecModel.eachComponent('dataZoom', processSingle);
  49057. } while (foundNewLink);
  49058. function processSingle(dataZoomModel) {
  49059. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  49060. addToEffected(dataZoomModel);
  49061. foundNewLink = true;
  49062. }
  49063. }
  49064. function addToEffected(dataZoom) {
  49065. effectedModelMap.set(dataZoom.uid, true);
  49066. effectedModels.push(dataZoom);
  49067. markAxisControlled(dataZoom);
  49068. }
  49069. function isLinked(dataZoomModel) {
  49070. var isLink = false;
  49071. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  49072. var axisIdxArr = axisRecords.get(axisDim);
  49073. if (axisIdxArr && axisIdxArr[axisIndex]) {
  49074. isLink = true;
  49075. }
  49076. });
  49077. return isLink;
  49078. }
  49079. function markAxisControlled(dataZoomModel) {
  49080. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  49081. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  49082. });
  49083. }
  49084. return effectedModels;
  49085. }
  49086. /**
  49087. * Find the first target coordinate system.
  49088. * Available after model built.
  49089. *
  49090. * @return Like {
  49091. * grid: [
  49092. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  49093. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  49094. * ...
  49095. * ], // cartesians must not be null/undefined.
  49096. * polar: [
  49097. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  49098. * ...
  49099. * ], // polars must not be null/undefined.
  49100. * singleAxis: [
  49101. * {model: coord0, axisModels: [], coordIndex: 0}
  49102. * ]
  49103. * }
  49104. */
  49105. function collectReferCoordSysModelInfo(dataZoomModel) {
  49106. var ecModel = dataZoomModel.ecModel;
  49107. var coordSysInfoWrap = {
  49108. infoList: [],
  49109. infoMap: createHashMap()
  49110. };
  49111. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  49112. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  49113. if (!axisModel) {
  49114. return;
  49115. }
  49116. var coordSysModel = axisModel.getCoordSysModel();
  49117. if (!coordSysModel) {
  49118. return;
  49119. }
  49120. var coordSysUid = coordSysModel.uid;
  49121. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  49122. if (!coordSysInfo) {
  49123. coordSysInfo = {
  49124. model: coordSysModel,
  49125. axisModels: []
  49126. };
  49127. coordSysInfoWrap.infoList.push(coordSysInfo);
  49128. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  49129. }
  49130. coordSysInfo.axisModels.push(axisModel);
  49131. });
  49132. return coordSysInfoWrap;
  49133. }
  49134. var DataZoomAxisInfo = /** @class */function () {
  49135. function DataZoomAxisInfo() {
  49136. this.indexList = [];
  49137. this.indexMap = [];
  49138. }
  49139. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  49140. // Remove duplication.
  49141. if (!this.indexMap[axisCmptIdx]) {
  49142. this.indexList.push(axisCmptIdx);
  49143. this.indexMap[axisCmptIdx] = true;
  49144. }
  49145. };
  49146. return DataZoomAxisInfo;
  49147. }();
  49148. var DataZoomModel = /** @class */function (_super) {
  49149. __extends(DataZoomModel, _super);
  49150. function DataZoomModel() {
  49151. var _this = _super !== null && _super.apply(this, arguments) || this;
  49152. _this.type = DataZoomModel.type;
  49153. _this._autoThrottle = true;
  49154. _this._noTarget = true;
  49155. /**
  49156. * It is `[rangeModeForMin, rangeModeForMax]`.
  49157. * The optional values for `rangeMode`:
  49158. * + `'value'` mode: the axis extent will always be determined by
  49159. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  49160. * how data like and how `axis.min` and `axis.max` are.
  49161. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  49162. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  49163. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  49164. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  49165. *
  49166. * For example, when users are using dynamic data (update data periodically via `setOption`),
  49167. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  49168. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  49169. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  49170. */
  49171. _this._rangePropMode = ['percent', 'percent'];
  49172. return _this;
  49173. }
  49174. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  49175. var inputRawOption = retrieveRawOption(option);
  49176. /**
  49177. * Suppose a "main process" start at the point that model prepared (that is,
  49178. * model initialized or merged or method called in `action`).
  49179. * We should keep the `main process` idempotent, that is, given a set of values
  49180. * on `option`, we get the same result.
  49181. *
  49182. * But sometimes, values on `option` will be updated for providing users
  49183. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  49184. * should not be the base/input of the `main process`.
  49185. *
  49186. * So in that case we should save and keep the input of the `main process`
  49187. * separately, called `settledOption`.
  49188. *
  49189. * For example, consider the case:
  49190. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  49191. * where the original input `option.startValue`, `option.endValue` are earsed by
  49192. * calculated value.
  49193. * (Step)2) click the legend to hide and show a series,
  49194. * where the new range is calculated by the earsed `startValue` and `endValue`,
  49195. * which brings incorrect result.
  49196. */
  49197. this.settledOption = inputRawOption;
  49198. this.mergeDefaultAndTheme(option, ecModel);
  49199. this._doInit(inputRawOption);
  49200. };
  49201. DataZoomModel.prototype.mergeOption = function (newOption) {
  49202. var inputRawOption = retrieveRawOption(newOption);
  49203. // FIX #2591
  49204. merge(this.option, newOption, true);
  49205. merge(this.settledOption, inputRawOption, true);
  49206. this._doInit(inputRawOption);
  49207. };
  49208. DataZoomModel.prototype._doInit = function (inputRawOption) {
  49209. var thisOption = this.option;
  49210. this._setDefaultThrottle(inputRawOption);
  49211. this._updateRangeUse(inputRawOption);
  49212. var settledOption = this.settledOption;
  49213. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  49214. // start/end has higher priority over startValue/endValue if they
  49215. // both set, but we should make chart.setOption({endValue: 1000})
  49216. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  49217. if (this._rangePropMode[index] === 'value') {
  49218. thisOption[names[0]] = settledOption[names[0]] = null;
  49219. }
  49220. // Otherwise do nothing and use the merge result.
  49221. }, this);
  49222. this._resetTarget();
  49223. };
  49224. DataZoomModel.prototype._resetTarget = function () {
  49225. var optionOrient = this.get('orient', true);
  49226. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  49227. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  49228. if (hasAxisSpecified) {
  49229. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  49230. } else {
  49231. this._orient = optionOrient || 'horizontal';
  49232. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  49233. }
  49234. this._noTarget = true;
  49235. targetAxisIndexMap.each(function (axisInfo) {
  49236. if (axisInfo.indexList.length) {
  49237. this._noTarget = false;
  49238. }
  49239. }, this);
  49240. };
  49241. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  49242. var hasAxisSpecified = false;
  49243. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  49244. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING);
  49245. // When user set axisIndex as a empty array, we think that user specify axisIndex
  49246. // but do not want use auto mode. Because empty array may be encountered when
  49247. // some error occurred.
  49248. if (!refering.specified) {
  49249. return;
  49250. }
  49251. hasAxisSpecified = true;
  49252. var axisInfo = new DataZoomAxisInfo();
  49253. each(refering.models, function (axisModel) {
  49254. axisInfo.add(axisModel.componentIndex);
  49255. });
  49256. targetAxisIndexMap.set(axisDim, axisInfo);
  49257. }, this);
  49258. return hasAxisSpecified;
  49259. };
  49260. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  49261. var ecModel = this.ecModel;
  49262. var needAuto = true;
  49263. // Find axis that parallel to dataZoom as default.
  49264. if (needAuto) {
  49265. var axisDim = orient === 'vertical' ? 'y' : 'x';
  49266. var axisModels = ecModel.findComponents({
  49267. mainType: axisDim + 'Axis'
  49268. });
  49269. setParallelAxis(axisModels, axisDim);
  49270. }
  49271. // Find axis that parallel to dataZoom as default.
  49272. if (needAuto) {
  49273. var axisModels = ecModel.findComponents({
  49274. mainType: 'singleAxis',
  49275. filter: function (axisModel) {
  49276. return axisModel.get('orient', true) === orient;
  49277. }
  49278. });
  49279. setParallelAxis(axisModels, 'single');
  49280. }
  49281. function setParallelAxis(axisModels, axisDim) {
  49282. // At least use the first parallel axis as the target axis.
  49283. var axisModel = axisModels[0];
  49284. if (!axisModel) {
  49285. return;
  49286. }
  49287. var axisInfo = new DataZoomAxisInfo();
  49288. axisInfo.add(axisModel.componentIndex);
  49289. targetAxisIndexMap.set(axisDim, axisInfo);
  49290. needAuto = false;
  49291. // Find parallel axes in the same grid.
  49292. if (axisDim === 'x' || axisDim === 'y') {
  49293. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  49294. gridModel_1 && each(axisModels, function (axModel) {
  49295. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  49296. axisInfo.add(axModel.componentIndex);
  49297. }
  49298. });
  49299. }
  49300. }
  49301. if (needAuto) {
  49302. // If no parallel axis, find the first category axis as default. (Also consider polar).
  49303. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  49304. if (!needAuto) {
  49305. return;
  49306. }
  49307. var axisModels = ecModel.findComponents({
  49308. mainType: getAxisMainType(axisDim),
  49309. filter: function (axisModel) {
  49310. return axisModel.get('type', true) === 'category';
  49311. }
  49312. });
  49313. if (axisModels[0]) {
  49314. var axisInfo = new DataZoomAxisInfo();
  49315. axisInfo.add(axisModels[0].componentIndex);
  49316. targetAxisIndexMap.set(axisDim, axisInfo);
  49317. needAuto = false;
  49318. }
  49319. }, this);
  49320. }
  49321. };
  49322. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  49323. var dim;
  49324. // Find the first axis
  49325. this.eachTargetAxis(function (axisDim) {
  49326. !dim && (dim = axisDim);
  49327. }, this);
  49328. return dim === 'y' ? 'vertical' : 'horizontal';
  49329. };
  49330. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  49331. // When first time user set throttle, auto throttle ends.
  49332. if (inputRawOption.hasOwnProperty('throttle')) {
  49333. this._autoThrottle = false;
  49334. }
  49335. if (this._autoThrottle) {
  49336. var globalOption = this.ecModel.option;
  49337. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  49338. }
  49339. };
  49340. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  49341. var rangePropMode = this._rangePropMode;
  49342. var rangeModeInOption = this.get('rangeMode');
  49343. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  49344. var percentSpecified = inputRawOption[names[0]] != null;
  49345. var valueSpecified = inputRawOption[names[1]] != null;
  49346. if (percentSpecified && !valueSpecified) {
  49347. rangePropMode[index] = 'percent';
  49348. } else if (!percentSpecified && valueSpecified) {
  49349. rangePropMode[index] = 'value';
  49350. } else if (rangeModeInOption) {
  49351. rangePropMode[index] = rangeModeInOption[index];
  49352. } else if (percentSpecified) {
  49353. // percentSpecified && valueSpecified
  49354. rangePropMode[index] = 'percent';
  49355. }
  49356. // else remain its original setting.
  49357. });
  49358. };
  49359. DataZoomModel.prototype.noTarget = function () {
  49360. return this._noTarget;
  49361. };
  49362. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  49363. var firstAxisModel;
  49364. this.eachTargetAxis(function (axisDim, axisIndex) {
  49365. if (firstAxisModel == null) {
  49366. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  49367. }
  49368. }, this);
  49369. return firstAxisModel;
  49370. };
  49371. /**
  49372. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  49373. */
  49374. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  49375. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  49376. each(axisInfo.indexList, function (axisIndex) {
  49377. callback.call(context, axisDim, axisIndex);
  49378. });
  49379. });
  49380. };
  49381. /**
  49382. * @return If not found, return null/undefined.
  49383. */
  49384. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  49385. var axisModel = this.getAxisModel(axisDim, axisIndex);
  49386. if (axisModel) {
  49387. return axisModel.__dzAxisProxy;
  49388. }
  49389. };
  49390. /**
  49391. * @return If not found, return null/undefined.
  49392. */
  49393. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  49394. if ("development" !== 'production') {
  49395. assert(axisDim && axisIndex != null);
  49396. }
  49397. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  49398. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  49399. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  49400. }
  49401. };
  49402. /**
  49403. * If not specified, set to undefined.
  49404. */
  49405. DataZoomModel.prototype.setRawRange = function (opt) {
  49406. var thisOption = this.option;
  49407. var settledOption = this.settledOption;
  49408. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  49409. // Consider the pair <start, startValue>:
  49410. // If one has value and the other one is `null/undefined`, we both set them
  49411. // to `settledOption`. This strategy enables the feature to clear the original
  49412. // value in `settledOption` to `null/undefined`.
  49413. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  49414. // and keep `settledOption` with the original value. This strategy enables users to
  49415. // only set <end or endValue> but not set <start or startValue> when calling
  49416. // `dispatchAction`.
  49417. // The pair <end, endValue> is treated in the same way.
  49418. if (opt[names[0]] != null || opt[names[1]] != null) {
  49419. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  49420. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  49421. }
  49422. }, this);
  49423. this._updateRangeUse(opt);
  49424. };
  49425. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  49426. var option = this.option;
  49427. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  49428. option[name] = opt[name];
  49429. });
  49430. };
  49431. DataZoomModel.prototype.getPercentRange = function () {
  49432. var axisProxy = this.findRepresentativeAxisProxy();
  49433. if (axisProxy) {
  49434. return axisProxy.getDataPercentWindow();
  49435. }
  49436. };
  49437. /**
  49438. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  49439. *
  49440. * @return [startValue, endValue] value can only be '-' or finite number.
  49441. */
  49442. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  49443. if (axisDim == null && axisIndex == null) {
  49444. var axisProxy = this.findRepresentativeAxisProxy();
  49445. if (axisProxy) {
  49446. return axisProxy.getDataValueWindow();
  49447. }
  49448. } else {
  49449. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  49450. }
  49451. };
  49452. /**
  49453. * @param axisModel If axisModel given, find axisProxy
  49454. * corresponding to the axisModel
  49455. */
  49456. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  49457. if (axisModel) {
  49458. return axisModel.__dzAxisProxy;
  49459. }
  49460. // Find the first hosted axisProxy
  49461. var firstProxy;
  49462. var axisDimList = this._targetAxisInfoMap.keys();
  49463. for (var i = 0; i < axisDimList.length; i++) {
  49464. var axisDim = axisDimList[i];
  49465. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  49466. for (var j = 0; j < axisInfo.indexList.length; j++) {
  49467. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  49468. if (proxy.hostedBy(this)) {
  49469. return proxy;
  49470. }
  49471. if (!firstProxy) {
  49472. firstProxy = proxy;
  49473. }
  49474. }
  49475. }
  49476. // If no hosted proxy found, still need to return a proxy.
  49477. // This case always happens in toolbox dataZoom, where axes are all hosted by
  49478. // other dataZooms.
  49479. return firstProxy;
  49480. };
  49481. DataZoomModel.prototype.getRangePropMode = function () {
  49482. return this._rangePropMode.slice();
  49483. };
  49484. DataZoomModel.prototype.getOrient = function () {
  49485. if ("development" !== 'production') {
  49486. // Should not be called before initialized.
  49487. assert(this._orient);
  49488. }
  49489. return this._orient;
  49490. };
  49491. DataZoomModel.type = 'dataZoom';
  49492. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  49493. DataZoomModel.defaultOption = {
  49494. // zlevel: 0,
  49495. z: 4,
  49496. filterMode: 'filter',
  49497. start: 0,
  49498. end: 100
  49499. };
  49500. return DataZoomModel;
  49501. }(ComponentModel);
  49502. /**
  49503. * Retrieve those raw params from option, which will be cached separately,
  49504. * because they will be overwritten by normalized/calculated values in the main
  49505. * process.
  49506. */
  49507. function retrieveRawOption(option) {
  49508. var ret = {};
  49509. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  49510. option.hasOwnProperty(name) && (ret[name] = option[name]);
  49511. });
  49512. return ret;
  49513. }
  49514. var SelectDataZoomModel = /** @class */function (_super) {
  49515. __extends(SelectDataZoomModel, _super);
  49516. function SelectDataZoomModel() {
  49517. var _this = _super !== null && _super.apply(this, arguments) || this;
  49518. _this.type = SelectDataZoomModel.type;
  49519. return _this;
  49520. }
  49521. SelectDataZoomModel.type = 'dataZoom.select';
  49522. return SelectDataZoomModel;
  49523. }(DataZoomModel);
  49524. var DataZoomView = /** @class */function (_super) {
  49525. __extends(DataZoomView, _super);
  49526. function DataZoomView() {
  49527. var _this = _super !== null && _super.apply(this, arguments) || this;
  49528. _this.type = DataZoomView.type;
  49529. return _this;
  49530. }
  49531. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  49532. this.dataZoomModel = dataZoomModel;
  49533. this.ecModel = ecModel;
  49534. this.api = api;
  49535. };
  49536. DataZoomView.type = 'dataZoom';
  49537. return DataZoomView;
  49538. }(ComponentView);
  49539. var SelectDataZoomView = /** @class */function (_super) {
  49540. __extends(SelectDataZoomView, _super);
  49541. function SelectDataZoomView() {
  49542. var _this = _super !== null && _super.apply(this, arguments) || this;
  49543. _this.type = SelectDataZoomView.type;
  49544. return _this;
  49545. }
  49546. SelectDataZoomView.type = 'dataZoom.select';
  49547. return SelectDataZoomView;
  49548. }(DataZoomView);
  49549. /*
  49550. * Licensed to the Apache Software Foundation (ASF) under one
  49551. * or more contributor license agreements. See the NOTICE file
  49552. * distributed with this work for additional information
  49553. * regarding copyright ownership. The ASF licenses this file
  49554. * to you under the Apache License, Version 2.0 (the
  49555. * "License"); you may not use this file except in compliance
  49556. * with the License. You may obtain a copy of the License at
  49557. *
  49558. * http://www.apache.org/licenses/LICENSE-2.0
  49559. *
  49560. * Unless required by applicable law or agreed to in writing,
  49561. * software distributed under the License is distributed on an
  49562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49563. * KIND, either express or implied. See the License for the
  49564. * specific language governing permissions and limitations
  49565. * under the License.
  49566. */
  49567. /**
  49568. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49569. */
  49570. /*
  49571. * Licensed to the Apache Software Foundation (ASF) under one
  49572. * or more contributor license agreements. See the NOTICE file
  49573. * distributed with this work for additional information
  49574. * regarding copyright ownership. The ASF licenses this file
  49575. * to you under the Apache License, Version 2.0 (the
  49576. * "License"); you may not use this file except in compliance
  49577. * with the License. You may obtain a copy of the License at
  49578. *
  49579. * http://www.apache.org/licenses/LICENSE-2.0
  49580. *
  49581. * Unless required by applicable law or agreed to in writing,
  49582. * software distributed under the License is distributed on an
  49583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49584. * KIND, either express or implied. See the License for the
  49585. * specific language governing permissions and limitations
  49586. * under the License.
  49587. */
  49588. /**
  49589. * Calculate slider move result.
  49590. * Usage:
  49591. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  49592. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  49593. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  49594. *
  49595. * @param delta Move length.
  49596. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  49597. * handleEnds will be modified in this method.
  49598. * @param extent handleEnds is restricted by extent.
  49599. * extent[0] should less or equals than extent[1].
  49600. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  49601. * @param minSpan The range of dataZoom can not be smaller than that.
  49602. * If not set, handle0 and cross handle1. If set as a non-negative
  49603. * number (including `0`), handles will push each other when reaching
  49604. * the minSpan.
  49605. * @param maxSpan The range of dataZoom can not be larger than that.
  49606. * @return The input handleEnds.
  49607. */
  49608. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  49609. delta = delta || 0;
  49610. var extentSpan = extent[1] - extent[0];
  49611. // Notice maxSpan and minSpan can be null/undefined.
  49612. if (minSpan != null) {
  49613. minSpan = restrict(minSpan, [0, extentSpan]);
  49614. }
  49615. if (maxSpan != null) {
  49616. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  49617. }
  49618. if (handleIndex === 'all') {
  49619. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  49620. handleSpan = restrict(handleSpan, [0, extentSpan]);
  49621. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  49622. handleIndex = 0;
  49623. }
  49624. handleEnds[0] = restrict(handleEnds[0], extent);
  49625. handleEnds[1] = restrict(handleEnds[1], extent);
  49626. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  49627. handleEnds[handleIndex] += delta;
  49628. // Restrict in extent.
  49629. var extentMinSpan = minSpan || 0;
  49630. var realExtent = extent.slice();
  49631. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  49632. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  49633. // Expand span.
  49634. var currDistSign;
  49635. currDistSign = getSpanSign(handleEnds, handleIndex);
  49636. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  49637. // If minSpan exists, 'cross' is forbidden.
  49638. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  49639. }
  49640. // Shrink span.
  49641. currDistSign = getSpanSign(handleEnds, handleIndex);
  49642. if (maxSpan != null && currDistSign.span > maxSpan) {
  49643. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  49644. }
  49645. return handleEnds;
  49646. }
  49647. function getSpanSign(handleEnds, handleIndex) {
  49648. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  49649. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  49650. // is at left of handleEnds[1] for non-cross case.
  49651. return {
  49652. span: Math.abs(dist),
  49653. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  49654. };
  49655. }
  49656. function restrict(value, extend) {
  49657. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  49658. }
  49659. var each$4 = each;
  49660. var asc$1 = asc;
  49661. /**
  49662. * Operate single axis.
  49663. * One axis can only operated by one axis operator.
  49664. * Different dataZoomModels may be defined to operate the same axis.
  49665. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  49666. * So dataZoomModels share one axisProxy in that case.
  49667. */
  49668. var AxisProxy = /** @class */function () {
  49669. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  49670. this._dimName = dimName;
  49671. this._axisIndex = axisIndex;
  49672. this.ecModel = ecModel;
  49673. this._dataZoomModel = dataZoomModel;
  49674. // /**
  49675. // * @readOnly
  49676. // * @private
  49677. // */
  49678. // this.hasSeriesStacked;
  49679. }
  49680. /**
  49681. * Whether the axisProxy is hosted by dataZoomModel.
  49682. */
  49683. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  49684. return this._dataZoomModel === dataZoomModel;
  49685. };
  49686. /**
  49687. * @return Value can only be NaN or finite value.
  49688. */
  49689. AxisProxy.prototype.getDataValueWindow = function () {
  49690. return this._valueWindow.slice();
  49691. };
  49692. /**
  49693. * @return {Array.<number>}
  49694. */
  49695. AxisProxy.prototype.getDataPercentWindow = function () {
  49696. return this._percentWindow.slice();
  49697. };
  49698. AxisProxy.prototype.getTargetSeriesModels = function () {
  49699. var seriesModels = [];
  49700. this.ecModel.eachSeries(function (seriesModel) {
  49701. if (isCoordSupported(seriesModel)) {
  49702. var axisMainType = getAxisMainType(this._dimName);
  49703. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  49704. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  49705. seriesModels.push(seriesModel);
  49706. }
  49707. }
  49708. }, this);
  49709. return seriesModels;
  49710. };
  49711. AxisProxy.prototype.getAxisModel = function () {
  49712. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  49713. };
  49714. AxisProxy.prototype.getMinMaxSpan = function () {
  49715. return clone(this._minMaxSpan);
  49716. };
  49717. /**
  49718. * Only calculate by given range and this._dataExtent, do not change anything.
  49719. */
  49720. AxisProxy.prototype.calculateDataWindow = function (opt) {
  49721. var dataExtent = this._dataExtent;
  49722. var axisModel = this.getAxisModel();
  49723. var scale = axisModel.axis.scale;
  49724. var rangePropMode = this._dataZoomModel.getRangePropMode();
  49725. var percentExtent = [0, 100];
  49726. var percentWindow = [];
  49727. var valueWindow = [];
  49728. var hasPropModeValue;
  49729. each$4(['start', 'end'], function (prop, idx) {
  49730. var boundPercent = opt[prop];
  49731. var boundValue = opt[prop + 'Value'];
  49732. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  49733. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  49734. // but not min/max of axis, which will be calculated by data window then).
  49735. // The former one is suitable for cases that a dataZoom component controls multiple
  49736. // axes with different unit or extent, and the latter one is suitable for accurate
  49737. // zoom by pixel (e.g., in dataZoomSelect).
  49738. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  49739. // only when setOption or dispatchAction, otherwise it remains its original value.
  49740. // (Why not only record `percentProp` and always map to `valueProp`? Because
  49741. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  49742. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  49743. // data extent. All of values that are overflow the `dataExtent` will be calculated
  49744. // to percent '100%').
  49745. if (rangePropMode[idx] === 'percent') {
  49746. boundPercent == null && (boundPercent = percentExtent[idx]);
  49747. // Use scale.parse to math round for category or time axis.
  49748. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  49749. } else {
  49750. hasPropModeValue = true;
  49751. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  49752. // Calculating `percent` from `value` may be not accurate, because
  49753. // This calculation can not be inversed, because all of values that
  49754. // are overflow the `dataExtent` will be calculated to percent '100%'
  49755. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  49756. }
  49757. // valueWindow[idx] = round(boundValue);
  49758. // percentWindow[idx] = round(boundPercent);
  49759. // fallback to extent start/end when parsed value or percent is invalid
  49760. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  49761. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  49762. });
  49763. asc$1(valueWindow);
  49764. asc$1(percentWindow);
  49765. // The windows from user calling of `dispatchAction` might be out of the extent,
  49766. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  49767. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  49768. // where API is able to initialize/modify the window size even though `zoomLock`
  49769. // specified.
  49770. var spans = this._minMaxSpan;
  49771. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  49772. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  49773. var suffix = toValue ? 'Span' : 'ValueSpan';
  49774. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  49775. for (var i = 0; i < 2; i++) {
  49776. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  49777. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  49778. }
  49779. }
  49780. return {
  49781. valueWindow: valueWindow,
  49782. percentWindow: percentWindow
  49783. };
  49784. };
  49785. /**
  49786. * Notice: reset should not be called before series.restoreData() is called,
  49787. * so it is recommended to be called in "process stage" but not "model init
  49788. * stage".
  49789. */
  49790. AxisProxy.prototype.reset = function (dataZoomModel) {
  49791. if (dataZoomModel !== this._dataZoomModel) {
  49792. return;
  49793. }
  49794. var targetSeries = this.getTargetSeriesModels();
  49795. // Culculate data window and data extent, and record them.
  49796. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  49797. // `calculateDataWindow` uses min/maxSpan.
  49798. this._updateMinMaxSpan();
  49799. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  49800. this._valueWindow = dataWindow.valueWindow;
  49801. this._percentWindow = dataWindow.percentWindow;
  49802. // Update axis setting then.
  49803. this._setAxisModel();
  49804. };
  49805. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  49806. if (dataZoomModel !== this._dataZoomModel) {
  49807. return;
  49808. }
  49809. var axisDim = this._dimName;
  49810. var seriesModels = this.getTargetSeriesModels();
  49811. var filterMode = dataZoomModel.get('filterMode');
  49812. var valueWindow = this._valueWindow;
  49813. if (filterMode === 'none') {
  49814. return;
  49815. }
  49816. // FIXME
  49817. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  49818. // with NaN data, NaN will be filtered and stack will be wrong.
  49819. // So we need to force the mode to be set empty.
  49820. // In fect, it is not a big deal that do not support filterMode-'filter'
  49821. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  49822. // selection" some day, which might need "adapt to data extent on the
  49823. // otherAxis", which is disabled by filterMode-'empty'.
  49824. // But currently, stack has been fixed to based on value but not index,
  49825. // so this is not an issue any more.
  49826. // let otherAxisModel = this.getOtherAxisModel();
  49827. // if (dataZoomModel.get('$fromToolbox')
  49828. // && otherAxisModel
  49829. // && otherAxisModel.hasSeriesStacked
  49830. // ) {
  49831. // filterMode = 'empty';
  49832. // }
  49833. // TODO
  49834. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  49835. each$4(seriesModels, function (seriesModel) {
  49836. var seriesData = seriesModel.getData();
  49837. var dataDims = seriesData.mapDimensionsAll(axisDim);
  49838. if (!dataDims.length) {
  49839. return;
  49840. }
  49841. if (filterMode === 'weakFilter') {
  49842. var store_1 = seriesData.getStore();
  49843. var dataDimIndices_1 = map(dataDims, function (dim) {
  49844. return seriesData.getDimensionIndex(dim);
  49845. }, seriesData);
  49846. seriesData.filterSelf(function (dataIndex) {
  49847. var leftOut;
  49848. var rightOut;
  49849. var hasValue;
  49850. for (var i = 0; i < dataDims.length; i++) {
  49851. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  49852. var thisHasValue = !isNaN(value);
  49853. var thisLeftOut = value < valueWindow[0];
  49854. var thisRightOut = value > valueWindow[1];
  49855. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  49856. return true;
  49857. }
  49858. thisHasValue && (hasValue = true);
  49859. thisLeftOut && (leftOut = true);
  49860. thisRightOut && (rightOut = true);
  49861. }
  49862. // If both left out and right out, do not filter.
  49863. return hasValue && leftOut && rightOut;
  49864. });
  49865. } else {
  49866. each$4(dataDims, function (dim) {
  49867. if (filterMode === 'empty') {
  49868. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  49869. return !isInWindow(value) ? NaN : value;
  49870. }));
  49871. } else {
  49872. var range = {};
  49873. range[dim] = valueWindow;
  49874. // console.time('select');
  49875. seriesData.selectRange(range);
  49876. // console.timeEnd('select');
  49877. }
  49878. });
  49879. }
  49880. each$4(dataDims, function (dim) {
  49881. seriesData.setApproximateExtent(valueWindow, dim);
  49882. });
  49883. });
  49884. function isInWindow(value) {
  49885. return value >= valueWindow[0] && value <= valueWindow[1];
  49886. }
  49887. };
  49888. AxisProxy.prototype._updateMinMaxSpan = function () {
  49889. var minMaxSpan = this._minMaxSpan = {};
  49890. var dataZoomModel = this._dataZoomModel;
  49891. var dataExtent = this._dataExtent;
  49892. each$4(['min', 'max'], function (minMax) {
  49893. var percentSpan = dataZoomModel.get(minMax + 'Span');
  49894. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  49895. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan));
  49896. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  49897. if (valueSpan != null) {
  49898. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  49899. } else if (percentSpan != null) {
  49900. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  49901. }
  49902. minMaxSpan[minMax + 'Span'] = percentSpan;
  49903. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  49904. }, this);
  49905. };
  49906. AxisProxy.prototype._setAxisModel = function () {
  49907. var axisModel = this.getAxisModel();
  49908. var percentWindow = this._percentWindow;
  49909. var valueWindow = this._valueWindow;
  49910. if (!percentWindow) {
  49911. return;
  49912. }
  49913. // [0, 500]: arbitrary value, guess axis extent.
  49914. var precision = getPixelPrecision(valueWindow, [0, 500]);
  49915. precision = Math.min(precision, 20);
  49916. // For value axis, if min/max/scale are not set, we just use the extent obtained
  49917. // by series data, which may be a little different from the extent calculated by
  49918. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  49919. // little when zooming. So it will not be fixed until some users require it strongly.
  49920. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  49921. if (percentWindow[0] !== 0) {
  49922. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  49923. }
  49924. if (percentWindow[1] !== 100) {
  49925. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  49926. }
  49927. rawExtentInfo.freeze();
  49928. };
  49929. return AxisProxy;
  49930. }();
  49931. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  49932. var dataExtent = [Infinity, -Infinity];
  49933. each$4(seriesModels, function (seriesModel) {
  49934. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  49935. });
  49936. // It is important to get "consistent" extent when more then one axes is
  49937. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  49938. // when zooming. But it is difficult to know what is "consistent", considering
  49939. // axes have different type or even different meanings (For example, two
  49940. // time axes are used to compare data of the same date in different years).
  49941. // So basically dataZoom just obtains extent by series.data (in category axis
  49942. // extent can be obtained from axis.data).
  49943. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  49944. // consistent.
  49945. var axisModel = axisProxy.getAxisModel();
  49946. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  49947. return [rawExtentResult.min, rawExtentResult.max];
  49948. }
  49949. var dataZoomProcessor = {
  49950. // `dataZoomProcessor` will only be performed in needed series. Consider if
  49951. // there is a line series and a pie series, it is better not to update the
  49952. // line series if only pie series is needed to be updated.
  49953. getTargetSeries: function (ecModel) {
  49954. function eachAxisModel(cb) {
  49955. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49956. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  49957. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  49958. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  49959. });
  49960. });
  49961. }
  49962. // FIXME: it brings side-effect to `getTargetSeries`.
  49963. // Prepare axis proxies.
  49964. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  49965. // dispose all last axis proxy, in case that some axis are deleted.
  49966. axisModel.__dzAxisProxy = null;
  49967. });
  49968. var proxyList = [];
  49969. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  49970. // Different dataZooms may constrol the same axis. In that case,
  49971. // an axisProxy serves both of them.
  49972. if (!axisModel.__dzAxisProxy) {
  49973. // Use the first dataZoomModel as the main model of axisProxy.
  49974. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  49975. proxyList.push(axisModel.__dzAxisProxy);
  49976. }
  49977. });
  49978. var seriesModelMap = createHashMap();
  49979. each(proxyList, function (axisProxy) {
  49980. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  49981. seriesModelMap.set(seriesModel.uid, seriesModel);
  49982. });
  49983. });
  49984. return seriesModelMap;
  49985. },
  49986. // Consider appendData, where filter should be performed. Because data process is
  49987. // in block mode currently, it is not need to worry about that the overallProgress
  49988. // execute every frame.
  49989. overallReset: function (ecModel, api) {
  49990. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49991. // We calculate window and reset axis here but not in model
  49992. // init stage and not after action dispatch handler, because
  49993. // reset should be called after seriesData.restoreData.
  49994. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  49995. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  49996. });
  49997. // Caution: data zoom filtering is order sensitive when using
  49998. // percent range and no min/max/scale set on axis.
  49999. // For example, we have dataZoom definition:
  50000. // [
  50001. // {xAxisIndex: 0, start: 30, end: 70},
  50002. // {yAxisIndex: 0, start: 20, end: 80}
  50003. // ]
  50004. // In this case, [20, 80] of y-dataZoom should be based on data
  50005. // that have filtered by x-dataZoom using range of [30, 70],
  50006. // but should not be based on full raw data. Thus sliding
  50007. // x-dataZoom will change both ranges of xAxis and yAxis,
  50008. // while sliding y-dataZoom will only change the range of yAxis.
  50009. // So we should filter x-axis after reset x-axis immediately,
  50010. // and then reset y-axis and filter y-axis.
  50011. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  50012. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  50013. });
  50014. });
  50015. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  50016. // Fullfill all of the range props so that user
  50017. // is able to get them from chart.getOption().
  50018. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  50019. if (axisProxy) {
  50020. var percentRange = axisProxy.getDataPercentWindow();
  50021. var valueRange = axisProxy.getDataValueWindow();
  50022. dataZoomModel.setCalculatedRange({
  50023. start: percentRange[0],
  50024. end: percentRange[1],
  50025. startValue: valueRange[0],
  50026. endValue: valueRange[1]
  50027. });
  50028. }
  50029. });
  50030. }
  50031. };
  50032. function installDataZoomAction(registers) {
  50033. registers.registerAction('dataZoom', function (payload, ecModel) {
  50034. var effectedModels = findEffectedDataZooms(ecModel, payload);
  50035. each(effectedModels, function (dataZoomModel) {
  50036. dataZoomModel.setRawRange({
  50037. start: payload.start,
  50038. end: payload.end,
  50039. startValue: payload.startValue,
  50040. endValue: payload.endValue
  50041. });
  50042. });
  50043. });
  50044. }
  50045. var installed = false;
  50046. function installCommon(registers) {
  50047. if (installed) {
  50048. return;
  50049. }
  50050. installed = true;
  50051. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  50052. installDataZoomAction(registers);
  50053. registers.registerSubTypeDefaulter('dataZoom', function () {
  50054. // Default 'slider' when no type specified.
  50055. return 'slider';
  50056. });
  50057. }
  50058. function install$a(registers) {
  50059. registers.registerComponentModel(SelectDataZoomModel);
  50060. registers.registerComponentView(SelectDataZoomView);
  50061. installCommon(registers);
  50062. }
  50063. /*
  50064. * Licensed to the Apache Software Foundation (ASF) under one
  50065. * or more contributor license agreements. See the NOTICE file
  50066. * distributed with this work for additional information
  50067. * regarding copyright ownership. The ASF licenses this file
  50068. * to you under the Apache License, Version 2.0 (the
  50069. * "License"); you may not use this file except in compliance
  50070. * with the License. You may obtain a copy of the License at
  50071. *
  50072. * http://www.apache.org/licenses/LICENSE-2.0
  50073. *
  50074. * Unless required by applicable law or agreed to in writing,
  50075. * software distributed under the License is distributed on an
  50076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50077. * KIND, either express or implied. See the License for the
  50078. * specific language governing permissions and limitations
  50079. * under the License.
  50080. */
  50081. /**
  50082. * AUTO-GENERATED FILE. DO NOT MODIFY.
  50083. */
  50084. var ToolboxFeature = /** @class */function () {
  50085. function ToolboxFeature() {}
  50086. return ToolboxFeature;
  50087. }();
  50088. var features = {};
  50089. function registerFeature(name, ctor) {
  50090. features[name] = ctor;
  50091. }
  50092. function getFeature(name) {
  50093. return features[name];
  50094. }
  50095. var ToolboxModel = /** @class */function (_super) {
  50096. __extends(ToolboxModel, _super);
  50097. function ToolboxModel() {
  50098. var _this = _super !== null && _super.apply(this, arguments) || this;
  50099. _this.type = ToolboxModel.type;
  50100. return _this;
  50101. }
  50102. ToolboxModel.prototype.optionUpdated = function () {
  50103. _super.prototype.optionUpdated.apply(this, arguments);
  50104. var ecModel = this.ecModel;
  50105. each(this.option.feature, function (featureOpt, featureName) {
  50106. var Feature = getFeature(featureName);
  50107. if (Feature) {
  50108. if (Feature.getDefaultOption) {
  50109. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  50110. }
  50111. merge(featureOpt, Feature.defaultOption);
  50112. }
  50113. });
  50114. };
  50115. ToolboxModel.type = 'toolbox';
  50116. ToolboxModel.layoutMode = {
  50117. type: 'box',
  50118. ignoreSize: true
  50119. };
  50120. ToolboxModel.defaultOption = {
  50121. show: true,
  50122. z: 6,
  50123. // zlevel: 0,
  50124. orient: 'horizontal',
  50125. left: 'right',
  50126. top: 'top',
  50127. // right
  50128. // bottom
  50129. backgroundColor: 'transparent',
  50130. borderColor: tokens.color.border,
  50131. borderRadius: 0,
  50132. borderWidth: 0,
  50133. padding: tokens.size.m,
  50134. itemSize: 15,
  50135. itemGap: tokens.size.s,
  50136. showTitle: true,
  50137. iconStyle: {
  50138. borderColor: tokens.color.accent50,
  50139. color: 'none'
  50140. },
  50141. emphasis: {
  50142. iconStyle: {
  50143. borderColor: tokens.color.accent50
  50144. }
  50145. },
  50146. // textStyle: {},
  50147. // feature
  50148. tooltip: {
  50149. show: false,
  50150. position: 'bottom'
  50151. }
  50152. };
  50153. return ToolboxModel;
  50154. }(ComponentModel);
  50155. function makeBackground(rect, componentModel) {
  50156. var padding = normalizeCssArray$1(componentModel.get('padding'));
  50157. var style = componentModel.getItemStyle(['color', 'opacity']);
  50158. style.fill = componentModel.get('backgroundColor');
  50159. var bgRect = new Rect({
  50160. shape: {
  50161. x: rect.x - padding[3],
  50162. y: rect.y - padding[0],
  50163. width: rect.width + padding[1] + padding[3],
  50164. height: rect.height + padding[0] + padding[2],
  50165. r: componentModel.get('borderRadius')
  50166. },
  50167. style: style,
  50168. silent: true,
  50169. z2: -1
  50170. });
  50171. // FIXME
  50172. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  50173. // and background rect when setting like `left: 0`, `top: 0`.
  50174. // graphic.subPixelOptimizeRect(rect);
  50175. return bgRect;
  50176. }
  50177. var ToolboxView = /** @class */function (_super) {
  50178. __extends(ToolboxView, _super);
  50179. function ToolboxView() {
  50180. return _super !== null && _super.apply(this, arguments) || this;
  50181. }
  50182. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  50183. var group = this.group;
  50184. group.removeAll();
  50185. if (!toolboxModel.get('show')) {
  50186. return;
  50187. }
  50188. var itemSize = +toolboxModel.get('itemSize');
  50189. var isVertical = toolboxModel.get('orient') === 'vertical';
  50190. var featureOpts = toolboxModel.get('feature') || {};
  50191. var features = this._features || (this._features = {});
  50192. var featureNames = [];
  50193. each(featureOpts, function (opt, name) {
  50194. featureNames.push(name);
  50195. });
  50196. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute();
  50197. // Keep for diff.
  50198. this._featureNames = featureNames;
  50199. function processFeature(newIndex, oldIndex) {
  50200. var featureName = featureNames[newIndex];
  50201. var oldName = featureNames[oldIndex];
  50202. var featureOpt = featureOpts[featureName];
  50203. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  50204. var feature;
  50205. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  50206. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  50207. featureOpt.title = payload.newTitle;
  50208. }
  50209. if (featureName && !oldName) {
  50210. // Create
  50211. if (isUserFeatureName(featureName)) {
  50212. feature = {
  50213. onclick: featureModel.option.onclick,
  50214. featureName: featureName
  50215. };
  50216. } else {
  50217. var Feature = getFeature(featureName);
  50218. if (!Feature) {
  50219. return;
  50220. }
  50221. feature = new Feature();
  50222. }
  50223. features[featureName] = feature;
  50224. } else {
  50225. feature = features[oldName];
  50226. // If feature does not exist.
  50227. if (!feature) {
  50228. return;
  50229. }
  50230. }
  50231. feature.uid = getUID('toolbox-feature');
  50232. feature.model = featureModel;
  50233. feature.ecModel = ecModel;
  50234. feature.api = api;
  50235. var isToolboxFeature = feature instanceof ToolboxFeature;
  50236. if (!featureName && oldName) {
  50237. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  50238. return;
  50239. }
  50240. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  50241. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  50242. return;
  50243. }
  50244. createIconPaths(featureModel, feature, featureName);
  50245. featureModel.setIconStatus = function (iconName, status) {
  50246. var option = this.option;
  50247. var iconPaths = this.iconPaths;
  50248. option.iconStatus = option.iconStatus || {};
  50249. option.iconStatus[iconName] = status;
  50250. if (iconPaths[iconName]) {
  50251. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  50252. }
  50253. };
  50254. if (feature instanceof ToolboxFeature) {
  50255. if (feature.render) {
  50256. feature.render(featureModel, ecModel, api, payload);
  50257. }
  50258. }
  50259. }
  50260. function createIconPaths(featureModel, feature, featureName) {
  50261. var iconStyleModel = featureModel.getModel('iconStyle');
  50262. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']);
  50263. // If one feature has multiple icons, they are organized as
  50264. // {
  50265. // icon: {
  50266. // foo: '',
  50267. // bar: ''
  50268. // },
  50269. // title: {
  50270. // foo: '',
  50271. // bar: ''
  50272. // }
  50273. // }
  50274. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  50275. var titles = featureModel.get('title') || {};
  50276. var iconsMap;
  50277. var titlesMap;
  50278. if (isString(icons)) {
  50279. iconsMap = {};
  50280. iconsMap[featureName] = icons;
  50281. } else {
  50282. iconsMap = icons;
  50283. }
  50284. if (isString(titles)) {
  50285. titlesMap = {};
  50286. titlesMap[featureName] = titles;
  50287. } else {
  50288. titlesMap = titles;
  50289. }
  50290. var iconPaths = featureModel.iconPaths = {};
  50291. each(iconsMap, function (iconStr, iconName) {
  50292. var path = createIcon(iconStr, {}, {
  50293. x: -itemSize / 2,
  50294. y: -itemSize / 2,
  50295. width: itemSize,
  50296. height: itemSize
  50297. }); // TODO handling image
  50298. path.setStyle(iconStyleModel.getItemStyle());
  50299. var pathEmphasisState = path.ensureState('emphasis');
  50300. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle();
  50301. // Text position calculation
  50302. // TODO: extract `textStyle` from `iconStyle` and use `createTextStyle`
  50303. var textContent = new ZRText({
  50304. style: {
  50305. text: titlesMap[iconName],
  50306. align: iconStyleEmphasisModel.get('textAlign'),
  50307. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  50308. padding: iconStyleEmphasisModel.get('textPadding'),
  50309. fill: null,
  50310. font: getFont({
  50311. fontStyle: iconStyleEmphasisModel.get('textFontStyle'),
  50312. fontFamily: iconStyleEmphasisModel.get('textFontFamily'),
  50313. fontSize: iconStyleEmphasisModel.get('textFontSize'),
  50314. fontWeight: iconStyleEmphasisModel.get('textFontWeight')
  50315. }, ecModel)
  50316. },
  50317. ignore: true
  50318. });
  50319. path.setTextContent(textContent);
  50320. setTooltipConfig({
  50321. el: path,
  50322. componentModel: toolboxModel,
  50323. itemName: iconName,
  50324. formatterParamsExtra: {
  50325. title: titlesMap[iconName]
  50326. }
  50327. });
  50328. path.__title = titlesMap[iconName];
  50329. path.on('mouseover', function () {
  50330. // Should not reuse above hoverStyle, which might be modified.
  50331. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50332. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  50333. textContent.setStyle({
  50334. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || tokens.color.neutral99,
  50335. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  50336. });
  50337. path.setTextConfig({
  50338. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  50339. });
  50340. textContent.ignore = !toolboxModel.get('showTitle');
  50341. // Use enterEmphasis and leaveEmphasis provide by ec.
  50342. // There are flags managed by the echarts.
  50343. api.enterEmphasis(this);
  50344. }).on('mouseout', function () {
  50345. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  50346. api.leaveEmphasis(this);
  50347. }
  50348. textContent.hide();
  50349. });
  50350. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  50351. group.add(path);
  50352. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  50353. iconPaths[iconName] = path;
  50354. });
  50355. }
  50356. var refContainer = createBoxLayoutReference(toolboxModel, api).refContainer;
  50357. var boxLayoutParams = toolboxModel.getBoxLayoutParams();
  50358. var padding = toolboxModel.get('padding');
  50359. var viewRect = getLayoutRect(boxLayoutParams, refContainer, padding);
  50360. box(toolboxModel.get('orient'), group, toolboxModel.get('itemGap'), viewRect.width, viewRect.height);
  50361. positionElement(group, boxLayoutParams, refContainer, padding);
  50362. // Render background after group is layout
  50363. // FIXME
  50364. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  50365. // Adjust icon title positions to avoid them out of screen
  50366. isVertical || group.eachChild(function (icon) {
  50367. var titleText = icon.__title;
  50368. // const hoverStyle = icon.hoverStyle;
  50369. // TODO simplify code?
  50370. var emphasisState = icon.ensureState('emphasis');
  50371. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  50372. var textContent = icon.getTextContent();
  50373. var emphasisTextState = textContent && textContent.ensureState('emphasis');
  50374. // May be background element
  50375. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  50376. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  50377. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  50378. var offsetX = icon.x + group.x;
  50379. var offsetY = icon.y + group.y + itemSize;
  50380. var needPutOnTop = false;
  50381. if (offsetY + rect.height > api.getHeight()) {
  50382. emphasisTextConfig.position = 'top';
  50383. needPutOnTop = true;
  50384. }
  50385. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  50386. if (offsetX + rect.width / 2 > api.getWidth()) {
  50387. emphasisTextConfig.position = ['100%', topOffset];
  50388. emphasisTextStyle.align = 'right';
  50389. } else if (offsetX - rect.width / 2 < 0) {
  50390. emphasisTextConfig.position = [0, topOffset];
  50391. emphasisTextStyle.align = 'left';
  50392. }
  50393. }
  50394. });
  50395. };
  50396. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  50397. each(this._features, function (feature) {
  50398. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  50399. });
  50400. };
  50401. // updateLayout(toolboxModel, ecModel, api, payload) {
  50402. // zrUtil.each(this._features, function (feature) {
  50403. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  50404. // });
  50405. // },
  50406. ToolboxView.prototype.remove = function (ecModel, api) {
  50407. each(this._features, function (feature) {
  50408. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  50409. });
  50410. this.group.removeAll();
  50411. };
  50412. ToolboxView.prototype.dispose = function (ecModel, api) {
  50413. each(this._features, function (feature) {
  50414. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  50415. });
  50416. };
  50417. ToolboxView.type = 'toolbox';
  50418. return ToolboxView;
  50419. }(ComponentView);
  50420. function isUserFeatureName(featureName) {
  50421. return featureName.indexOf('my') === 0;
  50422. }
  50423. var SaveAsImage = /** @class */function (_super) {
  50424. __extends(SaveAsImage, _super);
  50425. function SaveAsImage() {
  50426. return _super !== null && _super.apply(this, arguments) || this;
  50427. }
  50428. SaveAsImage.prototype.onclick = function (ecModel, api) {
  50429. var model = this.model;
  50430. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  50431. var isSvg = api.getZr().painter.getType() === 'svg';
  50432. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  50433. var url = api.getConnectedDataURL({
  50434. type: type,
  50435. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || tokens.color.neutral00,
  50436. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  50437. excludeComponents: model.get('excludeComponents'),
  50438. pixelRatio: model.get('pixelRatio')
  50439. });
  50440. var browser = env.browser;
  50441. // Chrome, Firefox, New Edge
  50442. if (typeof MouseEvent === 'function' && (browser.newEdge || !browser.ie && !browser.edge)) {
  50443. var $a = document.createElement('a');
  50444. $a.download = title + '.' + type;
  50445. $a.target = '_blank';
  50446. $a.href = url;
  50447. var evt = new MouseEvent('click', {
  50448. // some micro front-end framework, window maybe is a Proxy
  50449. view: document.defaultView,
  50450. bubbles: true,
  50451. cancelable: false
  50452. });
  50453. $a.dispatchEvent(evt);
  50454. }
  50455. // IE or old Edge
  50456. else {
  50457. // @ts-ignore
  50458. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  50459. var parts = url.split(',');
  50460. // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  50461. var base64Encoded = parts[0].indexOf('base64') > -1;
  50462. var bstr = isSvg
  50463. // should decode the svg data uri first
  50464. ? decodeURIComponent(parts[1]) : parts[1];
  50465. // only `atob` when the data uri is encoded with base64
  50466. // otherwise, like `svg` data uri exported by zrender,
  50467. // there will be an error, for it's not encoded with base64.
  50468. // (just a url-encoded string through `encodeURIComponent`)
  50469. base64Encoded && (bstr = window.atob(bstr));
  50470. var filename = title + '.' + type;
  50471. // @ts-ignore
  50472. if (window.navigator.msSaveOrOpenBlob) {
  50473. var n = bstr.length;
  50474. var u8arr = new Uint8Array(n);
  50475. while (n--) {
  50476. u8arr[n] = bstr.charCodeAt(n);
  50477. }
  50478. var blob = new Blob([u8arr]); // @ts-ignore
  50479. window.navigator.msSaveOrOpenBlob(blob, filename);
  50480. } else {
  50481. var frame = document.createElement('iframe');
  50482. document.body.appendChild(frame);
  50483. var cw = frame.contentWindow;
  50484. var doc = cw.document;
  50485. doc.open('image/svg+xml', 'replace');
  50486. doc.write(bstr);
  50487. doc.close();
  50488. cw.focus();
  50489. doc.execCommand('SaveAs', true, filename);
  50490. document.body.removeChild(frame);
  50491. }
  50492. } else {
  50493. var lang = model.get('lang');
  50494. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  50495. var tab = window.open();
  50496. tab.document.write(html);
  50497. tab.document.title = title;
  50498. }
  50499. }
  50500. };
  50501. SaveAsImage.getDefaultOption = function (ecModel) {
  50502. var defaultOption = {
  50503. show: true,
  50504. 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',
  50505. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  50506. type: 'png',
  50507. // Default use option.backgroundColor
  50508. // backgroundColor: '#fff',
  50509. connectedBackgroundColor: tokens.color.neutral00,
  50510. name: '',
  50511. excludeComponents: ['toolbox'],
  50512. // use current pixel ratio of device by default
  50513. // pixelRatio: 1,
  50514. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  50515. };
  50516. return defaultOption;
  50517. };
  50518. return SaveAsImage;
  50519. }(ToolboxFeature);
  50520. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  50521. var radioTypes = [['line', 'bar'], ['stack']];
  50522. var MagicType = /** @class */function (_super) {
  50523. __extends(MagicType, _super);
  50524. function MagicType() {
  50525. return _super !== null && _super.apply(this, arguments) || this;
  50526. }
  50527. MagicType.prototype.getIcons = function () {
  50528. var model = this.model;
  50529. var availableIcons = model.get('icon');
  50530. var icons = {};
  50531. each(model.get('type'), function (type) {
  50532. if (availableIcons[type]) {
  50533. icons[type] = availableIcons[type];
  50534. }
  50535. });
  50536. return icons;
  50537. };
  50538. MagicType.getDefaultOption = function (ecModel) {
  50539. var defaultOption = {
  50540. show: true,
  50541. type: [],
  50542. // Icon group
  50543. icon: {
  50544. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  50545. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  50546. // eslint-disable-next-line
  50547. 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
  50548. },
  50549. // `line`, `bar`, `stack`, `tiled`
  50550. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  50551. option: {},
  50552. seriesIndex: {}
  50553. };
  50554. return defaultOption;
  50555. };
  50556. MagicType.prototype.onclick = function (ecModel, api, type) {
  50557. var model = this.model;
  50558. var seriesIndex = model.get(['seriesIndex', type]);
  50559. // Not supported magicType
  50560. if (!seriesOptGenreator[type]) {
  50561. return;
  50562. }
  50563. var newOption = {
  50564. series: []
  50565. };
  50566. var generateNewSeriesTypes = function (seriesModel) {
  50567. var seriesType = seriesModel.subType;
  50568. var seriesId = seriesModel.id;
  50569. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  50570. if (newSeriesOpt) {
  50571. // PENDING If merge original option?
  50572. defaults(newSeriesOpt, seriesModel.option);
  50573. newOption.series.push(newSeriesOpt);
  50574. }
  50575. // Modify boundaryGap
  50576. var coordSys = seriesModel.coordinateSystem;
  50577. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  50578. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  50579. if (categoryAxis) {
  50580. var axisDim = categoryAxis.dim;
  50581. var axisType = axisDim + 'Axis';
  50582. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  50583. var axisIndex = axisModel.componentIndex;
  50584. newOption[axisType] = newOption[axisType] || [];
  50585. for (var i = 0; i <= axisIndex; i++) {
  50586. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  50587. }
  50588. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  50589. }
  50590. }
  50591. };
  50592. each(radioTypes, function (radio) {
  50593. if (indexOf(radio, type) >= 0) {
  50594. each(radio, function (item) {
  50595. model.setIconStatus(item, 'normal');
  50596. });
  50597. }
  50598. });
  50599. model.setIconStatus(type, 'emphasis');
  50600. ecModel.eachComponent({
  50601. mainType: 'series',
  50602. query: seriesIndex == null ? null : {
  50603. seriesIndex: seriesIndex
  50604. }
  50605. }, generateNewSeriesTypes);
  50606. var newTitle;
  50607. var currentType = type;
  50608. // Change title of stack
  50609. if (type === 'stack') {
  50610. // use titles in model instead of ecModel
  50611. // as stack and tiled appears in pair, just flip them
  50612. // no need of checking stack state
  50613. newTitle = merge({
  50614. stack: model.option.title.tiled,
  50615. tiled: model.option.title.stack
  50616. }, model.option.title);
  50617. if (model.get(['iconStatus', type]) !== 'emphasis') {
  50618. currentType = 'tiled';
  50619. }
  50620. }
  50621. api.dispatchAction({
  50622. type: 'changeMagicType',
  50623. currentType: currentType,
  50624. newOption: newOption,
  50625. newTitle: newTitle,
  50626. featureName: 'magicType'
  50627. });
  50628. };
  50629. return MagicType;
  50630. }(ToolboxFeature);
  50631. var seriesOptGenreator = {
  50632. 'line': function (seriesType, seriesId, seriesModel, model) {
  50633. if (seriesType === 'bar') {
  50634. return merge({
  50635. id: seriesId,
  50636. type: 'line',
  50637. // Preserve data related option
  50638. data: seriesModel.get('data'),
  50639. stack: seriesModel.get('stack'),
  50640. markPoint: seriesModel.get('markPoint'),
  50641. markLine: seriesModel.get('markLine')
  50642. }, model.get(['option', 'line']) || {}, true);
  50643. }
  50644. },
  50645. 'bar': function (seriesType, seriesId, seriesModel, model) {
  50646. if (seriesType === 'line') {
  50647. return merge({
  50648. id: seriesId,
  50649. type: 'bar',
  50650. // Preserve data related option
  50651. data: seriesModel.get('data'),
  50652. stack: seriesModel.get('stack'),
  50653. markPoint: seriesModel.get('markPoint'),
  50654. markLine: seriesModel.get('markLine')
  50655. }, model.get(['option', 'bar']) || {}, true);
  50656. }
  50657. },
  50658. 'stack': function (seriesType, seriesId, seriesModel, model) {
  50659. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  50660. if (seriesType === 'line' || seriesType === 'bar') {
  50661. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  50662. return merge({
  50663. id: seriesId,
  50664. stack: isStack ? '' : INNER_STACK_KEYWORD
  50665. }, model.get(['option', 'stack']) || {}, true);
  50666. }
  50667. }
  50668. };
  50669. // TODO: SELF REGISTERED.
  50670. registerAction({
  50671. type: 'changeMagicType',
  50672. event: 'magicTypeChanged',
  50673. update: 'prepareAndUpdate'
  50674. }, function (payload, ecModel) {
  50675. ecModel.mergeOption(payload.newOption);
  50676. });
  50677. /* global document */
  50678. var BLOCK_SPLITER = new Array(60).join('-');
  50679. var ITEM_SPLITER = '\t';
  50680. /**
  50681. * Group series into two types
  50682. * 1. on category axis, like line, bar
  50683. * 2. others, like scatter, pie
  50684. */
  50685. function groupSeries(ecModel) {
  50686. var seriesGroupByCategoryAxis = {};
  50687. var otherSeries = [];
  50688. var meta = [];
  50689. ecModel.eachRawSeries(function (seriesModel) {
  50690. var coordSys = seriesModel.coordinateSystem;
  50691. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  50692. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  50693. var baseAxis = coordSys.getBaseAxis();
  50694. if (baseAxis.type === 'category') {
  50695. var key = baseAxis.dim + '_' + baseAxis.index;
  50696. if (!seriesGroupByCategoryAxis[key]) {
  50697. seriesGroupByCategoryAxis[key] = {
  50698. categoryAxis: baseAxis,
  50699. valueAxis: coordSys.getOtherAxis(baseAxis),
  50700. series: []
  50701. };
  50702. meta.push({
  50703. axisDim: baseAxis.dim,
  50704. axisIndex: baseAxis.index
  50705. });
  50706. }
  50707. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  50708. } else {
  50709. otherSeries.push(seriesModel);
  50710. }
  50711. } else {
  50712. otherSeries.push(seriesModel);
  50713. }
  50714. });
  50715. return {
  50716. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  50717. other: otherSeries,
  50718. meta: meta
  50719. };
  50720. }
  50721. /**
  50722. * Assemble content of series on cateogory axis
  50723. * @inner
  50724. */
  50725. function assembleSeriesWithCategoryAxis(groups) {
  50726. var tables = [];
  50727. each(groups, function (group, key) {
  50728. var categoryAxis = group.categoryAxis;
  50729. var valueAxis = group.valueAxis;
  50730. var valueAxisDim = valueAxis.dim;
  50731. var headers = [' '].concat(map(group.series, function (series) {
  50732. return series.name;
  50733. }));
  50734. // @ts-ignore TODO Polar
  50735. var columns = [categoryAxis.model.getCategories()];
  50736. each(group.series, function (series) {
  50737. var rawData = series.getRawData();
  50738. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  50739. return val;
  50740. }));
  50741. });
  50742. // Assemble table content
  50743. var lines = [headers.join(ITEM_SPLITER)];
  50744. for (var i = 0; i < columns[0].length; i++) {
  50745. var items = [];
  50746. for (var j = 0; j < columns.length; j++) {
  50747. items.push(columns[j][i]);
  50748. }
  50749. lines.push(items.join(ITEM_SPLITER));
  50750. }
  50751. tables.push(lines.join('\n'));
  50752. });
  50753. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  50754. }
  50755. /**
  50756. * Assemble content of other series
  50757. */
  50758. function assembleOtherSeries(series) {
  50759. return map(series, function (series) {
  50760. var data = series.getRawData();
  50761. var lines = [series.name];
  50762. var vals = [];
  50763. data.each(data.dimensions, function () {
  50764. var argLen = arguments.length;
  50765. var dataIndex = arguments[argLen - 1];
  50766. var name = data.getName(dataIndex);
  50767. for (var i = 0; i < argLen - 1; i++) {
  50768. vals[i] = arguments[i];
  50769. }
  50770. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  50771. });
  50772. return lines.join('\n');
  50773. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  50774. }
  50775. function getContentFromModel(ecModel) {
  50776. var result = groupSeries(ecModel);
  50777. return {
  50778. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  50779. return !!str.replace(/[\n\t\s]/g, '');
  50780. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  50781. meta: result.meta
  50782. };
  50783. }
  50784. function trim$1(str) {
  50785. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  50786. }
  50787. /**
  50788. * If a block is tsv format
  50789. */
  50790. function isTSVFormat(block) {
  50791. // Simple method to find out if a block is tsv format
  50792. var firstLine = block.slice(0, block.indexOf('\n'));
  50793. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  50794. return true;
  50795. }
  50796. }
  50797. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  50798. /**
  50799. * @param {string} tsv
  50800. * @return {Object}
  50801. */
  50802. function parseTSVContents(tsv) {
  50803. var tsvLines = tsv.split(/\n+/g);
  50804. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  50805. var categories = [];
  50806. var series = map(headers, function (header) {
  50807. return {
  50808. name: header,
  50809. data: []
  50810. };
  50811. });
  50812. for (var i = 0; i < tsvLines.length; i++) {
  50813. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  50814. categories.push(items.shift());
  50815. for (var j = 0; j < items.length; j++) {
  50816. series[j] && (series[j].data[i] = items[j]);
  50817. }
  50818. }
  50819. return {
  50820. series: series,
  50821. categories: categories
  50822. };
  50823. }
  50824. function parseListContents(str) {
  50825. var lines = str.split(/\n+/g);
  50826. var seriesName = trim$1(lines.shift());
  50827. var data = [];
  50828. for (var i = 0; i < lines.length; i++) {
  50829. // if line is empty, ignore it.
  50830. // there is a case that a user forgot to delete `\n`.
  50831. var line = trim$1(lines[i]);
  50832. if (!line) {
  50833. continue;
  50834. }
  50835. var items = line.split(itemSplitRegex);
  50836. var name_1 = '';
  50837. var value = void 0;
  50838. var hasName = false;
  50839. if (isNaN(items[0])) {
  50840. // First item is name
  50841. hasName = true;
  50842. name_1 = items[0];
  50843. items = items.slice(1);
  50844. data[i] = {
  50845. name: name_1,
  50846. value: []
  50847. };
  50848. value = data[i].value;
  50849. } else {
  50850. value = data[i] = [];
  50851. }
  50852. for (var j = 0; j < items.length; j++) {
  50853. value.push(+items[j]);
  50854. }
  50855. if (value.length === 1) {
  50856. hasName ? data[i].value = value[0] : data[i] = value[0];
  50857. }
  50858. }
  50859. return {
  50860. name: seriesName,
  50861. data: data
  50862. };
  50863. }
  50864. function parseContents(str, blockMetaList) {
  50865. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  50866. var newOption = {
  50867. series: []
  50868. };
  50869. each(blocks, function (block, idx) {
  50870. if (isTSVFormat(block)) {
  50871. var result = parseTSVContents(block);
  50872. var blockMeta = blockMetaList[idx];
  50873. var axisKey = blockMeta.axisDim + 'Axis';
  50874. if (blockMeta) {
  50875. newOption[axisKey] = newOption[axisKey] || [];
  50876. newOption[axisKey][blockMeta.axisIndex] = {
  50877. data: result.categories
  50878. };
  50879. newOption.series = newOption.series.concat(result.series);
  50880. }
  50881. } else {
  50882. var result = parseListContents(block);
  50883. newOption.series.push(result);
  50884. }
  50885. });
  50886. return newOption;
  50887. }
  50888. var DataView = /** @class */function (_super) {
  50889. __extends(DataView, _super);
  50890. function DataView() {
  50891. return _super !== null && _super.apply(this, arguments) || this;
  50892. }
  50893. DataView.prototype.onclick = function (ecModel, api) {
  50894. // FIXME: better way?
  50895. setTimeout(function () {
  50896. api.dispatchAction({
  50897. type: 'hideTip'
  50898. });
  50899. });
  50900. var container = api.getDom();
  50901. var model = this.model;
  50902. if (this._dom) {
  50903. container.removeChild(this._dom);
  50904. }
  50905. var root = document.createElement('div');
  50906. // use padding to avoid 5px whitespace
  50907. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  50908. root.style.backgroundColor = model.get('backgroundColor') || tokens.color.neutral00;
  50909. // Create elements
  50910. var header = document.createElement('h4');
  50911. var lang = model.get('lang') || [];
  50912. header.innerHTML = lang[0] || model.get('title');
  50913. header.style.cssText = 'margin:10px 20px';
  50914. header.style.color = model.get('textColor');
  50915. var viewMain = document.createElement('div');
  50916. var textarea = document.createElement('textarea');
  50917. viewMain.style.cssText = 'overflow:auto';
  50918. var optionToContent = model.get('optionToContent');
  50919. var contentToOption = model.get('contentToOption');
  50920. var result = getContentFromModel(ecModel);
  50921. if (isFunction(optionToContent)) {
  50922. var htmlOrDom = optionToContent(api.getOption());
  50923. if (isString(htmlOrDom)) {
  50924. viewMain.innerHTML = htmlOrDom;
  50925. } else if (isDom(htmlOrDom)) {
  50926. viewMain.appendChild(htmlOrDom);
  50927. }
  50928. } else {
  50929. // Use default textarea
  50930. textarea.readOnly = model.get('readOnly');
  50931. var style = textarea.style;
  50932. // eslint-disable-next-line max-len
  50933. 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';
  50934. style.color = model.get('textColor');
  50935. style.borderColor = model.get('textareaBorderColor');
  50936. style.backgroundColor = model.get('textareaColor');
  50937. textarea.value = result.value;
  50938. viewMain.appendChild(textarea);
  50939. }
  50940. var blockMetaList = result.meta;
  50941. var buttonContainer = document.createElement('div');
  50942. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0';
  50943. // eslint-disable-next-line max-len
  50944. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  50945. var closeButton = document.createElement('div');
  50946. var refreshButton = document.createElement('div');
  50947. buttonStyle += ';background-color:' + model.get('buttonColor');
  50948. buttonStyle += ';color:' + model.get('buttonTextColor');
  50949. var self = this;
  50950. function close() {
  50951. container.removeChild(root);
  50952. self._dom = null;
  50953. }
  50954. addEventListener(closeButton, 'click', close);
  50955. addEventListener(refreshButton, 'click', function () {
  50956. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  50957. if ("development" !== 'production') {
  50958. // eslint-disable-next-line
  50959. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  50960. }
  50961. close();
  50962. return;
  50963. }
  50964. var newOption;
  50965. try {
  50966. if (isFunction(contentToOption)) {
  50967. newOption = contentToOption(viewMain, api.getOption());
  50968. } else {
  50969. newOption = parseContents(textarea.value, blockMetaList);
  50970. }
  50971. } catch (e) {
  50972. close();
  50973. throw new Error('Data view format error ' + e);
  50974. }
  50975. if (newOption) {
  50976. api.dispatchAction({
  50977. type: 'changeDataView',
  50978. newOption: newOption
  50979. });
  50980. }
  50981. close();
  50982. });
  50983. closeButton.innerHTML = lang[1];
  50984. refreshButton.innerHTML = lang[2];
  50985. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  50986. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  50987. buttonContainer.appendChild(closeButton);
  50988. root.appendChild(header);
  50989. root.appendChild(viewMain);
  50990. root.appendChild(buttonContainer);
  50991. viewMain.style.height = container.clientHeight - 80 + 'px';
  50992. container.appendChild(root);
  50993. this._dom = root;
  50994. };
  50995. DataView.prototype.remove = function (ecModel, api) {
  50996. this._dom && api.getDom().removeChild(this._dom);
  50997. };
  50998. DataView.prototype.dispose = function (ecModel, api) {
  50999. this.remove(ecModel, api);
  51000. };
  51001. DataView.getDefaultOption = function (ecModel) {
  51002. var defaultOption = {
  51003. show: true,
  51004. readOnly: false,
  51005. optionToContent: null,
  51006. contentToOption: null,
  51007. // eslint-disable-next-line
  51008. 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',
  51009. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  51010. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  51011. backgroundColor: tokens.color.background,
  51012. textColor: tokens.color.primary,
  51013. textareaColor: tokens.color.background,
  51014. textareaBorderColor: tokens.color.border,
  51015. buttonColor: tokens.color.accent50,
  51016. buttonTextColor: tokens.color.neutral00
  51017. };
  51018. return defaultOption;
  51019. };
  51020. return DataView;
  51021. }(ToolboxFeature);
  51022. /**
  51023. * @inner
  51024. */
  51025. function tryMergeDataOption(newData, originalData) {
  51026. return map(newData, function (newVal, idx) {
  51027. var original = originalData && originalData[idx];
  51028. if (isObject(original) && !isArray(original)) {
  51029. var newValIsObject = isObject(newVal) && !isArray(newVal);
  51030. if (!newValIsObject) {
  51031. newVal = {
  51032. value: newVal
  51033. };
  51034. }
  51035. // original data has name but new data has no name
  51036. var shouldDeleteName = original.name != null && newVal.name == null;
  51037. // Original data has option
  51038. newVal = defaults(newVal, original);
  51039. shouldDeleteName && delete newVal.name;
  51040. return newVal;
  51041. } else {
  51042. return newVal;
  51043. }
  51044. });
  51045. }
  51046. // TODO: SELF REGISTERED.
  51047. registerAction({
  51048. type: 'changeDataView',
  51049. event: 'dataViewChanged',
  51050. update: 'prepareAndUpdate'
  51051. }, function (payload, ecModel) {
  51052. var newSeriesOptList = [];
  51053. each(payload.newOption.series, function (seriesOpt) {
  51054. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  51055. if (!seriesModel) {
  51056. // New created series
  51057. // Geuss the series type
  51058. newSeriesOptList.push(extend({
  51059. // Default is scatter
  51060. type: 'scatter'
  51061. }, seriesOpt));
  51062. } else {
  51063. var originalData = seriesModel.get('data');
  51064. newSeriesOptList.push({
  51065. name: seriesOpt.name,
  51066. data: tryMergeDataOption(seriesOpt.data, originalData)
  51067. });
  51068. }
  51069. });
  51070. ecModel.mergeOption(defaults({
  51071. series: newSeriesOptList
  51072. }, payload.newOption));
  51073. });
  51074. var each$5 = each;
  51075. var inner$a = makeInner();
  51076. /**
  51077. * @param ecModel
  51078. * @param newSnapshot key is dataZoomId
  51079. */
  51080. function push(ecModel, newSnapshot) {
  51081. var storedSnapshots = getStoreSnapshots(ecModel);
  51082. // If previous dataZoom can not be found,
  51083. // complete an range with current range.
  51084. each$5(newSnapshot, function (batchItem, dataZoomId) {
  51085. var i = storedSnapshots.length - 1;
  51086. for (; i >= 0; i--) {
  51087. var snapshot = storedSnapshots[i];
  51088. if (snapshot[dataZoomId]) {
  51089. break;
  51090. }
  51091. }
  51092. if (i < 0) {
  51093. // No origin range set, create one by current range.
  51094. var dataZoomModel = ecModel.queryComponents({
  51095. mainType: 'dataZoom',
  51096. subType: 'select',
  51097. id: dataZoomId
  51098. })[0];
  51099. if (dataZoomModel) {
  51100. var percentRange = dataZoomModel.getPercentRange();
  51101. storedSnapshots[0][dataZoomId] = {
  51102. dataZoomId: dataZoomId,
  51103. start: percentRange[0],
  51104. end: percentRange[1]
  51105. };
  51106. }
  51107. }
  51108. });
  51109. storedSnapshots.push(newSnapshot);
  51110. }
  51111. function pop(ecModel) {
  51112. var storedSnapshots = getStoreSnapshots(ecModel);
  51113. var head = storedSnapshots[storedSnapshots.length - 1];
  51114. storedSnapshots.length > 1 && storedSnapshots.pop();
  51115. // Find top for all dataZoom.
  51116. var snapshot = {};
  51117. each$5(head, function (batchItem, dataZoomId) {
  51118. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  51119. batchItem = storedSnapshots[i][dataZoomId];
  51120. if (batchItem) {
  51121. snapshot[dataZoomId] = batchItem;
  51122. break;
  51123. }
  51124. }
  51125. });
  51126. return snapshot;
  51127. }
  51128. function clear$1(ecModel) {
  51129. inner$a(ecModel).snapshots = null;
  51130. }
  51131. function count(ecModel) {
  51132. return getStoreSnapshots(ecModel).length;
  51133. }
  51134. /**
  51135. * History length of each dataZoom may be different.
  51136. * this._history[0] is used to store origin range.
  51137. */
  51138. function getStoreSnapshots(ecModel) {
  51139. var store = inner$a(ecModel);
  51140. if (!store.snapshots) {
  51141. store.snapshots = [{}];
  51142. }
  51143. return store.snapshots;
  51144. }
  51145. var RestoreOption = /** @class */function (_super) {
  51146. __extends(RestoreOption, _super);
  51147. function RestoreOption() {
  51148. return _super !== null && _super.apply(this, arguments) || this;
  51149. }
  51150. RestoreOption.prototype.onclick = function (ecModel, api) {
  51151. clear$1(ecModel);
  51152. api.dispatchAction({
  51153. type: 'restore',
  51154. from: this.uid
  51155. });
  51156. };
  51157. RestoreOption.getDefaultOption = function (ecModel) {
  51158. var defaultOption = {
  51159. show: true,
  51160. // eslint-disable-next-line
  51161. 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',
  51162. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  51163. };
  51164. return defaultOption;
  51165. };
  51166. return RestoreOption;
  51167. }(ToolboxFeature);
  51168. // TODO: SELF REGISTERED.
  51169. registerAction({
  51170. type: 'restore',
  51171. event: 'restore',
  51172. update: 'prepareAndUpdate'
  51173. }, function (payload, ecModel) {
  51174. ecModel.resetOption('recreate');
  51175. });
  51176. var inner$b = makeInner();
  51177. function take(zr, resourceKey, userKey) {
  51178. inner$b(zr)[resourceKey] = userKey;
  51179. }
  51180. function release(zr, resourceKey, userKey) {
  51181. var store = inner$b(zr);
  51182. var uKey = store[resourceKey];
  51183. if (uKey === userKey) {
  51184. store[resourceKey] = null;
  51185. }
  51186. }
  51187. function isTaken(zr, resourceKey) {
  51188. return !!inner$b(zr)[resourceKey];
  51189. }
  51190. /**
  51191. * payload: {
  51192. * type: 'takeGlobalCursor',
  51193. * key: 'dataZoomSelect', or 'brush', or ...,
  51194. * If no userKey, release global cursor.
  51195. * }
  51196. */
  51197. // TODO: SELF REGISTERED.
  51198. registerAction({
  51199. type: 'takeGlobalCursor',
  51200. event: 'globalCursorTaken',
  51201. update: 'update'
  51202. }, noop);
  51203. var BRUSH_PANEL_GLOBAL = true;
  51204. var mathMin$8 = Math.min;
  51205. var mathMax$8 = Math.max;
  51206. var mathPow$2 = Math.pow;
  51207. var COVER_Z = 10000;
  51208. var UNSELECT_THRESHOLD = 6;
  51209. var MIN_RESIZE_LINE_WIDTH = 6;
  51210. var MUTEX_RESOURCE_KEY = 'globalPan';
  51211. var DIRECTION_MAP = {
  51212. w: [0, 0],
  51213. e: [0, 1],
  51214. n: [1, 0],
  51215. s: [1, 1]
  51216. };
  51217. var CURSOR_MAP = {
  51218. w: 'ew',
  51219. e: 'ew',
  51220. n: 'ns',
  51221. s: 'ns',
  51222. ne: 'nesw',
  51223. sw: 'nesw',
  51224. nw: 'nwse',
  51225. se: 'nwse'
  51226. };
  51227. var DEFAULT_BRUSH_OPT = {
  51228. brushStyle: {
  51229. lineWidth: 2,
  51230. stroke: tokens.color.backgroundTint,
  51231. fill: tokens.color.borderTint
  51232. },
  51233. transformable: true,
  51234. brushMode: 'single',
  51235. removeOnClick: false
  51236. };
  51237. var baseUID = 0;
  51238. /**
  51239. * params:
  51240. * areas: Array.<Array>, coord relates to container group,
  51241. * If no container specified, to global.
  51242. * opt {
  51243. * isEnd: boolean,
  51244. * removeOnClick: boolean
  51245. * }
  51246. */
  51247. var BrushController = /** @class */function (_super) {
  51248. __extends(BrushController, _super);
  51249. function BrushController(zr) {
  51250. var _this = _super.call(this) || this;
  51251. /**
  51252. * @internal
  51253. */
  51254. _this._track = [];
  51255. /**
  51256. * @internal
  51257. */
  51258. _this._covers = [];
  51259. _this._handlers = {};
  51260. if ("development" !== 'production') {
  51261. assert(zr);
  51262. }
  51263. _this._zr = zr;
  51264. _this.group = new Group();
  51265. _this._uid = 'brushController_' + baseUID++;
  51266. each(pointerHandlers, function (handler, eventName) {
  51267. this._handlers[eventName] = bind(handler, this);
  51268. }, _this);
  51269. return _this;
  51270. }
  51271. /**
  51272. * If set to `false`, select disabled.
  51273. */
  51274. BrushController.prototype.enableBrush = function (brushOption) {
  51275. if ("development" !== 'production') {
  51276. assert(this._mounted);
  51277. }
  51278. this._brushType && this._doDisableBrush();
  51279. brushOption.brushType && this._doEnableBrush(brushOption);
  51280. return this;
  51281. };
  51282. BrushController.prototype._doEnableBrush = function (brushOption) {
  51283. var zr = this._zr;
  51284. // Consider roam, which takes globalPan too.
  51285. if (!this._enableGlobalPan) {
  51286. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  51287. }
  51288. each(this._handlers, function (handler, eventName) {
  51289. zr.on(eventName, handler);
  51290. });
  51291. this._brushType = brushOption.brushType;
  51292. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51293. };
  51294. BrushController.prototype._doDisableBrush = function () {
  51295. var zr = this._zr;
  51296. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  51297. each(this._handlers, function (handler, eventName) {
  51298. zr.off(eventName, handler);
  51299. });
  51300. this._brushType = this._brushOption = null;
  51301. };
  51302. /**
  51303. * @param panelOpts If not pass, it is global brush.
  51304. */
  51305. BrushController.prototype.setPanels = function (panelOpts) {
  51306. if (panelOpts && panelOpts.length) {
  51307. var panels_1 = this._panels = {};
  51308. each(panelOpts, function (panelOpts) {
  51309. panels_1[panelOpts.panelId] = clone(panelOpts);
  51310. });
  51311. } else {
  51312. this._panels = null;
  51313. }
  51314. return this;
  51315. };
  51316. BrushController.prototype.mount = function (opt) {
  51317. opt = opt || {};
  51318. if ("development" !== 'production') {
  51319. this._mounted = true; // should be at first.
  51320. }
  51321. this._enableGlobalPan = opt.enableGlobalPan;
  51322. var thisGroup = this.group;
  51323. this._zr.add(thisGroup);
  51324. thisGroup.attr({
  51325. x: opt.x || 0,
  51326. y: opt.y || 0,
  51327. rotation: opt.rotation || 0,
  51328. scaleX: opt.scaleX || 1,
  51329. scaleY: opt.scaleY || 1
  51330. });
  51331. this._transform = thisGroup.getLocalTransform();
  51332. return this;
  51333. };
  51334. // eachCover(cb, context): void {
  51335. // each(this._covers, cb, context);
  51336. // }
  51337. /**
  51338. * Update covers.
  51339. * @param coverConfigList
  51340. * If coverConfigList is null/undefined, all covers removed.
  51341. */
  51342. BrushController.prototype.updateCovers = function (coverConfigList) {
  51343. if ("development" !== 'production') {
  51344. assert(this._mounted);
  51345. }
  51346. coverConfigList = map(coverConfigList, function (coverConfig) {
  51347. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  51348. });
  51349. var tmpIdPrefix = '\0-brush-index-';
  51350. var oldCovers = this._covers;
  51351. var newCovers = this._covers = [];
  51352. var controller = this;
  51353. var creatingCover = this._creatingCover;
  51354. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  51355. return this;
  51356. function getKey(brushOption, index) {
  51357. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  51358. }
  51359. function oldGetKey(cover, index) {
  51360. return getKey(cover.__brushOption, index);
  51361. }
  51362. function addOrUpdate(newIndex, oldIndex) {
  51363. var newBrushInternal = coverConfigList[newIndex];
  51364. // Consider setOption in event listener of brushSelect,
  51365. // where updating cover when creating should be forbidden.
  51366. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  51367. newCovers[newIndex] = oldCovers[oldIndex];
  51368. } else {
  51369. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  51370. updateCoverAfterCreation(controller, cover);
  51371. }
  51372. }
  51373. function remove(oldIndex) {
  51374. if (oldCovers[oldIndex] !== creatingCover) {
  51375. controller.group.remove(oldCovers[oldIndex]);
  51376. }
  51377. }
  51378. };
  51379. BrushController.prototype.unmount = function () {
  51380. if ("development" !== 'production') {
  51381. if (!this._mounted) {
  51382. return;
  51383. }
  51384. }
  51385. this.enableBrush(false);
  51386. // container may 'removeAll' outside.
  51387. clearCovers(this);
  51388. this._zr.remove(this.group);
  51389. if ("development" !== 'production') {
  51390. this._mounted = false; // should be at last.
  51391. }
  51392. return this;
  51393. };
  51394. BrushController.prototype.dispose = function () {
  51395. this.unmount();
  51396. this.off();
  51397. };
  51398. return BrushController;
  51399. }(Eventful);
  51400. function createCover(controller, brushOption) {
  51401. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  51402. cover.__brushOption = brushOption;
  51403. updateZ(cover, brushOption);
  51404. controller.group.add(cover);
  51405. return cover;
  51406. }
  51407. function endCreating(controller, creatingCover) {
  51408. var coverRenderer = getCoverRenderer(creatingCover);
  51409. if (coverRenderer.endCreating) {
  51410. coverRenderer.endCreating(controller, creatingCover);
  51411. updateZ(creatingCover, creatingCover.__brushOption);
  51412. }
  51413. return creatingCover;
  51414. }
  51415. function updateCoverShape(controller, cover) {
  51416. var brushOption = cover.__brushOption;
  51417. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  51418. }
  51419. function updateZ(cover, brushOption) {
  51420. var z = brushOption.z;
  51421. z == null && (z = COVER_Z);
  51422. cover.traverse(function (el) {
  51423. el.z = z;
  51424. el.z2 = z; // Consider in given container.
  51425. });
  51426. }
  51427. function updateCoverAfterCreation(controller, cover) {
  51428. getCoverRenderer(cover).updateCommon(controller, cover);
  51429. updateCoverShape(controller, cover);
  51430. }
  51431. function getCoverRenderer(cover) {
  51432. return coverRenderers[cover.__brushOption.brushType];
  51433. }
  51434. // return target panel or `true` (means global panel)
  51435. function getPanelByPoint(controller, e, localCursorPoint) {
  51436. var panels = controller._panels;
  51437. if (!panels) {
  51438. return BRUSH_PANEL_GLOBAL; // Global panel
  51439. }
  51440. var panel;
  51441. var transform = controller._transform;
  51442. each(panels, function (pn) {
  51443. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  51444. });
  51445. return panel;
  51446. }
  51447. // Return a panel or true
  51448. function getPanelByCover(controller, cover) {
  51449. var panels = controller._panels;
  51450. if (!panels) {
  51451. return BRUSH_PANEL_GLOBAL; // Global panel
  51452. }
  51453. var panelId = cover.__brushOption.panelId;
  51454. // User may give cover without coord sys info,
  51455. // which is then treated as global panel.
  51456. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  51457. }
  51458. function clearCovers(controller) {
  51459. var covers = controller._covers;
  51460. var originalLength = covers.length;
  51461. each(covers, function (cover) {
  51462. controller.group.remove(cover);
  51463. }, controller);
  51464. covers.length = 0;
  51465. return !!originalLength;
  51466. }
  51467. function trigger(controller, opt) {
  51468. var areas = map(controller._covers, function (cover) {
  51469. var brushOption = cover.__brushOption;
  51470. var range = clone(brushOption.range);
  51471. return {
  51472. brushType: brushOption.brushType,
  51473. panelId: brushOption.panelId,
  51474. range: range
  51475. };
  51476. });
  51477. controller.trigger('brush', {
  51478. areas: areas,
  51479. isEnd: !!opt.isEnd,
  51480. removeOnClick: !!opt.removeOnClick
  51481. });
  51482. }
  51483. function shouldShowCover(controller) {
  51484. var track = controller._track;
  51485. if (!track.length) {
  51486. return false;
  51487. }
  51488. var p2 = track[track.length - 1];
  51489. var p1 = track[0];
  51490. var dx = p2[0] - p1[0];
  51491. var dy = p2[1] - p1[1];
  51492. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  51493. return dist > UNSELECT_THRESHOLD;
  51494. }
  51495. function getTrackEnds(track) {
  51496. var tail = track.length - 1;
  51497. tail < 0 && (tail = 0);
  51498. return [track[0], track[tail]];
  51499. }
  51500. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  51501. var cover = new Group();
  51502. cover.add(new Rect({
  51503. name: 'main',
  51504. style: makeStyle(brushOption),
  51505. silent: true,
  51506. draggable: true,
  51507. cursor: 'move',
  51508. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  51509. ondragend: curry(trigger, controller, {
  51510. isEnd: true
  51511. })
  51512. }));
  51513. each(edgeNameSequences, function (nameSequence) {
  51514. cover.add(new Rect({
  51515. name: nameSequence.join(''),
  51516. style: {
  51517. opacity: 0
  51518. },
  51519. draggable: true,
  51520. silent: true,
  51521. invisible: true,
  51522. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  51523. ondragend: curry(trigger, controller, {
  51524. isEnd: true
  51525. })
  51526. }));
  51527. });
  51528. return cover;
  51529. }
  51530. function updateBaseRect(controller, cover, localRange, brushOption) {
  51531. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  51532. var handleSize = mathMax$8(lineWidth, MIN_RESIZE_LINE_WIDTH);
  51533. var x = localRange[0][0];
  51534. var y = localRange[1][0];
  51535. var xa = x - lineWidth / 2;
  51536. var ya = y - lineWidth / 2;
  51537. var x2 = localRange[0][1];
  51538. var y2 = localRange[1][1];
  51539. var x2a = x2 - handleSize + lineWidth / 2;
  51540. var y2a = y2 - handleSize + lineWidth / 2;
  51541. var width = x2 - x;
  51542. var height = y2 - y;
  51543. var widtha = width + lineWidth;
  51544. var heighta = height + lineWidth;
  51545. updateRectShape(controller, cover, 'main', x, y, width, height);
  51546. if (brushOption.transformable) {
  51547. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  51548. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  51549. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  51550. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  51551. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  51552. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  51553. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  51554. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  51555. }
  51556. }
  51557. function updateCommon(controller, cover) {
  51558. var brushOption = cover.__brushOption;
  51559. var transformable = brushOption.transformable;
  51560. var mainEl = cover.childAt(0);
  51561. mainEl.useStyle(makeStyle(brushOption));
  51562. mainEl.attr({
  51563. silent: !transformable,
  51564. cursor: transformable ? 'move' : 'default'
  51565. });
  51566. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  51567. var el = cover.childOfName(nameSequence.join(''));
  51568. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  51569. el && el.attr({
  51570. silent: !transformable,
  51571. invisible: !transformable,
  51572. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  51573. });
  51574. });
  51575. }
  51576. function updateRectShape(controller, cover, name, x, y, w, h) {
  51577. var el = cover.childOfName(name);
  51578. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  51579. }
  51580. function makeStyle(brushOption) {
  51581. return defaults({
  51582. strokeNoScale: true
  51583. }, brushOption.brushStyle);
  51584. }
  51585. function formatRectRange(x, y, x2, y2) {
  51586. var min = [mathMin$8(x, x2), mathMin$8(y, y2)];
  51587. var max = [mathMax$8(x, x2), mathMax$8(y, y2)];
  51588. return [[min[0], max[0]], [min[1], max[1]] // y range
  51589. ];
  51590. }
  51591. function getTransform$1(controller) {
  51592. return getTransform(controller.group);
  51593. }
  51594. function getGlobalDirection1(controller, localDirName) {
  51595. var map = {
  51596. w: 'left',
  51597. e: 'right',
  51598. n: 'top',
  51599. s: 'bottom'
  51600. };
  51601. var inverseMap = {
  51602. left: 'w',
  51603. right: 'e',
  51604. top: 'n',
  51605. bottom: 's'
  51606. };
  51607. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  51608. return inverseMap[dir];
  51609. }
  51610. function getGlobalDirection2(controller, localDirNameSeq) {
  51611. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  51612. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  51613. return globalDir.join('');
  51614. }
  51615. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  51616. var brushOption = cover.__brushOption;
  51617. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  51618. var localDelta = toLocalDelta(controller, dx, dy);
  51619. each(dirNameSequence, function (dirName) {
  51620. var ind = DIRECTION_MAP[dirName];
  51621. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  51622. });
  51623. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  51624. updateCoverAfterCreation(controller, cover);
  51625. trigger(controller, {
  51626. isEnd: false
  51627. });
  51628. }
  51629. function driftPolygon(controller, cover, dx, dy) {
  51630. var range = cover.__brushOption.range;
  51631. var localDelta = toLocalDelta(controller, dx, dy);
  51632. each(range, function (point) {
  51633. point[0] += localDelta[0];
  51634. point[1] += localDelta[1];
  51635. });
  51636. updateCoverAfterCreation(controller, cover);
  51637. trigger(controller, {
  51638. isEnd: false
  51639. });
  51640. }
  51641. function toLocalDelta(controller, dx, dy) {
  51642. var thisGroup = controller.group;
  51643. var localD = thisGroup.transformCoordToLocal(dx, dy);
  51644. var localZero = thisGroup.transformCoordToLocal(0, 0);
  51645. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  51646. }
  51647. function clipByPanel(controller, cover, data) {
  51648. var panel = getPanelByCover(controller, cover);
  51649. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  51650. }
  51651. function pointsToRect(points) {
  51652. var xmin = mathMin$8(points[0][0], points[1][0]);
  51653. var ymin = mathMin$8(points[0][1], points[1][1]);
  51654. var xmax = mathMax$8(points[0][0], points[1][0]);
  51655. var ymax = mathMax$8(points[0][1], points[1][1]);
  51656. return {
  51657. x: xmin,
  51658. y: ymin,
  51659. width: xmax - xmin,
  51660. height: ymax - ymin
  51661. };
  51662. }
  51663. function resetCursor(controller, e, localCursorPoint) {
  51664. if (
  51665. // Check active
  51666. !controller._brushType
  51667. // resetCursor should be always called when mouse is in zr area,
  51668. // but not called when mouse is out of zr area to avoid bad influence
  51669. // if `mousemove`, `mouseup` are triggered from `document` event.
  51670. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  51671. return;
  51672. }
  51673. var zr = controller._zr;
  51674. var covers = controller._covers;
  51675. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  51676. // Check whether in covers.
  51677. if (!controller._dragging) {
  51678. for (var i = 0; i < covers.length; i++) {
  51679. var brushOption = covers[i].__brushOption;
  51680. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  51681. // Use cursor style set on cover.
  51682. return;
  51683. }
  51684. }
  51685. }
  51686. currPanel && zr.setCursorStyle('crosshair');
  51687. }
  51688. function preventDefault(e) {
  51689. var rawE = e.event;
  51690. rawE.preventDefault && rawE.preventDefault();
  51691. }
  51692. function mainShapeContain(cover, x, y) {
  51693. return cover.childOfName('main').contain(x, y);
  51694. }
  51695. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  51696. var creatingCover = controller._creatingCover;
  51697. var panel = controller._creatingPanel;
  51698. var thisBrushOption = controller._brushOption;
  51699. var eventParams;
  51700. controller._track.push(localCursorPoint.slice());
  51701. if (shouldShowCover(controller) || creatingCover) {
  51702. if (panel && !creatingCover) {
  51703. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  51704. var brushOption = clone(thisBrushOption);
  51705. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  51706. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  51707. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  51708. controller._covers.push(creatingCover);
  51709. }
  51710. if (creatingCover) {
  51711. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  51712. var coverBrushOption = creatingCover.__brushOption;
  51713. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  51714. if (isEnd) {
  51715. endCreating(controller, creatingCover);
  51716. coverRenderer.updateCommon(controller, creatingCover);
  51717. }
  51718. updateCoverShape(controller, creatingCover);
  51719. eventParams = {
  51720. isEnd: isEnd
  51721. };
  51722. }
  51723. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  51724. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  51725. // But a single click do not clear covers, because user may have casual
  51726. // clicks (for example, click on other component and do not expect covers
  51727. // disappear).
  51728. // Only some cover removed, trigger action, but not every click trigger action.
  51729. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  51730. eventParams = {
  51731. isEnd: isEnd,
  51732. removeOnClick: true
  51733. };
  51734. }
  51735. }
  51736. return eventParams;
  51737. }
  51738. function determineBrushType(brushType, panel) {
  51739. if (brushType === 'auto') {
  51740. if ("development" !== 'production') {
  51741. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  51742. }
  51743. return panel.defaultBrushType;
  51744. }
  51745. return brushType;
  51746. }
  51747. var pointerHandlers = {
  51748. mousedown: function (e) {
  51749. if (this._dragging) {
  51750. // In case some browser do not support globalOut,
  51751. // and release mouse out side the browser.
  51752. handleDragEnd(this, e);
  51753. } else if (!e.target || !e.target.draggable) {
  51754. preventDefault(e);
  51755. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51756. this._creatingCover = null;
  51757. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  51758. if (panel) {
  51759. this._dragging = true;
  51760. this._track = [localCursorPoint.slice()];
  51761. }
  51762. }
  51763. },
  51764. mousemove: function (e) {
  51765. var x = e.offsetX;
  51766. var y = e.offsetY;
  51767. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  51768. resetCursor(this, e, localCursorPoint);
  51769. if (this._dragging) {
  51770. preventDefault(e);
  51771. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  51772. eventParams && trigger(this, eventParams);
  51773. }
  51774. },
  51775. mouseup: function (e) {
  51776. handleDragEnd(this, e);
  51777. }
  51778. };
  51779. function handleDragEnd(controller, e) {
  51780. if (controller._dragging) {
  51781. preventDefault(e);
  51782. var x = e.offsetX;
  51783. var y = e.offsetY;
  51784. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  51785. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  51786. controller._dragging = false;
  51787. controller._track = [];
  51788. controller._creatingCover = null;
  51789. // trigger event should be at final, after procedure will be nested.
  51790. eventParams && trigger(controller, eventParams);
  51791. }
  51792. }
  51793. function isOutsideZrArea(controller, x, y) {
  51794. var zr = controller._zr;
  51795. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  51796. }
  51797. /**
  51798. * key: brushType
  51799. */
  51800. var coverRenderers = {
  51801. lineX: getLineRenderer(0),
  51802. lineY: getLineRenderer(1),
  51803. rect: {
  51804. createCover: function (controller, brushOption) {
  51805. function returnInput(range) {
  51806. return range;
  51807. }
  51808. return createBaseRectCover({
  51809. toRectRange: returnInput,
  51810. fromRectRange: returnInput
  51811. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  51812. },
  51813. getCreatingRange: function (localTrack) {
  51814. var ends = getTrackEnds(localTrack);
  51815. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  51816. },
  51817. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51818. updateBaseRect(controller, cover, localRange, brushOption);
  51819. },
  51820. updateCommon: updateCommon,
  51821. contain: mainShapeContain
  51822. },
  51823. polygon: {
  51824. createCover: function (controller, brushOption) {
  51825. var cover = new Group();
  51826. // Do not use graphic.Polygon because graphic.Polyline do not close the
  51827. // border of the shape when drawing, which is a better experience for user.
  51828. cover.add(new Polyline({
  51829. name: 'main',
  51830. style: makeStyle(brushOption),
  51831. silent: true
  51832. }));
  51833. return cover;
  51834. },
  51835. getCreatingRange: function (localTrack) {
  51836. return localTrack;
  51837. },
  51838. endCreating: function (controller, cover) {
  51839. cover.remove(cover.childAt(0));
  51840. // Use graphic.Polygon close the shape.
  51841. cover.add(new Polygon({
  51842. name: 'main',
  51843. draggable: true,
  51844. drift: curry(driftPolygon, controller, cover),
  51845. ondragend: curry(trigger, controller, {
  51846. isEnd: true
  51847. })
  51848. }));
  51849. },
  51850. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51851. cover.childAt(0).setShape({
  51852. points: clipByPanel(controller, cover, localRange)
  51853. });
  51854. },
  51855. updateCommon: updateCommon,
  51856. contain: mainShapeContain
  51857. }
  51858. };
  51859. function getLineRenderer(xyIndex) {
  51860. return {
  51861. createCover: function (controller, brushOption) {
  51862. return createBaseRectCover({
  51863. toRectRange: function (range) {
  51864. var rectRange = [range, [0, 100]];
  51865. xyIndex && rectRange.reverse();
  51866. return rectRange;
  51867. },
  51868. fromRectRange: function (rectRange) {
  51869. return rectRange[xyIndex];
  51870. }
  51871. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  51872. },
  51873. getCreatingRange: function (localTrack) {
  51874. var ends = getTrackEnds(localTrack);
  51875. var min = mathMin$8(ends[0][xyIndex], ends[1][xyIndex]);
  51876. var max = mathMax$8(ends[0][xyIndex], ends[1][xyIndex]);
  51877. return [min, max];
  51878. },
  51879. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51880. var otherExtent;
  51881. // If brushWidth not specified, fit the panel.
  51882. var panel = getPanelByCover(controller, cover);
  51883. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  51884. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  51885. } else {
  51886. var zr = controller._zr;
  51887. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  51888. }
  51889. var rectRange = [localRange, otherExtent];
  51890. xyIndex && rectRange.reverse();
  51891. updateBaseRect(controller, cover, rectRange, brushOption);
  51892. },
  51893. updateCommon: updateCommon,
  51894. contain: mainShapeContain
  51895. };
  51896. }
  51897. var IRRELEVANT_EXCLUDES = {
  51898. 'axisPointer': 1,
  51899. 'tooltip': 1,
  51900. 'brush': 1
  51901. };
  51902. /**
  51903. * Used on roam/brush triggering determination.
  51904. * This is to avoid that: mouse clicking on an elements that is over geo or graph,
  51905. * but roam is triggered unexpectedly.
  51906. */
  51907. function onIrrelevantElement(e, api, targetComponent) {
  51908. var eventElComponent = api.getComponentByElement(e.topTarget);
  51909. if (!eventElComponent || eventElComponent === targetComponent || IRRELEVANT_EXCLUDES.hasOwnProperty(eventElComponent.mainType)) {
  51910. return false;
  51911. }
  51912. // At present the `true` return is conservative. That is, the caller, such as a RoamController,
  51913. // is more likely to get a `false` return and start a roam behavior, becuase even if the
  51914. // `model.coordinateSystem` does not exist, the `e.topTarget` may be also a relevant element,
  51915. // such as axis split line/area or series elements, where roam should be available. Otherwise,
  51916. // if a dataZoom-served cartesian is full of series elements, the dataZoom-roaming can hardly
  51917. // be triggered.
  51918. var eventElCoordSys = eventElComponent.coordinateSystem;
  51919. // If eventElComponent is axisModel, it works only if it is injected with coordinateSystem.
  51920. if (!eventElCoordSys || eventElCoordSys.model === targetComponent) {
  51921. return false;
  51922. }
  51923. // e.g., if a cartesian is covered by a graph, the graph has a higher presedence in roam.
  51924. // A potential bad case is that RoamController does not prevent the cartesian from handling zr
  51925. // event, such as click and hovering, but it's fine so far.
  51926. // Aslo be conservative, if equals, return false.
  51927. var eventElCmptZInfo = retrieveZInfo(eventElComponent);
  51928. var targetCmptZInfo = retrieveZInfo(targetComponent);
  51929. if ((eventElCmptZInfo.zlevel - targetCmptZInfo.zlevel || eventElCmptZInfo.z - targetCmptZInfo.z) <= 0) {
  51930. return false;
  51931. }
  51932. return true;
  51933. }
  51934. function makeRectPanelClipPath(rect) {
  51935. rect = normalizeRect(rect);
  51936. return function (localPoints) {
  51937. return clipPointsByRect(localPoints, rect);
  51938. };
  51939. }
  51940. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  51941. rect = normalizeRect(rect);
  51942. return function (xyIndex) {
  51943. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  51944. var brushWidth = idx ? rect.width : rect.height;
  51945. var base = idx ? rect.x : rect.y;
  51946. return [base, base + (brushWidth || 0)];
  51947. };
  51948. }
  51949. function makeRectIsTargetByCursor(rect, api, targetModel) {
  51950. var boundingRect = normalizeRect(rect);
  51951. return function (e, localCursorPoint) {
  51952. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  51953. };
  51954. }
  51955. // Consider width/height is negative.
  51956. function normalizeRect(rect) {
  51957. return BoundingRect.create(rect);
  51958. }
  51959. // FIXME
  51960. // how to genarialize to more coordinate systems.
  51961. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  51962. var BrushTargetManager = /** @class */function () {
  51963. /**
  51964. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  51965. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  51966. * @param opt.include include coordinate system types.
  51967. */
  51968. function BrushTargetManager(finder, ecModel, opt) {
  51969. var _this = this;
  51970. this._targetInfoList = [];
  51971. var foundCpts = parseFinder$1(ecModel, finder);
  51972. each(targetInfoBuilders, function (builder, type) {
  51973. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  51974. builder(foundCpts, _this._targetInfoList);
  51975. }
  51976. });
  51977. }
  51978. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  51979. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  51980. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  51981. // area.coordRange is the first of area.coordRanges
  51982. if (!area.coordRange) {
  51983. area.coordRange = coordRange;
  51984. // In 'category' axis, coord to pixel is not reversible, so we can not
  51985. // rebuild range by coordRange accrately, which may bring trouble when
  51986. // brushing only one item. So we use __rangeOffset to rebuilding range
  51987. // by coordRange. And this it only used in brush component so it is no
  51988. // need to be adapted to coordRanges.
  51989. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  51990. area.__rangeOffset = {
  51991. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  51992. xyMinMax: result.xyMinMax
  51993. };
  51994. }
  51995. });
  51996. return areas;
  51997. };
  51998. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  51999. each(areas, function (area) {
  52000. var targetInfo = this.findTargetInfo(area, ecModel);
  52001. if (targetInfo && targetInfo !== true) {
  52002. each(targetInfo.coordSyses, function (coordSys) {
  52003. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  52004. cb(area, result.values, coordSys, ecModel);
  52005. });
  52006. }
  52007. }, this);
  52008. };
  52009. /**
  52010. * the `areas` is `BrushModel.areas`.
  52011. * Called in layout stage.
  52012. * convert `area.coordRange` to global range and set panelId to `area.range`.
  52013. */
  52014. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  52015. each(areas, function (area) {
  52016. var targetInfo = this.findTargetInfo(area, ecModel);
  52017. if ("development" !== 'production') {
  52018. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  52019. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  52020. }
  52021. area.range = area.range || [];
  52022. // convert coordRange to global range and set panelId.
  52023. if (targetInfo && targetInfo !== true) {
  52024. area.panelId = targetInfo.panelId;
  52025. // (1) area.range should always be calculate from coordRange but does
  52026. // not keep its original value, for the sake of the dataZoom scenario,
  52027. // where area.coordRange remains unchanged but area.range may be changed.
  52028. // (2) Only support converting one coordRange to pixel range in brush
  52029. // component. So do not consider `coordRanges`.
  52030. // (3) About __rangeOffset, see comment above.
  52031. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  52032. var rangeOffset = area.__rangeOffset;
  52033. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  52034. }
  52035. }, this);
  52036. };
  52037. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  52038. return map(this._targetInfoList, function (targetInfo) {
  52039. var rect = targetInfo.getPanelRect();
  52040. return {
  52041. panelId: targetInfo.panelId,
  52042. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  52043. clipPath: makeRectPanelClipPath(rect),
  52044. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  52045. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  52046. };
  52047. });
  52048. };
  52049. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  52050. // Check whether area is bound in coord, and series do not belong to that coord.
  52051. // If do not do this check, some brush (like lineX) will controll all axes.
  52052. var targetInfo = this.findTargetInfo(area, ecModel);
  52053. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  52054. };
  52055. /**
  52056. * If return Object, a coord found.
  52057. * If return true, global found.
  52058. * Otherwise nothing found.
  52059. */
  52060. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  52061. var targetInfoList = this._targetInfoList;
  52062. var foundCpts = parseFinder$1(ecModel, area);
  52063. for (var i = 0; i < targetInfoList.length; i++) {
  52064. var targetInfo = targetInfoList[i];
  52065. var areaPanelId = area.panelId;
  52066. if (areaPanelId) {
  52067. if (targetInfo.panelId === areaPanelId) {
  52068. return targetInfo;
  52069. }
  52070. } else {
  52071. for (var j = 0; j < targetInfoMatchers.length; j++) {
  52072. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  52073. return targetInfo;
  52074. }
  52075. }
  52076. }
  52077. }
  52078. return true;
  52079. };
  52080. return BrushTargetManager;
  52081. }();
  52082. function formatMinMax(minMax) {
  52083. minMax[0] > minMax[1] && minMax.reverse();
  52084. return minMax;
  52085. }
  52086. function parseFinder$1(ecModel, finder) {
  52087. return parseFinder(ecModel, finder, {
  52088. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  52089. });
  52090. }
  52091. var targetInfoBuilders = {
  52092. grid: function (foundCpts, targetInfoList) {
  52093. var xAxisModels = foundCpts.xAxisModels;
  52094. var yAxisModels = foundCpts.yAxisModels;
  52095. var gridModels = foundCpts.gridModels;
  52096. // Remove duplicated.
  52097. var gridModelMap = createHashMap();
  52098. var xAxesHas = {};
  52099. var yAxesHas = {};
  52100. if (!xAxisModels && !yAxisModels && !gridModels) {
  52101. return;
  52102. }
  52103. each(xAxisModels, function (axisModel) {
  52104. var gridModel = axisModel.axis.grid.model;
  52105. gridModelMap.set(gridModel.id, gridModel);
  52106. xAxesHas[gridModel.id] = true;
  52107. });
  52108. each(yAxisModels, function (axisModel) {
  52109. var gridModel = axisModel.axis.grid.model;
  52110. gridModelMap.set(gridModel.id, gridModel);
  52111. yAxesHas[gridModel.id] = true;
  52112. });
  52113. each(gridModels, function (gridModel) {
  52114. gridModelMap.set(gridModel.id, gridModel);
  52115. xAxesHas[gridModel.id] = true;
  52116. yAxesHas[gridModel.id] = true;
  52117. });
  52118. gridModelMap.each(function (gridModel) {
  52119. var grid = gridModel.coordinateSystem;
  52120. var cartesians = [];
  52121. each(grid.getCartesians(), function (cartesian, index) {
  52122. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  52123. cartesians.push(cartesian);
  52124. }
  52125. });
  52126. targetInfoList.push({
  52127. panelId: 'grid--' + gridModel.id,
  52128. gridModel: gridModel,
  52129. coordSysModel: gridModel,
  52130. // Use the first one as the representitive coordSys.
  52131. coordSys: cartesians[0],
  52132. coordSyses: cartesians,
  52133. getPanelRect: panelRectBuilders.grid,
  52134. xAxisDeclared: xAxesHas[gridModel.id],
  52135. yAxisDeclared: yAxesHas[gridModel.id]
  52136. });
  52137. });
  52138. },
  52139. geo: function (foundCpts, targetInfoList) {
  52140. each(foundCpts.geoModels, function (geoModel) {
  52141. var coordSys = geoModel.coordinateSystem;
  52142. targetInfoList.push({
  52143. panelId: 'geo--' + geoModel.id,
  52144. geoModel: geoModel,
  52145. coordSysModel: geoModel,
  52146. coordSys: coordSys,
  52147. coordSyses: [coordSys],
  52148. getPanelRect: panelRectBuilders.geo
  52149. });
  52150. });
  52151. }
  52152. };
  52153. var targetInfoMatchers = [
  52154. // grid
  52155. function (foundCpts, targetInfo) {
  52156. var xAxisModel = foundCpts.xAxisModel;
  52157. var yAxisModel = foundCpts.yAxisModel;
  52158. var gridModel = foundCpts.gridModel;
  52159. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  52160. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  52161. return gridModel && gridModel === targetInfo.gridModel;
  52162. },
  52163. // geo
  52164. function (foundCpts, targetInfo) {
  52165. var geoModel = foundCpts.geoModel;
  52166. return geoModel && geoModel === targetInfo.geoModel;
  52167. }];
  52168. var panelRectBuilders = {
  52169. grid: function () {
  52170. // grid is not Transformable.
  52171. return this.coordSys.master.getRect().clone();
  52172. },
  52173. geo: function () {
  52174. var coordSys = this.coordSys;
  52175. var rect = coordSys.getBoundingRect().clone();
  52176. // geo roam and zoom transform
  52177. rect.applyTransform(getTransform(coordSys));
  52178. return rect;
  52179. }
  52180. };
  52181. var coordConvert = {
  52182. lineX: curry(axisConvert, 0),
  52183. lineY: curry(axisConvert, 1),
  52184. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  52185. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  52186. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  52187. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  52188. return {
  52189. values: values,
  52190. xyMinMax: values
  52191. };
  52192. },
  52193. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  52194. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  52195. var values = map(rangeOrCoordRange, function (item) {
  52196. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  52197. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  52198. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  52199. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  52200. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  52201. return p;
  52202. });
  52203. return {
  52204. values: values,
  52205. xyMinMax: xyMinMax
  52206. };
  52207. }
  52208. };
  52209. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  52210. if ("development" !== 'production') {
  52211. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  52212. }
  52213. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  52214. var values = formatMinMax(map([0, 1], function (i) {
  52215. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  52216. }));
  52217. var xyMinMax = [];
  52218. xyMinMax[axisNameIndex] = values;
  52219. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  52220. return {
  52221. values: values,
  52222. xyMinMax: xyMinMax
  52223. };
  52224. }
  52225. var diffProcessor = {
  52226. lineX: curry(axisDiffProcessor, 0),
  52227. lineY: curry(axisDiffProcessor, 1),
  52228. rect: function (values, refer, scales) {
  52229. 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]]];
  52230. },
  52231. polygon: function (values, refer, scales) {
  52232. return map(values, function (item, idx) {
  52233. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  52234. });
  52235. }
  52236. };
  52237. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  52238. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  52239. }
  52240. // We have to process scale caused by dataZoom manually,
  52241. // although it might be not accurate.
  52242. // Return [0~1, 0~1]
  52243. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  52244. var sizeCurr = getSize$1(xyMinMaxCurr);
  52245. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  52246. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  52247. isNaN(scales[0]) && (scales[0] = 1);
  52248. isNaN(scales[1]) && (scales[1] = 1);
  52249. return scales;
  52250. }
  52251. function getSize$1(xyMinMax) {
  52252. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  52253. }
  52254. var each$6 = each;
  52255. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  52256. var DataZoomFeature = /** @class */function (_super) {
  52257. __extends(DataZoomFeature, _super);
  52258. function DataZoomFeature() {
  52259. return _super !== null && _super.apply(this, arguments) || this;
  52260. }
  52261. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  52262. if (!this._brushController) {
  52263. this._brushController = new BrushController(api.getZr());
  52264. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  52265. }
  52266. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  52267. updateBackBtnStatus(featureModel, ecModel);
  52268. };
  52269. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  52270. handlers[type].call(this);
  52271. };
  52272. DataZoomFeature.prototype.remove = function (ecModel, api) {
  52273. this._brushController && this._brushController.unmount();
  52274. };
  52275. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  52276. this._brushController && this._brushController.dispose();
  52277. };
  52278. DataZoomFeature.prototype._onBrush = function (eventParam) {
  52279. var areas = eventParam.areas;
  52280. if (!eventParam.isEnd || !areas.length) {
  52281. return;
  52282. }
  52283. var snapshot = {};
  52284. var ecModel = this.ecModel;
  52285. this._brushController.updateCovers([]); // remove cover
  52286. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  52287. include: ['grid']
  52288. });
  52289. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  52290. if (coordSys.type !== 'cartesian2d') {
  52291. return;
  52292. }
  52293. var brushType = area.brushType;
  52294. if (brushType === 'rect') {
  52295. setBatch('x', coordSys, coordRange[0]);
  52296. setBatch('y', coordSys, coordRange[1]);
  52297. } else {
  52298. setBatch({
  52299. lineX: 'x',
  52300. lineY: 'y'
  52301. }[brushType], coordSys, coordRange);
  52302. }
  52303. });
  52304. push(ecModel, snapshot);
  52305. this._dispatchZoomAction(snapshot);
  52306. function setBatch(dimName, coordSys, minMax) {
  52307. var axis = coordSys.getAxis(dimName);
  52308. var axisModel = axis.model;
  52309. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  52310. // Restrict range.
  52311. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  52312. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  52313. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  52314. }
  52315. dataZoomModel && (snapshot[dataZoomModel.id] = {
  52316. dataZoomId: dataZoomModel.id,
  52317. startValue: minMax[0],
  52318. endValue: minMax[1]
  52319. });
  52320. }
  52321. function findDataZoom(dimName, axisModel, ecModel) {
  52322. var found;
  52323. ecModel.eachComponent({
  52324. mainType: 'dataZoom',
  52325. subType: 'select'
  52326. }, function (dzModel) {
  52327. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  52328. has && (found = dzModel);
  52329. });
  52330. return found;
  52331. }
  52332. };
  52333. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  52334. var batch = [];
  52335. // Convert from hash map to array.
  52336. each$6(snapshot, function (batchItem, dataZoomId) {
  52337. batch.push(clone(batchItem));
  52338. });
  52339. batch.length && this.api.dispatchAction({
  52340. type: 'dataZoom',
  52341. from: this.uid,
  52342. batch: batch
  52343. });
  52344. };
  52345. DataZoomFeature.getDefaultOption = function (ecModel) {
  52346. var defaultOption = {
  52347. show: true,
  52348. filterMode: 'filter',
  52349. // Icon group
  52350. icon: {
  52351. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  52352. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  52353. },
  52354. // `zoom`, `back`
  52355. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  52356. brushStyle: {
  52357. borderWidth: 0,
  52358. color: tokens.color.backgroundTint
  52359. }
  52360. };
  52361. return defaultOption;
  52362. };
  52363. return DataZoomFeature;
  52364. }(ToolboxFeature);
  52365. var handlers = {
  52366. zoom: function () {
  52367. var nextActive = !this._isZoomActive;
  52368. this.api.dispatchAction({
  52369. type: 'takeGlobalCursor',
  52370. key: 'dataZoomSelect',
  52371. dataZoomSelectActive: nextActive
  52372. });
  52373. },
  52374. back: function () {
  52375. this._dispatchZoomAction(pop(this.ecModel));
  52376. }
  52377. };
  52378. function makeAxisFinder(dzFeatureModel) {
  52379. var setting = {
  52380. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  52381. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  52382. xAxisId: dzFeatureModel.get('xAxisId', true),
  52383. yAxisId: dzFeatureModel.get('yAxisId', true)
  52384. };
  52385. // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  52386. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  52387. // Some old cases set like this below to close yAxis control but leave xAxis control:
  52388. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  52389. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  52390. setting.xAxisIndex = 'all';
  52391. }
  52392. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  52393. setting.yAxisIndex = 'all';
  52394. }
  52395. return setting;
  52396. }
  52397. function updateBackBtnStatus(featureModel, ecModel) {
  52398. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  52399. }
  52400. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  52401. var zoomActive = view._isZoomActive;
  52402. if (payload && payload.type === 'takeGlobalCursor') {
  52403. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  52404. }
  52405. view._isZoomActive = zoomActive;
  52406. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  52407. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  52408. include: ['grid']
  52409. });
  52410. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  52411. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  52412. });
  52413. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  52414. brushType: 'auto',
  52415. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  52416. } : false);
  52417. }
  52418. registerInternalOptionCreator('dataZoom', function (ecModel) {
  52419. var toolboxModel = ecModel.getComponent('toolbox', 0);
  52420. var featureDataZoomPath = ['feature', 'dataZoom'];
  52421. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  52422. return;
  52423. }
  52424. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  52425. var dzOptions = [];
  52426. var finder = makeAxisFinder(dzFeatureModel);
  52427. var finderResult = parseFinder(ecModel, finder);
  52428. each$6(finderResult.xAxisModels, function (axisModel) {
  52429. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  52430. });
  52431. each$6(finderResult.yAxisModels, function (axisModel) {
  52432. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  52433. });
  52434. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  52435. var axisIndex = axisModel.componentIndex;
  52436. var newOpt = {
  52437. type: 'select',
  52438. $fromToolbox: true,
  52439. // Default to be filter
  52440. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  52441. // Id for merge mapping.
  52442. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  52443. };
  52444. newOpt[axisIndexPropName] = axisIndex;
  52445. dzOptions.push(newOpt);
  52446. }
  52447. return dzOptions;
  52448. });
  52449. function install$b(registers) {
  52450. registers.registerComponentModel(ToolboxModel);
  52451. registers.registerComponentView(ToolboxView);
  52452. registerFeature('saveAsImage', SaveAsImage);
  52453. registerFeature('magicType', MagicType);
  52454. registerFeature('dataView', DataView);
  52455. registerFeature('dataZoom', DataZoomFeature);
  52456. registerFeature('restore', RestoreOption);
  52457. use(install$a);
  52458. }
  52459. var TooltipModel = /** @class */function (_super) {
  52460. __extends(TooltipModel, _super);
  52461. function TooltipModel() {
  52462. var _this = _super !== null && _super.apply(this, arguments) || this;
  52463. _this.type = TooltipModel.type;
  52464. return _this;
  52465. }
  52466. TooltipModel.type = 'tooltip';
  52467. TooltipModel.dependencies = ['axisPointer'];
  52468. TooltipModel.defaultOption = {
  52469. // zlevel: 0,
  52470. z: 60,
  52471. show: true,
  52472. // tooltip main content
  52473. showContent: true,
  52474. // 'trigger' only works on coordinate system.
  52475. // 'item' | 'axis' | 'none'
  52476. trigger: 'item',
  52477. // 'click' | 'mousemove' | 'none'
  52478. triggerOn: 'mousemove|click',
  52479. alwaysShowContent: false,
  52480. renderMode: 'auto',
  52481. // whether restraint content inside viewRect.
  52482. // If renderMode: 'richText', default true.
  52483. // If renderMode: 'html', defaults to `false` (for backward compat).
  52484. confine: null,
  52485. showDelay: 0,
  52486. hideDelay: 100,
  52487. // Animation transition time, unit is second
  52488. transitionDuration: 0.4,
  52489. displayTransition: true,
  52490. enterable: false,
  52491. backgroundColor: tokens.color.neutral00,
  52492. // box shadow
  52493. shadowBlur: 10,
  52494. shadowColor: 'rgba(0, 0, 0, .2)',
  52495. shadowOffsetX: 1,
  52496. shadowOffsetY: 2,
  52497. // tooltip border radius, unit is px, default is 4
  52498. borderRadius: 4,
  52499. // tooltip border width, unit is px, default is 0 (no border)
  52500. borderWidth: 1,
  52501. defaultBorderColor: tokens.color.border,
  52502. // Tooltip inside padding, default is 5 for all direction
  52503. // Array is allowed to set up, right, bottom, left, same with css
  52504. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  52505. padding: null,
  52506. // Extra css text
  52507. extraCssText: '',
  52508. // axis indicator, trigger by axis
  52509. axisPointer: {
  52510. // default is line
  52511. // legal values: 'line' | 'shadow' | 'cross'
  52512. type: 'line',
  52513. // Valid when type is line, appoint tooltip line locate on which line. Optional
  52514. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  52515. // default is 'auto', chose the axis which type is category.
  52516. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  52517. axis: 'auto',
  52518. animation: 'auto',
  52519. animationDurationUpdate: 200,
  52520. animationEasingUpdate: 'exponentialOut',
  52521. crossStyle: {
  52522. color: tokens.color.borderShade,
  52523. width: 1,
  52524. type: 'dashed',
  52525. // TODO formatter
  52526. textStyle: {}
  52527. }
  52528. // lineStyle and shadowStyle should not be specified here,
  52529. // otherwise it will always override those styles on option.axisPointer.
  52530. },
  52531. textStyle: {
  52532. color: tokens.color.tertiary,
  52533. fontSize: 14
  52534. }
  52535. };
  52536. return TooltipModel;
  52537. }(ComponentModel);
  52538. /* global document */
  52539. function shouldTooltipConfine(tooltipModel) {
  52540. var confineOption = tooltipModel.get('confine');
  52541. return confineOption != null ? !!confineOption
  52542. // In richText mode, the outside part can not be visible.
  52543. : tooltipModel.get('renderMode') === 'richText';
  52544. }
  52545. function testStyle(styleProps) {
  52546. if (!env.domSupported) {
  52547. return;
  52548. }
  52549. var style = document.documentElement.style;
  52550. for (var i = 0, len = styleProps.length; i < len; i++) {
  52551. if (styleProps[i] in style) {
  52552. return styleProps[i];
  52553. }
  52554. }
  52555. }
  52556. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  52557. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  52558. function toCSSVendorPrefix(styleVendor, styleProp) {
  52559. if (!styleVendor) {
  52560. return styleProp;
  52561. }
  52562. styleProp = toCamelCase(styleProp, true);
  52563. var idx = styleVendor.indexOf(styleProp);
  52564. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  52565. return styleVendor.toLowerCase();
  52566. }
  52567. function getComputedStyle(el, style) {
  52568. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  52569. return stl ? style ? stl[style] : stl : null;
  52570. }
  52571. /* global document, window */
  52572. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  52573. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform');
  52574. // eslint-disable-next-line
  52575. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  52576. function mirrorPos(pos) {
  52577. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  52578. return pos;
  52579. }
  52580. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  52581. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  52582. return '';
  52583. }
  52584. var backgroundColor = tooltipModel.get('backgroundColor');
  52585. var borderWidth = tooltipModel.get('borderWidth');
  52586. borderColor = convertToColorString(borderColor);
  52587. var arrowPos = mirrorPos(arrowPosition);
  52588. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  52589. var positionStyle = '';
  52590. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  52591. var rotateDeg;
  52592. if (indexOf(['left', 'right'], arrowPos) > -1) {
  52593. positionStyle += 'top:50%';
  52594. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  52595. } else {
  52596. positionStyle += 'left:50%';
  52597. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  52598. }
  52599. var rotateRadian = rotateDeg * Math.PI / 180;
  52600. var arrowWH = arrowSize + borderWidth;
  52601. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  52602. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  52603. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  52604. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  52605. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  52606. return "<div style=\"" + styleCss.join('') + "\"></div>";
  52607. }
  52608. function assembleTransition(duration, onlyFadeTransition, enableDisplayTransition) {
  52609. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  52610. var transitionOption = '';
  52611. var transitionText = '';
  52612. if (enableDisplayTransition) {
  52613. transitionOption = " " + duration / 2 + "s " + transitionCurve;
  52614. transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  52615. }
  52616. if (!onlyFadeTransition) {
  52617. transitionOption = " " + duration + "s " + transitionCurve;
  52618. transitionText += (transitionText.length ? ',' : '') + (env.transformSupported ? "" + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption);
  52619. }
  52620. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  52621. }
  52622. function assembleTransform(x, y, toString) {
  52623. // If using float on style, the final width of the dom might
  52624. // keep changing slightly while mouse move. So `toFixed(0)` them.
  52625. var x0 = x.toFixed(0) + 'px';
  52626. var y0 = y.toFixed(0) + 'px';
  52627. // not support transform, use `left` and `top` instead.
  52628. if (!env.transformSupported) {
  52629. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  52630. }
  52631. // support transform
  52632. var is3d = env.transform3dSupported;
  52633. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  52634. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  52635. }
  52636. /**
  52637. * @param {Object} textStyle
  52638. * @return {string}
  52639. * @inner
  52640. */
  52641. function assembleFont(textStyleModel) {
  52642. var cssText = [];
  52643. var fontSize = textStyleModel.get('fontSize');
  52644. var color = textStyleModel.getTextColor();
  52645. color && cssText.push('color:' + color);
  52646. cssText.push('font:' + textStyleModel.getFont());
  52647. // @ts-ignore, leave it to the tooltip refactor.
  52648. var lineHeight = retrieve2(textStyleModel.get('lineHeight'), Math.round(fontSize * 3 / 2));
  52649. fontSize && cssText.push('line-height:' + lineHeight + 'px');
  52650. var shadowColor = textStyleModel.get('textShadowColor');
  52651. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  52652. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  52653. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  52654. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  52655. each(['decoration', 'align'], function (name) {
  52656. var val = textStyleModel.get(name);
  52657. val && cssText.push('text-' + name + ':' + val);
  52658. });
  52659. return cssText.join(';');
  52660. }
  52661. function assembleCssText(tooltipModel, enableTransition, onlyFadeTransition, enableDisplayTransition) {
  52662. var cssText = [];
  52663. var transitionDuration = tooltipModel.get('transitionDuration');
  52664. var backgroundColor = tooltipModel.get('backgroundColor');
  52665. var shadowBlur = tooltipModel.get('shadowBlur');
  52666. var shadowColor = tooltipModel.get('shadowColor');
  52667. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  52668. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  52669. var textStyleModel = tooltipModel.getModel('textStyle');
  52670. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  52671. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  52672. cssText.push('box-shadow:' + boxShadow);
  52673. // Animation transition. Do not animate when transitionDuration <= 0.
  52674. enableTransition && transitionDuration > 0 && cssText.push(assembleTransition(transitionDuration, onlyFadeTransition, enableDisplayTransition));
  52675. if (backgroundColor) {
  52676. cssText.push('background-color:' + backgroundColor);
  52677. }
  52678. // Border style
  52679. each(['width', 'color', 'radius'], function (name) {
  52680. var borderName = 'border-' + name;
  52681. var camelCase = toCamelCase(borderName);
  52682. var val = tooltipModel.get(camelCase);
  52683. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  52684. });
  52685. // Text style
  52686. cssText.push(assembleFont(textStyleModel));
  52687. // Padding
  52688. if (padding != null) {
  52689. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  52690. }
  52691. return cssText.join(';') + ';';
  52692. }
  52693. // If not able to make, do not modify the input `out`.
  52694. function makeStyleCoord(out, zr, container, zrX, zrY) {
  52695. var zrPainter = zr && zr.painter;
  52696. if (container) {
  52697. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  52698. if (zrViewportRoot) {
  52699. // Some APPs might use scale on body, so we support CSS transform here.
  52700. transformLocalCoord(out, zrViewportRoot, container, zrX, zrY);
  52701. }
  52702. } else {
  52703. out[0] = zrX;
  52704. out[1] = zrY;
  52705. // xy should be based on canvas root. But tooltipContent is
  52706. // the sibling of canvas root. So padding of ec container
  52707. // should be considered here.
  52708. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  52709. if (viewportRootOffset) {
  52710. out[0] += viewportRootOffset.offsetLeft;
  52711. out[1] += viewportRootOffset.offsetTop;
  52712. }
  52713. }
  52714. out[2] = out[0] / zr.getWidth();
  52715. out[3] = out[1] / zr.getHeight();
  52716. }
  52717. var TooltipHTMLContent = /** @class */function () {
  52718. function TooltipHTMLContent(api, opt) {
  52719. this._show = false;
  52720. this._styleCoord = [0, 0, 0, 0];
  52721. this._enterable = true;
  52722. this._alwaysShowContent = false;
  52723. this._firstShow = true;
  52724. this._longHide = true;
  52725. if (env.wxa) {
  52726. return null;
  52727. }
  52728. var el = document.createElement('div');
  52729. // TODO: TYPE
  52730. el.domBelongToZr = true;
  52731. this.el = el;
  52732. var zr = this._zr = api.getZr();
  52733. var appendTo = opt.appendTo;
  52734. var container = appendTo && (isString(appendTo) ? document.querySelector(appendTo) : isDom(appendTo) ? appendTo : isFunction(appendTo) && appendTo(api.getDom()));
  52735. makeStyleCoord(this._styleCoord, zr, container, api.getWidth() / 2, api.getHeight() / 2);
  52736. (container || api.getDom()).appendChild(el);
  52737. this._api = api;
  52738. this._container = container;
  52739. // FIXME
  52740. // Is it needed to trigger zr event manually if
  52741. // the browser do not support `pointer-events: none`.
  52742. var self = this;
  52743. el.onmouseenter = function () {
  52744. // clear the timeout in hideLater and keep showing tooltip
  52745. if (self._enterable) {
  52746. clearTimeout(self._hideTimeout);
  52747. self._show = true;
  52748. }
  52749. self._inContent = true;
  52750. };
  52751. el.onmousemove = function (e) {
  52752. e = e || window.event;
  52753. if (!self._enterable) {
  52754. // `pointer-events: none` is set to tooltip content div
  52755. // if `enterable` is set as `false`, and `el.onmousemove`
  52756. // can not be triggered. But in browser that do not
  52757. // support `pointer-events`, we need to do this:
  52758. // Try trigger zrender event to avoid mouse
  52759. // in and out shape too frequently
  52760. var handler = zr.handler;
  52761. var zrViewportRoot = zr.painter.getViewportRoot();
  52762. normalizeEvent(zrViewportRoot, e, true);
  52763. handler.dispatch('mousemove', e);
  52764. }
  52765. };
  52766. el.onmouseleave = function () {
  52767. // set `_inContent` to `false` before `hideLater`
  52768. self._inContent = false;
  52769. if (self._enterable) {
  52770. if (self._show) {
  52771. self.hideLater(self._hideDelay);
  52772. }
  52773. }
  52774. };
  52775. }
  52776. /**
  52777. * Update when tooltip is rendered
  52778. */
  52779. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  52780. // FIXME
  52781. // Move this logic to ec main?
  52782. if (!this._container) {
  52783. var container = this._api.getDom();
  52784. var position = getComputedStyle(container, 'position');
  52785. var domStyle = container.style;
  52786. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  52787. domStyle.position = 'relative';
  52788. }
  52789. }
  52790. // move tooltip if chart resized
  52791. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  52792. alwaysShowContent && this._moveIfResized();
  52793. // update alwaysShowContent
  52794. this._alwaysShowContent = alwaysShowContent;
  52795. this._enableDisplayTransition = tooltipModel.get('displayTransition') && tooltipModel.get('transitionDuration') > 0;
  52796. // update className
  52797. this.el.className = tooltipModel.get('className') || '';
  52798. // Hide the tooltip
  52799. // PENDING
  52800. // this.hide();
  52801. };
  52802. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  52803. clearTimeout(this._hideTimeout);
  52804. clearTimeout(this._longHideTimeout);
  52805. var el = this.el;
  52806. var style = el.style;
  52807. var styleCoord = this._styleCoord;
  52808. if (!el.innerHTML) {
  52809. style.display = 'none';
  52810. } else {
  52811. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide, this._enableDisplayTransition)
  52812. // initial transform
  52813. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '')
  52814. // If mouse occasionally move over the tooltip, a mouseout event will be
  52815. // triggered by canvas, and cause some unexpectable result like dragging
  52816. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  52817. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  52818. // scenario.
  52819. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  52820. }
  52821. this._show = true;
  52822. this._firstShow = false;
  52823. this._longHide = false;
  52824. };
  52825. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  52826. var el = this.el;
  52827. if (content == null) {
  52828. el.innerHTML = '';
  52829. return;
  52830. }
  52831. var arrow = '';
  52832. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  52833. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  52834. }
  52835. if (isString(content)) {
  52836. el.innerHTML = content + arrow;
  52837. } else if (content) {
  52838. // Clear previous
  52839. el.innerHTML = '';
  52840. if (!isArray(content)) {
  52841. content = [content];
  52842. }
  52843. for (var i = 0; i < content.length; i++) {
  52844. if (isDom(content[i]) && content[i].parentNode !== el) {
  52845. el.appendChild(content[i]);
  52846. }
  52847. }
  52848. // no arrow if empty
  52849. if (arrow && el.childNodes.length) {
  52850. // no need to create a new parent element, but it's not supported by IE 10 and older.
  52851. // const arrowEl = document.createRange().createContextualFragment(arrow);
  52852. var arrowEl = document.createElement('div');
  52853. arrowEl.innerHTML = arrow;
  52854. el.appendChild(arrowEl);
  52855. }
  52856. }
  52857. };
  52858. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  52859. this._enterable = enterable;
  52860. };
  52861. TooltipHTMLContent.prototype.getSize = function () {
  52862. var el = this.el;
  52863. return el ? [el.offsetWidth, el.offsetHeight] : [0, 0];
  52864. };
  52865. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  52866. if (!this.el) {
  52867. return;
  52868. }
  52869. var styleCoord = this._styleCoord;
  52870. makeStyleCoord(styleCoord, this._zr, this._container, zrX, zrY);
  52871. if (styleCoord[0] != null && styleCoord[1] != null) {
  52872. var style_1 = this.el.style;
  52873. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  52874. each(transforms, function (transform) {
  52875. style_1[transform[0]] = transform[1];
  52876. });
  52877. }
  52878. };
  52879. /**
  52880. * when `alwaysShowContent` is true,
  52881. * move the tooltip after chart resized
  52882. */
  52883. TooltipHTMLContent.prototype._moveIfResized = function () {
  52884. // The ratio of left to width
  52885. var ratioX = this._styleCoord[2];
  52886. // The ratio of top to height
  52887. var ratioY = this._styleCoord[3];
  52888. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  52889. };
  52890. TooltipHTMLContent.prototype.hide = function () {
  52891. var _this = this;
  52892. var style = this.el.style;
  52893. if (this._enableDisplayTransition) {
  52894. style.visibility = 'hidden';
  52895. style.opacity = '0';
  52896. } else {
  52897. style.display = 'none';
  52898. }
  52899. env.transform3dSupported && (style.willChange = '');
  52900. this._show = false;
  52901. this._longHideTimeout = setTimeout(function () {
  52902. return _this._longHide = true;
  52903. }, 500);
  52904. };
  52905. TooltipHTMLContent.prototype.hideLater = function (time) {
  52906. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  52907. if (time) {
  52908. this._hideDelay = time;
  52909. // Set show false to avoid invoke hideLater multiple times
  52910. this._show = false;
  52911. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  52912. } else {
  52913. this.hide();
  52914. }
  52915. }
  52916. };
  52917. TooltipHTMLContent.prototype.isShow = function () {
  52918. return this._show;
  52919. };
  52920. TooltipHTMLContent.prototype.dispose = function () {
  52921. clearTimeout(this._hideTimeout);
  52922. clearTimeout(this._longHideTimeout);
  52923. var zr = this._zr;
  52924. transformLocalCoordClear(zr && zr.painter && zr.painter.getViewportRoot(), this._container);
  52925. var el = this.el;
  52926. if (el) {
  52927. el.onmouseenter = el.onmousemove = el.onmouseleave = null;
  52928. var parentNode = el.parentNode;
  52929. parentNode && parentNode.removeChild(el);
  52930. }
  52931. this.el = this._container = null;
  52932. };
  52933. return TooltipHTMLContent;
  52934. }();
  52935. var TooltipRichContent = /** @class */function () {
  52936. function TooltipRichContent(api) {
  52937. this._show = false;
  52938. this._styleCoord = [0, 0, 0, 0];
  52939. this._alwaysShowContent = false;
  52940. this._enterable = true;
  52941. this._zr = api.getZr();
  52942. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  52943. }
  52944. /**
  52945. * Update when tooltip is rendered
  52946. */
  52947. TooltipRichContent.prototype.update = function (tooltipModel) {
  52948. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  52949. alwaysShowContent && this._moveIfResized();
  52950. // update alwaysShowContent
  52951. this._alwaysShowContent = alwaysShowContent;
  52952. };
  52953. TooltipRichContent.prototype.show = function () {
  52954. if (this._hideTimeout) {
  52955. clearTimeout(this._hideTimeout);
  52956. }
  52957. this.el.show();
  52958. this._show = true;
  52959. };
  52960. /**
  52961. * Set tooltip content
  52962. */
  52963. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  52964. var _this = this;
  52965. if (isObject(content)) {
  52966. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  52967. }
  52968. if (this.el) {
  52969. this._zr.remove(this.el);
  52970. }
  52971. var textStyleModel = tooltipModel.getModel('textStyle');
  52972. this.el = new ZRText({
  52973. style: {
  52974. rich: markupStyleCreator.richTextStyles,
  52975. text: content,
  52976. lineHeight: 22,
  52977. borderWidth: 1,
  52978. borderColor: borderColor,
  52979. textShadowColor: textStyleModel.get('textShadowColor'),
  52980. fill: tooltipModel.get(['textStyle', 'color']),
  52981. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  52982. verticalAlign: 'top',
  52983. align: 'left'
  52984. },
  52985. z: tooltipModel.get('z')
  52986. });
  52987. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  52988. _this.el.style[propName] = tooltipModel.get(propName);
  52989. });
  52990. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  52991. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  52992. });
  52993. this._zr.add(this.el);
  52994. var self = this;
  52995. this.el.on('mouseover', function () {
  52996. // clear the timeout in hideLater and keep showing tooltip
  52997. if (self._enterable) {
  52998. clearTimeout(self._hideTimeout);
  52999. self._show = true;
  53000. }
  53001. self._inContent = true;
  53002. });
  53003. this.el.on('mouseout', function () {
  53004. if (self._enterable) {
  53005. if (self._show) {
  53006. self.hideLater(self._hideDelay);
  53007. }
  53008. }
  53009. self._inContent = false;
  53010. });
  53011. };
  53012. TooltipRichContent.prototype.setEnterable = function (enterable) {
  53013. this._enterable = enterable;
  53014. };
  53015. TooltipRichContent.prototype.getSize = function () {
  53016. var el = this.el;
  53017. var bounding = this.el.getBoundingRect();
  53018. // bounding rect does not include shadow. For renderMode richText,
  53019. // if overflow, it will be cut. So calculate them accurately.
  53020. var shadowOuterSize = calcShadowOuterSize(el.style);
  53021. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  53022. };
  53023. TooltipRichContent.prototype.moveTo = function (x, y) {
  53024. var el = this.el;
  53025. if (el) {
  53026. var styleCoord = this._styleCoord;
  53027. makeStyleCoord$1(styleCoord, this._zr, x, y);
  53028. x = styleCoord[0];
  53029. y = styleCoord[1];
  53030. var style = el.style;
  53031. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  53032. var shadowOuterSize = calcShadowOuterSize(style);
  53033. // rich text x, y do not include border.
  53034. el.x = x + borderWidth + shadowOuterSize.left;
  53035. el.y = y + borderWidth + shadowOuterSize.top;
  53036. el.markRedraw();
  53037. }
  53038. };
  53039. /**
  53040. * when `alwaysShowContent` is true,
  53041. * move the tooltip after chart resized
  53042. */
  53043. TooltipRichContent.prototype._moveIfResized = function () {
  53044. // The ratio of left to width
  53045. var ratioX = this._styleCoord[2];
  53046. // The ratio of top to height
  53047. var ratioY = this._styleCoord[3];
  53048. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  53049. };
  53050. TooltipRichContent.prototype.hide = function () {
  53051. if (this.el) {
  53052. this.el.hide();
  53053. }
  53054. this._show = false;
  53055. };
  53056. TooltipRichContent.prototype.hideLater = function (time) {
  53057. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  53058. if (time) {
  53059. this._hideDelay = time;
  53060. // Set show false to avoid invoke hideLater multiple times
  53061. this._show = false;
  53062. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  53063. } else {
  53064. this.hide();
  53065. }
  53066. }
  53067. };
  53068. TooltipRichContent.prototype.isShow = function () {
  53069. return this._show;
  53070. };
  53071. TooltipRichContent.prototype.dispose = function () {
  53072. this._zr.remove(this.el);
  53073. };
  53074. return TooltipRichContent;
  53075. }();
  53076. function mathMaxWith0(val) {
  53077. return Math.max(0, val);
  53078. }
  53079. function calcShadowOuterSize(style) {
  53080. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  53081. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  53082. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  53083. return {
  53084. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  53085. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  53086. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  53087. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  53088. };
  53089. }
  53090. function makeStyleCoord$1(out, zr, zrX, zrY) {
  53091. out[0] = zrX;
  53092. out[1] = zrY;
  53093. out[2] = out[0] / zr.getWidth();
  53094. out[3] = out[1] / zr.getHeight();
  53095. }
  53096. var proxyRect = new Rect({
  53097. shape: {
  53098. x: -1,
  53099. y: -1,
  53100. width: 2,
  53101. height: 2
  53102. }
  53103. });
  53104. var TooltipView = /** @class */function (_super) {
  53105. __extends(TooltipView, _super);
  53106. function TooltipView() {
  53107. var _this = _super !== null && _super.apply(this, arguments) || this;
  53108. _this.type = TooltipView.type;
  53109. return _this;
  53110. }
  53111. TooltipView.prototype.init = function (ecModel, api) {
  53112. if (env.node || !api.getDom()) {
  53113. return;
  53114. }
  53115. var tooltipModel = ecModel.getComponent('tooltip');
  53116. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  53117. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api, {
  53118. appendTo: tooltipModel.get('appendToBody', true) ? 'body' : tooltipModel.get('appendTo', true)
  53119. });
  53120. };
  53121. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  53122. if (env.node || !api.getDom()) {
  53123. return;
  53124. }
  53125. // Reset
  53126. this.group.removeAll();
  53127. this._tooltipModel = tooltipModel;
  53128. this._ecModel = ecModel;
  53129. this._api = api;
  53130. var tooltipContent = this._tooltipContent;
  53131. tooltipContent.update(tooltipModel);
  53132. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  53133. this._initGlobalListener();
  53134. this._keepShow();
  53135. // PENDING
  53136. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  53137. // which causes that the `updatePosition` function was also called frequently.
  53138. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  53139. // To avoid frequent triggering,
  53140. // consider throttling it in 50ms when transition is enabled
  53141. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  53142. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  53143. } else {
  53144. clear(this, '_updatePosition');
  53145. }
  53146. };
  53147. TooltipView.prototype._initGlobalListener = function () {
  53148. var tooltipModel = this._tooltipModel;
  53149. var triggerOn = tooltipModel.get('triggerOn');
  53150. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  53151. // If 'none', it is not controlled by mouse totally.
  53152. if (triggerOn !== 'none') {
  53153. if (triggerOn.indexOf(currTrigger) >= 0) {
  53154. this._tryShow(e, dispatchAction);
  53155. } else if (currTrigger === 'leave') {
  53156. this._hide(dispatchAction);
  53157. }
  53158. }
  53159. }, this));
  53160. };
  53161. TooltipView.prototype._keepShow = function () {
  53162. var tooltipModel = this._tooltipModel;
  53163. var ecModel = this._ecModel;
  53164. var api = this._api;
  53165. var triggerOn = tooltipModel.get('triggerOn');
  53166. // Try to keep the tooltip show when refreshing
  53167. if (this._lastX != null && this._lastY != null
  53168. // When user is willing to control tooltip totally using API,
  53169. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  53170. // which is not expected.
  53171. && triggerOn !== 'none' && triggerOn !== 'click') {
  53172. var self_1 = this;
  53173. clearTimeout(this._refreshUpdateTimeout);
  53174. this._refreshUpdateTimeout = setTimeout(function () {
  53175. // Show tip next tick after other charts are rendered
  53176. // In case highlight action has wrong result
  53177. // FIXME
  53178. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  53179. x: self_1._lastX,
  53180. y: self_1._lastY,
  53181. dataByCoordSys: self_1._lastDataByCoordSys
  53182. });
  53183. });
  53184. }
  53185. };
  53186. /**
  53187. * Show tip manually by
  53188. * dispatchAction({
  53189. * type: 'showTip',
  53190. * x: 10,
  53191. * y: 10
  53192. * });
  53193. * Or
  53194. * dispatchAction({
  53195. * type: 'showTip',
  53196. * seriesIndex: 0,
  53197. * dataIndex or dataIndexInside or name
  53198. * });
  53199. *
  53200. * TODO Batch
  53201. */
  53202. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  53203. if (payload.from === this.uid || env.node || !api.getDom()) {
  53204. return;
  53205. }
  53206. var dispatchAction = makeDispatchAction$1(payload, api);
  53207. // Reset ticket
  53208. this._ticket = '';
  53209. // When triggered from axisPointer.
  53210. var dataByCoordSys = payload.dataByCoordSys;
  53211. var cmptRef = findComponentReference(payload, ecModel, api);
  53212. if (cmptRef) {
  53213. var rect = cmptRef.el.getBoundingRect().clone();
  53214. rect.applyTransform(cmptRef.el.transform);
  53215. this._tryShow({
  53216. offsetX: rect.x + rect.width / 2,
  53217. offsetY: rect.y + rect.height / 2,
  53218. target: cmptRef.el,
  53219. position: payload.position,
  53220. // When manully trigger, the mouse is not on the el, so we'd better to
  53221. // position tooltip on the bottom of the el and display arrow is possible.
  53222. positionDefault: 'bottom'
  53223. }, dispatchAction);
  53224. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  53225. var el = proxyRect;
  53226. el.x = payload.x;
  53227. el.y = payload.y;
  53228. el.update();
  53229. getECData(el).tooltipConfig = {
  53230. name: null,
  53231. option: payload.tooltip
  53232. };
  53233. // Manually show tooltip while view is not using zrender elements.
  53234. this._tryShow({
  53235. offsetX: payload.x,
  53236. offsetY: payload.y,
  53237. target: el
  53238. }, dispatchAction);
  53239. } else if (dataByCoordSys) {
  53240. this._tryShow({
  53241. offsetX: payload.x,
  53242. offsetY: payload.y,
  53243. position: payload.position,
  53244. dataByCoordSys: dataByCoordSys,
  53245. tooltipOption: payload.tooltipOption
  53246. }, dispatchAction);
  53247. } else if (payload.seriesIndex != null) {
  53248. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  53249. return;
  53250. }
  53251. var pointInfo = findPointFromSeries(payload, ecModel);
  53252. var cx = pointInfo.point[0];
  53253. var cy = pointInfo.point[1];
  53254. if (cx != null && cy != null) {
  53255. this._tryShow({
  53256. offsetX: cx,
  53257. offsetY: cy,
  53258. target: pointInfo.el,
  53259. position: payload.position,
  53260. // When manully trigger, the mouse is not on the el, so we'd better to
  53261. // position tooltip on the bottom of the el and display arrow is possible.
  53262. positionDefault: 'bottom'
  53263. }, dispatchAction);
  53264. }
  53265. } else if (payload.x != null && payload.y != null) {
  53266. // FIXME
  53267. // should wrap dispatchAction like `axisPointer/globalListener` ?
  53268. api.dispatchAction({
  53269. type: 'updateAxisPointer',
  53270. x: payload.x,
  53271. y: payload.y
  53272. });
  53273. this._tryShow({
  53274. offsetX: payload.x,
  53275. offsetY: payload.y,
  53276. position: payload.position,
  53277. target: api.getZr().findHover(payload.x, payload.y).target
  53278. }, dispatchAction);
  53279. }
  53280. };
  53281. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  53282. var tooltipContent = this._tooltipContent;
  53283. if (this._tooltipModel) {
  53284. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  53285. }
  53286. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  53287. if (payload.from !== this.uid) {
  53288. this._hide(makeDispatchAction$1(payload, api));
  53289. }
  53290. };
  53291. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  53292. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  53293. // and tooltip.
  53294. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  53295. var seriesIndex = payload.seriesIndex;
  53296. var dataIndex = payload.dataIndex;
  53297. // @ts-ignore
  53298. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  53299. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  53300. return;
  53301. }
  53302. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  53303. if (!seriesModel) {
  53304. return;
  53305. }
  53306. var data = seriesModel.getData();
  53307. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  53308. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  53309. return;
  53310. }
  53311. api.dispatchAction({
  53312. type: 'updateAxisPointer',
  53313. seriesIndex: seriesIndex,
  53314. dataIndex: dataIndex,
  53315. position: payload.position
  53316. });
  53317. return true;
  53318. };
  53319. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  53320. var el = e.target;
  53321. var tooltipModel = this._tooltipModel;
  53322. if (!tooltipModel) {
  53323. return;
  53324. }
  53325. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  53326. this._lastX = e.offsetX;
  53327. this._lastY = e.offsetY;
  53328. var dataByCoordSys = e.dataByCoordSys;
  53329. if (dataByCoordSys && dataByCoordSys.length) {
  53330. this._showAxisTooltip(dataByCoordSys, e);
  53331. } else if (el) {
  53332. var ecData = getECData(el);
  53333. if (ecData.ssrType === 'legend') {
  53334. // Don't trigger tooltip for legend tooltip item
  53335. return;
  53336. }
  53337. this._lastDataByCoordSys = null;
  53338. var seriesDispatcher_1;
  53339. var cmptDispatcher_1;
  53340. findEventDispatcher(el, function (target) {
  53341. if (target.tooltipDisabled) {
  53342. seriesDispatcher_1 = cmptDispatcher_1 = null;
  53343. return true;
  53344. }
  53345. if (seriesDispatcher_1 || cmptDispatcher_1) {
  53346. return;
  53347. }
  53348. // Always show item tooltip if mouse is on the element with dataIndex
  53349. if (getECData(target).dataIndex != null) {
  53350. seriesDispatcher_1 = target;
  53351. }
  53352. // Tooltip provided directly. Like legend.
  53353. else if (getECData(target).tooltipConfig != null) {
  53354. cmptDispatcher_1 = target;
  53355. }
  53356. }, true);
  53357. if (seriesDispatcher_1) {
  53358. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  53359. } else if (cmptDispatcher_1) {
  53360. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  53361. } else {
  53362. this._hide(dispatchAction);
  53363. }
  53364. } else {
  53365. this._lastDataByCoordSys = null;
  53366. this._hide(dispatchAction);
  53367. }
  53368. };
  53369. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  53370. // showDelay is used in this case: tooltip.enterable is set
  53371. // as true. User intent to move mouse into tooltip and click
  53372. // something. `showDelay` makes it easier to enter the content
  53373. // but tooltip do not move immediately.
  53374. var delay = tooltipModel.get('showDelay');
  53375. cb = bind(cb, this);
  53376. clearTimeout(this._showTimout);
  53377. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  53378. };
  53379. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  53380. var ecModel = this._ecModel;
  53381. var globalTooltipModel = this._tooltipModel;
  53382. var point = [e.offsetX, e.offsetY];
  53383. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  53384. var renderMode = this._renderMode;
  53385. var cbParamsList = [];
  53386. var articleMarkup = createTooltipMarkup('section', {
  53387. blocks: [],
  53388. noHeader: true
  53389. });
  53390. // Only for legacy: `Serise['formatTooltip']` returns a string.
  53391. var markupTextArrLegacy = [];
  53392. var markupStyleCreator = new TooltipMarkupStyleCreator();
  53393. each(dataByCoordSys, function (itemCoordSys) {
  53394. each(itemCoordSys.dataByAxis, function (axisItem) {
  53395. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  53396. var axisValue = axisItem.value;
  53397. if (!axisModel || axisValue == null) {
  53398. return;
  53399. }
  53400. // FIXME: when using `tooltip.trigger: 'axis'`, the precision of the axis value displayed in tooltip
  53401. // should match the original series values rather than using the default stretegy in Interval.ts
  53402. // (getPrecision(interval) + 2); otherwise it may cuase confusion.
  53403. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  53404. var axisSectionMarkup = createTooltipMarkup('section', {
  53405. header: axisValueLabel,
  53406. noHeader: !trim(axisValueLabel),
  53407. sortBlocks: true,
  53408. blocks: []
  53409. });
  53410. articleMarkup.blocks.push(axisSectionMarkup);
  53411. each(axisItem.seriesDataIndices, function (idxItem) {
  53412. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  53413. var dataIndex = idxItem.dataIndexInside;
  53414. var cbParams = series.getDataParams(dataIndex);
  53415. // Can't find data.
  53416. if (cbParams.dataIndex < 0) {
  53417. return;
  53418. }
  53419. cbParams.axisDim = axisItem.axisDim;
  53420. cbParams.axisIndex = axisItem.axisIndex;
  53421. cbParams.axisType = axisItem.axisType;
  53422. cbParams.axisId = axisItem.axisId;
  53423. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  53424. value: axisValue
  53425. });
  53426. cbParams.axisValueLabel = axisValueLabel;
  53427. // Pre-create marker style for makers. Users can assemble richText
  53428. // text in `formatter` callback and use those markers style.
  53429. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  53430. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  53431. var frag = seriesTooltipResult.frag;
  53432. if (frag) {
  53433. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  53434. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  53435. valueFormatter: valueFormatter
  53436. }, frag) : frag);
  53437. }
  53438. if (seriesTooltipResult.text) {
  53439. markupTextArrLegacy.push(seriesTooltipResult.text);
  53440. }
  53441. cbParamsList.push(cbParams);
  53442. });
  53443. });
  53444. });
  53445. // In most cases, the second axis is displays upper on the first one.
  53446. // So we reverse it to look better.
  53447. articleMarkup.blocks.reverse();
  53448. markupTextArrLegacy.reverse();
  53449. var positionExpr = e.position;
  53450. var orderMode = singleTooltipModel.get('order');
  53451. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  53452. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  53453. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  53454. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  53455. this._showOrMove(singleTooltipModel, function () {
  53456. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  53457. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  53458. } else {
  53459. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  53460. }
  53461. });
  53462. // Do not trigger events here, because this branch only be entered
  53463. // from dispatchAction.
  53464. };
  53465. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  53466. var ecModel = this._ecModel;
  53467. var ecData = getECData(dispatcher);
  53468. // Use dataModel in element if possible
  53469. // Used when mouseover on a element like markPoint or edge
  53470. // In which case, the data is not main data in series.
  53471. var seriesIndex = ecData.seriesIndex;
  53472. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  53473. // For example, graph link.
  53474. var dataModel = ecData.dataModel || seriesModel;
  53475. var dataIndex = ecData.dataIndex;
  53476. var dataType = ecData.dataType;
  53477. var data = dataModel.getData(dataType);
  53478. var renderMode = this._renderMode;
  53479. var positionDefault = e.positionDefault;
  53480. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  53481. position: positionDefault
  53482. } : null);
  53483. var tooltipTrigger = tooltipModel.get('trigger');
  53484. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  53485. return;
  53486. }
  53487. var params = dataModel.getDataParams(dataIndex, dataType);
  53488. var markupStyleCreator = new TooltipMarkupStyleCreator();
  53489. // Pre-create marker style for makers. Users can assemble richText
  53490. // text in `formatter` callback and use those markers style.
  53491. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  53492. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  53493. var orderMode = tooltipModel.get('order');
  53494. var valueFormatter = tooltipModel.get('valueFormatter');
  53495. var frag = seriesTooltipResult.frag;
  53496. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  53497. valueFormatter: valueFormatter
  53498. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  53499. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  53500. this._showOrMove(tooltipModel, function () {
  53501. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  53502. });
  53503. // FIXME
  53504. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  53505. dispatchAction({
  53506. type: 'showTip',
  53507. dataIndexInside: dataIndex,
  53508. dataIndex: data.getRawIndex(dataIndex),
  53509. seriesIndex: seriesIndex,
  53510. from: this.uid
  53511. });
  53512. };
  53513. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  53514. var isHTMLRenderMode = this._renderMode === 'html';
  53515. var ecData = getECData(el);
  53516. var tooltipConfig = ecData.tooltipConfig;
  53517. var tooltipOpt = tooltipConfig.option || {};
  53518. var encodeHTMLContent = tooltipOpt.encodeHTMLContent;
  53519. if (isString(tooltipOpt)) {
  53520. var content = tooltipOpt;
  53521. tooltipOpt = {
  53522. content: content,
  53523. // Fixed formatter
  53524. formatter: content
  53525. };
  53526. // when `tooltipConfig.option` is a string rather than an object,
  53527. // we can't know if the content needs to be encoded
  53528. // for the sake of security, encode it by default.
  53529. encodeHTMLContent = true;
  53530. }
  53531. if (encodeHTMLContent && isHTMLRenderMode && tooltipOpt.content) {
  53532. // clone might be unnecessary?
  53533. tooltipOpt = clone(tooltipOpt);
  53534. tooltipOpt.content = encodeHTML(tooltipOpt.content);
  53535. }
  53536. var tooltipModelCascade = [tooltipOpt];
  53537. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  53538. if (cmpt) {
  53539. tooltipModelCascade.push(cmpt);
  53540. }
  53541. // In most cases, component tooltip formatter has different params with series tooltip formatter,
  53542. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  53543. // by convention, we do not use it as the default formatter for component.
  53544. tooltipModelCascade.push({
  53545. formatter: tooltipOpt.content
  53546. });
  53547. var positionDefault = e.positionDefault;
  53548. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  53549. position: positionDefault
  53550. } : null);
  53551. var defaultHtml = subTooltipModel.get('content');
  53552. var asyncTicket = Math.random() + '';
  53553. // PENDING: this case do not support richText style yet.
  53554. var markupStyleCreator = new TooltipMarkupStyleCreator();
  53555. // Do not check whether `trigger` is 'none' here, because `trigger`
  53556. // only works on coordinate system. In fact, we have not found case
  53557. // that requires setting `trigger` nothing on component yet.
  53558. this._showOrMove(subTooltipModel, function () {
  53559. // Use formatterParams from element defined in component
  53560. // Avoid users modify it.
  53561. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  53562. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  53563. });
  53564. // If not dispatch showTip, tip may be hide triggered by axis.
  53565. dispatchAction({
  53566. type: 'showTip',
  53567. from: this.uid
  53568. });
  53569. };
  53570. TooltipView.prototype._showTooltipContent = function (
  53571. // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  53572. // Instead of top level tooltip.
  53573. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  53574. // Reset ticket
  53575. this._ticket = '';
  53576. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  53577. return;
  53578. }
  53579. var tooltipContent = this._tooltipContent;
  53580. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  53581. var formatter = tooltipModel.get('formatter');
  53582. positionExpr = positionExpr || tooltipModel.get('position');
  53583. var html = defaultHtml;
  53584. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'), tooltipModel.get('defaultBorderColor', true));
  53585. var nearPointColor = nearPoint.color;
  53586. if (formatter) {
  53587. if (isString(formatter)) {
  53588. var useUTC = tooltipModel.ecModel.get('useUTC');
  53589. var params0 = isArray(params) ? params[0] : params;
  53590. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  53591. html = formatter;
  53592. if (isTimeAxis) {
  53593. html = format(params0.axisValue, html, useUTC);
  53594. }
  53595. html = formatTpl(html, params, true);
  53596. } else if (isFunction(formatter)) {
  53597. var callback = bind(function (cbTicket, html) {
  53598. if (cbTicket === this._ticket) {
  53599. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  53600. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  53601. }
  53602. }, this);
  53603. this._ticket = asyncTicket;
  53604. html = formatter(params, asyncTicket, callback);
  53605. } else {
  53606. html = formatter;
  53607. }
  53608. }
  53609. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  53610. tooltipContent.show(tooltipModel, nearPointColor);
  53611. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  53612. };
  53613. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor, defaultBorderColor) {
  53614. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  53615. return {
  53616. color: borderColor || defaultBorderColor
  53617. };
  53618. }
  53619. if (!isArray(tooltipDataParams)) {
  53620. return {
  53621. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  53622. };
  53623. }
  53624. };
  53625. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x,
  53626. // Mouse x
  53627. y,
  53628. // Mouse y
  53629. content, params, el) {
  53630. var viewWidth = this._api.getWidth();
  53631. var viewHeight = this._api.getHeight();
  53632. positionExpr = positionExpr || tooltipModel.get('position');
  53633. var contentSize = content.getSize();
  53634. var align = tooltipModel.get('align');
  53635. var vAlign = tooltipModel.get('verticalAlign');
  53636. var rect = el && el.getBoundingRect().clone();
  53637. el && rect.applyTransform(el.transform);
  53638. if (isFunction(positionExpr)) {
  53639. // Callback of position can be an array or a string specify the position
  53640. positionExpr = positionExpr([x, y], params, content.el, rect, {
  53641. viewSize: [viewWidth, viewHeight],
  53642. contentSize: contentSize.slice()
  53643. });
  53644. }
  53645. if (isArray(positionExpr)) {
  53646. x = parsePercent$1(positionExpr[0], viewWidth);
  53647. y = parsePercent$1(positionExpr[1], viewHeight);
  53648. } else if (isObject(positionExpr)) {
  53649. var boxLayoutPosition = positionExpr;
  53650. boxLayoutPosition.width = contentSize[0];
  53651. boxLayoutPosition.height = contentSize[1];
  53652. var layoutRect = getLayoutRect(boxLayoutPosition, {
  53653. width: viewWidth,
  53654. height: viewHeight
  53655. });
  53656. x = layoutRect.x;
  53657. y = layoutRect.y;
  53658. align = null;
  53659. // When positionExpr is left/top/right/bottom,
  53660. // align and verticalAlign will not work.
  53661. vAlign = null;
  53662. }
  53663. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  53664. else if (isString(positionExpr) && el) {
  53665. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  53666. x = pos[0];
  53667. y = pos[1];
  53668. } else {
  53669. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  53670. x = pos[0];
  53671. y = pos[1];
  53672. }
  53673. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  53674. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  53675. if (shouldTooltipConfine(tooltipModel)) {
  53676. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  53677. x = pos[0];
  53678. y = pos[1];
  53679. }
  53680. content.moveTo(x, y);
  53681. };
  53682. // FIXME
  53683. // Should we remove this but leave this to user?
  53684. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  53685. var lastCoordSys = this._lastDataByCoordSys;
  53686. var lastCbParamsList = this._cbParamsList;
  53687. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  53688. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  53689. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  53690. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  53691. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  53692. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  53693. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  53694. var thisItem = thisDataByAxis[indexAxis] || {};
  53695. var lastIndices = lastItem.seriesDataIndices || [];
  53696. var newIndices = thisItem.seriesDataIndices || [];
  53697. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  53698. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  53699. var newIdxItem = newIndices[j];
  53700. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  53701. });
  53702. // check is cbParams data value changed
  53703. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  53704. var seriesIdx = idxItem.seriesIndex;
  53705. var cbParams = cbParamsList[seriesIdx];
  53706. var lastCbParams = lastCbParamsList[seriesIdx];
  53707. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  53708. contentNotChanged = false;
  53709. }
  53710. });
  53711. });
  53712. });
  53713. this._lastDataByCoordSys = dataByCoordSys;
  53714. this._cbParamsList = cbParamsList;
  53715. return !!contentNotChanged;
  53716. };
  53717. TooltipView.prototype._hide = function (dispatchAction) {
  53718. // Do not directly hideLater here, because this behavior may be prevented
  53719. // in dispatchAction when showTip is dispatched.
  53720. // FIXME
  53721. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  53722. this._lastDataByCoordSys = null;
  53723. dispatchAction({
  53724. type: 'hideTip',
  53725. from: this.uid
  53726. });
  53727. };
  53728. TooltipView.prototype.dispose = function (ecModel, api) {
  53729. if (env.node || !api.getDom()) {
  53730. return;
  53731. }
  53732. clear(this, '_updatePosition');
  53733. this._tooltipContent.dispose();
  53734. unregister('itemTooltip', api);
  53735. };
  53736. TooltipView.type = 'tooltip';
  53737. return TooltipView;
  53738. }(ComponentView);
  53739. /**
  53740. * From top to bottom. (the last one should be globalTooltipModel);
  53741. */
  53742. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  53743. // Last is always tooltip model.
  53744. var ecModel = globalTooltipModel.ecModel;
  53745. var resultModel;
  53746. if (defaultTooltipOption) {
  53747. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  53748. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  53749. } else {
  53750. resultModel = globalTooltipModel;
  53751. }
  53752. for (var i = modelCascade.length - 1; i >= 0; i--) {
  53753. var tooltipOpt = modelCascade[i];
  53754. if (tooltipOpt) {
  53755. if (tooltipOpt instanceof Model) {
  53756. tooltipOpt = tooltipOpt.get('tooltip', true);
  53757. }
  53758. // In each data item tooltip can be simply write:
  53759. // {
  53760. // value: 10,
  53761. // tooltip: 'Something you need to know'
  53762. // }
  53763. if (isString(tooltipOpt)) {
  53764. tooltipOpt = {
  53765. formatter: tooltipOpt
  53766. };
  53767. }
  53768. if (tooltipOpt) {
  53769. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  53770. }
  53771. }
  53772. }
  53773. return resultModel;
  53774. }
  53775. function makeDispatchAction$1(payload, api) {
  53776. return payload.dispatchAction || bind(api.dispatchAction, api);
  53777. }
  53778. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  53779. var size = content.getSize();
  53780. var width = size[0];
  53781. var height = size[1];
  53782. if (gapH != null) {
  53783. // Add extra 2 pixels for this case:
  53784. // At present the "values" in default tooltip are using CSS `float: right`.
  53785. // When the right edge of the tooltip box is on the right side of the
  53786. // viewport, the `float` layout might push the "values" to the second line.
  53787. if (x + width + gapH + 2 > viewWidth) {
  53788. x -= width + gapH;
  53789. } else {
  53790. x += gapH;
  53791. }
  53792. }
  53793. if (gapV != null) {
  53794. if (y + height + gapV > viewHeight) {
  53795. y -= height + gapV;
  53796. } else {
  53797. y += gapV;
  53798. }
  53799. }
  53800. return [x, y];
  53801. }
  53802. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  53803. var size = content.getSize();
  53804. var width = size[0];
  53805. var height = size[1];
  53806. x = Math.min(x + width, viewWidth) - width;
  53807. y = Math.min(y + height, viewHeight) - height;
  53808. x = Math.max(x, 0);
  53809. y = Math.max(y, 0);
  53810. return [x, y];
  53811. }
  53812. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  53813. var domWidth = contentSize[0];
  53814. var domHeight = contentSize[1];
  53815. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  53816. var x = 0;
  53817. var y = 0;
  53818. var rectWidth = rect.width;
  53819. var rectHeight = rect.height;
  53820. switch (position) {
  53821. case 'inside':
  53822. x = rect.x + rectWidth / 2 - domWidth / 2;
  53823. y = rect.y + rectHeight / 2 - domHeight / 2;
  53824. break;
  53825. case 'top':
  53826. x = rect.x + rectWidth / 2 - domWidth / 2;
  53827. y = rect.y - domHeight - offset;
  53828. break;
  53829. case 'bottom':
  53830. x = rect.x + rectWidth / 2 - domWidth / 2;
  53831. y = rect.y + rectHeight + offset;
  53832. break;
  53833. case 'left':
  53834. x = rect.x - domWidth - offset;
  53835. y = rect.y + rectHeight / 2 - domHeight / 2;
  53836. break;
  53837. case 'right':
  53838. x = rect.x + rectWidth + offset;
  53839. y = rect.y + rectHeight / 2 - domHeight / 2;
  53840. }
  53841. return [x, y];
  53842. }
  53843. function isCenterAlign(align) {
  53844. return align === 'center' || align === 'middle';
  53845. }
  53846. /**
  53847. * Find target component by payload like:
  53848. * ```js
  53849. * { legendId: 'some_id', name: 'xxx' }
  53850. * { toolboxIndex: 1, name: 'xxx' }
  53851. * { geoName: 'some_name', name: 'xxx' }
  53852. * ```
  53853. * PENDING: at present only
  53854. *
  53855. * If not found, return null/undefined.
  53856. */
  53857. function findComponentReference(payload, ecModel, api) {
  53858. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  53859. var componentMainType = queryOptionMap.keys()[0];
  53860. if (!componentMainType || componentMainType === 'series') {
  53861. return;
  53862. }
  53863. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  53864. useDefault: false,
  53865. enableAll: false,
  53866. enableNone: false
  53867. });
  53868. var model = queryResult.models[0];
  53869. if (!model) {
  53870. return;
  53871. }
  53872. var view = api.getViewOfComponentModel(model);
  53873. var el;
  53874. view.group.traverse(function (subEl) {
  53875. var tooltipConfig = getECData(subEl).tooltipConfig;
  53876. if (tooltipConfig && tooltipConfig.name === payload.name) {
  53877. el = subEl;
  53878. return true; // stop
  53879. }
  53880. });
  53881. if (el) {
  53882. return {
  53883. componentMainType: componentMainType,
  53884. componentIndex: model.componentIndex,
  53885. el: el
  53886. };
  53887. }
  53888. }
  53889. function install$c(registers) {
  53890. use(install$7);
  53891. registers.registerComponentModel(TooltipModel);
  53892. registers.registerComponentView(TooltipView);
  53893. /**
  53894. * @action
  53895. * @property {string} type
  53896. * @property {number} seriesIndex
  53897. * @property {number} dataIndex
  53898. * @property {number} [x]
  53899. * @property {number} [y]
  53900. */
  53901. registers.registerAction({
  53902. type: 'showTip',
  53903. event: 'showTip',
  53904. update: 'tooltip:manuallyShowTip'
  53905. }, noop);
  53906. registers.registerAction({
  53907. type: 'hideTip',
  53908. event: 'hideTip',
  53909. update: 'tooltip:manuallyHideTip'
  53910. }, noop);
  53911. }
  53912. var TitleModel = /** @class */function (_super) {
  53913. __extends(TitleModel, _super);
  53914. function TitleModel() {
  53915. var _this = _super !== null && _super.apply(this, arguments) || this;
  53916. _this.type = TitleModel.type;
  53917. _this.layoutMode = {
  53918. type: 'box',
  53919. ignoreSize: true
  53920. };
  53921. return _this;
  53922. }
  53923. TitleModel.type = 'title';
  53924. TitleModel.defaultOption = {
  53925. // zlevel: 0,
  53926. z: 6,
  53927. show: true,
  53928. text: '',
  53929. target: 'blank',
  53930. subtext: '',
  53931. subtarget: 'blank',
  53932. left: 'center',
  53933. top: tokens.size.m,
  53934. backgroundColor: tokens.color.transparent,
  53935. borderColor: tokens.color.primary,
  53936. borderWidth: 0,
  53937. padding: 5,
  53938. itemGap: 10,
  53939. textStyle: {
  53940. fontSize: 18,
  53941. fontWeight: 'bold',
  53942. color: tokens.color.primary
  53943. },
  53944. subtextStyle: {
  53945. fontSize: 12,
  53946. color: tokens.color.quaternary
  53947. }
  53948. };
  53949. return TitleModel;
  53950. }(ComponentModel);
  53951. // View
  53952. var TitleView = /** @class */function (_super) {
  53953. __extends(TitleView, _super);
  53954. function TitleView() {
  53955. var _this = _super !== null && _super.apply(this, arguments) || this;
  53956. _this.type = TitleView.type;
  53957. return _this;
  53958. }
  53959. TitleView.prototype.render = function (titleModel, ecModel, api) {
  53960. this.group.removeAll();
  53961. if (!titleModel.get('show')) {
  53962. return;
  53963. }
  53964. var group = this.group;
  53965. var textStyleModel = titleModel.getModel('textStyle');
  53966. var subtextStyleModel = titleModel.getModel('subtextStyle');
  53967. var textAlign = titleModel.get('textAlign');
  53968. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  53969. var textEl = new ZRText({
  53970. style: createTextStyle(textStyleModel, {
  53971. text: titleModel.get('text'),
  53972. fill: textStyleModel.getTextColor()
  53973. }, {
  53974. disableBox: true
  53975. }),
  53976. z2: 10
  53977. });
  53978. var textRect = textEl.getBoundingRect();
  53979. var subText = titleModel.get('subtext');
  53980. var subTextEl = new ZRText({
  53981. style: createTextStyle(subtextStyleModel, {
  53982. text: subText,
  53983. fill: subtextStyleModel.getTextColor(),
  53984. y: textRect.height + titleModel.get('itemGap'),
  53985. verticalAlign: 'top'
  53986. }, {
  53987. disableBox: true
  53988. }),
  53989. z2: 10
  53990. });
  53991. var link = titleModel.get('link');
  53992. var sublink = titleModel.get('sublink');
  53993. var triggerEvent = titleModel.get('triggerEvent', true);
  53994. textEl.silent = !link && !triggerEvent;
  53995. subTextEl.silent = !sublink && !triggerEvent;
  53996. if (link) {
  53997. textEl.on('click', function () {
  53998. windowOpen(link, '_' + titleModel.get('target'));
  53999. });
  54000. }
  54001. if (sublink) {
  54002. subTextEl.on('click', function () {
  54003. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  54004. });
  54005. }
  54006. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  54007. componentType: 'title',
  54008. componentIndex: titleModel.componentIndex
  54009. } : null;
  54010. group.add(textEl);
  54011. subText && group.add(subTextEl);
  54012. // If no subText, but add subTextEl, there will be an empty line.
  54013. var groupRect = group.getBoundingRect();
  54014. var layoutOption = titleModel.getBoxLayoutParams();
  54015. layoutOption.width = groupRect.width;
  54016. layoutOption.height = groupRect.height;
  54017. var layoutRef = createBoxLayoutReference(titleModel, api);
  54018. var layoutRect = getLayoutRect(layoutOption, layoutRef.refContainer, titleModel.get('padding'));
  54019. // Adjust text align based on position
  54020. if (!textAlign) {
  54021. // Align left if title is on the left. center and right is same
  54022. textAlign = titleModel.get('left') || titleModel.get('right');
  54023. // @ts-ignore
  54024. if (textAlign === 'middle') {
  54025. textAlign = 'center';
  54026. }
  54027. // Adjust layout by text align
  54028. if (textAlign === 'right') {
  54029. layoutRect.x += layoutRect.width;
  54030. } else if (textAlign === 'center') {
  54031. layoutRect.x += layoutRect.width / 2;
  54032. }
  54033. }
  54034. if (!textVerticalAlign) {
  54035. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  54036. // @ts-ignore
  54037. if (textVerticalAlign === 'center') {
  54038. textVerticalAlign = 'middle';
  54039. }
  54040. if (textVerticalAlign === 'bottom') {
  54041. layoutRect.y += layoutRect.height;
  54042. } else if (textVerticalAlign === 'middle') {
  54043. layoutRect.y += layoutRect.height / 2;
  54044. }
  54045. textVerticalAlign = textVerticalAlign || 'top';
  54046. }
  54047. group.x = layoutRect.x;
  54048. group.y = layoutRect.y;
  54049. group.markRedraw();
  54050. var alignStyle = {
  54051. align: textAlign,
  54052. verticalAlign: textVerticalAlign
  54053. };
  54054. textEl.setStyle(alignStyle);
  54055. subTextEl.setStyle(alignStyle);
  54056. // Render background
  54057. // Get groupRect again because textAlign has been changed
  54058. groupRect = group.getBoundingRect();
  54059. var padding = layoutRect.margin;
  54060. var style = titleModel.getItemStyle(['color', 'opacity']);
  54061. style.fill = titleModel.get('backgroundColor');
  54062. var rect = new Rect({
  54063. shape: {
  54064. x: groupRect.x - padding[3],
  54065. y: groupRect.y - padding[0],
  54066. width: groupRect.width + padding[1] + padding[3],
  54067. height: groupRect.height + padding[0] + padding[2],
  54068. r: titleModel.get('borderRadius')
  54069. },
  54070. style: style,
  54071. subPixelOptimize: true,
  54072. silent: true
  54073. });
  54074. group.add(rect);
  54075. };
  54076. TitleView.type = 'title';
  54077. return TitleView;
  54078. }(ComponentView);
  54079. function install$d(registers) {
  54080. registers.registerComponentModel(TitleModel);
  54081. registers.registerComponentView(TitleView);
  54082. }
  54083. function checkMarkerInSeries(seriesOpts, markerType) {
  54084. if (!seriesOpts) {
  54085. return false;
  54086. }
  54087. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  54088. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  54089. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  54090. return true;
  54091. }
  54092. }
  54093. return false;
  54094. }
  54095. function fillLabel(opt) {
  54096. defaultEmphasis(opt, 'label', ['show']);
  54097. }
  54098. // { [componentType]: MarkerModel }
  54099. var inner$c = makeInner();
  54100. var MarkerModel = /** @class */function (_super) {
  54101. __extends(MarkerModel, _super);
  54102. function MarkerModel() {
  54103. var _this = _super !== null && _super.apply(this, arguments) || this;
  54104. _this.type = MarkerModel.type;
  54105. /**
  54106. * If marker model is created by self from series
  54107. */
  54108. _this.createdBySelf = false;
  54109. _this.preventAutoZ = true;
  54110. return _this;
  54111. }
  54112. /**
  54113. * @overrite
  54114. */
  54115. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  54116. if ("development" !== 'production') {
  54117. if (this.type === 'marker') {
  54118. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  54119. }
  54120. }
  54121. this.mergeDefaultAndTheme(option, ecModel);
  54122. this._mergeOption(option, ecModel, false, true);
  54123. };
  54124. MarkerModel.prototype.isAnimationEnabled = function () {
  54125. if (env.node) {
  54126. return false;
  54127. }
  54128. var hostSeries = this.__hostSeries;
  54129. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  54130. };
  54131. /**
  54132. * @overrite
  54133. */
  54134. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  54135. this._mergeOption(newOpt, ecModel, false, false);
  54136. };
  54137. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  54138. var componentType = this.mainType;
  54139. if (!createdBySelf) {
  54140. ecModel.eachSeries(function (seriesModel) {
  54141. // mainType can be markPoint, markLine, markArea
  54142. var markerOpt = seriesModel.get(this.mainType, true);
  54143. var markerModel = inner$c(seriesModel)[componentType];
  54144. if (!markerOpt || !markerOpt.data) {
  54145. inner$c(seriesModel)[componentType] = null;
  54146. return;
  54147. }
  54148. if (!markerModel) {
  54149. if (isInit) {
  54150. // Default label emphasis `position` and `show`
  54151. fillLabel(markerOpt);
  54152. }
  54153. each(markerOpt.data, function (item) {
  54154. // FIXME Overwrite fillLabel method ?
  54155. if (item instanceof Array) {
  54156. fillLabel(item[0]);
  54157. fillLabel(item[1]);
  54158. } else {
  54159. fillLabel(item);
  54160. }
  54161. });
  54162. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel);
  54163. // markerModel = new ImplementedMarkerModel(
  54164. // markerOpt, this, ecModel
  54165. // );
  54166. extend(markerModel, {
  54167. mainType: this.mainType,
  54168. // Use the same series index and name
  54169. seriesIndex: seriesModel.seriesIndex,
  54170. name: seriesModel.name,
  54171. createdBySelf: true
  54172. });
  54173. markerModel.__hostSeries = seriesModel;
  54174. } else {
  54175. markerModel._mergeOption(markerOpt, ecModel, true);
  54176. }
  54177. inner$c(seriesModel)[componentType] = markerModel;
  54178. }, this);
  54179. }
  54180. };
  54181. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  54182. var data = this.getData();
  54183. var value = this.getRawValue(dataIndex);
  54184. var itemName = data.getName(dataIndex);
  54185. return createTooltipMarkup('section', {
  54186. header: this.name,
  54187. blocks: [createTooltipMarkup('nameValue', {
  54188. name: itemName,
  54189. value: value,
  54190. noName: !itemName,
  54191. noValue: value == null
  54192. })]
  54193. });
  54194. };
  54195. MarkerModel.prototype.getData = function () {
  54196. return this._data;
  54197. };
  54198. MarkerModel.prototype.setData = function (data) {
  54199. this._data = data;
  54200. };
  54201. MarkerModel.prototype.getDataParams = function (dataIndex, dataType) {
  54202. var params = DataFormatMixin.prototype.getDataParams.call(this, dataIndex, dataType);
  54203. var hostSeries = this.__hostSeries;
  54204. if (hostSeries) {
  54205. params.seriesId = hostSeries.id;
  54206. params.seriesName = hostSeries.name;
  54207. params.seriesType = hostSeries.subType;
  54208. }
  54209. return params;
  54210. };
  54211. MarkerModel.getMarkerModelFromSeries = function (seriesModel,
  54212. // Support three types of markers. Strict check.
  54213. componentType) {
  54214. return inner$c(seriesModel)[componentType];
  54215. };
  54216. MarkerModel.type = 'marker';
  54217. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  54218. return MarkerModel;
  54219. }(ComponentModel);
  54220. mixin(MarkerModel, DataFormatMixin.prototype);
  54221. var MarkPointModel = /** @class */function (_super) {
  54222. __extends(MarkPointModel, _super);
  54223. function MarkPointModel() {
  54224. var _this = _super !== null && _super.apply(this, arguments) || this;
  54225. _this.type = MarkPointModel.type;
  54226. return _this;
  54227. }
  54228. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  54229. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  54230. };
  54231. MarkPointModel.type = 'markPoint';
  54232. MarkPointModel.defaultOption = {
  54233. // zlevel: 0,
  54234. z: 5,
  54235. symbol: 'pin',
  54236. symbolSize: 50,
  54237. // symbolRotate: 0,
  54238. // symbolOffset: [0, 0]
  54239. tooltip: {
  54240. trigger: 'item'
  54241. },
  54242. label: {
  54243. show: true,
  54244. position: 'inside'
  54245. },
  54246. itemStyle: {
  54247. borderWidth: 2
  54248. },
  54249. emphasis: {
  54250. label: {
  54251. show: true
  54252. }
  54253. }
  54254. };
  54255. return MarkPointModel;
  54256. }(MarkerModel);
  54257. function hasXOrY(item) {
  54258. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  54259. }
  54260. function hasXAndY(item) {
  54261. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  54262. }
  54263. function markerTypeCalculatorWithExtent(markerType, data, axisDim, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  54264. var coordArr = [];
  54265. var stacked = isDimensionStacked(data, targetDataDim /* , otherDataDim */);
  54266. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  54267. var value = numCalculate(data, calcDataDim, markerType);
  54268. var seriesModel = data.hostModel;
  54269. var dataIndex = seriesModel.indicesOfNearest(axisDim, calcDataDim, value)[0];
  54270. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  54271. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  54272. var coordArrValue = data.get(targetDataDim, dataIndex);
  54273. // Make it simple, do not visit all stacked value to count precision.
  54274. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  54275. precision = Math.min(precision, 20);
  54276. if (precision >= 0) {
  54277. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  54278. }
  54279. return [coordArr, coordArrValue];
  54280. }
  54281. // TODO Specified percent
  54282. var markerTypeCalculator = {
  54283. min: curry(markerTypeCalculatorWithExtent, 'min'),
  54284. max: curry(markerTypeCalculatorWithExtent, 'max'),
  54285. average: curry(markerTypeCalculatorWithExtent, 'average'),
  54286. median: curry(markerTypeCalculatorWithExtent, 'median')
  54287. };
  54288. /**
  54289. * Transform markPoint data item to format used in List by do the following
  54290. * 1. Calculate statistic like `max`, `min`, `average`
  54291. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  54292. */
  54293. function dataTransform(seriesModel, item) {
  54294. if (!item) {
  54295. return;
  54296. }
  54297. var data = seriesModel.getData();
  54298. var coordSys = seriesModel.coordinateSystem;
  54299. var dims = coordSys && coordSys.dimensions;
  54300. // 1. If not specify the position with pixel directly
  54301. // 2. If `coord` is not a data array. Which uses `xAxis`,
  54302. // `yAxis` to specify the coord on each dimension
  54303. // parseFloat first because item.x and item.y can be percent string like '20%'
  54304. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  54305. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  54306. // Clone the option
  54307. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  54308. item = clone(item);
  54309. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  54310. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  54311. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  54312. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.valueAxis.dim, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  54313. item.coord = coordInfo[0];
  54314. // Force to use the value of calculated value.
  54315. // let item use the value without stack.
  54316. item.value = coordInfo[1];
  54317. } else {
  54318. // FIXME Only has one of xAxis and yAxis.
  54319. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  54320. }
  54321. }
  54322. // x y is provided
  54323. if (item.coord == null || !isArray(dims)) {
  54324. item.coord = [];
  54325. var baseAxis = seriesModel.getBaseAxis();
  54326. if (baseAxis && item.type && markerTypeCalculator[item.type]) {
  54327. var otherAxis = coordSys.getOtherAxis(baseAxis);
  54328. if (otherAxis) {
  54329. item.value = numCalculate(data, data.mapDimension(otherAxis.dim), item.type);
  54330. }
  54331. }
  54332. } else {
  54333. // Each coord support max, min, average
  54334. var coord = item.coord;
  54335. for (var i = 0; i < 2; i++) {
  54336. if (markerTypeCalculator[coord[i]]) {
  54337. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  54338. }
  54339. }
  54340. }
  54341. return item;
  54342. }
  54343. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  54344. var ret = {};
  54345. if (item.valueIndex != null || item.valueDim != null) {
  54346. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  54347. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  54348. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  54349. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  54350. } else {
  54351. ret.baseAxis = seriesModel.getBaseAxis();
  54352. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  54353. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  54354. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  54355. }
  54356. return ret;
  54357. }
  54358. function dataDimToCoordDim(seriesModel, dataDim) {
  54359. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  54360. return dimItem && dimItem.coordDim;
  54361. }
  54362. /**
  54363. * Filter data which is out of coordinateSystem range
  54364. * [dataFilter description]
  54365. */
  54366. function dataFilter$1(
  54367. // Currently only polar and cartesian has containData.
  54368. coordSys, item) {
  54369. // Always return true if there is no coordSys
  54370. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  54371. }
  54372. function zoneFilter(
  54373. // Currently only polar and cartesian has containData.
  54374. coordSys, item1, item2) {
  54375. // Always return true if there is no coordSys
  54376. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  54377. }
  54378. function createMarkerDimValueGetter(inCoordSys, dims) {
  54379. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  54380. var rawVal = dimIndex < 2
  54381. // x, y, radius, angle
  54382. ? item.coord && item.coord[dimIndex] : item.value;
  54383. return parseDataValue(rawVal, dims[dimIndex]);
  54384. } : function (item, dimName, dataIndex, dimIndex) {
  54385. return parseDataValue(item.value, dims[dimIndex]);
  54386. };
  54387. }
  54388. function numCalculate(data, valueDataDim, type) {
  54389. if (type === 'average') {
  54390. var sum_1 = 0;
  54391. var count_1 = 0;
  54392. data.each(valueDataDim, function (val, idx) {
  54393. if (!isNaN(val)) {
  54394. sum_1 += val;
  54395. count_1++;
  54396. }
  54397. });
  54398. return sum_1 / count_1;
  54399. } else if (type === 'median') {
  54400. return data.getMedian(valueDataDim);
  54401. } else {
  54402. // max & min
  54403. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  54404. }
  54405. }
  54406. var inner$d = makeInner();
  54407. var MarkerView = /** @class */function (_super) {
  54408. __extends(MarkerView, _super);
  54409. function MarkerView() {
  54410. var _this = _super !== null && _super.apply(this, arguments) || this;
  54411. _this.type = MarkerView.type;
  54412. return _this;
  54413. }
  54414. MarkerView.prototype.init = function () {
  54415. this.markerGroupMap = createHashMap();
  54416. };
  54417. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  54418. var _this = this;
  54419. var markerGroupMap = this.markerGroupMap;
  54420. markerGroupMap.each(function (item) {
  54421. inner$d(item).keep = false;
  54422. });
  54423. ecModel.eachSeries(function (seriesModel) {
  54424. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  54425. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  54426. });
  54427. markerGroupMap.each(function (item) {
  54428. !inner$d(item).keep && _this.group.remove(item.group);
  54429. });
  54430. updateZ$1(ecModel, markerGroupMap, this.type);
  54431. };
  54432. MarkerView.prototype.markKeep = function (drawGroup) {
  54433. inner$d(drawGroup).keep = true;
  54434. };
  54435. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  54436. var _this = this;
  54437. each(seriesModelList, function (seriesModel) {
  54438. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  54439. if (markerModel) {
  54440. var data = markerModel.getData();
  54441. data.eachItemGraphicEl(function (el) {
  54442. if (el) {
  54443. isBlur ? enterBlur(el) : leaveBlur(el);
  54444. }
  54445. });
  54446. }
  54447. });
  54448. };
  54449. MarkerView.type = 'marker';
  54450. return MarkerView;
  54451. }(ComponentView);
  54452. function updateZ$1(ecModel, markerGroupMap, type) {
  54453. ecModel.eachSeries(function (seriesModel) {
  54454. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, type);
  54455. var markerDraw = markerGroupMap.get(seriesModel.id);
  54456. if (markerModel && markerDraw && markerDraw.group) {
  54457. var _a = retrieveZInfo(markerModel),
  54458. z = _a.z,
  54459. zlevel = _a.zlevel;
  54460. traverseUpdateZ(markerDraw.group, z, zlevel);
  54461. }
  54462. });
  54463. }
  54464. function updateMarkerLayout(mpData, seriesModel, api) {
  54465. var coordSys = seriesModel.coordinateSystem;
  54466. var apiWidth = api.getWidth();
  54467. var apiHeight = api.getHeight();
  54468. var coordRect = coordSys && coordSys.getArea && coordSys.getArea();
  54469. mpData.each(function (idx) {
  54470. var itemModel = mpData.getItemModel(idx);
  54471. var isRelativeToCoordinate = itemModel.get('relativeTo') === 'coordinate';
  54472. var width = isRelativeToCoordinate ? coordRect ? coordRect.width : 0 : apiWidth;
  54473. var height = isRelativeToCoordinate ? coordRect ? coordRect.height : 0 : apiHeight;
  54474. var left = isRelativeToCoordinate && coordRect ? coordRect.x : 0;
  54475. var top = isRelativeToCoordinate && coordRect ? coordRect.y : 0;
  54476. var point;
  54477. var xPx = parsePercent$1(itemModel.get('x'), width) + left;
  54478. var yPx = parsePercent$1(itemModel.get('y'), height) + top;
  54479. if (!isNaN(xPx) && !isNaN(yPx)) {
  54480. point = [xPx, yPx];
  54481. }
  54482. // Chart like bar may have there own marker positioning logic
  54483. else if (seriesModel.getMarkerPosition) {
  54484. // Use the getMarkerPosition
  54485. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  54486. } else if (coordSys) {
  54487. var x = mpData.get(coordSys.dimensions[0], idx);
  54488. var y = mpData.get(coordSys.dimensions[1], idx);
  54489. point = coordSys.dataToPoint([x, y]);
  54490. }
  54491. // Use x, y if has any
  54492. if (!isNaN(xPx)) {
  54493. point[0] = xPx;
  54494. }
  54495. if (!isNaN(yPx)) {
  54496. point[1] = yPx;
  54497. }
  54498. mpData.setItemLayout(idx, point);
  54499. });
  54500. }
  54501. var MarkPointView = /** @class */function (_super) {
  54502. __extends(MarkPointView, _super);
  54503. function MarkPointView() {
  54504. var _this = _super !== null && _super.apply(this, arguments) || this;
  54505. _this.type = MarkPointView.type;
  54506. return _this;
  54507. }
  54508. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  54509. ecModel.eachSeries(function (seriesModel) {
  54510. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  54511. if (mpModel) {
  54512. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  54513. this.markerGroupMap.get(seriesModel.id).updateLayout();
  54514. }
  54515. }, this);
  54516. };
  54517. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  54518. var coordSys = seriesModel.coordinateSystem;
  54519. var seriesId = seriesModel.id;
  54520. var seriesData = seriesModel.getData();
  54521. var symbolDrawMap = this.markerGroupMap;
  54522. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  54523. var mpData = createData(coordSys, seriesModel, mpModel);
  54524. // FIXME
  54525. mpModel.setData(mpData);
  54526. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  54527. mpData.each(function (idx) {
  54528. var itemModel = mpData.getItemModel(idx);
  54529. var symbol = itemModel.getShallow('symbol');
  54530. var symbolSize = itemModel.getShallow('symbolSize');
  54531. var symbolRotate = itemModel.getShallow('symbolRotate');
  54532. var symbolOffset = itemModel.getShallow('symbolOffset');
  54533. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect');
  54534. // TODO: refactor needed: single data item should not support callback function
  54535. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  54536. var rawIdx = mpModel.getRawValue(idx);
  54537. var dataParams = mpModel.getDataParams(idx);
  54538. if (isFunction(symbol)) {
  54539. symbol = symbol(rawIdx, dataParams);
  54540. }
  54541. if (isFunction(symbolSize)) {
  54542. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  54543. symbolSize = symbolSize(rawIdx, dataParams);
  54544. }
  54545. if (isFunction(symbolRotate)) {
  54546. symbolRotate = symbolRotate(rawIdx, dataParams);
  54547. }
  54548. if (isFunction(symbolOffset)) {
  54549. symbolOffset = symbolOffset(rawIdx, dataParams);
  54550. }
  54551. }
  54552. var style = itemModel.getModel('itemStyle').getItemStyle();
  54553. var z2 = itemModel.get('z2');
  54554. var color = getVisualFromData(seriesData, 'color');
  54555. if (!style.fill) {
  54556. style.fill = color;
  54557. }
  54558. mpData.setItemVisual(idx, {
  54559. z2: retrieve2(z2, 0),
  54560. symbol: symbol,
  54561. symbolSize: symbolSize,
  54562. symbolRotate: symbolRotate,
  54563. symbolOffset: symbolOffset,
  54564. symbolKeepAspect: symbolKeepAspect,
  54565. style: style
  54566. });
  54567. });
  54568. // TODO Text are wrong
  54569. symbolDraw.updateData(mpData);
  54570. this.group.add(symbolDraw.group);
  54571. // Set host model for tooltip
  54572. // FIXME
  54573. mpData.eachItemGraphicEl(function (el) {
  54574. el.traverse(function (child) {
  54575. getECData(child).dataModel = mpModel;
  54576. });
  54577. });
  54578. this.markKeep(symbolDraw);
  54579. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  54580. };
  54581. MarkPointView.type = 'markPoint';
  54582. return MarkPointView;
  54583. }(MarkerView);
  54584. function createData(coordSys, seriesModel, mpModel) {
  54585. var coordDimsInfos;
  54586. if (coordSys) {
  54587. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  54588. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {};
  54589. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  54590. return extend(extend({}, info), {
  54591. name: coordDim,
  54592. // DON'T use ordinalMeta to parse and collect ordinal.
  54593. ordinalMeta: null
  54594. });
  54595. });
  54596. } else {
  54597. coordDimsInfos = [{
  54598. name: 'value',
  54599. type: 'float'
  54600. }];
  54601. }
  54602. var mpData = new SeriesData(coordDimsInfos, mpModel);
  54603. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  54604. if (coordSys) {
  54605. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  54606. }
  54607. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  54608. mpData.initData(dataOpt, null, dimValueGetter);
  54609. return mpData;
  54610. }
  54611. function install$e(registers) {
  54612. registers.registerComponentModel(MarkPointModel);
  54613. registers.registerComponentView(MarkPointView);
  54614. registers.registerPreprocessor(function (opt) {
  54615. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  54616. // Make sure markPoint component is enabled
  54617. opt.markPoint = opt.markPoint || {};
  54618. }
  54619. });
  54620. }
  54621. var MarkLineModel = /** @class */function (_super) {
  54622. __extends(MarkLineModel, _super);
  54623. function MarkLineModel() {
  54624. var _this = _super !== null && _super.apply(this, arguments) || this;
  54625. _this.type = MarkLineModel.type;
  54626. return _this;
  54627. }
  54628. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  54629. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  54630. };
  54631. MarkLineModel.type = 'markLine';
  54632. MarkLineModel.defaultOption = {
  54633. // zlevel: 0,
  54634. z: 5,
  54635. symbol: ['circle', 'arrow'],
  54636. symbolSize: [8, 16],
  54637. // symbolRotate: 0,
  54638. symbolOffset: 0,
  54639. precision: 2,
  54640. tooltip: {
  54641. trigger: 'item'
  54642. },
  54643. label: {
  54644. show: true,
  54645. position: 'end',
  54646. distance: 5
  54647. },
  54648. lineStyle: {
  54649. type: 'dashed'
  54650. },
  54651. emphasis: {
  54652. label: {
  54653. show: true
  54654. },
  54655. lineStyle: {
  54656. width: 3
  54657. }
  54658. },
  54659. animationEasing: 'linear'
  54660. };
  54661. return MarkLineModel;
  54662. }(MarkerModel);
  54663. var straightLineProto = Line.prototype;
  54664. var bezierCurveProto = BezierCurve.prototype;
  54665. var StraightLineShape = /** @class */function () {
  54666. function StraightLineShape() {
  54667. // Start point
  54668. this.x1 = 0;
  54669. this.y1 = 0;
  54670. // End point
  54671. this.x2 = 0;
  54672. this.y2 = 0;
  54673. this.percent = 1;
  54674. }
  54675. return StraightLineShape;
  54676. }();
  54677. var CurveShape = /** @class */function (_super) {
  54678. __extends(CurveShape, _super);
  54679. function CurveShape() {
  54680. return _super !== null && _super.apply(this, arguments) || this;
  54681. }
  54682. return CurveShape;
  54683. }(StraightLineShape);
  54684. function isStraightLine(shape) {
  54685. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  54686. }
  54687. var ECLinePath = /** @class */function (_super) {
  54688. __extends(ECLinePath, _super);
  54689. function ECLinePath(opts) {
  54690. var _this = _super.call(this, opts) || this;
  54691. _this.type = 'ec-line';
  54692. return _this;
  54693. }
  54694. ECLinePath.prototype.getDefaultStyle = function () {
  54695. return {
  54696. stroke: tokens.color.neutral99,
  54697. fill: null
  54698. };
  54699. };
  54700. ECLinePath.prototype.getDefaultShape = function () {
  54701. return new StraightLineShape();
  54702. };
  54703. ECLinePath.prototype.buildPath = function (ctx, shape) {
  54704. if (isStraightLine(shape)) {
  54705. straightLineProto.buildPath.call(this, ctx, shape);
  54706. } else {
  54707. bezierCurveProto.buildPath.call(this, ctx, shape);
  54708. }
  54709. };
  54710. ECLinePath.prototype.pointAt = function (t) {
  54711. if (isStraightLine(this.shape)) {
  54712. return straightLineProto.pointAt.call(this, t);
  54713. } else {
  54714. return bezierCurveProto.pointAt.call(this, t);
  54715. }
  54716. };
  54717. ECLinePath.prototype.tangentAt = function (t) {
  54718. var shape = this.shape;
  54719. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  54720. return normalize(p, p);
  54721. };
  54722. return ECLinePath;
  54723. }(Path);
  54724. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  54725. function makeSymbolTypeKey(symbolCategory) {
  54726. return '_' + symbolCategory + 'Type';
  54727. }
  54728. function makeSymbolTypeValue(name, lineData, idx) {
  54729. var symbolType = lineData.getItemVisual(idx, name);
  54730. if (!symbolType || symbolType === 'none') {
  54731. return symbolType;
  54732. }
  54733. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  54734. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  54735. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  54736. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  54737. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  54738. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  54739. return symbolType + symbolSizeArr + symbolOffsetArr + (symbolRotate || '') + (symbolKeepAspect || '');
  54740. }
  54741. /**
  54742. * @inner
  54743. */
  54744. function createSymbol$1(name, lineData, idx) {
  54745. var symbolType = lineData.getItemVisual(idx, name);
  54746. if (!symbolType || symbolType === 'none') {
  54747. return;
  54748. }
  54749. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  54750. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  54751. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  54752. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  54753. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  54754. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  54755. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  54756. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  54757. symbolPath.name = name;
  54758. return symbolPath;
  54759. }
  54760. function createLine(points) {
  54761. var line = new ECLinePath({
  54762. name: 'line',
  54763. subPixelOptimize: true
  54764. });
  54765. setLinePoints(line.shape, points);
  54766. return line;
  54767. }
  54768. function setLinePoints(targetShape, points) {
  54769. targetShape.x1 = points[0][0];
  54770. targetShape.y1 = points[0][1];
  54771. targetShape.x2 = points[1][0];
  54772. targetShape.y2 = points[1][1];
  54773. targetShape.percent = 1;
  54774. var cp1 = points[2];
  54775. if (cp1) {
  54776. targetShape.cpx1 = cp1[0];
  54777. targetShape.cpy1 = cp1[1];
  54778. } else {
  54779. targetShape.cpx1 = NaN;
  54780. targetShape.cpy1 = NaN;
  54781. }
  54782. }
  54783. var Line$1 = /** @class */function (_super) {
  54784. __extends(Line, _super);
  54785. function Line(lineData, idx, seriesScope) {
  54786. var _this = _super.call(this) || this;
  54787. _this._createLine(lineData, idx, seriesScope);
  54788. return _this;
  54789. }
  54790. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  54791. var seriesModel = lineData.hostModel;
  54792. var linePoints = lineData.getItemLayout(idx);
  54793. var z2 = lineData.getItemVisual(idx, 'z2');
  54794. var line = createLine(linePoints);
  54795. line.shape.percent = 0;
  54796. initProps(line, {
  54797. z2: retrieve2(z2, 0),
  54798. shape: {
  54799. percent: 1
  54800. }
  54801. }, seriesModel, idx);
  54802. this.add(line);
  54803. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  54804. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  54805. // symbols must added after line to make sure
  54806. // it will be updated after line#update.
  54807. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  54808. this.add(symbol);
  54809. this[makeSymbolTypeKey(symbolCategory)] = makeSymbolTypeValue(symbolCategory, lineData, idx);
  54810. }, this);
  54811. this._updateCommonStl(lineData, idx, seriesScope);
  54812. };
  54813. // TODO More strict on the List type in parameters?
  54814. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  54815. var seriesModel = lineData.hostModel;
  54816. var line = this.childOfName('line');
  54817. var linePoints = lineData.getItemLayout(idx);
  54818. var target = {
  54819. shape: {}
  54820. };
  54821. setLinePoints(target.shape, linePoints);
  54822. updateProps(line, target, seriesModel, idx);
  54823. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  54824. var symbolType = makeSymbolTypeValue(symbolCategory, lineData, idx);
  54825. var key = makeSymbolTypeKey(symbolCategory);
  54826. // Symbol changed
  54827. if (this[key] !== symbolType) {
  54828. this.remove(this.childOfName(symbolCategory));
  54829. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  54830. this.add(symbol);
  54831. }
  54832. this[key] = symbolType;
  54833. }, this);
  54834. this._updateCommonStl(lineData, idx, seriesScope);
  54835. };
  54836. Line.prototype.getLinePath = function () {
  54837. return this.childAt(0);
  54838. };
  54839. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  54840. var seriesModel = lineData.hostModel;
  54841. var line = this.childOfName('line');
  54842. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  54843. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  54844. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  54845. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  54846. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  54847. var focus = seriesScope && seriesScope.focus;
  54848. var blurScope = seriesScope && seriesScope.blurScope;
  54849. // Optimization for large dataset
  54850. if (!seriesScope || lineData.hasItemOption) {
  54851. var itemModel = lineData.getItemModel(idx);
  54852. var emphasisModel = itemModel.getModel('emphasis');
  54853. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  54854. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  54855. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  54856. emphasisDisabled = emphasisModel.get('disabled');
  54857. focus = emphasisModel.get('focus');
  54858. blurScope = emphasisModel.get('blurScope');
  54859. labelStatesModels = getLabelStatesModels(itemModel);
  54860. }
  54861. var lineStyle = lineData.getItemVisual(idx, 'style');
  54862. var visualColor = lineStyle.stroke;
  54863. line.useStyle(lineStyle);
  54864. line.style.fill = null;
  54865. line.style.strokeNoScale = true;
  54866. line.ensureState('emphasis').style = emphasisLineStyle;
  54867. line.ensureState('blur').style = blurLineStyle;
  54868. line.ensureState('select').style = selectLineStyle;
  54869. // Update symbol
  54870. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  54871. var symbol = this.childOfName(symbolCategory);
  54872. if (symbol) {
  54873. // Share opacity and color with line.
  54874. symbol.setColor(visualColor);
  54875. symbol.style.opacity = lineStyle.opacity;
  54876. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  54877. var stateName = SPECIAL_STATES[i];
  54878. var lineState = line.getState(stateName);
  54879. if (lineState) {
  54880. var lineStateStyle = lineState.style || {};
  54881. var state = symbol.ensureState(stateName);
  54882. var stateStyle = state.style || (state.style = {});
  54883. if (lineStateStyle.stroke != null) {
  54884. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  54885. }
  54886. if (lineStateStyle.opacity != null) {
  54887. stateStyle.opacity = lineStateStyle.opacity;
  54888. }
  54889. }
  54890. }
  54891. symbol.markRedraw();
  54892. }
  54893. }, this);
  54894. var rawVal = seriesModel.getRawValue(idx);
  54895. setLabelStyle(this, labelStatesModels, {
  54896. labelDataIndex: idx,
  54897. labelFetcher: {
  54898. getFormattedLabel: function (dataIndex, stateName) {
  54899. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  54900. }
  54901. },
  54902. inheritColor: visualColor || tokens.color.neutral99,
  54903. defaultOpacity: lineStyle.opacity,
  54904. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  54905. });
  54906. var label = this.getTextContent();
  54907. // Always set `textStyle` even if `normalStyle.text` is null, because default
  54908. // values have to be set on `normalStyle`.
  54909. if (label) {
  54910. var labelNormalModel = labelStatesModels.normal;
  54911. label.__align = label.style.align;
  54912. label.__verticalAlign = label.style.verticalAlign;
  54913. // 'start', 'middle', 'end'
  54914. label.__position = labelNormalModel.get('position') || 'middle';
  54915. var distance = labelNormalModel.get('distance');
  54916. if (!isArray(distance)) {
  54917. distance = [distance, distance];
  54918. }
  54919. label.__labelDistance = distance;
  54920. }
  54921. this.setTextConfig({
  54922. position: null,
  54923. local: true,
  54924. inside: false // Can't be inside for stroke element.
  54925. });
  54926. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  54927. };
  54928. Line.prototype.highlight = function () {
  54929. enterEmphasis(this);
  54930. };
  54931. Line.prototype.downplay = function () {
  54932. leaveEmphasis(this);
  54933. };
  54934. Line.prototype.updateLayout = function (lineData, idx) {
  54935. this.setLinePoints(lineData.getItemLayout(idx));
  54936. };
  54937. Line.prototype.setLinePoints = function (points) {
  54938. var linePath = this.childOfName('line');
  54939. setLinePoints(linePath.shape, points);
  54940. linePath.dirty();
  54941. };
  54942. Line.prototype.beforeUpdate = function () {
  54943. var lineGroup = this;
  54944. var symbolFrom = lineGroup.childOfName('fromSymbol');
  54945. var symbolTo = lineGroup.childOfName('toSymbol');
  54946. var label = lineGroup.getTextContent();
  54947. // Quick reject
  54948. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  54949. return;
  54950. }
  54951. var invScale = 1;
  54952. var parentNode = this.parent;
  54953. while (parentNode) {
  54954. if (parentNode.scaleX) {
  54955. invScale /= parentNode.scaleX;
  54956. }
  54957. parentNode = parentNode.parent;
  54958. }
  54959. var line = lineGroup.childOfName('line');
  54960. // If line not changed
  54961. // FIXME Parent scale changed
  54962. if (!this.__dirty && !line.__dirty) {
  54963. return;
  54964. }
  54965. var percent = line.shape.percent;
  54966. var fromPos = line.pointAt(0);
  54967. var toPos = line.pointAt(percent);
  54968. var d = sub([], toPos, fromPos);
  54969. normalize(d, d);
  54970. function setSymbolRotation(symbol, percent) {
  54971. // Fix #12388
  54972. // when symbol is set to be 'arrow' in markLine,
  54973. // symbolRotate value will be ignored, and compulsively use tangent angle.
  54974. // rotate by default if symbol rotation is not specified
  54975. var specifiedRotation = symbol.__specifiedRotation;
  54976. if (specifiedRotation == null) {
  54977. var tangent = line.tangentAt(percent);
  54978. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  54979. } else {
  54980. symbol.attr('rotation', specifiedRotation);
  54981. }
  54982. }
  54983. if (symbolFrom) {
  54984. symbolFrom.setPosition(fromPos);
  54985. setSymbolRotation(symbolFrom, 0);
  54986. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  54987. symbolFrom.markRedraw();
  54988. }
  54989. if (symbolTo) {
  54990. symbolTo.setPosition(toPos);
  54991. setSymbolRotation(symbolTo, 1);
  54992. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  54993. symbolTo.markRedraw();
  54994. }
  54995. if (label && !label.ignore) {
  54996. label.x = label.y = 0;
  54997. label.originX = label.originY = 0;
  54998. var textAlign = void 0;
  54999. var textVerticalAlign = void 0;
  55000. var distance = label.__labelDistance;
  55001. var distanceX = distance[0] * invScale;
  55002. var distanceY = distance[1] * invScale;
  55003. var halfPercent = percent / 2;
  55004. var tangent = line.tangentAt(halfPercent);
  55005. var n = [tangent[1], -tangent[0]];
  55006. var cp = line.pointAt(halfPercent);
  55007. if (n[1] > 0) {
  55008. n[0] = -n[0];
  55009. n[1] = -n[1];
  55010. }
  55011. var dir = tangent[0] < 0 ? -1 : 1;
  55012. if (label.__position !== 'start' && label.__position !== 'end') {
  55013. var rotation = -Math.atan2(tangent[1], tangent[0]);
  55014. if (toPos[0] < fromPos[0]) {
  55015. rotation = Math.PI + rotation;
  55016. }
  55017. label.rotation = rotation;
  55018. }
  55019. var dy = void 0;
  55020. switch (label.__position) {
  55021. case 'insideStartTop':
  55022. case 'insideMiddleTop':
  55023. case 'insideEndTop':
  55024. case 'middle':
  55025. dy = -distanceY;
  55026. textVerticalAlign = 'bottom';
  55027. break;
  55028. case 'insideStartBottom':
  55029. case 'insideMiddleBottom':
  55030. case 'insideEndBottom':
  55031. dy = distanceY;
  55032. textVerticalAlign = 'top';
  55033. break;
  55034. default:
  55035. dy = 0;
  55036. textVerticalAlign = 'middle';
  55037. }
  55038. switch (label.__position) {
  55039. case 'end':
  55040. label.x = d[0] * distanceX + toPos[0];
  55041. label.y = d[1] * distanceY + toPos[1];
  55042. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  55043. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  55044. break;
  55045. case 'start':
  55046. label.x = -d[0] * distanceX + fromPos[0];
  55047. label.y = -d[1] * distanceY + fromPos[1];
  55048. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  55049. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  55050. break;
  55051. case 'insideStartTop':
  55052. case 'insideStart':
  55053. case 'insideStartBottom':
  55054. label.x = distanceX * dir + fromPos[0];
  55055. label.y = fromPos[1] + dy;
  55056. textAlign = tangent[0] < 0 ? 'right' : 'left';
  55057. label.originX = -distanceX * dir;
  55058. label.originY = -dy;
  55059. break;
  55060. case 'insideMiddleTop':
  55061. case 'insideMiddle':
  55062. case 'insideMiddleBottom':
  55063. case 'middle':
  55064. label.x = cp[0];
  55065. label.y = cp[1] + dy;
  55066. textAlign = 'center';
  55067. label.originY = -dy;
  55068. break;
  55069. case 'insideEndTop':
  55070. case 'insideEnd':
  55071. case 'insideEndBottom':
  55072. label.x = -distanceX * dir + toPos[0];
  55073. label.y = toPos[1] + dy;
  55074. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  55075. label.originX = distanceX * dir;
  55076. label.originY = -dy;
  55077. break;
  55078. }
  55079. label.scaleX = label.scaleY = invScale;
  55080. label.setStyle({
  55081. // Use the user specified text align and baseline first
  55082. verticalAlign: label.__verticalAlign || textVerticalAlign,
  55083. align: label.__align || textAlign
  55084. });
  55085. }
  55086. };
  55087. return Line;
  55088. }(Group);
  55089. var LineDraw = /** @class */function () {
  55090. function LineDraw(LineCtor) {
  55091. this.group = new Group();
  55092. this._LineCtor = LineCtor || Line$1;
  55093. }
  55094. LineDraw.prototype.updateData = function (lineData) {
  55095. var _this = this;
  55096. // Remove progressive els.
  55097. this._progressiveEls = null;
  55098. var lineDraw = this;
  55099. var group = lineDraw.group;
  55100. var oldLineData = lineDraw._lineData;
  55101. lineDraw._lineData = lineData;
  55102. // There is no oldLineData only when first rendering or switching from
  55103. // stream mode to normal mode, where previous elements should be removed.
  55104. if (!oldLineData) {
  55105. group.removeAll();
  55106. }
  55107. var seriesScope = makeSeriesScope$1(lineData);
  55108. lineData.diff(oldLineData).add(function (idx) {
  55109. _this._doAdd(lineData, idx, seriesScope);
  55110. }).update(function (newIdx, oldIdx) {
  55111. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  55112. }).remove(function (idx) {
  55113. group.remove(oldLineData.getItemGraphicEl(idx));
  55114. }).execute();
  55115. };
  55116. LineDraw.prototype.updateLayout = function () {
  55117. var lineData = this._lineData;
  55118. // Do not support update layout in incremental mode.
  55119. if (!lineData) {
  55120. return;
  55121. }
  55122. lineData.eachItemGraphicEl(function (el, idx) {
  55123. el.updateLayout(lineData, idx);
  55124. }, this);
  55125. };
  55126. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  55127. this._seriesScope = makeSeriesScope$1(lineData);
  55128. this._lineData = null;
  55129. this.group.removeAll();
  55130. };
  55131. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  55132. this._progressiveEls = [];
  55133. function updateIncrementalAndHover(el) {
  55134. if (!el.isGroup && !isEffectObject(el)) {
  55135. el.incremental = true;
  55136. el.ensureState('emphasis').hoverLayer = true;
  55137. }
  55138. }
  55139. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  55140. var itemLayout = lineData.getItemLayout(idx);
  55141. if (lineNeedsDraw(itemLayout)) {
  55142. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  55143. el.traverse(updateIncrementalAndHover);
  55144. this.group.add(el);
  55145. lineData.setItemGraphicEl(idx, el);
  55146. this._progressiveEls.push(el);
  55147. }
  55148. }
  55149. };
  55150. LineDraw.prototype.remove = function () {
  55151. this.group.removeAll();
  55152. };
  55153. LineDraw.prototype.eachRendered = function (cb) {
  55154. traverseElements(this._progressiveEls || this.group, cb);
  55155. };
  55156. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  55157. var itemLayout = lineData.getItemLayout(idx);
  55158. if (!lineNeedsDraw(itemLayout)) {
  55159. return;
  55160. }
  55161. var el = new this._LineCtor(lineData, idx, seriesScope);
  55162. lineData.setItemGraphicEl(idx, el);
  55163. this.group.add(el);
  55164. };
  55165. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  55166. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  55167. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  55168. this.group.remove(itemEl);
  55169. return;
  55170. }
  55171. if (!itemEl) {
  55172. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  55173. } else {
  55174. itemEl.updateData(newLineData, newIdx, seriesScope);
  55175. }
  55176. newLineData.setItemGraphicEl(newIdx, itemEl);
  55177. this.group.add(itemEl);
  55178. };
  55179. return LineDraw;
  55180. }();
  55181. function isEffectObject(el) {
  55182. return el.animators && el.animators.length > 0;
  55183. }
  55184. function makeSeriesScope$1(lineData) {
  55185. var hostModel = lineData.hostModel;
  55186. var emphasisModel = hostModel.getModel('emphasis');
  55187. return {
  55188. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  55189. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  55190. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  55191. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  55192. emphasisDisabled: emphasisModel.get('disabled'),
  55193. blurScope: emphasisModel.get('blurScope'),
  55194. focus: emphasisModel.get('focus'),
  55195. labelStatesModels: getLabelStatesModels(hostModel)
  55196. };
  55197. }
  55198. function isPointNaN(pt) {
  55199. return isNaN(pt[0]) || isNaN(pt[1]);
  55200. }
  55201. function lineNeedsDraw(pts) {
  55202. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  55203. }
  55204. var inner$e = makeInner();
  55205. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  55206. var data = seriesModel.getData();
  55207. var itemArray;
  55208. if (!isArray(item)) {
  55209. // Special type markLine like 'min', 'max', 'average', 'median'
  55210. var mlType = item.type;
  55211. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  55212. // In case
  55213. // data: [{
  55214. // yAxis: 10
  55215. // }]
  55216. || item.xAxis != null || item.yAxis != null) {
  55217. var valueAxis = void 0;
  55218. var value = void 0;
  55219. if (item.yAxis != null || item.xAxis != null) {
  55220. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  55221. value = retrieve(item.yAxis, item.xAxis);
  55222. } else {
  55223. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  55224. valueAxis = axisInfo.valueAxis;
  55225. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  55226. value = numCalculate(data, valueDataDim, mlType);
  55227. }
  55228. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  55229. var baseIndex = 1 - valueIndex;
  55230. // Normized to 2d data with start and end point
  55231. var mlFrom = clone(item);
  55232. var mlTo = {
  55233. coord: []
  55234. };
  55235. mlFrom.type = null;
  55236. mlFrom.coord = [];
  55237. mlFrom.coord[baseIndex] = -Infinity;
  55238. mlTo.coord[baseIndex] = Infinity;
  55239. var precision = mlModel.get('precision');
  55240. if (precision >= 0 && isNumber(value)) {
  55241. value = +value.toFixed(Math.min(precision, 20));
  55242. }
  55243. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  55244. itemArray = [mlFrom, mlTo, {
  55245. type: mlType,
  55246. valueIndex: item.valueIndex,
  55247. // Force to use the value of calculated value.
  55248. value: value
  55249. }];
  55250. } else {
  55251. // Invalid data
  55252. if ("development" !== 'production') {
  55253. logError('Invalid markLine data.');
  55254. }
  55255. itemArray = [];
  55256. }
  55257. } else {
  55258. itemArray = item;
  55259. }
  55260. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])];
  55261. // Avoid line data type is extended by from(to) data type
  55262. normalizedItem[2].type = normalizedItem[2].type || null;
  55263. // Merge from option and to option into line option
  55264. merge(normalizedItem[2], normalizedItem[0]);
  55265. merge(normalizedItem[2], normalizedItem[1]);
  55266. return normalizedItem;
  55267. };
  55268. function isInfinity(val) {
  55269. return !isNaN(val) && !isFinite(val);
  55270. }
  55271. // If a markLine has one dim
  55272. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  55273. var otherDimIndex = 1 - dimIndex;
  55274. var dimName = coordSys.dimensions[dimIndex];
  55275. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  55276. }
  55277. function markLineFilter(coordSys, item) {
  55278. if (coordSys.type === 'cartesian2d') {
  55279. var fromCoord = item[0].coord;
  55280. var toCoord = item[1].coord;
  55281. // In case
  55282. // {
  55283. // markLine: {
  55284. // data: [{ yAxis: 2 }]
  55285. // }
  55286. // }
  55287. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  55288. return true;
  55289. }
  55290. }
  55291. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  55292. }
  55293. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  55294. var coordSys = seriesModel.coordinateSystem;
  55295. var itemModel = data.getItemModel(idx);
  55296. var point;
  55297. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  55298. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  55299. if (!isNaN(xPx) && !isNaN(yPx)) {
  55300. point = [xPx, yPx];
  55301. } else {
  55302. // Chart like bar may have there own marker positioning logic
  55303. if (seriesModel.getMarkerPosition) {
  55304. // Use the getMarkerPosition
  55305. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  55306. } else {
  55307. var dims = coordSys.dimensions;
  55308. var x = data.get(dims[0], idx);
  55309. var y = data.get(dims[1], idx);
  55310. point = coordSys.dataToPoint([x, y]);
  55311. }
  55312. // Expand line to the edge of grid if value on one axis is Inifnity
  55313. // In case
  55314. // markLine: {
  55315. // data: [{
  55316. // yAxis: 2
  55317. // // or
  55318. // type: 'average'
  55319. // }]
  55320. // }
  55321. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  55322. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  55323. var xAxis = coordSys.getAxis('x');
  55324. var yAxis = coordSys.getAxis('y');
  55325. var dims = coordSys.dimensions;
  55326. if (isInfinity(data.get(dims[0], idx))) {
  55327. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  55328. } else if (isInfinity(data.get(dims[1], idx))) {
  55329. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  55330. }
  55331. }
  55332. // Use x, y if has any
  55333. if (!isNaN(xPx)) {
  55334. point[0] = xPx;
  55335. }
  55336. if (!isNaN(yPx)) {
  55337. point[1] = yPx;
  55338. }
  55339. }
  55340. data.setItemLayout(idx, point);
  55341. }
  55342. var MarkLineView = /** @class */function (_super) {
  55343. __extends(MarkLineView, _super);
  55344. function MarkLineView() {
  55345. var _this = _super !== null && _super.apply(this, arguments) || this;
  55346. _this.type = MarkLineView.type;
  55347. return _this;
  55348. }
  55349. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  55350. ecModel.eachSeries(function (seriesModel) {
  55351. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  55352. if (mlModel) {
  55353. var mlData_1 = mlModel.getData();
  55354. var fromData_1 = inner$e(mlModel).from;
  55355. var toData_1 = inner$e(mlModel).to;
  55356. // Update visual and layout of from symbol and to symbol
  55357. fromData_1.each(function (idx) {
  55358. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  55359. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  55360. });
  55361. // Update layout of line
  55362. mlData_1.each(function (idx) {
  55363. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  55364. });
  55365. this.markerGroupMap.get(seriesModel.id).updateLayout();
  55366. }
  55367. }, this);
  55368. };
  55369. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  55370. var coordSys = seriesModel.coordinateSystem;
  55371. var seriesId = seriesModel.id;
  55372. var seriesData = seriesModel.getData();
  55373. var lineDrawMap = this.markerGroupMap;
  55374. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  55375. this.group.add(lineDraw.group);
  55376. var mlData = createList$1(coordSys, seriesModel, mlModel);
  55377. var fromData = mlData.from;
  55378. var toData = mlData.to;
  55379. var lineData = mlData.line;
  55380. inner$e(mlModel).from = fromData;
  55381. inner$e(mlModel).to = toData;
  55382. // Line data for tooltip and formatter
  55383. mlModel.setData(lineData);
  55384. // TODO
  55385. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  55386. // But the related logic and type definition are not finished yet.
  55387. // Finish it if required
  55388. var symbolType = mlModel.get('symbol');
  55389. var symbolSize = mlModel.get('symbolSize');
  55390. var symbolRotate = mlModel.get('symbolRotate');
  55391. var symbolOffset = mlModel.get('symbolOffset');
  55392. // TODO: support callback function like markPoint
  55393. if (!isArray(symbolType)) {
  55394. symbolType = [symbolType, symbolType];
  55395. }
  55396. if (!isArray(symbolSize)) {
  55397. symbolSize = [symbolSize, symbolSize];
  55398. }
  55399. if (!isArray(symbolRotate)) {
  55400. symbolRotate = [symbolRotate, symbolRotate];
  55401. }
  55402. if (!isArray(symbolOffset)) {
  55403. symbolOffset = [symbolOffset, symbolOffset];
  55404. }
  55405. // Update visual and layout of from symbol and to symbol
  55406. mlData.from.each(function (idx) {
  55407. updateDataVisualAndLayout(fromData, idx, true);
  55408. updateDataVisualAndLayout(toData, idx, false);
  55409. });
  55410. // Update visual and layout of line
  55411. lineData.each(function (idx) {
  55412. var itemModel = lineData.getItemModel(idx);
  55413. var lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  55414. // lineData.setItemVisual(idx, {
  55415. // color: lineColor || fromData.getItemVisual(idx, 'color')
  55416. // });
  55417. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  55418. var z2 = itemModel.get('z2');
  55419. if (lineStyle.stroke == null) {
  55420. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  55421. }
  55422. lineData.setItemVisual(idx, {
  55423. z2: retrieve2(z2, 0),
  55424. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  55425. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  55426. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  55427. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  55428. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  55429. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  55430. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  55431. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  55432. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  55433. toSymbol: toData.getItemVisual(idx, 'symbol'),
  55434. style: lineStyle
  55435. });
  55436. });
  55437. lineDraw.updateData(lineData);
  55438. // Set host model for tooltip
  55439. // FIXME
  55440. mlData.line.eachItemGraphicEl(function (el) {
  55441. getECData(el).dataModel = mlModel;
  55442. el.traverse(function (child) {
  55443. getECData(child).dataModel = mlModel;
  55444. });
  55445. });
  55446. function updateDataVisualAndLayout(data, idx, isFrom) {
  55447. var itemModel = data.getItemModel(idx);
  55448. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  55449. var style = itemModel.getModel('itemStyle').getItemStyle();
  55450. if (style.fill == null) {
  55451. style.fill = getVisualFromData(seriesData, 'color');
  55452. }
  55453. data.setItemVisual(idx, {
  55454. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  55455. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  55456. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  55457. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  55458. // TODO: when 2d array is supported, it should ignore parent
  55459. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  55460. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  55461. style: style
  55462. });
  55463. }
  55464. this.markKeep(lineDraw);
  55465. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  55466. };
  55467. MarkLineView.type = 'markLine';
  55468. return MarkLineView;
  55469. }(MarkerView);
  55470. function createList$1(coordSys, seriesModel, mlModel) {
  55471. var coordDimsInfos;
  55472. if (coordSys) {
  55473. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  55474. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {};
  55475. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  55476. return extend(extend({}, info), {
  55477. name: coordDim,
  55478. // DON'T use ordinalMeta to parse and collect ordinal.
  55479. ordinalMeta: null
  55480. });
  55481. });
  55482. } else {
  55483. coordDimsInfos = [{
  55484. name: 'value',
  55485. type: 'float'
  55486. }];
  55487. }
  55488. var fromData = new SeriesData(coordDimsInfos, mlModel);
  55489. var toData = new SeriesData(coordDimsInfos, mlModel);
  55490. // No dimensions
  55491. var lineData = new SeriesData([], mlModel);
  55492. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  55493. if (coordSys) {
  55494. optData = filter(optData, curry(markLineFilter, coordSys));
  55495. }
  55496. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  55497. fromData.initData(map(optData, function (item) {
  55498. return item[0];
  55499. }), null, dimValueGetter);
  55500. toData.initData(map(optData, function (item) {
  55501. return item[1];
  55502. }), null, dimValueGetter);
  55503. lineData.initData(map(optData, function (item) {
  55504. return item[2];
  55505. }));
  55506. lineData.hasItemOption = true;
  55507. return {
  55508. from: fromData,
  55509. to: toData,
  55510. line: lineData
  55511. };
  55512. }
  55513. function install$f(registers) {
  55514. registers.registerComponentModel(MarkLineModel);
  55515. registers.registerComponentView(MarkLineView);
  55516. registers.registerPreprocessor(function (opt) {
  55517. if (checkMarkerInSeries(opt.series, 'markLine')) {
  55518. // Make sure markLine component is enabled
  55519. opt.markLine = opt.markLine || {};
  55520. }
  55521. });
  55522. }
  55523. var MarkAreaModel = /** @class */function (_super) {
  55524. __extends(MarkAreaModel, _super);
  55525. function MarkAreaModel() {
  55526. var _this = _super !== null && _super.apply(this, arguments) || this;
  55527. _this.type = MarkAreaModel.type;
  55528. return _this;
  55529. }
  55530. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  55531. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  55532. };
  55533. MarkAreaModel.type = 'markArea';
  55534. MarkAreaModel.defaultOption = {
  55535. // zlevel: 0,
  55536. // PENDING
  55537. z: 1,
  55538. tooltip: {
  55539. trigger: 'item'
  55540. },
  55541. // markArea should fixed on the coordinate system
  55542. animation: false,
  55543. label: {
  55544. show: true,
  55545. position: 'top'
  55546. },
  55547. itemStyle: {
  55548. // color and borderColor default to use color from series
  55549. // color: 'auto'
  55550. // borderColor: 'auto'
  55551. borderWidth: 0
  55552. },
  55553. emphasis: {
  55554. label: {
  55555. show: true,
  55556. position: 'top'
  55557. }
  55558. }
  55559. };
  55560. return MarkAreaModel;
  55561. }(MarkerModel);
  55562. var inner$f = makeInner();
  55563. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  55564. // item may be null
  55565. var item0 = item[0];
  55566. var item1 = item[1];
  55567. if (!item0 || !item1) {
  55568. return;
  55569. }
  55570. var lt = dataTransform(seriesModel, item0);
  55571. var rb = dataTransform(seriesModel, item1);
  55572. // FIXME make sure lt is less than rb
  55573. var ltCoord = lt.coord;
  55574. var rbCoord = rb.coord;
  55575. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  55576. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  55577. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  55578. rbCoord[1] = retrieve(rbCoord[1], Infinity);
  55579. // Merge option into one
  55580. var result = mergeAll([{}, lt, rb]);
  55581. result.coord = [lt.coord, rb.coord];
  55582. result.x0 = lt.x;
  55583. result.y0 = lt.y;
  55584. result.x1 = rb.x;
  55585. result.y1 = rb.y;
  55586. return result;
  55587. };
  55588. function isInfinity$1(val) {
  55589. return !isNaN(val) && !isFinite(val);
  55590. }
  55591. // If a markArea has one dim
  55592. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  55593. var otherDimIndex = 1 - dimIndex;
  55594. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  55595. }
  55596. function markAreaFilter(coordSys, item) {
  55597. var fromCoord = item.coord[0];
  55598. var toCoord = item.coord[1];
  55599. var item0 = {
  55600. coord: fromCoord,
  55601. x: item.x0,
  55602. y: item.y0
  55603. };
  55604. var item1 = {
  55605. coord: toCoord,
  55606. x: item.x1,
  55607. y: item.y1
  55608. };
  55609. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  55610. // In case
  55611. // {
  55612. // markArea: {
  55613. // data: [{ yAxis: 2 }]
  55614. // }
  55615. // }
  55616. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  55617. return true;
  55618. }
  55619. // Directly returning true may also do the work,
  55620. // because markArea will not be shown automatically
  55621. // when it's not included in coordinate system.
  55622. // But filtering ahead can avoid keeping rendering markArea
  55623. // when there are too many of them.
  55624. return zoneFilter(coordSys, item0, item1);
  55625. }
  55626. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  55627. }
  55628. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  55629. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  55630. var coordSys = seriesModel.coordinateSystem;
  55631. var itemModel = data.getItemModel(idx);
  55632. var point;
  55633. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  55634. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  55635. if (!isNaN(xPx) && !isNaN(yPx)) {
  55636. point = [xPx, yPx];
  55637. } else {
  55638. // Chart like bar may have there own marker positioning logic
  55639. if (seriesModel.getMarkerPosition) {
  55640. // Consider the case that user input the right-bottom point first
  55641. // Pick the larger x and y as 'x1' and 'y1'
  55642. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  55643. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  55644. var clampPointValue0 = coordSys.clampData(pointValue0);
  55645. var clampPointValue1 = coordSys.clampData(pointValue1);
  55646. var pointValue = [];
  55647. if (dims[0] === 'x0') {
  55648. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  55649. } else {
  55650. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  55651. }
  55652. if (dims[1] === 'y0') {
  55653. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  55654. } else {
  55655. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  55656. }
  55657. // Use the getMarkerPosition
  55658. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  55659. } else {
  55660. var x = data.get(dims[0], idx);
  55661. var y = data.get(dims[1], idx);
  55662. var pt = [x, y];
  55663. coordSys.clampData && coordSys.clampData(pt, pt);
  55664. point = coordSys.dataToPoint(pt, true);
  55665. }
  55666. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  55667. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  55668. var xAxis = coordSys.getAxis('x');
  55669. var yAxis = coordSys.getAxis('y');
  55670. var x = data.get(dims[0], idx);
  55671. var y = data.get(dims[1], idx);
  55672. if (isInfinity$1(x)) {
  55673. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  55674. } else if (isInfinity$1(y)) {
  55675. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  55676. }
  55677. }
  55678. // Use x, y if has any
  55679. if (!isNaN(xPx)) {
  55680. point[0] = xPx;
  55681. }
  55682. if (!isNaN(yPx)) {
  55683. point[1] = yPx;
  55684. }
  55685. }
  55686. return point;
  55687. }
  55688. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  55689. var MarkAreaView = /** @class */function (_super) {
  55690. __extends(MarkAreaView, _super);
  55691. function MarkAreaView() {
  55692. var _this = _super !== null && _super.apply(this, arguments) || this;
  55693. _this.type = MarkAreaView.type;
  55694. return _this;
  55695. }
  55696. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  55697. ecModel.eachSeries(function (seriesModel) {
  55698. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  55699. if (maModel) {
  55700. var areaData_1 = maModel.getData();
  55701. areaData_1.each(function (idx) {
  55702. var points = map(dimPermutations, function (dim) {
  55703. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  55704. });
  55705. // Layout
  55706. areaData_1.setItemLayout(idx, points);
  55707. var el = areaData_1.getItemGraphicEl(idx);
  55708. el.setShape('points', points);
  55709. });
  55710. }
  55711. }, this);
  55712. };
  55713. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  55714. var coordSys = seriesModel.coordinateSystem;
  55715. var seriesId = seriesModel.id;
  55716. var seriesData = seriesModel.getData();
  55717. var areaGroupMap = this.markerGroupMap;
  55718. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  55719. group: new Group()
  55720. });
  55721. this.group.add(polygonGroup.group);
  55722. this.markKeep(polygonGroup);
  55723. var areaData = createList$2(coordSys, seriesModel, maModel);
  55724. // Line data for tooltip and formatter
  55725. maModel.setData(areaData);
  55726. // Update visual and layout of line
  55727. areaData.each(function (idx) {
  55728. // Layout
  55729. var points = map(dimPermutations, function (dim) {
  55730. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  55731. });
  55732. var xAxisScale = coordSys.getAxis('x').scale;
  55733. var yAxisScale = coordSys.getAxis('y').scale;
  55734. var xAxisExtent = xAxisScale.getExtent();
  55735. var yAxisExtent = yAxisScale.getExtent();
  55736. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  55737. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  55738. asc(xPointExtent);
  55739. asc(yPointExtent);
  55740. var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]);
  55741. // If none of the area is inside coordSys, allClipped is set to be true
  55742. // in layout so that label will not be displayed. See #12591
  55743. var allClipped = !overlapped;
  55744. areaData.setItemLayout(idx, {
  55745. points: points,
  55746. allClipped: allClipped
  55747. });
  55748. var itemModel = areaData.getItemModel(idx);
  55749. var style = itemModel.getModel('itemStyle').getItemStyle();
  55750. var z2 = itemModel.get('z2');
  55751. var color$1 = getVisualFromData(seriesData, 'color');
  55752. if (!style.fill) {
  55753. style.fill = color$1;
  55754. if (isString(style.fill)) {
  55755. style.fill = modifyAlpha(style.fill, 0.4);
  55756. }
  55757. }
  55758. if (!style.stroke) {
  55759. style.stroke = color$1;
  55760. }
  55761. // Visual
  55762. areaData.setItemVisual(idx, 'style', style);
  55763. areaData.setItemVisual(idx, 'z2', retrieve2(z2, 0));
  55764. });
  55765. areaData.diff(inner$f(polygonGroup).data).add(function (idx) {
  55766. var layout = areaData.getItemLayout(idx);
  55767. var z2 = areaData.getItemVisual(idx, 'z2');
  55768. if (!layout.allClipped) {
  55769. var polygon = new Polygon({
  55770. z2: retrieve2(z2, 0),
  55771. shape: {
  55772. points: layout.points
  55773. }
  55774. });
  55775. areaData.setItemGraphicEl(idx, polygon);
  55776. polygonGroup.group.add(polygon);
  55777. }
  55778. }).update(function (newIdx, oldIdx) {
  55779. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(oldIdx);
  55780. var layout = areaData.getItemLayout(newIdx);
  55781. var z2 = areaData.getItemVisual(newIdx, 'z2');
  55782. if (!layout.allClipped) {
  55783. if (polygon) {
  55784. updateProps(polygon, {
  55785. z2: retrieve2(z2, 0),
  55786. shape: {
  55787. points: layout.points
  55788. }
  55789. }, maModel, newIdx);
  55790. } else {
  55791. polygon = new Polygon({
  55792. shape: {
  55793. points: layout.points
  55794. }
  55795. });
  55796. }
  55797. areaData.setItemGraphicEl(newIdx, polygon);
  55798. polygonGroup.group.add(polygon);
  55799. } else if (polygon) {
  55800. polygonGroup.group.remove(polygon);
  55801. }
  55802. }).remove(function (idx) {
  55803. var polygon = inner$f(polygonGroup).data.getItemGraphicEl(idx);
  55804. polygonGroup.group.remove(polygon);
  55805. }).execute();
  55806. areaData.eachItemGraphicEl(function (polygon, idx) {
  55807. var itemModel = areaData.getItemModel(idx);
  55808. var style = areaData.getItemVisual(idx, 'style');
  55809. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  55810. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  55811. labelFetcher: maModel,
  55812. labelDataIndex: idx,
  55813. defaultText: areaData.getName(idx) || '',
  55814. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : tokens.color.neutral99
  55815. });
  55816. setStatesStylesFromModel(polygon, itemModel);
  55817. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  55818. getECData(polygon).dataModel = maModel;
  55819. });
  55820. inner$f(polygonGroup).data = areaData;
  55821. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  55822. };
  55823. MarkAreaView.type = 'markArea';
  55824. return MarkAreaView;
  55825. }(MarkerView);
  55826. function createList$2(coordSys, seriesModel, maModel) {
  55827. var areaData;
  55828. var dataDims;
  55829. var dims = ['x0', 'y0', 'x1', 'y1'];
  55830. if (coordSys) {
  55831. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  55832. var data = seriesModel.getData();
  55833. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {};
  55834. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  55835. return extend(extend({}, info), {
  55836. name: coordDim,
  55837. // DON'T use ordinalMeta to parse and collect ordinal.
  55838. ordinalMeta: null
  55839. });
  55840. });
  55841. dataDims = map(dims, function (dim, idx) {
  55842. return {
  55843. name: dim,
  55844. type: coordDimsInfos_1[idx % 2].type
  55845. };
  55846. });
  55847. areaData = new SeriesData(dataDims, maModel);
  55848. } else {
  55849. dataDims = [{
  55850. name: 'value',
  55851. type: 'float'
  55852. }];
  55853. areaData = new SeriesData(dataDims, maModel);
  55854. }
  55855. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  55856. if (coordSys) {
  55857. optData = filter(optData, curry(markAreaFilter, coordSys));
  55858. }
  55859. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  55860. // TODO should convert to ParsedValue?
  55861. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  55862. return parseDataValue(rawVal, dataDims[dimIndex]);
  55863. } : function (item, dimName, dataIndex, dimIndex) {
  55864. return parseDataValue(item.value, dataDims[dimIndex]);
  55865. };
  55866. areaData.initData(optData, null, dimValueGetter);
  55867. areaData.hasItemOption = true;
  55868. return areaData;
  55869. }
  55870. function install$g(registers) {
  55871. registers.registerComponentModel(MarkAreaModel);
  55872. registers.registerComponentView(MarkAreaView);
  55873. registers.registerPreprocessor(function (opt) {
  55874. if (checkMarkerInSeries(opt.series, 'markArea')) {
  55875. // Make sure markArea component is enabled
  55876. opt.markArea = opt.markArea || {};
  55877. }
  55878. });
  55879. }
  55880. var getDefaultSelectorOptions = function (ecModel, type) {
  55881. if (type === 'all') {
  55882. return {
  55883. type: 'all',
  55884. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  55885. };
  55886. } else if (type === 'inverse') {
  55887. return {
  55888. type: 'inverse',
  55889. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  55890. };
  55891. }
  55892. };
  55893. var LegendModel = /** @class */function (_super) {
  55894. __extends(LegendModel, _super);
  55895. function LegendModel() {
  55896. var _this = _super !== null && _super.apply(this, arguments) || this;
  55897. _this.type = LegendModel.type;
  55898. _this.layoutMode = {
  55899. type: 'box',
  55900. // legend.width/height are maxWidth/maxHeight actually,
  55901. // whereas real width/height is calculated by its content.
  55902. // (Setting {left: 10, right: 10} does not make sense).
  55903. // So consider the case:
  55904. // `setOption({legend: {left: 10});`
  55905. // then `setOption({legend: {right: 10});`
  55906. // The previous `left` should be cleared by setting `ignoreSize`.
  55907. ignoreSize: true
  55908. };
  55909. return _this;
  55910. }
  55911. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  55912. this.mergeDefaultAndTheme(option, ecModel);
  55913. option.selected = option.selected || {};
  55914. this._updateSelector(option);
  55915. };
  55916. LegendModel.prototype.mergeOption = function (option, ecModel) {
  55917. _super.prototype.mergeOption.call(this, option, ecModel);
  55918. this._updateSelector(option);
  55919. };
  55920. LegendModel.prototype._updateSelector = function (option) {
  55921. var selector = option.selector;
  55922. var ecModel = this.ecModel;
  55923. if (selector === true) {
  55924. selector = option.selector = ['all', 'inverse'];
  55925. }
  55926. if (isArray(selector)) {
  55927. each(selector, function (item, index) {
  55928. isString(item) && (item = {
  55929. type: item
  55930. });
  55931. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  55932. });
  55933. }
  55934. };
  55935. LegendModel.prototype.optionUpdated = function () {
  55936. this._updateData(this.ecModel);
  55937. var legendData = this._data;
  55938. // If selectedMode is single, try to select one
  55939. if (legendData[0] && this.get('selectedMode') === 'single') {
  55940. var hasSelected = false;
  55941. // If has any selected in option.selected
  55942. for (var i = 0; i < legendData.length; i++) {
  55943. var name_1 = legendData[i].get('name');
  55944. if (this.isSelected(name_1)) {
  55945. // Force to unselect others
  55946. this.select(name_1);
  55947. hasSelected = true;
  55948. break;
  55949. }
  55950. }
  55951. // Try select the first if selectedMode is single
  55952. !hasSelected && this.select(legendData[0].get('name'));
  55953. }
  55954. };
  55955. LegendModel.prototype._updateData = function (ecModel) {
  55956. var potentialData = [];
  55957. var availableNames = [];
  55958. ecModel.eachRawSeries(function (seriesModel) {
  55959. var seriesName = seriesModel.name;
  55960. availableNames.push(seriesName);
  55961. var isPotential;
  55962. if (seriesModel.legendVisualProvider) {
  55963. var provider = seriesModel.legendVisualProvider;
  55964. var names = provider.getAllNames();
  55965. if (!ecModel.isSeriesFiltered(seriesModel)) {
  55966. availableNames = availableNames.concat(names);
  55967. }
  55968. if (names.length) {
  55969. potentialData = potentialData.concat(names);
  55970. } else {
  55971. isPotential = true;
  55972. }
  55973. } else {
  55974. isPotential = true;
  55975. }
  55976. if (isPotential && isNameSpecified(seriesModel)) {
  55977. potentialData.push(seriesModel.name);
  55978. }
  55979. });
  55980. /**
  55981. * @type {Array.<string>}
  55982. * @private
  55983. */
  55984. this._availableNames = availableNames;
  55985. // If legend.data is not specified in option, use availableNames as data,
  55986. // which is convenient for user preparing option.
  55987. var rawData = this.get('data') || potentialData;
  55988. var legendNameMap = createHashMap();
  55989. var legendData = map(rawData, function (dataItem) {
  55990. // Can be string or number
  55991. if (isString(dataItem) || isNumber(dataItem)) {
  55992. dataItem = {
  55993. name: dataItem
  55994. };
  55995. }
  55996. if (legendNameMap.get(dataItem.name)) {
  55997. // remove legend name duplicate
  55998. return null;
  55999. }
  56000. legendNameMap.set(dataItem.name, true);
  56001. return new Model(dataItem, this, this.ecModel);
  56002. }, this);
  56003. /**
  56004. * @type {Array.<module:echarts/model/Model>}
  56005. * @private
  56006. */
  56007. this._data = filter(legendData, function (item) {
  56008. return !!item;
  56009. });
  56010. };
  56011. LegendModel.prototype.getData = function () {
  56012. return this._data;
  56013. };
  56014. LegendModel.prototype.select = function (name) {
  56015. var selected = this.option.selected;
  56016. var selectedMode = this.get('selectedMode');
  56017. if (selectedMode === 'single') {
  56018. var data = this._data;
  56019. each(data, function (dataItem) {
  56020. selected[dataItem.get('name')] = false;
  56021. });
  56022. }
  56023. selected[name] = true;
  56024. };
  56025. LegendModel.prototype.unSelect = function (name) {
  56026. if (this.get('selectedMode') !== 'single') {
  56027. this.option.selected[name] = false;
  56028. }
  56029. };
  56030. LegendModel.prototype.toggleSelected = function (name) {
  56031. var selected = this.option.selected;
  56032. // Default is true
  56033. if (!selected.hasOwnProperty(name)) {
  56034. selected[name] = true;
  56035. }
  56036. this[selected[name] ? 'unSelect' : 'select'](name);
  56037. };
  56038. LegendModel.prototype.allSelect = function () {
  56039. var data = this._data;
  56040. var selected = this.option.selected;
  56041. each(data, function (dataItem) {
  56042. selected[dataItem.get('name', true)] = true;
  56043. });
  56044. };
  56045. LegendModel.prototype.inverseSelect = function () {
  56046. var data = this._data;
  56047. var selected = this.option.selected;
  56048. each(data, function (dataItem) {
  56049. var name = dataItem.get('name', true);
  56050. // Initially, default value is true
  56051. if (!selected.hasOwnProperty(name)) {
  56052. selected[name] = true;
  56053. }
  56054. selected[name] = !selected[name];
  56055. });
  56056. };
  56057. LegendModel.prototype.isSelected = function (name) {
  56058. var selected = this.option.selected;
  56059. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  56060. };
  56061. LegendModel.prototype.getOrient = function () {
  56062. return this.get('orient') === 'vertical' ? {
  56063. index: 1,
  56064. name: 'vertical'
  56065. } : {
  56066. index: 0,
  56067. name: 'horizontal'
  56068. };
  56069. };
  56070. LegendModel.type = 'legend.plain';
  56071. LegendModel.dependencies = ['series'];
  56072. LegendModel.defaultOption = {
  56073. // zlevel: 0,
  56074. z: 4,
  56075. show: true,
  56076. orient: 'horizontal',
  56077. left: 'center',
  56078. // right: 'center',
  56079. // top: 0,
  56080. bottom: tokens.size.m,
  56081. align: 'auto',
  56082. backgroundColor: tokens.color.transparent,
  56083. borderColor: tokens.color.border,
  56084. borderRadius: 0,
  56085. borderWidth: 0,
  56086. padding: 5,
  56087. itemGap: 8,
  56088. itemWidth: 25,
  56089. itemHeight: 14,
  56090. symbolRotate: 'inherit',
  56091. symbolKeepAspect: true,
  56092. inactiveColor: tokens.color.disabled,
  56093. inactiveBorderColor: tokens.color.disabled,
  56094. inactiveBorderWidth: 'auto',
  56095. itemStyle: {
  56096. color: 'inherit',
  56097. opacity: 'inherit',
  56098. borderColor: 'inherit',
  56099. borderWidth: 'auto',
  56100. borderCap: 'inherit',
  56101. borderJoin: 'inherit',
  56102. borderDashOffset: 'inherit',
  56103. borderMiterLimit: 'inherit'
  56104. },
  56105. lineStyle: {
  56106. width: 'auto',
  56107. color: 'inherit',
  56108. inactiveColor: tokens.color.disabled,
  56109. inactiveWidth: 2,
  56110. opacity: 'inherit',
  56111. type: 'inherit',
  56112. cap: 'inherit',
  56113. join: 'inherit',
  56114. dashOffset: 'inherit',
  56115. miterLimit: 'inherit'
  56116. },
  56117. textStyle: {
  56118. color: tokens.color.secondary
  56119. },
  56120. selectedMode: true,
  56121. selector: false,
  56122. selectorLabel: {
  56123. show: true,
  56124. borderRadius: 10,
  56125. padding: [3, 5, 3, 5],
  56126. fontSize: 12,
  56127. fontFamily: 'sans-serif',
  56128. color: tokens.color.tertiary,
  56129. borderWidth: 1,
  56130. borderColor: tokens.color.border
  56131. },
  56132. emphasis: {
  56133. selectorLabel: {
  56134. show: true,
  56135. color: tokens.color.quaternary
  56136. }
  56137. },
  56138. selectorPosition: 'auto',
  56139. selectorItemGap: 7,
  56140. selectorButtonGap: 10,
  56141. tooltip: {
  56142. show: false
  56143. },
  56144. triggerEvent: false
  56145. };
  56146. return LegendModel;
  56147. }(ComponentModel);
  56148. var curry$1 = curry;
  56149. var each$7 = each;
  56150. var Group$1 = Group;
  56151. var LegendView = /** @class */function (_super) {
  56152. __extends(LegendView, _super);
  56153. function LegendView() {
  56154. var _this = _super !== null && _super.apply(this, arguments) || this;
  56155. _this.type = LegendView.type;
  56156. _this.newlineDisabled = false;
  56157. return _this;
  56158. }
  56159. LegendView.prototype.init = function () {
  56160. this.group.add(this._contentGroup = new Group$1());
  56161. this.group.add(this._selectorGroup = new Group$1());
  56162. this._isFirstRender = true;
  56163. };
  56164. /**
  56165. * @protected
  56166. */
  56167. LegendView.prototype.getContentGroup = function () {
  56168. return this._contentGroup;
  56169. };
  56170. /**
  56171. * @protected
  56172. */
  56173. LegendView.prototype.getSelectorGroup = function () {
  56174. return this._selectorGroup;
  56175. };
  56176. /**
  56177. * @override
  56178. */
  56179. LegendView.prototype.render = function (legendModel, ecModel, api) {
  56180. var isFirstRender = this._isFirstRender;
  56181. this._isFirstRender = false;
  56182. this.resetInner();
  56183. if (!legendModel.get('show', true)) {
  56184. return;
  56185. }
  56186. var itemAlign = legendModel.get('align');
  56187. var orient = legendModel.get('orient');
  56188. if (!itemAlign || itemAlign === 'auto') {
  56189. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  56190. }
  56191. // selector has been normalized to an array in model
  56192. var selector = legendModel.get('selector', true);
  56193. var selectorPosition = legendModel.get('selectorPosition', true);
  56194. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  56195. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  56196. }
  56197. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  56198. // Perform layout.
  56199. var refContainer = createBoxLayoutReference(legendModel, api).refContainer;
  56200. var positionInfo = legendModel.getBoxLayoutParams();
  56201. var padding = legendModel.get('padding');
  56202. var maxSize = getLayoutRect(positionInfo, refContainer, padding);
  56203. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  56204. // Place mainGroup, based on the calculated `mainRect`.
  56205. var layoutRect = getLayoutRect(defaults({
  56206. width: mainRect.width,
  56207. height: mainRect.height
  56208. }, positionInfo), refContainer, padding);
  56209. this.group.x = layoutRect.x - mainRect.x;
  56210. this.group.y = layoutRect.y - mainRect.y;
  56211. this.group.markRedraw();
  56212. // Render background after group is layout.
  56213. this.group.add(this._backgroundEl = makeBackground(mainRect,
  56214. // FXIME: most itemStyle options does not work in background because inherit is not handled yet.
  56215. legendModel));
  56216. };
  56217. LegendView.prototype.resetInner = function () {
  56218. this.getContentGroup().removeAll();
  56219. this._backgroundEl && this.group.remove(this._backgroundEl);
  56220. this.getSelectorGroup().removeAll();
  56221. };
  56222. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  56223. var contentGroup = this.getContentGroup();
  56224. var legendDrawnMap = createHashMap();
  56225. var selectMode = legendModel.get('selectedMode');
  56226. var triggerEvent = legendModel.get('triggerEvent');
  56227. var excludeSeriesId = [];
  56228. ecModel.eachRawSeries(function (seriesModel) {
  56229. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  56230. });
  56231. each$7(legendModel.getData(), function (legendItemModel, dataIndex) {
  56232. var _this = this;
  56233. var name = legendItemModel.get('name');
  56234. // Use empty string or \n as a newline string
  56235. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  56236. var g = new Group$1();
  56237. // @ts-ignore
  56238. g.newline = true;
  56239. contentGroup.add(g);
  56240. return;
  56241. }
  56242. // Representitive series.
  56243. var seriesModel = ecModel.getSeriesByName(name)[0];
  56244. if (legendDrawnMap.get(name)) {
  56245. // Have been drawn
  56246. return;
  56247. }
  56248. // Legend to control series.
  56249. if (seriesModel) {
  56250. var data = seriesModel.getData();
  56251. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  56252. var legendIcon = data.getVisual('legendIcon');
  56253. /**
  56254. * `data.getVisual('style')` may be the color from the register
  56255. * in series. For example, for line series,
  56256. */
  56257. var style = data.getVisual('style');
  56258. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  56259. 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));
  56260. if (ecModel.ssr) {
  56261. itemGroup.eachChild(function (child) {
  56262. var ecData = getECData(child);
  56263. ecData.seriesIndex = seriesModel.seriesIndex;
  56264. ecData.dataIndex = dataIndex;
  56265. ecData.ssrType = 'legend';
  56266. });
  56267. }
  56268. if (triggerEvent) {
  56269. itemGroup.eachChild(function (child) {
  56270. _this.packEventData(child, legendModel, seriesModel, dataIndex, name);
  56271. });
  56272. }
  56273. legendDrawnMap.set(name, true);
  56274. } else {
  56275. // Legend to control data. In pie and funnel.
  56276. ecModel.eachRawSeries(function (seriesModel) {
  56277. var _this = this;
  56278. // In case multiple series has same data name
  56279. if (legendDrawnMap.get(name)) {
  56280. return;
  56281. }
  56282. if (seriesModel.legendVisualProvider) {
  56283. var provider = seriesModel.legendVisualProvider;
  56284. if (!provider.containName(name)) {
  56285. return;
  56286. }
  56287. var idx = provider.indexOfName(name);
  56288. var style = provider.getItemVisual(idx, 'style');
  56289. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  56290. var colorArr = parse(style.fill);
  56291. // Color may be set to transparent in visualMap when data is out of range.
  56292. // Do not show nothing.
  56293. if (colorArr && colorArr[3] === 0) {
  56294. colorArr[3] = 0.2;
  56295. // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  56296. style = extend(extend({}, style), {
  56297. fill: stringify(colorArr, 'rgba')
  56298. });
  56299. }
  56300. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api);
  56301. // FIXME: consider different series has items with the same name.
  56302. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId))
  56303. // Should not specify the series name, consider legend controls
  56304. // more than one pie series.
  56305. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  56306. if (ecModel.ssr) {
  56307. itemGroup.eachChild(function (child) {
  56308. var ecData = getECData(child);
  56309. ecData.seriesIndex = seriesModel.seriesIndex;
  56310. ecData.dataIndex = dataIndex;
  56311. ecData.ssrType = 'legend';
  56312. });
  56313. }
  56314. if (triggerEvent) {
  56315. itemGroup.eachChild(function (child) {
  56316. _this.packEventData(child, legendModel, seriesModel, dataIndex, name);
  56317. });
  56318. }
  56319. legendDrawnMap.set(name, true);
  56320. }
  56321. }, this);
  56322. }
  56323. if ("development" !== 'production') {
  56324. if (!legendDrawnMap.get(name)) {
  56325. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  56326. }
  56327. }
  56328. }, this);
  56329. if (selector) {
  56330. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  56331. }
  56332. };
  56333. LegendView.prototype.packEventData = function (el, legendModel, seriesModel, dataIndex, name) {
  56334. var eventData = {
  56335. componentType: 'legend',
  56336. componentIndex: legendModel.componentIndex,
  56337. dataIndex: dataIndex,
  56338. value: name,
  56339. seriesIndex: seriesModel.seriesIndex
  56340. };
  56341. getECData(el).eventData = eventData;
  56342. };
  56343. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  56344. var selectorGroup = this.getSelectorGroup();
  56345. each$7(selector, function createSelectorButton(selectorItem) {
  56346. var type = selectorItem.type;
  56347. var labelText = new ZRText({
  56348. style: {
  56349. x: 0,
  56350. y: 0,
  56351. align: 'center',
  56352. verticalAlign: 'middle'
  56353. },
  56354. onclick: function () {
  56355. api.dispatchAction({
  56356. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect',
  56357. legendId: legendModel.id
  56358. });
  56359. }
  56360. });
  56361. selectorGroup.add(labelText);
  56362. var labelModel = legendModel.getModel('selectorLabel');
  56363. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  56364. setLabelStyle(labelText, {
  56365. normal: labelModel,
  56366. emphasis: emphasisLabelModel
  56367. }, {
  56368. defaultText: selectorItem.title
  56369. });
  56370. enableHoverEmphasis(labelText);
  56371. });
  56372. };
  56373. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  56374. var drawType = seriesModel.visualDrawType;
  56375. var itemWidth = legendModel.get('itemWidth');
  56376. var itemHeight = legendModel.get('itemHeight');
  56377. var isSelected = legendModel.isSelected(name);
  56378. var iconRotate = legendItemModel.get('symbolRotate');
  56379. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  56380. var legendIconType = legendItemModel.get('icon');
  56381. legendIcon = legendIconType || legendIcon || 'roundRect';
  56382. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  56383. var itemGroup = new Group$1();
  56384. var textStyleModel = legendItemModel.getModel('textStyle');
  56385. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  56386. // Series has specific way to define legend icon
  56387. itemGroup.add(seriesModel.getLegendIcon({
  56388. itemWidth: itemWidth,
  56389. itemHeight: itemHeight,
  56390. icon: legendIcon,
  56391. iconRotate: iconRotate,
  56392. itemStyle: style.itemStyle,
  56393. lineStyle: style.lineStyle,
  56394. symbolKeepAspect: symbolKeepAspect
  56395. }));
  56396. } else {
  56397. // Use default legend icon policy for most series
  56398. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  56399. itemGroup.add(getDefaultLegendIcon({
  56400. itemWidth: itemWidth,
  56401. itemHeight: itemHeight,
  56402. icon: legendIcon,
  56403. iconRotate: rotate,
  56404. itemStyle: style.itemStyle,
  56405. lineStyle: style.lineStyle,
  56406. symbolKeepAspect: symbolKeepAspect
  56407. }));
  56408. }
  56409. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  56410. var textAlign = itemAlign;
  56411. var formatter = legendModel.get('formatter');
  56412. var content = name;
  56413. if (isString(formatter) && formatter) {
  56414. content = formatter.replace('{name}', name != null ? name : '');
  56415. } else if (isFunction(formatter)) {
  56416. content = formatter(name);
  56417. }
  56418. var textColor = isSelected ? textStyleModel.getTextColor() : legendItemModel.get('inactiveColor');
  56419. itemGroup.add(new ZRText({
  56420. style: createTextStyle(textStyleModel, {
  56421. text: content,
  56422. x: textX,
  56423. y: itemHeight / 2,
  56424. fill: textColor,
  56425. align: textAlign,
  56426. verticalAlign: 'middle'
  56427. }, {
  56428. inheritColor: textColor
  56429. })
  56430. }));
  56431. // Add a invisible rect to increase the area of mouse hover
  56432. var hitRect = new Rect({
  56433. shape: itemGroup.getBoundingRect(),
  56434. style: {
  56435. // Cannot use 'invisible' because SVG SSR will miss the node
  56436. fill: 'transparent'
  56437. }
  56438. });
  56439. var tooltipModel = legendItemModel.getModel('tooltip');
  56440. if (tooltipModel.get('show')) {
  56441. setTooltipConfig({
  56442. el: hitRect,
  56443. componentModel: legendModel,
  56444. itemName: name,
  56445. itemTooltipOption: tooltipModel.option
  56446. });
  56447. }
  56448. itemGroup.add(hitRect);
  56449. itemGroup.eachChild(function (child) {
  56450. child.silent = true;
  56451. });
  56452. hitRect.silent = !selectMode;
  56453. this.getContentGroup().add(itemGroup);
  56454. enableHoverEmphasis(itemGroup);
  56455. // @ts-ignore
  56456. itemGroup.__legendDataIndex = dataIndex;
  56457. return itemGroup;
  56458. };
  56459. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  56460. var contentGroup = this.getContentGroup();
  56461. var selectorGroup = this.getSelectorGroup();
  56462. // Place items in contentGroup.
  56463. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  56464. var contentRect = contentGroup.getBoundingRect();
  56465. var contentPos = [-contentRect.x, -contentRect.y];
  56466. selectorGroup.markRedraw();
  56467. contentGroup.markRedraw();
  56468. if (selector) {
  56469. // Place buttons in selectorGroup
  56470. box(
  56471. // Buttons in selectorGroup always layout horizontally
  56472. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  56473. var selectorRect = selectorGroup.getBoundingRect();
  56474. var selectorPos = [-selectorRect.x, -selectorRect.y];
  56475. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  56476. var orientIdx = legendModel.getOrient().index;
  56477. var wh = orientIdx === 0 ? 'width' : 'height';
  56478. var hw = orientIdx === 0 ? 'height' : 'width';
  56479. var yx = orientIdx === 0 ? 'y' : 'x';
  56480. if (selectorPosition === 'end') {
  56481. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  56482. } else {
  56483. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  56484. }
  56485. // Always align selector to content as 'middle'
  56486. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  56487. selectorGroup.x = selectorPos[0];
  56488. selectorGroup.y = selectorPos[1];
  56489. contentGroup.x = contentPos[0];
  56490. contentGroup.y = contentPos[1];
  56491. var mainRect = {
  56492. x: 0,
  56493. y: 0
  56494. };
  56495. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  56496. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  56497. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  56498. return mainRect;
  56499. } else {
  56500. contentGroup.x = contentPos[0];
  56501. contentGroup.y = contentPos[1];
  56502. return this.group.getBoundingRect();
  56503. }
  56504. };
  56505. /**
  56506. * @protected
  56507. */
  56508. LegendView.prototype.remove = function () {
  56509. this.getContentGroup().removeAll();
  56510. this._isFirstRender = true;
  56511. };
  56512. LegendView.type = 'legend.plain';
  56513. return LegendView;
  56514. }(ComponentView);
  56515. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  56516. /**
  56517. * Use series style if is inherit;
  56518. * elsewise, use legend style
  56519. */
  56520. function handleCommonProps(style, visualStyle) {
  56521. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  56522. if (style.lineWidth === 'auto') {
  56523. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  56524. }
  56525. each$7(style, function (propVal, propName) {
  56526. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  56527. });
  56528. }
  56529. // itemStyle
  56530. var itemStyleModel = legendItemModel.getModel('itemStyle');
  56531. var itemStyle = itemStyleModel.getItemStyle();
  56532. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  56533. var decalStyle = itemStyleModel.getShallow('decal');
  56534. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  56535. if (itemStyle.fill === 'inherit') {
  56536. /**
  56537. * Series with visualDrawType as 'stroke' should have
  56538. * series stroke as legend fill
  56539. */
  56540. itemStyle.fill = itemVisualStyle[drawType];
  56541. }
  56542. if (itemStyle.stroke === 'inherit') {
  56543. /**
  56544. * icon type with "emptyXXX" should use fill color
  56545. * in visual style
  56546. */
  56547. itemStyle.stroke = itemVisualStyle[iconBrushType];
  56548. }
  56549. if (itemStyle.opacity === 'inherit') {
  56550. /**
  56551. * Use lineStyle.opacity if drawType is stroke
  56552. */
  56553. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  56554. }
  56555. handleCommonProps(itemStyle, itemVisualStyle);
  56556. // lineStyle
  56557. var legendLineModel = legendItemModel.getModel('lineStyle');
  56558. var lineStyle = legendLineModel.getLineStyle();
  56559. handleCommonProps(lineStyle, lineVisualStyle);
  56560. // Fix auto color to real color
  56561. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  56562. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  56563. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  56564. if (!isSelected) {
  56565. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  56566. /**
  56567. * Since stroke is set to be inactiveBorderColor, it may occur that
  56568. * there is no border in series but border in legend, so we need to
  56569. * use border only when series has border if is set to be auto
  56570. */
  56571. var visualHasBorder = itemStyle[iconBrushType];
  56572. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  56573. itemStyle.fill = legendItemModel.get('inactiveColor');
  56574. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  56575. lineStyle.stroke = legendLineModel.get('inactiveColor');
  56576. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  56577. }
  56578. return {
  56579. itemStyle: itemStyle,
  56580. lineStyle: lineStyle
  56581. };
  56582. }
  56583. function getDefaultLegendIcon(opt) {
  56584. var symboType = opt.icon || 'roundRect';
  56585. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  56586. icon.setStyle(opt.itemStyle);
  56587. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  56588. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  56589. if (symboType.indexOf('empty') > -1) {
  56590. icon.style.stroke = icon.style.fill;
  56591. icon.style.fill = tokens.color.neutral00;
  56592. icon.style.lineWidth = 2;
  56593. }
  56594. return icon;
  56595. }
  56596. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  56597. // downplay before unselect
  56598. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  56599. api.dispatchAction({
  56600. type: 'legendToggleSelect',
  56601. name: seriesName != null ? seriesName : dataName
  56602. });
  56603. // highlight after select
  56604. // TODO highlight immediately may cause animation loss.
  56605. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  56606. }
  56607. function isUseHoverLayer(api) {
  56608. var list = api.getZr().storage.getDisplayList();
  56609. var emphasisState;
  56610. var i = 0;
  56611. var len = list.length;
  56612. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  56613. i++;
  56614. }
  56615. return emphasisState && emphasisState.hoverLayer;
  56616. }
  56617. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  56618. // If element hover will move to a hoverLayer.
  56619. if (!isUseHoverLayer(api)) {
  56620. api.dispatchAction({
  56621. type: 'highlight',
  56622. seriesName: seriesName,
  56623. name: dataName,
  56624. excludeSeriesId: excludeSeriesId
  56625. });
  56626. }
  56627. }
  56628. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  56629. // If element hover will move to a hoverLayer.
  56630. if (!isUseHoverLayer(api)) {
  56631. api.dispatchAction({
  56632. type: 'downplay',
  56633. seriesName: seriesName,
  56634. name: dataName,
  56635. excludeSeriesId: excludeSeriesId
  56636. });
  56637. }
  56638. }
  56639. /*
  56640. * Licensed to the Apache Software Foundation (ASF) under one
  56641. * or more contributor license agreements. See the NOTICE file
  56642. * distributed with this work for additional information
  56643. * regarding copyright ownership. The ASF licenses this file
  56644. * to you under the Apache License, Version 2.0 (the
  56645. * "License"); you may not use this file except in compliance
  56646. * with the License. You may obtain a copy of the License at
  56647. *
  56648. * http://www.apache.org/licenses/LICENSE-2.0
  56649. *
  56650. * Unless required by applicable law or agreed to in writing,
  56651. * software distributed under the License is distributed on an
  56652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56653. * KIND, either express or implied. See the License for the
  56654. * specific language governing permissions and limitations
  56655. * under the License.
  56656. */
  56657. /**
  56658. * AUTO-GENERATED FILE. DO NOT MODIFY.
  56659. */
  56660. /*
  56661. * Licensed to the Apache Software Foundation (ASF) under one
  56662. * or more contributor license agreements. See the NOTICE file
  56663. * distributed with this work for additional information
  56664. * regarding copyright ownership. The ASF licenses this file
  56665. * to you under the Apache License, Version 2.0 (the
  56666. * "License"); you may not use this file except in compliance
  56667. * with the License. You may obtain a copy of the License at
  56668. *
  56669. * http://www.apache.org/licenses/LICENSE-2.0
  56670. *
  56671. * Unless required by applicable law or agreed to in writing,
  56672. * software distributed under the License is distributed on an
  56673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56674. * KIND, either express or implied. See the License for the
  56675. * specific language governing permissions and limitations
  56676. * under the License.
  56677. */
  56678. function legendFilter(ecModel) {
  56679. var legendModels = ecModel.findComponents({
  56680. mainType: 'legend'
  56681. });
  56682. if (legendModels && legendModels.length) {
  56683. ecModel.filterSeries(function (series) {
  56684. // If in any legend component the status is not selected.
  56685. // Because in legend series is assumed selected when it is not in the legend data.
  56686. for (var i = 0; i < legendModels.length; i++) {
  56687. if (!legendModels[i].isSelected(series.name)) {
  56688. return false;
  56689. }
  56690. }
  56691. return true;
  56692. });
  56693. }
  56694. }
  56695. function legendSelectActionHandler(methodName, payload, ecModel) {
  56696. var isAllSelect = methodName === 'allSelect' || methodName === 'inverseSelect';
  56697. var selectedMap = {};
  56698. var actionLegendIndices = [];
  56699. ecModel.eachComponent({
  56700. mainType: 'legend',
  56701. query: payload
  56702. }, function (legendModel) {
  56703. if (isAllSelect) {
  56704. legendModel[methodName]();
  56705. } else {
  56706. legendModel[methodName](payload.name);
  56707. }
  56708. makeSelectedMap(legendModel, selectedMap);
  56709. actionLegendIndices.push(legendModel.componentIndex);
  56710. });
  56711. var allSelectedMap = {};
  56712. // make selectedMap from all legend components
  56713. ecModel.eachComponent('legend', function (legendModel) {
  56714. each(selectedMap, function (isSelected, name) {
  56715. // Force other legend has same selected status
  56716. // Or the first is toggled to true and other are toggled to false
  56717. // In the case one legend has some item unSelected in option. And if other legend
  56718. // doesn't has the item, they will assume it is selected.
  56719. legendModel[isSelected ? 'select' : 'unSelect'](name);
  56720. });
  56721. makeSelectedMap(legendModel, allSelectedMap);
  56722. });
  56723. // Return the event explicitly
  56724. return isAllSelect ? {
  56725. selected: allSelectedMap,
  56726. // return legendIndex array to tell the developers which legends are allSelect / inverseSelect
  56727. legendIndex: actionLegendIndices
  56728. } : {
  56729. name: payload.name,
  56730. selected: allSelectedMap
  56731. };
  56732. }
  56733. function makeSelectedMap(legendModel, out) {
  56734. var selectedMap = out || {};
  56735. each(legendModel.getData(), function (model) {
  56736. var name = model.get('name');
  56737. // Wrap element
  56738. if (name === '\n' || name === '') {
  56739. return;
  56740. }
  56741. var isItemSelected = legendModel.isSelected(name);
  56742. if (hasOwn(selectedMap, name)) {
  56743. // Unselected if any legend is unselected
  56744. selectedMap[name] = selectedMap[name] && isItemSelected;
  56745. } else {
  56746. selectedMap[name] = isItemSelected;
  56747. }
  56748. });
  56749. return selectedMap;
  56750. }
  56751. function installLegendAction(registers) {
  56752. /**
  56753. * @event legendToggleSelect
  56754. * @type {Object}
  56755. * @property {string} type 'legendToggleSelect'
  56756. * @property {string} [from]
  56757. * @property {string} name Series name or data item name
  56758. */
  56759. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  56760. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  56761. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  56762. /**
  56763. * @event legendSelect
  56764. * @type {Object}
  56765. * @property {string} type 'legendSelect'
  56766. * @property {string} name Series name or data item name
  56767. */
  56768. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  56769. /**
  56770. * @event legendUnSelect
  56771. * @type {Object}
  56772. * @property {string} type 'legendUnSelect'
  56773. * @property {string} name Series name or data item name
  56774. */
  56775. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  56776. }
  56777. function install$h(registers) {
  56778. registers.registerComponentModel(LegendModel);
  56779. registers.registerComponentView(LegendView);
  56780. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  56781. registers.registerSubTypeDefaulter('legend', function () {
  56782. return 'plain';
  56783. });
  56784. installLegendAction(registers);
  56785. }
  56786. var ScrollableLegendModel = /** @class */function (_super) {
  56787. __extends(ScrollableLegendModel, _super);
  56788. function ScrollableLegendModel() {
  56789. var _this = _super !== null && _super.apply(this, arguments) || this;
  56790. _this.type = ScrollableLegendModel.type;
  56791. return _this;
  56792. }
  56793. /**
  56794. * @param {number} scrollDataIndex
  56795. */
  56796. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  56797. this.option.scrollDataIndex = scrollDataIndex;
  56798. };
  56799. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  56800. var inputPositionParams = getLayoutParams(option);
  56801. _super.prototype.init.call(this, option, parentModel, ecModel);
  56802. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  56803. };
  56804. /**
  56805. * @override
  56806. */
  56807. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  56808. _super.prototype.mergeOption.call(this, option, ecModel);
  56809. mergeAndNormalizeLayoutParams(this, this.option, option);
  56810. };
  56811. ScrollableLegendModel.type = 'legend.scroll';
  56812. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  56813. scrollDataIndex: 0,
  56814. pageButtonItemGap: 5,
  56815. pageButtonGap: null,
  56816. pageButtonPosition: 'end',
  56817. pageFormatter: '{current}/{total}',
  56818. pageIcons: {
  56819. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  56820. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  56821. },
  56822. pageIconColor: tokens.color.accent50,
  56823. pageIconInactiveColor: tokens.color.accent10,
  56824. pageIconSize: 15,
  56825. pageTextStyle: {
  56826. color: tokens.color.tertiary
  56827. },
  56828. animationDurationUpdate: 800
  56829. });
  56830. return ScrollableLegendModel;
  56831. }(LegendModel);
  56832. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  56833. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  56834. var orient = legendModel.getOrient();
  56835. var ignoreSize = [1, 1];
  56836. ignoreSize[orient.index] = 0;
  56837. mergeLayoutParam(target, raw, {
  56838. type: 'box',
  56839. ignoreSize: !!ignoreSize
  56840. });
  56841. }
  56842. var Group$2 = Group;
  56843. var WH$2 = ['width', 'height'];
  56844. var XY$2 = ['x', 'y'];
  56845. var ScrollableLegendView = /** @class */function (_super) {
  56846. __extends(ScrollableLegendView, _super);
  56847. function ScrollableLegendView() {
  56848. var _this = _super !== null && _super.apply(this, arguments) || this;
  56849. _this.type = ScrollableLegendView.type;
  56850. _this.newlineDisabled = true;
  56851. _this._currentIndex = 0;
  56852. return _this;
  56853. }
  56854. ScrollableLegendView.prototype.init = function () {
  56855. _super.prototype.init.call(this);
  56856. this.group.add(this._containerGroup = new Group$2());
  56857. this._containerGroup.add(this.getContentGroup());
  56858. this.group.add(this._controllerGroup = new Group$2());
  56859. };
  56860. /**
  56861. * @override
  56862. */
  56863. ScrollableLegendView.prototype.resetInner = function () {
  56864. _super.prototype.resetInner.call(this);
  56865. this._controllerGroup.removeAll();
  56866. this._containerGroup.removeClipPath();
  56867. this._containerGroup.__rectSize = null;
  56868. };
  56869. /**
  56870. * @override
  56871. */
  56872. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  56873. var self = this;
  56874. // Render content items.
  56875. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  56876. var controllerGroup = this._controllerGroup;
  56877. // FIXME: support be 'auto' adapt to size number text length,
  56878. // e.g., '3/12345' should not overlap with the control arrow button.
  56879. var pageIconSize = legendModel.get('pageIconSize', true);
  56880. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  56881. createPageButton('pagePrev', 0);
  56882. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  56883. controllerGroup.add(new ZRText({
  56884. name: 'pageText',
  56885. style: {
  56886. // Placeholder to calculate a proper layout.
  56887. text: 'xx/xx',
  56888. fill: pageTextStyleModel.getTextColor(),
  56889. font: pageTextStyleModel.getFont(),
  56890. verticalAlign: 'middle',
  56891. align: 'center'
  56892. },
  56893. silent: true
  56894. }));
  56895. createPageButton('pageNext', 1);
  56896. function createPageButton(name, iconIdx) {
  56897. var pageDataIndexName = name + 'DataIndex';
  56898. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  56899. // Buttons will be created in each render, so we do not need
  56900. // to worry about avoiding using legendModel kept in scope.
  56901. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  56902. }, {
  56903. x: -pageIconSizeArr[0] / 2,
  56904. y: -pageIconSizeArr[1] / 2,
  56905. width: pageIconSizeArr[0],
  56906. height: pageIconSizeArr[1]
  56907. });
  56908. icon.name = name;
  56909. controllerGroup.add(icon);
  56910. }
  56911. };
  56912. /**
  56913. * @override
  56914. */
  56915. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  56916. var selectorGroup = this.getSelectorGroup();
  56917. var orientIdx = legendModel.getOrient().index;
  56918. var wh = WH$2[orientIdx];
  56919. var xy = XY$2[orientIdx];
  56920. var hw = WH$2[1 - orientIdx];
  56921. var yx = XY$2[1 - orientIdx];
  56922. selector && box(
  56923. // Buttons in selectorGroup always layout horizontally
  56924. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  56925. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  56926. var selectorRect = selectorGroup.getBoundingRect();
  56927. var selectorPos = [-selectorRect.x, -selectorRect.y];
  56928. var processMaxSize = clone(maxSize);
  56929. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  56930. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  56931. if (selector) {
  56932. if (selectorPosition === 'end') {
  56933. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  56934. } else {
  56935. var offset = selectorRect[wh] + selectorButtonGap;
  56936. selectorPos[orientIdx] -= offset;
  56937. mainRect[xy] -= offset;
  56938. }
  56939. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  56940. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  56941. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  56942. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  56943. selectorGroup.x = selectorPos[0];
  56944. selectorGroup.y = selectorPos[1];
  56945. selectorGroup.markRedraw();
  56946. }
  56947. return mainRect;
  56948. };
  56949. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  56950. var contentGroup = this.getContentGroup();
  56951. var containerGroup = this._containerGroup;
  56952. var controllerGroup = this._controllerGroup;
  56953. // Place items in contentGroup.
  56954. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  56955. box(
  56956. // Buttons in controller are layout always horizontally.
  56957. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  56958. var contentRect = contentGroup.getBoundingRect();
  56959. var controllerRect = controllerGroup.getBoundingRect();
  56960. var showController = this._showController = contentRect[wh] > maxSize[wh];
  56961. // In case that the inner elements of contentGroup layout do not based on [0, 0]
  56962. var contentPos = [-contentRect.x, -contentRect.y];
  56963. // Remain contentPos when scroll animation perfroming.
  56964. // If first rendering, `contentGroup.position` is [0, 0], which
  56965. // does not make sense and may cause unexepcted animation if adopted.
  56966. if (!isFirstRender) {
  56967. contentPos[orientIdx] = contentGroup[xy];
  56968. }
  56969. // Layout container group based on 0.
  56970. var containerPos = [0, 0];
  56971. var controllerPos = [-controllerRect.x, -controllerRect.y];
  56972. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true));
  56973. // Place containerGroup and controllerGroup and contentGroup.
  56974. if (showController) {
  56975. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  56976. // controller is on the right / bottom.
  56977. if (pageButtonPosition === 'end') {
  56978. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  56979. }
  56980. // controller is on the left / top.
  56981. else {
  56982. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  56983. }
  56984. }
  56985. // Always align controller to content as 'middle'.
  56986. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  56987. contentGroup.setPosition(contentPos);
  56988. containerGroup.setPosition(containerPos);
  56989. controllerGroup.setPosition(controllerPos);
  56990. // Calculate `mainRect` and set `clipPath`.
  56991. // mainRect should not be calculated by `this.group.getBoundingRect()`
  56992. // for sake of the overflow.
  56993. var mainRect = {
  56994. x: 0,
  56995. y: 0
  56996. };
  56997. // Consider content may be overflow (should be clipped).
  56998. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  56999. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  57000. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  57001. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  57002. containerGroup.__rectSize = maxSize[wh];
  57003. if (showController) {
  57004. var clipShape = {
  57005. x: 0,
  57006. y: 0
  57007. };
  57008. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  57009. clipShape[hw] = mainRect[hw];
  57010. containerGroup.setClipPath(new Rect({
  57011. shape: clipShape
  57012. }));
  57013. // Consider content may be larger than container, container rect
  57014. // can not be obtained from `containerGroup.getBoundingRect()`.
  57015. containerGroup.__rectSize = clipShape[wh];
  57016. } else {
  57017. // Do not remove or ignore controller. Keep them set as placeholders.
  57018. controllerGroup.eachChild(function (child) {
  57019. child.attr({
  57020. invisible: true,
  57021. silent: true
  57022. });
  57023. });
  57024. }
  57025. // Content translate animation.
  57026. var pageInfo = this._getPageInfo(legendModel);
  57027. pageInfo.pageIndex != null && updateProps(contentGroup, {
  57028. x: pageInfo.contentPosition[0],
  57029. y: pageInfo.contentPosition[1]
  57030. },
  57031. // When switch from "show controller" to "not show controller", view should be
  57032. // updated immediately without animation, otherwise causes weird effect.
  57033. showController ? legendModel : null);
  57034. this._updatePageInfoView(legendModel, pageInfo);
  57035. return mainRect;
  57036. };
  57037. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  57038. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  57039. scrollDataIndex != null && api.dispatchAction({
  57040. type: 'legendScroll',
  57041. scrollDataIndex: scrollDataIndex,
  57042. legendId: legendModel.id
  57043. });
  57044. };
  57045. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  57046. var controllerGroup = this._controllerGroup;
  57047. each(['pagePrev', 'pageNext'], function (name) {
  57048. var key = name + 'DataIndex';
  57049. var canJump = pageInfo[key] != null;
  57050. var icon = controllerGroup.childOfName(name);
  57051. if (icon) {
  57052. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  57053. icon.cursor = canJump ? 'pointer' : 'default';
  57054. }
  57055. });
  57056. var pageText = controllerGroup.childOfName('pageText');
  57057. var pageFormatter = legendModel.get('pageFormatter');
  57058. var pageIndex = pageInfo.pageIndex;
  57059. var current = pageIndex != null ? pageIndex + 1 : 0;
  57060. var total = pageInfo.pageCount;
  57061. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  57062. current: current,
  57063. total: total
  57064. }));
  57065. };
  57066. /**
  57067. * contentPosition: Array.<number>, null when data item not found.
  57068. * pageIndex: number, null when data item not found.
  57069. * pageCount: number, always be a number, can be 0.
  57070. * pagePrevDataIndex: number, null when no previous page.
  57071. * pageNextDataIndex: number, null when no next page.
  57072. * }
  57073. */
  57074. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  57075. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  57076. var contentGroup = this.getContentGroup();
  57077. var containerRectSize = this._containerGroup.__rectSize;
  57078. var orientIdx = legendModel.getOrient().index;
  57079. var wh = WH$2[orientIdx];
  57080. var xy = XY$2[orientIdx];
  57081. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  57082. var children = contentGroup.children();
  57083. var targetItem = children[targetItemIndex];
  57084. var itemCount = children.length;
  57085. var pCount = !itemCount ? 0 : 1;
  57086. var result = {
  57087. contentPosition: [contentGroup.x, contentGroup.y],
  57088. pageCount: pCount,
  57089. pageIndex: pCount - 1,
  57090. pagePrevDataIndex: null,
  57091. pageNextDataIndex: null
  57092. };
  57093. if (!targetItem) {
  57094. return result;
  57095. }
  57096. var targetItemInfo = getItemInfo(targetItem);
  57097. result.contentPosition[orientIdx] = -targetItemInfo.s;
  57098. // Strategy:
  57099. // (1) Always align based on the left/top most item.
  57100. // (2) It is user-friendly that the last item shown in the
  57101. // current window is shown at the begining of next window.
  57102. // Otherwise if half of the last item is cut by the window,
  57103. // it will have no chance to display entirely.
  57104. // (3) Consider that item size probably be different, we
  57105. // have calculate pageIndex by size rather than item index,
  57106. // and we can not get page index directly by division.
  57107. // (4) The window is to narrow to contain more than
  57108. // one item, we should make sure that the page can be fliped.
  57109. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  57110. currItemInfo = getItemInfo(children[i]);
  57111. if (
  57112. // Half of the last item is out of the window.
  57113. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize
  57114. // If the current item does not intersect with the window, the new page
  57115. // can be started at the current item or the last item.
  57116. || currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  57117. if (winEndItemInfo.i > winStartItemInfo.i) {
  57118. winStartItemInfo = winEndItemInfo;
  57119. } else {
  57120. // e.g., when page size is smaller than item size.
  57121. winStartItemInfo = currItemInfo;
  57122. }
  57123. if (winStartItemInfo) {
  57124. if (result.pageNextDataIndex == null) {
  57125. result.pageNextDataIndex = winStartItemInfo.i;
  57126. }
  57127. ++result.pageCount;
  57128. }
  57129. }
  57130. winEndItemInfo = currItemInfo;
  57131. }
  57132. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  57133. currItemInfo = getItemInfo(children[i]);
  57134. if (
  57135. // If the the end item does not intersect with the window started
  57136. // from the current item, a page can be settled.
  57137. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)
  57138. // e.g., when page size is smaller than item size.
  57139. ) && winStartItemInfo.i < winEndItemInfo.i) {
  57140. winEndItemInfo = winStartItemInfo;
  57141. if (result.pagePrevDataIndex == null) {
  57142. result.pagePrevDataIndex = winStartItemInfo.i;
  57143. }
  57144. ++result.pageCount;
  57145. ++result.pageIndex;
  57146. }
  57147. winStartItemInfo = currItemInfo;
  57148. }
  57149. return result;
  57150. function getItemInfo(el) {
  57151. if (el) {
  57152. var itemRect = el.getBoundingRect();
  57153. var start = itemRect[xy] + el[xy];
  57154. return {
  57155. s: start,
  57156. e: start + itemRect[wh],
  57157. i: el.__legendDataIndex
  57158. };
  57159. }
  57160. }
  57161. function intersect(itemInfo, winStart) {
  57162. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  57163. }
  57164. };
  57165. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  57166. if (!this._showController) {
  57167. return 0;
  57168. }
  57169. var index;
  57170. var contentGroup = this.getContentGroup();
  57171. var defaultIndex;
  57172. contentGroup.eachChild(function (child, idx) {
  57173. var legendDataIdx = child.__legendDataIndex;
  57174. // FIXME
  57175. // If the given targetDataIndex (from model) is illegal,
  57176. // we use defaultIndex. But the index on the legend model and
  57177. // action payload is still illegal. That case will not be
  57178. // changed until some scenario requires.
  57179. if (defaultIndex == null && legendDataIdx != null) {
  57180. defaultIndex = idx;
  57181. }
  57182. if (legendDataIdx === targetDataIndex) {
  57183. index = idx;
  57184. }
  57185. });
  57186. return index != null ? index : defaultIndex;
  57187. };
  57188. ScrollableLegendView.type = 'legend.scroll';
  57189. return ScrollableLegendView;
  57190. }(LegendView);
  57191. /*
  57192. * Licensed to the Apache Software Foundation (ASF) under one
  57193. * or more contributor license agreements. See the NOTICE file
  57194. * distributed with this work for additional information
  57195. * regarding copyright ownership. The ASF licenses this file
  57196. * to you under the Apache License, Version 2.0 (the
  57197. * "License"); you may not use this file except in compliance
  57198. * with the License. You may obtain a copy of the License at
  57199. *
  57200. * http://www.apache.org/licenses/LICENSE-2.0
  57201. *
  57202. * Unless required by applicable law or agreed to in writing,
  57203. * software distributed under the License is distributed on an
  57204. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57205. * KIND, either express or implied. See the License for the
  57206. * specific language governing permissions and limitations
  57207. * under the License.
  57208. */
  57209. /**
  57210. * AUTO-GENERATED FILE. DO NOT MODIFY.
  57211. */
  57212. /*
  57213. * Licensed to the Apache Software Foundation (ASF) under one
  57214. * or more contributor license agreements. See the NOTICE file
  57215. * distributed with this work for additional information
  57216. * regarding copyright ownership. The ASF licenses this file
  57217. * to you under the Apache License, Version 2.0 (the
  57218. * "License"); you may not use this file except in compliance
  57219. * with the License. You may obtain a copy of the License at
  57220. *
  57221. * http://www.apache.org/licenses/LICENSE-2.0
  57222. *
  57223. * Unless required by applicable law or agreed to in writing,
  57224. * software distributed under the License is distributed on an
  57225. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57226. * KIND, either express or implied. See the License for the
  57227. * specific language governing permissions and limitations
  57228. * under the License.
  57229. */
  57230. function installScrollableLegendAction(registers) {
  57231. /**
  57232. * @event legendScroll
  57233. * @type {Object}
  57234. * @property {string} type 'legendScroll'
  57235. * @property {string} scrollDataIndex
  57236. */
  57237. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  57238. var scrollDataIndex = payload.scrollDataIndex;
  57239. scrollDataIndex != null && ecModel.eachComponent({
  57240. mainType: 'legend',
  57241. subType: 'scroll',
  57242. query: payload
  57243. }, function (legendModel) {
  57244. legendModel.setScrollDataIndex(scrollDataIndex);
  57245. });
  57246. });
  57247. }
  57248. function install$i(registers) {
  57249. use(install$h);
  57250. registers.registerComponentModel(ScrollableLegendModel);
  57251. registers.registerComponentView(ScrollableLegendView);
  57252. installScrollableLegendAction(registers);
  57253. }
  57254. function install$j(registers) {
  57255. use(install$h);
  57256. use(install$i);
  57257. }
  57258. var InsideZoomModel = /** @class */function (_super) {
  57259. __extends(InsideZoomModel, _super);
  57260. function InsideZoomModel() {
  57261. var _this = _super !== null && _super.apply(this, arguments) || this;
  57262. _this.type = InsideZoomModel.type;
  57263. return _this;
  57264. }
  57265. InsideZoomModel.type = 'dataZoom.inside';
  57266. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  57267. disabled: false,
  57268. zoomLock: false,
  57269. zoomOnMouseWheel: true,
  57270. moveOnMouseMove: true,
  57271. moveOnMouseWheel: false,
  57272. preventDefaultMouseMove: true
  57273. });
  57274. return InsideZoomModel;
  57275. }(DataZoomModel);
  57276. /**
  57277. * An manager of zoom and pan(darg) hehavior.
  57278. * But it is not responsible for updating the view, since view updates vary and can
  57279. * not be handled in a uniform way.
  57280. *
  57281. * Note: regarding view updates:
  57282. * - Transformabe views typically use `coord/View` (e.g., geo and series.graph roaming).
  57283. * Some commonly used view update logic has been organized into `roamHelper.ts`.
  57284. * - Non-transformable views handle updates themselves, possibly involving re-layout,
  57285. * (e.g., treemap).
  57286. * - Some scenarios do not require transformation (e.g., dataZoom roaming for cartesian,
  57287. * brush component).
  57288. */
  57289. var RoamController = /** @class */function (_super) {
  57290. __extends(RoamController, _super);
  57291. function RoamController(zr) {
  57292. var _this = _super.call(this) || this;
  57293. _this._zr = zr;
  57294. // Avoid two roamController bind the same handler
  57295. var mousedownHandler = bind(_this._mousedownHandler, _this);
  57296. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  57297. var mouseupHandler = bind(_this._mouseupHandler, _this);
  57298. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  57299. var pinchHandler = bind(_this._pinchHandler, _this);
  57300. /**
  57301. * Notice:
  57302. * - only enable needed types. For example, if 'zoom'
  57303. * is not needed, 'zoom' should not be enabled, otherwise
  57304. * default mousewheel behaviour (scroll page) will be disabled.
  57305. * - This method is idempotent.
  57306. */
  57307. _this.enable = function (controlType, rawOpt) {
  57308. var zInfo = rawOpt.zInfo;
  57309. var _a = retrieveZInfo(zInfo.component),
  57310. z = _a.z,
  57311. zlevel = _a.zlevel;
  57312. var zInfoParsed = {
  57313. component: zInfo.component,
  57314. z: z,
  57315. zlevel: zlevel,
  57316. // By default roam controller is the lowest z2 comparing to other elememts in a component.
  57317. z2: retrieve2(zInfo.z2, -Infinity)
  57318. };
  57319. var triggerInfo = extend({}, rawOpt.triggerInfo);
  57320. this._opt = defaults(extend({}, rawOpt), {
  57321. zoomOnMouseWheel: true,
  57322. moveOnMouseMove: true,
  57323. // By default, wheel do not trigger move.
  57324. moveOnMouseWheel: false,
  57325. preventDefaultMouseMove: true,
  57326. zInfoParsed: zInfoParsed,
  57327. triggerInfo: triggerInfo
  57328. });
  57329. if (controlType == null) {
  57330. controlType = true;
  57331. }
  57332. // A handy optimization for repeatedly calling `enable` during roaming.
  57333. // Assert `disable` is only affected by `controlType`.
  57334. if (!this._enabled || this._controlType !== controlType) {
  57335. this._enabled = true;
  57336. // Disable previous first
  57337. this.disable();
  57338. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  57339. addRoamZrListener(zr, 'mousedown', mousedownHandler, zInfoParsed);
  57340. addRoamZrListener(zr, 'mousemove', mousemoveHandler, zInfoParsed);
  57341. addRoamZrListener(zr, 'mouseup', mouseupHandler, zInfoParsed);
  57342. }
  57343. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  57344. addRoamZrListener(zr, 'mousewheel', mousewheelHandler, zInfoParsed);
  57345. addRoamZrListener(zr, 'pinch', pinchHandler, zInfoParsed);
  57346. }
  57347. }
  57348. };
  57349. _this.disable = function () {
  57350. this._enabled = false;
  57351. removeRoamZrListener(zr, 'mousedown', mousedownHandler);
  57352. removeRoamZrListener(zr, 'mousemove', mousemoveHandler);
  57353. removeRoamZrListener(zr, 'mouseup', mouseupHandler);
  57354. removeRoamZrListener(zr, 'mousewheel', mousewheelHandler);
  57355. removeRoamZrListener(zr, 'pinch', pinchHandler);
  57356. };
  57357. return _this;
  57358. }
  57359. RoamController.prototype.isDragging = function () {
  57360. return this._dragging;
  57361. };
  57362. RoamController.prototype.isPinching = function () {
  57363. return this._pinching;
  57364. };
  57365. RoamController.prototype._checkPointer = function (e, x, y) {
  57366. var opt = this._opt;
  57367. var zInfoParsed = opt.zInfoParsed;
  57368. if (onIrrelevantElement(e, opt.api, zInfoParsed.component)) {
  57369. return false;
  57370. }
  57371. var triggerInfo = opt.triggerInfo;
  57372. var roamTrigger = triggerInfo.roamTrigger;
  57373. var inArea = false;
  57374. if (roamTrigger === 'global') {
  57375. inArea = true;
  57376. }
  57377. if (!inArea) {
  57378. inArea = triggerInfo.isInSelf(e, x, y);
  57379. }
  57380. if (inArea && triggerInfo.isInClip && !triggerInfo.isInClip(e, x, y)) {
  57381. inArea = false;
  57382. }
  57383. return inArea;
  57384. };
  57385. RoamController.prototype._decideCursorStyle = function (e, x, y, forReverse) {
  57386. // If this cursor style decision is not strictly consistent with zrender,
  57387. // it's fine - zr will set the cursor on the next mousemove.
  57388. // This `grab` cursor style should take the lowest precedence. If the hovring element already
  57389. // have a cursor, zrender will set it to be non-'default' before entering this handler.
  57390. // (note, e.target is never silent, e.topTarget can be silent be irrelevant.)
  57391. var target = e.target;
  57392. if (!target && this._checkPointer(e, x, y)) {
  57393. // To indicate users that this area is draggable, otherwise users probably cannot kwown
  57394. // that when hovering out of the shape but still inside the bounding rect.
  57395. return 'grab';
  57396. }
  57397. if (forReverse) {
  57398. return target && target.cursor || 'default';
  57399. }
  57400. };
  57401. RoamController.prototype.dispose = function () {
  57402. this.disable();
  57403. };
  57404. RoamController.prototype._mousedownHandler = function (e) {
  57405. if (isMiddleOrRightButtonOnMouseUpDown(e) || eventConsumed(e)) {
  57406. return;
  57407. }
  57408. var el = e.target;
  57409. while (el) {
  57410. if (el.draggable) {
  57411. return;
  57412. }
  57413. // check if host is draggable
  57414. el = el.__hostTarget || el.parent;
  57415. }
  57416. var x = e.offsetX;
  57417. var y = e.offsetY;
  57418. // To determine dragging start, only by checking on mosedown, but not mousemove.
  57419. // Mouse can be out of target when mouse moving.
  57420. if (this._checkPointer(e, x, y)) {
  57421. this._x = x;
  57422. this._y = y;
  57423. this._dragging = true;
  57424. }
  57425. };
  57426. RoamController.prototype._mousemoveHandler = function (e) {
  57427. var zr = this._zr;
  57428. if (e.gestureEvent === 'pinch' || isTaken(zr, 'globalPan') || eventConsumed(e)) {
  57429. return;
  57430. }
  57431. var x = e.offsetX;
  57432. var y = e.offsetY;
  57433. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt)) {
  57434. var cursorStyle = this._decideCursorStyle(e, x, y, false);
  57435. if (cursorStyle) {
  57436. zr.setCursorStyle(cursorStyle);
  57437. }
  57438. return;
  57439. }
  57440. zr.setCursorStyle('grabbing');
  57441. var oldX = this._x;
  57442. var oldY = this._y;
  57443. var dx = x - oldX;
  57444. var dy = y - oldY;
  57445. this._x = x;
  57446. this._y = y;
  57447. if (this._opt.preventDefaultMouseMove) {
  57448. stop(e.event);
  57449. }
  57450. e.__ecRoamConsumed = true;
  57451. trigger$1(this, 'pan', 'moveOnMouseMove', e, {
  57452. dx: dx,
  57453. dy: dy,
  57454. oldX: oldX,
  57455. oldY: oldY,
  57456. newX: x,
  57457. newY: y,
  57458. isAvailableBehavior: null
  57459. });
  57460. };
  57461. RoamController.prototype._mouseupHandler = function (e) {
  57462. if (eventConsumed(e)) {
  57463. return;
  57464. }
  57465. var zr = this._zr;
  57466. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  57467. this._dragging = false;
  57468. var cursorStyle = this._decideCursorStyle(e, e.offsetX, e.offsetY, true);
  57469. if (cursorStyle) {
  57470. zr.setCursorStyle(cursorStyle);
  57471. }
  57472. }
  57473. };
  57474. RoamController.prototype._mousewheelHandler = function (e) {
  57475. if (eventConsumed(e)) {
  57476. return;
  57477. }
  57478. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  57479. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  57480. var wheelDelta = e.wheelDelta;
  57481. var absWheelDeltaDelta = Math.abs(wheelDelta);
  57482. var originX = e.offsetX;
  57483. var originY = e.offsetY;
  57484. // wheelDelta maybe -0 in chrome mac.
  57485. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  57486. return;
  57487. }
  57488. // If both `shouldZoom` and `shouldMove` is true, trigger
  57489. // their event both, and the final behavior is determined
  57490. // by event listener themselves.
  57491. if (shouldZoom) {
  57492. // Convenience:
  57493. // Mac and VM Windows on Mac: scroll up: zoom out.
  57494. // Windows: scroll up: zoom in.
  57495. // FIXME: Should do more test in different environment.
  57496. // wheelDelta is too complicated in difference nvironment
  57497. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  57498. // although it has been normallized by zrender.
  57499. // wheelDelta of mouse wheel is bigger than touch pad.
  57500. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  57501. var scale = wheelDelta > 0 ? factor : 1 / factor;
  57502. this._checkTriggerMoveZoom(this, 'zoom', 'zoomOnMouseWheel', e, {
  57503. scale: scale,
  57504. originX: originX,
  57505. originY: originY,
  57506. isAvailableBehavior: null
  57507. });
  57508. }
  57509. if (shouldMove) {
  57510. // FIXME: Should do more test in different environment.
  57511. var absDelta = Math.abs(wheelDelta);
  57512. // wheelDelta of mouse wheel is bigger than touch pad.
  57513. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  57514. this._checkTriggerMoveZoom(this, 'scrollMove', 'moveOnMouseWheel', e, {
  57515. scrollDelta: scrollDelta,
  57516. originX: originX,
  57517. originY: originY,
  57518. isAvailableBehavior: null
  57519. });
  57520. }
  57521. };
  57522. RoamController.prototype._pinchHandler = function (e) {
  57523. if (isTaken(this._zr, 'globalPan') || eventConsumed(e)) {
  57524. return;
  57525. }
  57526. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  57527. this._checkTriggerMoveZoom(this, 'zoom', null, e, {
  57528. scale: scale,
  57529. originX: e.pinchX,
  57530. originY: e.pinchY,
  57531. isAvailableBehavior: null
  57532. });
  57533. };
  57534. RoamController.prototype._checkTriggerMoveZoom = function (controller, eventName, behaviorToCheck, e, contollerEvent) {
  57535. if (controller._checkPointer(e, contollerEvent.originX, contollerEvent.originY)) {
  57536. // When mouse is out of roamController rect,
  57537. // default befavoius should not be be disabled, otherwise
  57538. // page sliding is disabled, contrary to expectation.
  57539. stop(e.event);
  57540. e.__ecRoamConsumed = true;
  57541. trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent);
  57542. }
  57543. };
  57544. return RoamController;
  57545. }(Eventful);
  57546. function eventConsumed(e) {
  57547. return e.__ecRoamConsumed;
  57548. }
  57549. var innerZrStore = makeInner();
  57550. function ensureZrStore(zr) {
  57551. var store = innerZrStore(zr);
  57552. store.roam = store.roam || {};
  57553. store.uniform = store.uniform || {};
  57554. return store;
  57555. }
  57556. /**
  57557. * Listeners are sorted by z2/z/zlevel in descending order.
  57558. * This decides the precedence between different roam controllers if they are overlapped.
  57559. *
  57560. * [MEMO]: It's not easy to perfectly reconcile the conflicts caused by overlap.
  57561. * - Consider cases:
  57562. * - Multiple roam controllers overlapped.
  57563. * - Usually only the topmost can trigger roam.
  57564. * - Roam controllers overlap with other zr elements:
  57565. * - zr elements are relevant or irrelevent to the host of the roam controller. e.g., axis split line
  57566. * or series elements is relevant to a cartesian and should trigger roam.
  57567. * - zr elements is above or below the roam controller host, which affects the precedence of interaction.
  57568. * - zr elements may not silent only for triggering tooltip by hovering, which is available to roam;
  57569. * or may not silent for click, where roam is not preferable.
  57570. * - Approach - `addRoamZrListener+pointerChecker+onIrrelevantElement` (currently used):
  57571. * - Resolve the precedence between different roam controllers
  57572. * - But cannot prevent the handling on other zr elements that under the roam controller in z-order.
  57573. * - Approach - "use an invisible zr elements to receive the zr events to trigger roam":
  57574. * - More complicated in impl.
  57575. * - May cause bad cases where zr event cannot be receive due to other non-silient zr elements covering it.
  57576. */
  57577. function addRoamZrListener(zr, eventType, listener, zInfoParsed) {
  57578. var store = ensureZrStore(zr);
  57579. var roam = store.roam;
  57580. var listenerList = roam[eventType] = roam[eventType] || [];
  57581. var idx = 0;
  57582. for (; idx < listenerList.length; idx++) {
  57583. var currZInfo = listenerList[idx].zInfoParsed;
  57584. if ((currZInfo.zlevel - zInfoParsed.zlevel || currZInfo.z - zInfoParsed.z || currZInfo.z2 - zInfoParsed.z2
  57585. // If all equals, the latter added one has a higher precedence.
  57586. ) <= 0) {
  57587. break;
  57588. }
  57589. }
  57590. listenerList.splice(idx, 0, {
  57591. listener: listener,
  57592. zInfoParsed: zInfoParsed
  57593. });
  57594. ensureUniformListener(zr, eventType);
  57595. }
  57596. function removeRoamZrListener(zr, eventType, listener) {
  57597. var store = ensureZrStore(zr);
  57598. var listenerList = store.roam[eventType] || [];
  57599. for (var idx = 0; idx < listenerList.length; idx++) {
  57600. if (listenerList[idx].listener === listener) {
  57601. listenerList.splice(idx, 1);
  57602. if (!listenerList.length) {
  57603. removeUniformListener(zr, eventType);
  57604. }
  57605. return;
  57606. }
  57607. }
  57608. }
  57609. function ensureUniformListener(zr, eventType) {
  57610. var store = ensureZrStore(zr);
  57611. if (!store.uniform[eventType]) {
  57612. zr.on(eventType, store.uniform[eventType] = function (event) {
  57613. var listenerList = store.roam[eventType];
  57614. if (listenerList) {
  57615. for (var i = 0; i < listenerList.length; i++) {
  57616. listenerList[i].listener(event);
  57617. }
  57618. }
  57619. });
  57620. }
  57621. }
  57622. function removeUniformListener(zr, eventType) {
  57623. var store = ensureZrStore(zr);
  57624. var uniform = store.uniform;
  57625. if (uniform[eventType]) {
  57626. zr.off(eventType, uniform[eventType]);
  57627. uniform[eventType] = null;
  57628. }
  57629. }
  57630. function trigger$1(controller, eventName, behaviorToCheck, e, contollerEvent) {
  57631. // Also provide behavior checker for event listener, for some case that
  57632. // multiple components share one listener.
  57633. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  57634. // TODO should not have type issue.
  57635. controller.trigger(eventName, contollerEvent);
  57636. }
  57637. // settings: {
  57638. // zoomOnMouseWheel
  57639. // moveOnMouseMove
  57640. // moveOnMouseWheel
  57641. // }
  57642. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  57643. function isAvailableBehavior(behaviorToCheck, e, settings) {
  57644. var setting = settings[behaviorToCheck];
  57645. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  57646. }
  57647. var inner$g = makeInner();
  57648. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  57649. inner$g(api).coordSysRecordMap.each(function (coordSysRecord) {
  57650. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  57651. if (dzInfo) {
  57652. dzInfo.getRange = getRange;
  57653. }
  57654. });
  57655. }
  57656. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  57657. var coordSysRecordMap = inner$g(api).coordSysRecordMap;
  57658. var coordSysKeyArr = coordSysRecordMap.keys();
  57659. for (var i = 0; i < coordSysKeyArr.length; i++) {
  57660. var coordSysKey = coordSysKeyArr[i];
  57661. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  57662. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  57663. if (dataZoomInfoMap) {
  57664. var dzUid = dataZoomModel.uid;
  57665. var dzInfo = dataZoomInfoMap.get(dzUid);
  57666. if (dzInfo) {
  57667. dataZoomInfoMap.removeKey(dzUid);
  57668. if (!dataZoomInfoMap.keys().length) {
  57669. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  57670. }
  57671. }
  57672. }
  57673. }
  57674. }
  57675. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  57676. if (coordSysRecord) {
  57677. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  57678. var controller = coordSysRecord.controller;
  57679. controller && controller.dispose();
  57680. }
  57681. }
  57682. function createCoordSysRecord(api, coordSysModel) {
  57683. // These init props will never change after record created.
  57684. var coordSysRecord = {
  57685. model: coordSysModel,
  57686. containsPoint: curry(containsPoint, coordSysModel),
  57687. dispatchAction: curry(dispatchAction, api),
  57688. dataZoomInfoMap: null,
  57689. controller: null
  57690. };
  57691. // Must not do anything depends on coordSysRecord outside the event handler here,
  57692. // because coordSysRecord not completed yet.
  57693. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  57694. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  57695. controller.on(eventName, function (event) {
  57696. var batch = [];
  57697. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  57698. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  57699. // moveOnMouseWheel, ...) enabled.
  57700. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  57701. return;
  57702. }
  57703. var method = (dzInfo.getRange || {})[eventName];
  57704. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  57705. !dzInfo.model.get('disabled', true) && range && batch.push({
  57706. dataZoomId: dzInfo.model.id,
  57707. start: range[0],
  57708. end: range[1]
  57709. });
  57710. });
  57711. batch.length && coordSysRecord.dispatchAction(batch);
  57712. });
  57713. });
  57714. return coordSysRecord;
  57715. }
  57716. /**
  57717. * This action will be throttled.
  57718. */
  57719. function dispatchAction(api, batch) {
  57720. if (!api.isDisposed()) {
  57721. api.dispatchAction({
  57722. type: 'dataZoom',
  57723. animation: {
  57724. easing: 'cubicOut',
  57725. duration: 100
  57726. },
  57727. batch: batch
  57728. });
  57729. }
  57730. }
  57731. function containsPoint(coordSysModel, e, x, y) {
  57732. return coordSysModel.coordinateSystem.containPoint([x, y]);
  57733. }
  57734. /**
  57735. * Merge roamController settings when multiple dataZooms share one roamController.
  57736. */
  57737. function mergeControllerParams(dataZoomInfoMap, coordSysRecord, api) {
  57738. var controlType;
  57739. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  57740. // as string, it is probably revert to reserved word by compress tool. See #7411.
  57741. var prefix = 'type_';
  57742. var typePriority = {
  57743. 'type_true': 2,
  57744. 'type_move': 1,
  57745. 'type_false': 0,
  57746. 'type_undefined': -1
  57747. };
  57748. var preventDefaultMouseMove = true;
  57749. dataZoomInfoMap.each(function (dataZoomInfo) {
  57750. var dataZoomModel = dataZoomInfo.model;
  57751. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  57752. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  57753. controlType = oneType;
  57754. }
  57755. // Prevent default move event by default. If one false, do not prevent. Otherwise
  57756. // users may be confused why it does not work when multiple insideZooms exist.
  57757. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  57758. });
  57759. return {
  57760. controlType: controlType,
  57761. opt: {
  57762. // RoamController will enable all of these functionalities,
  57763. // and the final behavior is determined by its event listener
  57764. // provided by each inside zoom.
  57765. zoomOnMouseWheel: true,
  57766. moveOnMouseMove: true,
  57767. moveOnMouseWheel: true,
  57768. preventDefaultMouseMove: !!preventDefaultMouseMove,
  57769. api: api,
  57770. zInfo: {
  57771. component: coordSysRecord.model
  57772. },
  57773. triggerInfo: {
  57774. roamTrigger: null,
  57775. isInSelf: coordSysRecord.containsPoint
  57776. }
  57777. }
  57778. };
  57779. }
  57780. function installDataZoomRoamProcessor(registers) {
  57781. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  57782. var apiInner = inner$g(api);
  57783. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  57784. coordSysRecordMap.each(function (coordSysRecord) {
  57785. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  57786. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  57787. coordSysRecord.dataZoomInfoMap = null;
  57788. });
  57789. ecModel.eachComponent({
  57790. mainType: 'dataZoom',
  57791. subType: 'inside'
  57792. }, function (dataZoomModel) {
  57793. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  57794. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  57795. var coordSysUid = dzCoordSysInfo.model.uid;
  57796. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  57797. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap());
  57798. // Notice these props might be changed each time for a single dataZoomModel.
  57799. dataZoomInfoMap.set(dataZoomModel.uid, {
  57800. dzReferCoordSysInfo: dzCoordSysInfo,
  57801. model: dataZoomModel,
  57802. getRange: null
  57803. });
  57804. });
  57805. });
  57806. // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  57807. // (2) Clear coord sys if not refered by any dataZoom.
  57808. coordSysRecordMap.each(function (coordSysRecord) {
  57809. var controller = coordSysRecord.controller;
  57810. var firstDzInfo;
  57811. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  57812. if (dataZoomInfoMap) {
  57813. var firstDzKey = dataZoomInfoMap.keys()[0];
  57814. if (firstDzKey != null) {
  57815. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  57816. }
  57817. }
  57818. if (!firstDzInfo) {
  57819. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  57820. return;
  57821. }
  57822. var controllerParams = mergeControllerParams(dataZoomInfoMap, coordSysRecord, api);
  57823. controller.enable(controllerParams.controlType, controllerParams.opt);
  57824. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  57825. });
  57826. });
  57827. }
  57828. var InsideZoomView = /** @class */function (_super) {
  57829. __extends(InsideZoomView, _super);
  57830. function InsideZoomView() {
  57831. var _this = _super !== null && _super.apply(this, arguments) || this;
  57832. _this.type = 'dataZoom.inside';
  57833. return _this;
  57834. }
  57835. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  57836. _super.prototype.render.apply(this, arguments);
  57837. if (dataZoomModel.noTarget()) {
  57838. this._clear();
  57839. return;
  57840. }
  57841. // Hence the `throttle` util ensures to preserve command order,
  57842. // here simply updating range all the time will not cause missing
  57843. // any of the the roam change.
  57844. this.range = dataZoomModel.getPercentRange();
  57845. // Reset controllers.
  57846. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  57847. pan: bind(getRangeHandlers.pan, this),
  57848. zoom: bind(getRangeHandlers.zoom, this),
  57849. scrollMove: bind(getRangeHandlers.scrollMove, this)
  57850. });
  57851. };
  57852. InsideZoomView.prototype.dispose = function () {
  57853. this._clear();
  57854. _super.prototype.dispose.apply(this, arguments);
  57855. };
  57856. InsideZoomView.prototype._clear = function () {
  57857. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  57858. this.range = null;
  57859. };
  57860. InsideZoomView.type = 'dataZoom.inside';
  57861. return InsideZoomView;
  57862. }(DataZoomView);
  57863. var getRangeHandlers = {
  57864. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  57865. var lastRange = this.range;
  57866. var range = lastRange.slice();
  57867. // Calculate transform by the first axis.
  57868. var axisModel = coordSysInfo.axisModels[0];
  57869. if (!axisModel) {
  57870. return;
  57871. }
  57872. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  57873. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  57874. var scale = Math.max(1 / e.scale, 0);
  57875. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  57876. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  57877. // Restrict range.
  57878. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  57879. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  57880. this.range = range;
  57881. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  57882. return range;
  57883. }
  57884. },
  57885. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  57886. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  57887. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  57888. }),
  57889. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  57890. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  57891. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  57892. })
  57893. };
  57894. function makeMover(getPercentDelta) {
  57895. return function (coordSysInfo, coordSysMainType, controller, e) {
  57896. var lastRange = this.range;
  57897. var range = lastRange.slice();
  57898. // Calculate transform by the first axis.
  57899. var axisModel = coordSysInfo.axisModels[0];
  57900. if (!axisModel) {
  57901. return;
  57902. }
  57903. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  57904. sliderMove(percentDelta, range, [0, 100], 'all');
  57905. this.range = range;
  57906. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  57907. return range;
  57908. }
  57909. };
  57910. }
  57911. var getDirectionInfo = {
  57912. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  57913. var axis = axisModel.axis;
  57914. var ret = {};
  57915. var rect = coordSysInfo.model.coordinateSystem.getRect();
  57916. oldPoint = oldPoint || [0, 0];
  57917. if (axis.dim === 'x') {
  57918. ret.pixel = newPoint[0] - oldPoint[0];
  57919. ret.pixelLength = rect.width;
  57920. ret.pixelStart = rect.x;
  57921. ret.signal = axis.inverse ? 1 : -1;
  57922. } else {
  57923. // axis.dim === 'y'
  57924. ret.pixel = newPoint[1] - oldPoint[1];
  57925. ret.pixelLength = rect.height;
  57926. ret.pixelStart = rect.y;
  57927. ret.signal = axis.inverse ? -1 : 1;
  57928. }
  57929. return ret;
  57930. },
  57931. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  57932. var axis = axisModel.axis;
  57933. var ret = {};
  57934. var polar = coordSysInfo.model.coordinateSystem;
  57935. var radiusExtent = polar.getRadiusAxis().getExtent();
  57936. var angleExtent = polar.getAngleAxis().getExtent();
  57937. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  57938. newPoint = polar.pointToCoord(newPoint);
  57939. if (axisModel.mainType === 'radiusAxis') {
  57940. ret.pixel = newPoint[0] - oldPoint[0];
  57941. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  57942. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  57943. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  57944. ret.pixelStart = radiusExtent[0];
  57945. ret.signal = axis.inverse ? 1 : -1;
  57946. } else {
  57947. // 'angleAxis'
  57948. ret.pixel = newPoint[1] - oldPoint[1];
  57949. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  57950. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  57951. ret.pixelLength = angleExtent[1] - angleExtent[0];
  57952. ret.pixelStart = angleExtent[0];
  57953. ret.signal = axis.inverse ? -1 : 1;
  57954. }
  57955. return ret;
  57956. },
  57957. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  57958. var axis = axisModel.axis;
  57959. var rect = coordSysInfo.model.coordinateSystem.getRect();
  57960. var ret = {};
  57961. oldPoint = oldPoint || [0, 0];
  57962. if (axis.orient === 'horizontal') {
  57963. ret.pixel = newPoint[0] - oldPoint[0];
  57964. ret.pixelLength = rect.width;
  57965. ret.pixelStart = rect.x;
  57966. ret.signal = axis.inverse ? 1 : -1;
  57967. } else {
  57968. // 'vertical'
  57969. ret.pixel = newPoint[1] - oldPoint[1];
  57970. ret.pixelLength = rect.height;
  57971. ret.pixelStart = rect.y;
  57972. ret.signal = axis.inverse ? -1 : 1;
  57973. }
  57974. return ret;
  57975. }
  57976. };
  57977. function install$k(registers) {
  57978. installCommon(registers);
  57979. registers.registerComponentModel(InsideZoomModel);
  57980. registers.registerComponentView(InsideZoomView);
  57981. installDataZoomRoamProcessor(registers);
  57982. }
  57983. var SliderZoomModel = /** @class */function (_super) {
  57984. __extends(SliderZoomModel, _super);
  57985. function SliderZoomModel() {
  57986. var _this = _super !== null && _super.apply(this, arguments) || this;
  57987. _this.type = SliderZoomModel.type;
  57988. return _this;
  57989. }
  57990. SliderZoomModel.type = 'dataZoom.slider';
  57991. SliderZoomModel.layoutMode = 'box';
  57992. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  57993. show: true,
  57994. // deault value can only be drived in view stage.
  57995. right: 'ph',
  57996. top: 'ph',
  57997. width: 'ph',
  57998. height: 'ph',
  57999. left: null,
  58000. bottom: null,
  58001. borderColor: tokens.color.accent10,
  58002. borderRadius: 0,
  58003. backgroundColor: tokens.color.transparent,
  58004. // dataBackgroundColor: '#ddd',
  58005. dataBackground: {
  58006. lineStyle: {
  58007. color: tokens.color.accent30,
  58008. width: 0.5
  58009. },
  58010. areaStyle: {
  58011. color: tokens.color.accent20,
  58012. opacity: 0.2
  58013. }
  58014. },
  58015. selectedDataBackground: {
  58016. lineStyle: {
  58017. color: tokens.color.accent40,
  58018. width: 0.5
  58019. },
  58020. areaStyle: {
  58021. color: tokens.color.accent20,
  58022. opacity: 0.3
  58023. }
  58024. },
  58025. // Color of selected window.
  58026. fillerColor: 'rgba(135,175,274,0.2)',
  58027. 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',
  58028. // Percent of the slider height
  58029. handleSize: '100%',
  58030. handleStyle: {
  58031. color: tokens.color.neutral00,
  58032. borderColor: tokens.color.accent20
  58033. },
  58034. moveHandleSize: 7,
  58035. 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',
  58036. moveHandleStyle: {
  58037. color: tokens.color.accent40,
  58038. opacity: 0.5
  58039. },
  58040. showDetail: true,
  58041. showDataShadow: 'auto',
  58042. realtime: true,
  58043. zoomLock: false,
  58044. textStyle: {
  58045. color: tokens.color.tertiary
  58046. },
  58047. brushSelect: true,
  58048. brushStyle: {
  58049. color: tokens.color.accent30,
  58050. opacity: 0.3
  58051. },
  58052. emphasis: {
  58053. handleLabel: {
  58054. show: true
  58055. },
  58056. handleStyle: {
  58057. borderColor: tokens.color.accent40
  58058. },
  58059. moveHandleStyle: {
  58060. opacity: 0.8
  58061. }
  58062. },
  58063. defaultLocationEdgeGap: 15
  58064. });
  58065. return SliderZoomModel;
  58066. }(DataZoomModel);
  58067. var Rect$1 = Rect;
  58068. // Constants
  58069. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  58070. var DEFAULT_FILLER_SIZE = 30;
  58071. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  58072. var HORIZONTAL = 'horizontal';
  58073. var VERTICAL = 'vertical';
  58074. var LABEL_GAP = 5;
  58075. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  58076. var REALTIME_ANIMATION_CONFIG = {
  58077. easing: 'cubicOut',
  58078. duration: 100,
  58079. delay: 0
  58080. };
  58081. var SliderZoomView = /** @class */function (_super) {
  58082. __extends(SliderZoomView, _super);
  58083. function SliderZoomView() {
  58084. var _this = _super !== null && _super.apply(this, arguments) || this;
  58085. _this.type = SliderZoomView.type;
  58086. _this._displayables = {};
  58087. return _this;
  58088. }
  58089. SliderZoomView.prototype.init = function (ecModel, api) {
  58090. this.api = api;
  58091. // A unique handler for each dataZoom component
  58092. this._onBrush = bind(this._onBrush, this);
  58093. this._onBrushEnd = bind(this._onBrushEnd, this);
  58094. };
  58095. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  58096. _super.prototype.render.apply(this, arguments);
  58097. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  58098. this._orient = dataZoomModel.getOrient();
  58099. if (dataZoomModel.get('show') === false) {
  58100. this.group.removeAll();
  58101. return;
  58102. }
  58103. if (dataZoomModel.noTarget()) {
  58104. this._clear();
  58105. this.group.removeAll();
  58106. return;
  58107. }
  58108. // Notice: this._resetInterval() should not be executed when payload.type
  58109. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  58110. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  58111. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  58112. this._buildView();
  58113. }
  58114. this._updateView();
  58115. };
  58116. SliderZoomView.prototype.dispose = function () {
  58117. this._clear();
  58118. _super.prototype.dispose.apply(this, arguments);
  58119. };
  58120. SliderZoomView.prototype._clear = function () {
  58121. clear(this, '_dispatchZoomAction');
  58122. var zr = this.api.getZr();
  58123. zr.off('mousemove', this._onBrush);
  58124. zr.off('mouseup', this._onBrushEnd);
  58125. };
  58126. SliderZoomView.prototype._buildView = function () {
  58127. var thisGroup = this.group;
  58128. thisGroup.removeAll();
  58129. this._brushing = false;
  58130. this._displayables.brushRect = null;
  58131. this._resetLocation();
  58132. this._resetInterval();
  58133. var barGroup = this._displayables.sliderGroup = new Group();
  58134. this._renderBackground();
  58135. this._renderHandle();
  58136. this._renderDataShadow();
  58137. thisGroup.add(barGroup);
  58138. this._positionGroup();
  58139. };
  58140. SliderZoomView.prototype._resetLocation = function () {
  58141. var dataZoomModel = this.dataZoomModel;
  58142. var api = this.api;
  58143. var showMoveHandle = dataZoomModel.get('brushSelect');
  58144. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0;
  58145. var refContainer = createBoxLayoutReference(dataZoomModel, api).refContainer;
  58146. // If some of x/y/width/height are not specified,
  58147. // auto-adapt according to target grid.
  58148. var coordRect = this._findCoordRect();
  58149. var edgeGap = dataZoomModel.get('defaultLocationEdgeGap', true) || 0;
  58150. // Default align by coordinate system rect.
  58151. var positionInfo = this._orient === HORIZONTAL ? {
  58152. // Why using 'right', because right should be used in vertical,
  58153. // and it is better to be consistent for dealing with position param merge.
  58154. right: refContainer.width - coordRect.x - coordRect.width,
  58155. top: refContainer.height - DEFAULT_FILLER_SIZE - edgeGap - moveHandleSize,
  58156. width: coordRect.width,
  58157. height: DEFAULT_FILLER_SIZE
  58158. } : {
  58159. right: edgeGap,
  58160. top: coordRect.y,
  58161. width: DEFAULT_FILLER_SIZE,
  58162. height: coordRect.height
  58163. };
  58164. // Do not write back to option and replace value 'ph', because
  58165. // the 'ph' value should be recalculated when resize.
  58166. var layoutParams = getLayoutParams(dataZoomModel.option);
  58167. // Replace the placeholder value.
  58168. each(['right', 'top', 'width', 'height'], function (name) {
  58169. if (layoutParams[name] === 'ph') {
  58170. layoutParams[name] = positionInfo[name];
  58171. }
  58172. });
  58173. var layoutRect = getLayoutRect(layoutParams, refContainer);
  58174. this._location = {
  58175. x: layoutRect.x,
  58176. y: layoutRect.y
  58177. };
  58178. this._size = [layoutRect.width, layoutRect.height];
  58179. this._orient === VERTICAL && this._size.reverse();
  58180. };
  58181. SliderZoomView.prototype._positionGroup = function () {
  58182. var thisGroup = this.group;
  58183. var location = this._location;
  58184. var orient = this._orient;
  58185. // Just use the first axis to determine mapping.
  58186. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  58187. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  58188. var sliderGroup = this._displayables.sliderGroup;
  58189. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  58190. // Transform barGroup.
  58191. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  58192. scaleY: otherAxisInverse ? 1 : -1,
  58193. scaleX: 1
  58194. } : orient === HORIZONTAL && inverse ? {
  58195. scaleY: otherAxisInverse ? 1 : -1,
  58196. scaleX: -1
  58197. } : orient === VERTICAL && !inverse ? {
  58198. scaleY: otherAxisInverse ? -1 : 1,
  58199. scaleX: 1,
  58200. rotation: Math.PI / 2
  58201. }
  58202. // Don't use Math.PI, considering shadow direction.
  58203. : {
  58204. scaleY: otherAxisInverse ? -1 : 1,
  58205. scaleX: -1,
  58206. rotation: Math.PI / 2
  58207. });
  58208. // Position barGroup
  58209. var rect = thisGroup.getBoundingRect([sliderGroup]);
  58210. thisGroup.x = location.x - rect.x;
  58211. thisGroup.y = location.y - rect.y;
  58212. thisGroup.markRedraw();
  58213. };
  58214. SliderZoomView.prototype._getViewExtent = function () {
  58215. return [0, this._size[0]];
  58216. };
  58217. SliderZoomView.prototype._renderBackground = function () {
  58218. var dataZoomModel = this.dataZoomModel;
  58219. var size = this._size;
  58220. var barGroup = this._displayables.sliderGroup;
  58221. var brushSelect = dataZoomModel.get('brushSelect');
  58222. barGroup.add(new Rect$1({
  58223. silent: true,
  58224. shape: {
  58225. x: 0,
  58226. y: 0,
  58227. width: size[0],
  58228. height: size[1]
  58229. },
  58230. style: {
  58231. fill: dataZoomModel.get('backgroundColor')
  58232. },
  58233. z2: -40
  58234. }));
  58235. // Click panel, over shadow, below handles.
  58236. var clickPanel = new Rect$1({
  58237. shape: {
  58238. x: 0,
  58239. y: 0,
  58240. width: size[0],
  58241. height: size[1]
  58242. },
  58243. style: {
  58244. fill: 'transparent'
  58245. },
  58246. z2: 0,
  58247. onclick: bind(this._onClickPanel, this)
  58248. });
  58249. var zr = this.api.getZr();
  58250. if (brushSelect) {
  58251. clickPanel.on('mousedown', this._onBrushStart, this);
  58252. clickPanel.cursor = 'crosshair';
  58253. zr.on('mousemove', this._onBrush);
  58254. zr.on('mouseup', this._onBrushEnd);
  58255. } else {
  58256. zr.off('mousemove', this._onBrush);
  58257. zr.off('mouseup', this._onBrushEnd);
  58258. }
  58259. barGroup.add(clickPanel);
  58260. };
  58261. SliderZoomView.prototype._renderDataShadow = function () {
  58262. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  58263. this._displayables.dataShadowSegs = [];
  58264. if (!info) {
  58265. return;
  58266. }
  58267. var size = this._size;
  58268. var oldSize = this._shadowSize || [];
  58269. var seriesModel = info.series;
  58270. var data = seriesModel.getRawData();
  58271. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  58272. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  58273. : info.otherDim;
  58274. if (otherDim == null) {
  58275. return;
  58276. }
  58277. var polygonPts = this._shadowPolygonPts;
  58278. var polylinePts = this._shadowPolylinePts;
  58279. // Not re-render if data doesn't change.
  58280. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  58281. var thisDataExtent_1 = data.getDataExtent(info.thisDim);
  58282. var otherDataExtent_1 = data.getDataExtent(otherDim);
  58283. // Nice extent.
  58284. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  58285. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  58286. var otherShadowExtent_1 = [0, size[1]];
  58287. var thisShadowExtent = [0, size[0]];
  58288. var areaPoints_1 = [[size[0], 0], [0, 0]];
  58289. var linePoints_1 = [];
  58290. var step_1 = thisShadowExtent[1] / Math.max(1, data.count() - 1);
  58291. var normalizationConstant_1 = size[0] / (thisDataExtent_1[1] - thisDataExtent_1[0]);
  58292. var isTimeAxis_1 = info.thisAxis.type === 'time';
  58293. var thisCoord_1 = -step_1;
  58294. // Optimize for large data shadow
  58295. var stride_1 = Math.round(data.count() / size[0]);
  58296. var lastIsEmpty_1;
  58297. data.each([info.thisDim, otherDim], function (thisValue, otherValue, index) {
  58298. if (stride_1 > 0 && index % stride_1) {
  58299. if (!isTimeAxis_1) {
  58300. thisCoord_1 += step_1;
  58301. }
  58302. return;
  58303. }
  58304. thisCoord_1 = isTimeAxis_1 ? (+thisValue - thisDataExtent_1[0]) * normalizationConstant_1 : thisCoord_1 + step_1;
  58305. // FIXME
  58306. // Should consider axis.min/axis.max when drawing dataShadow.
  58307. // FIXME
  58308. // 应该使用统一的空判断?还是在list里进行空判断?
  58309. var isEmpty = otherValue == null || isNaN(otherValue) || otherValue === '';
  58310. // See #4235.
  58311. var otherCoord = isEmpty ? 0 : linearMap(otherValue, otherDataExtent_1, otherShadowExtent_1, true);
  58312. // Attempt to draw data shadow precisely when there are empty value.
  58313. if (isEmpty && !lastIsEmpty_1 && index) {
  58314. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  58315. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  58316. } else if (!isEmpty && lastIsEmpty_1) {
  58317. areaPoints_1.push([thisCoord_1, 0]);
  58318. linePoints_1.push([thisCoord_1, 0]);
  58319. }
  58320. if (!isEmpty) {
  58321. areaPoints_1.push([thisCoord_1, otherCoord]);
  58322. linePoints_1.push([thisCoord_1, otherCoord]);
  58323. }
  58324. lastIsEmpty_1 = isEmpty;
  58325. });
  58326. polygonPts = this._shadowPolygonPts = areaPoints_1;
  58327. polylinePts = this._shadowPolylinePts = linePoints_1;
  58328. }
  58329. this._shadowData = data;
  58330. this._shadowDim = otherDim;
  58331. this._shadowSize = [size[0], size[1]];
  58332. var dataZoomModel = this.dataZoomModel;
  58333. function createDataShadowGroup(isSelectedArea) {
  58334. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  58335. var group = new Group();
  58336. var polygon = new Polygon({
  58337. shape: {
  58338. points: polygonPts
  58339. },
  58340. segmentIgnoreThreshold: 1,
  58341. style: model.getModel('areaStyle').getAreaStyle(),
  58342. silent: true,
  58343. z2: -20
  58344. });
  58345. var polyline = new Polyline({
  58346. shape: {
  58347. points: polylinePts
  58348. },
  58349. segmentIgnoreThreshold: 1,
  58350. style: model.getModel('lineStyle').getLineStyle(),
  58351. silent: true,
  58352. z2: -19
  58353. });
  58354. group.add(polygon);
  58355. group.add(polyline);
  58356. return group;
  58357. }
  58358. // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  58359. for (var i = 0; i < 3; i++) {
  58360. var group = createDataShadowGroup(i === 1);
  58361. this._displayables.sliderGroup.add(group);
  58362. this._displayables.dataShadowSegs.push(group);
  58363. }
  58364. };
  58365. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  58366. var dataZoomModel = this.dataZoomModel;
  58367. var showDataShadow = dataZoomModel.get('showDataShadow');
  58368. if (showDataShadow === false) {
  58369. return;
  58370. }
  58371. // Find a representative series.
  58372. var result;
  58373. var ecModel = this.ecModel;
  58374. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  58375. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  58376. each(seriesModels, function (seriesModel) {
  58377. if (result) {
  58378. return;
  58379. }
  58380. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  58381. return;
  58382. }
  58383. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  58384. var otherDim = getOtherDim(axisDim);
  58385. var otherAxisInverse;
  58386. var coordSys = seriesModel.coordinateSystem;
  58387. if (otherDim != null && coordSys.getOtherAxis) {
  58388. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  58389. }
  58390. otherDim = seriesModel.getData().mapDimension(otherDim);
  58391. var thisDim = seriesModel.getData().mapDimension(axisDim);
  58392. result = {
  58393. thisAxis: thisAxis,
  58394. series: seriesModel,
  58395. thisDim: thisDim,
  58396. otherDim: otherDim,
  58397. otherAxisInverse: otherAxisInverse
  58398. };
  58399. }, this);
  58400. }, this);
  58401. return result;
  58402. };
  58403. SliderZoomView.prototype._renderHandle = function () {
  58404. var thisGroup = this.group;
  58405. var displayables = this._displayables;
  58406. var handles = displayables.handles = [null, null];
  58407. var handleLabels = displayables.handleLabels = [null, null];
  58408. var sliderGroup = this._displayables.sliderGroup;
  58409. var size = this._size;
  58410. var dataZoomModel = this.dataZoomModel;
  58411. var api = this.api;
  58412. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  58413. var brushSelect = dataZoomModel.get('brushSelect');
  58414. var filler = displayables.filler = new Rect$1({
  58415. silent: brushSelect,
  58416. style: {
  58417. fill: dataZoomModel.get('fillerColor')
  58418. },
  58419. textConfig: {
  58420. position: 'inside'
  58421. }
  58422. });
  58423. sliderGroup.add(filler);
  58424. // Frame border.
  58425. sliderGroup.add(new Rect$1({
  58426. silent: true,
  58427. subPixelOptimize: true,
  58428. shape: {
  58429. x: 0,
  58430. y: 0,
  58431. width: size[0],
  58432. height: size[1],
  58433. r: borderRadius
  58434. },
  58435. style: {
  58436. // deprecated option
  58437. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  58438. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  58439. fill: tokens.color.transparent
  58440. }
  58441. }));
  58442. // Left and right handle to resize
  58443. each([0, 1], function (handleIndex) {
  58444. var iconStr = dataZoomModel.get('handleIcon');
  58445. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  58446. // Compatitable with the old icon parsers. Which can use a path string without path://
  58447. iconStr = 'path://' + iconStr;
  58448. if ("development" !== 'production') {
  58449. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  58450. }
  58451. }
  58452. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  58453. path.attr({
  58454. cursor: getCursor(this._orient),
  58455. draggable: true,
  58456. drift: bind(this._onDragMove, this, handleIndex),
  58457. ondragend: bind(this._onDragEnd, this),
  58458. onmouseover: bind(this._showDataInfo, this, true),
  58459. onmouseout: bind(this._showDataInfo, this, false),
  58460. z2: 5
  58461. });
  58462. var bRect = path.getBoundingRect();
  58463. var handleSize = dataZoomModel.get('handleSize');
  58464. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  58465. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  58466. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  58467. path.style.strokeNoScale = true;
  58468. path.rectHover = true;
  58469. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  58470. enableHoverEmphasis(path);
  58471. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  58472. // Compatitable with previous version
  58473. if (handleColor != null) {
  58474. path.style.fill = handleColor;
  58475. }
  58476. sliderGroup.add(handles[handleIndex] = path);
  58477. var textStyleModel = dataZoomModel.getModel('textStyle');
  58478. var handleLabel = dataZoomModel.get('handleLabel') || {};
  58479. var handleLabelShow = handleLabel.show || false;
  58480. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  58481. silent: true,
  58482. invisible: !handleLabelShow,
  58483. style: createTextStyle(textStyleModel, {
  58484. x: 0,
  58485. y: 0,
  58486. text: '',
  58487. verticalAlign: 'middle',
  58488. align: 'center',
  58489. fill: textStyleModel.getTextColor(),
  58490. font: textStyleModel.getFont()
  58491. }),
  58492. z2: 10
  58493. }));
  58494. }, this);
  58495. // Handle to move. Only visible when brushSelect is set true.
  58496. var actualMoveZone = filler;
  58497. if (brushSelect) {
  58498. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  58499. var moveHandle_1 = displayables.moveHandle = new Rect({
  58500. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  58501. silent: true,
  58502. shape: {
  58503. r: [0, 0, 2, 2],
  58504. y: size[1] - 0.5,
  58505. height: moveHandleHeight
  58506. }
  58507. });
  58508. var iconSize = moveHandleHeight * 0.8;
  58509. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, tokens.color.neutral00, true);
  58510. moveHandleIcon.silent = true;
  58511. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  58512. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  58513. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  58514. actualMoveZone = displayables.moveZone = new Rect({
  58515. invisible: true,
  58516. shape: {
  58517. y: size[1] - moveZoneExpandSize,
  58518. height: moveHandleHeight + moveZoneExpandSize
  58519. }
  58520. });
  58521. actualMoveZone.on('mouseover', function () {
  58522. api.enterEmphasis(moveHandle_1);
  58523. }).on('mouseout', function () {
  58524. api.leaveEmphasis(moveHandle_1);
  58525. });
  58526. sliderGroup.add(moveHandle_1);
  58527. sliderGroup.add(moveHandleIcon);
  58528. sliderGroup.add(actualMoveZone);
  58529. }
  58530. actualMoveZone.attr({
  58531. draggable: true,
  58532. cursor: 'default',
  58533. drift: bind(this._onDragMove, this, 'all'),
  58534. ondragstart: bind(this._showDataInfo, this, true),
  58535. ondragend: bind(this._onDragEnd, this),
  58536. onmouseover: bind(this._showDataInfo, this, true),
  58537. onmouseout: bind(this._showDataInfo, this, false)
  58538. });
  58539. };
  58540. SliderZoomView.prototype._resetInterval = function () {
  58541. var range = this._range = this.dataZoomModel.getPercentRange();
  58542. var viewExtent = this._getViewExtent();
  58543. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  58544. };
  58545. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  58546. var dataZoomModel = this.dataZoomModel;
  58547. var handleEnds = this._handleEnds;
  58548. var viewExtend = this._getViewExtent();
  58549. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  58550. var percentExtent = [0, 100];
  58551. 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);
  58552. var lastRange = this._range;
  58553. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  58554. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  58555. };
  58556. SliderZoomView.prototype._updateView = function (nonRealtime) {
  58557. var displaybles = this._displayables;
  58558. var handleEnds = this._handleEnds;
  58559. var handleInterval = asc(handleEnds.slice());
  58560. var size = this._size;
  58561. each([0, 1], function (handleIndex) {
  58562. // Handles
  58563. var handle = displaybles.handles[handleIndex];
  58564. var handleHeight = this._handleHeight;
  58565. handle.attr({
  58566. scaleX: handleHeight / 2,
  58567. scaleY: handleHeight / 2,
  58568. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  58569. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  58570. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  58571. y: size[1] / 2 - handleHeight / 2
  58572. });
  58573. }, this);
  58574. // Filler
  58575. displaybles.filler.setShape({
  58576. x: handleInterval[0],
  58577. y: 0,
  58578. width: handleInterval[1] - handleInterval[0],
  58579. height: size[1]
  58580. });
  58581. var viewExtent = {
  58582. x: handleInterval[0],
  58583. width: handleInterval[1] - handleInterval[0]
  58584. };
  58585. // Move handle
  58586. if (displaybles.moveHandle) {
  58587. displaybles.moveHandle.setShape(viewExtent);
  58588. displaybles.moveZone.setShape(viewExtent);
  58589. // Force update path on the invisible object
  58590. displaybles.moveZone.getBoundingRect();
  58591. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  58592. }
  58593. // update clip path of shadow.
  58594. var dataShadowSegs = displaybles.dataShadowSegs;
  58595. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  58596. for (var i = 0; i < dataShadowSegs.length; i++) {
  58597. var segGroup = dataShadowSegs[i];
  58598. var clipPath = segGroup.getClipPath();
  58599. if (!clipPath) {
  58600. clipPath = new Rect();
  58601. segGroup.setClipPath(clipPath);
  58602. }
  58603. clipPath.setShape({
  58604. x: segIntervals[i],
  58605. y: 0,
  58606. width: segIntervals[i + 1] - segIntervals[i],
  58607. height: size[1]
  58608. });
  58609. }
  58610. this._updateDataInfo(nonRealtime);
  58611. };
  58612. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  58613. var dataZoomModel = this.dataZoomModel;
  58614. var displaybles = this._displayables;
  58615. var handleLabels = displaybles.handleLabels;
  58616. var orient = this._orient;
  58617. var labelTexts = ['', ''];
  58618. // FIXME
  58619. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  58620. if (dataZoomModel.get('showDetail')) {
  58621. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  58622. if (axisProxy) {
  58623. var axis = axisProxy.getAxisModel().axis;
  58624. var range = this._range;
  58625. var dataInterval = nonRealtime
  58626. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  58627. ? axisProxy.calculateDataWindow({
  58628. start: range[0],
  58629. end: range[1]
  58630. }).valueWindow : axisProxy.getDataValueWindow();
  58631. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  58632. }
  58633. }
  58634. var orderedHandleEnds = asc(this._handleEnds.slice());
  58635. setLabel.call(this, 0);
  58636. setLabel.call(this, 1);
  58637. function setLabel(handleIndex) {
  58638. // Label
  58639. // Text should not transform by barGroup.
  58640. // Ignore handlers transform
  58641. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  58642. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  58643. var offset = this._handleWidth / 2 + LABEL_GAP;
  58644. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  58645. handleLabels[handleIndex].setStyle({
  58646. x: textPoint[0],
  58647. y: textPoint[1],
  58648. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  58649. align: orient === HORIZONTAL ? direction : 'center',
  58650. text: labelTexts[handleIndex]
  58651. });
  58652. }
  58653. };
  58654. SliderZoomView.prototype._formatLabel = function (value, axis) {
  58655. var dataZoomModel = this.dataZoomModel;
  58656. var labelFormatter = dataZoomModel.get('labelFormatter');
  58657. var labelPrecision = dataZoomModel.get('labelPrecision');
  58658. if (labelPrecision == null || labelPrecision === 'auto') {
  58659. labelPrecision = axis.getPixelPrecision();
  58660. }
  58661. var valueStr = value == null || isNaN(value) ? ''
  58662. // FIXME Glue code
  58663. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  58664. value: Math.round(value)
  58665. })
  58666. // param of toFixed should less then 20.
  58667. : value.toFixed(Math.min(labelPrecision, 20));
  58668. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  58669. };
  58670. /**
  58671. * @param isEmphasis true: show, false: hide
  58672. */
  58673. SliderZoomView.prototype._showDataInfo = function (isEmphasis) {
  58674. var handleLabel = this.dataZoomModel.get('handleLabel') || {};
  58675. var normalShow = handleLabel.show || false;
  58676. var emphasisHandleLabel = this.dataZoomModel.getModel(['emphasis', 'handleLabel']);
  58677. var emphasisShow = emphasisHandleLabel.get('show') || false;
  58678. // Dragging is considered as emphasis, unless emphasisShow is false
  58679. var toShow = isEmphasis || this._dragging ? emphasisShow : normalShow;
  58680. var displayables = this._displayables;
  58681. var handleLabels = displayables.handleLabels;
  58682. handleLabels[0].attr('invisible', !toShow);
  58683. handleLabels[1].attr('invisible', !toShow);
  58684. // Highlight move handle
  58685. displayables.moveHandle && this.api[toShow ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  58686. };
  58687. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  58688. this._dragging = true;
  58689. // For mobile device, prevent screen slider on the button.
  58690. stop(event.event);
  58691. // Transform dx, dy to bar coordination.
  58692. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  58693. var vertex = applyTransform$1([dx, dy], barTransform, true);
  58694. var changed = this._updateInterval(handleIndex, vertex[0]);
  58695. var realtime = this.dataZoomModel.get('realtime');
  58696. this._updateView(!realtime);
  58697. // Avoid dispatch dataZoom repeatly but range not changed,
  58698. // which cause bad visual effect when progressive enabled.
  58699. changed && realtime && this._dispatchZoomAction(true);
  58700. };
  58701. SliderZoomView.prototype._onDragEnd = function () {
  58702. this._dragging = false;
  58703. this._showDataInfo(false);
  58704. // While in realtime mode and stream mode, dispatch action when
  58705. // drag end will cause the whole view rerender, which is unnecessary.
  58706. var realtime = this.dataZoomModel.get('realtime');
  58707. !realtime && this._dispatchZoomAction(false);
  58708. };
  58709. SliderZoomView.prototype._onClickPanel = function (e) {
  58710. var size = this._size;
  58711. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  58712. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  58713. return;
  58714. }
  58715. var handleEnds = this._handleEnds;
  58716. var center = (handleEnds[0] + handleEnds[1]) / 2;
  58717. var changed = this._updateInterval('all', localPoint[0] - center);
  58718. this._updateView();
  58719. changed && this._dispatchZoomAction(false);
  58720. };
  58721. SliderZoomView.prototype._onBrushStart = function (e) {
  58722. var x = e.offsetX;
  58723. var y = e.offsetY;
  58724. this._brushStart = new Point(x, y);
  58725. this._brushing = true;
  58726. this._brushStartTime = +new Date();
  58727. // this._updateBrushRect(x, y);
  58728. };
  58729. SliderZoomView.prototype._onBrushEnd = function (e) {
  58730. if (!this._brushing) {
  58731. return;
  58732. }
  58733. var brushRect = this._displayables.brushRect;
  58734. this._brushing = false;
  58735. if (!brushRect) {
  58736. return;
  58737. }
  58738. brushRect.attr('ignore', true);
  58739. var brushShape = brushRect.shape;
  58740. var brushEndTime = +new Date();
  58741. // console.log(brushEndTime - this._brushStartTime);
  58742. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  58743. // Will treat it as a click
  58744. return;
  58745. }
  58746. var viewExtend = this._getViewExtent();
  58747. var percentExtent = [0, 100];
  58748. var handleEnds = this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  58749. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  58750. // Restrict range.
  58751. sliderMove(0, handleEnds, viewExtend, 0, minMaxSpan.minSpan != null ? linearMap(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null, minMaxSpan.maxSpan != null ? linearMap(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null);
  58752. this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  58753. this._updateView();
  58754. this._dispatchZoomAction(false);
  58755. };
  58756. SliderZoomView.prototype._onBrush = function (e) {
  58757. if (this._brushing) {
  58758. // For mobile device, prevent screen slider on the button.
  58759. stop(e.event);
  58760. this._updateBrushRect(e.offsetX, e.offsetY);
  58761. }
  58762. };
  58763. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  58764. var displayables = this._displayables;
  58765. var dataZoomModel = this.dataZoomModel;
  58766. var brushRect = displayables.brushRect;
  58767. if (!brushRect) {
  58768. brushRect = displayables.brushRect = new Rect$1({
  58769. silent: true,
  58770. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  58771. });
  58772. displayables.sliderGroup.add(brushRect);
  58773. }
  58774. brushRect.attr('ignore', false);
  58775. var brushStart = this._brushStart;
  58776. var sliderGroup = this._displayables.sliderGroup;
  58777. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  58778. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  58779. var size = this._size;
  58780. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  58781. brushRect.setShape({
  58782. x: startPoint[0],
  58783. y: 0,
  58784. width: endPoint[0] - startPoint[0],
  58785. height: size[1]
  58786. });
  58787. };
  58788. /**
  58789. * This action will be throttled.
  58790. */
  58791. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  58792. var range = this._range;
  58793. this.api.dispatchAction({
  58794. type: 'dataZoom',
  58795. from: this.uid,
  58796. dataZoomId: this.dataZoomModel.id,
  58797. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  58798. start: range[0],
  58799. end: range[1]
  58800. });
  58801. };
  58802. SliderZoomView.prototype._findCoordRect = function () {
  58803. // Find the grid corresponding to the first axis referred by dataZoom.
  58804. var rect;
  58805. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  58806. if (!rect && coordSysInfoList.length) {
  58807. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  58808. rect = coordSys.getRect && coordSys.getRect();
  58809. }
  58810. if (!rect) {
  58811. var width = this.api.getWidth();
  58812. var height = this.api.getHeight();
  58813. rect = {
  58814. x: width * 0.2,
  58815. y: height * 0.2,
  58816. width: width * 0.6,
  58817. height: height * 0.6
  58818. };
  58819. }
  58820. return rect;
  58821. };
  58822. SliderZoomView.type = 'dataZoom.slider';
  58823. return SliderZoomView;
  58824. }(DataZoomView);
  58825. function getOtherDim(thisDim) {
  58826. // FIXME
  58827. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  58828. var map = {
  58829. x: 'y',
  58830. y: 'x',
  58831. radius: 'angle',
  58832. angle: 'radius'
  58833. };
  58834. return map[thisDim];
  58835. }
  58836. function getCursor(orient) {
  58837. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  58838. }
  58839. function install$l(registers) {
  58840. registers.registerComponentModel(SliderZoomModel);
  58841. registers.registerComponentView(SliderZoomView);
  58842. installCommon(registers);
  58843. }
  58844. function install$m(registers) {
  58845. use(install$k);
  58846. use(install$l);
  58847. // Do not install './dataZoomSelect',
  58848. // since it only work for toolbox dataZoom.
  58849. }
  58850. var DEFAULT_OPTION = {
  58851. label: {
  58852. enabled: true
  58853. },
  58854. decal: {
  58855. show: false
  58856. }
  58857. };
  58858. var inner$h = makeInner();
  58859. var decalPaletteScope = {};
  58860. function ariaVisual(ecModel, api) {
  58861. var ariaModel = ecModel.getModel('aria');
  58862. // See "area enabled" detection code in `GlobalModel.ts`.
  58863. if (!ariaModel.get('enabled')) {
  58864. return;
  58865. }
  58866. var defaultOption = clone(DEFAULT_OPTION);
  58867. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  58868. merge(ariaModel.option, defaultOption, false);
  58869. setDecal();
  58870. setLabel();
  58871. function setDecal() {
  58872. var decalModel = ariaModel.getModel('decal');
  58873. var useDecal = decalModel.get('show');
  58874. if (useDecal) {
  58875. // Each type of series use one scope.
  58876. // Pie and funnel are using different scopes.
  58877. var paletteScopeGroupByType_1 = createHashMap();
  58878. ecModel.eachSeries(function (seriesModel) {
  58879. if (seriesModel.isColorBySeries()) {
  58880. return;
  58881. }
  58882. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  58883. if (!decalScope) {
  58884. decalScope = {};
  58885. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  58886. }
  58887. inner$h(seriesModel).scope = decalScope;
  58888. });
  58889. ecModel.eachRawSeries(function (seriesModel) {
  58890. if (ecModel.isSeriesFiltered(seriesModel)) {
  58891. return;
  58892. }
  58893. if (isFunction(seriesModel.enableAriaDecal)) {
  58894. // Let series define how to use decal palette on data
  58895. seriesModel.enableAriaDecal();
  58896. return;
  58897. }
  58898. var data = seriesModel.getData();
  58899. if (!seriesModel.isColorBySeries()) {
  58900. var dataAll_1 = seriesModel.getRawData();
  58901. var idxMap_1 = {};
  58902. var decalScope_1 = inner$h(seriesModel).scope;
  58903. data.each(function (idx) {
  58904. var rawIdx = data.getRawIndex(idx);
  58905. idxMap_1[rawIdx] = idx;
  58906. });
  58907. var dataCount_1 = dataAll_1.count();
  58908. dataAll_1.each(function (rawIdx) {
  58909. var idx = idxMap_1[rawIdx];
  58910. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  58911. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  58912. var specifiedDecal = data.getItemVisual(idx, 'decal');
  58913. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  58914. });
  58915. } else {
  58916. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  58917. var specifiedDecal = data.getVisual('decal');
  58918. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  58919. }
  58920. function mergeDecal(specifiedDecal, paletteDecal) {
  58921. // Merge decal from palette to decal from itemStyle.
  58922. // User do not need to specify all of the decal props.
  58923. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  58924. resultDecal.dirty = true;
  58925. return resultDecal;
  58926. }
  58927. });
  58928. }
  58929. }
  58930. function setLabel() {
  58931. var dom = api.getZr().dom;
  58932. // TODO: support for SSR
  58933. if (!dom) {
  58934. return;
  58935. }
  58936. var labelLocale = ecModel.getLocaleModel().get('aria');
  58937. var labelModel = ariaModel.getModel('label');
  58938. labelModel.option = defaults(labelModel.option, labelLocale);
  58939. if (!labelModel.get('enabled')) {
  58940. return;
  58941. }
  58942. dom.setAttribute('role', 'img');
  58943. if (labelModel.get('description')) {
  58944. dom.setAttribute('aria-label', labelModel.get('description'));
  58945. return;
  58946. }
  58947. var seriesCnt = ecModel.getSeriesCount();
  58948. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  58949. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  58950. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  58951. var ariaLabel;
  58952. if (seriesCnt < 1) {
  58953. // No series, no aria label
  58954. return;
  58955. } else {
  58956. var title = getTitle();
  58957. if (title) {
  58958. var withTitle = labelModel.get(['general', 'withTitle']);
  58959. ariaLabel = replace(withTitle, {
  58960. title: title
  58961. });
  58962. } else {
  58963. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  58964. }
  58965. var seriesLabels_1 = [];
  58966. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  58967. ariaLabel += replace(prefix, {
  58968. seriesCount: seriesCnt
  58969. });
  58970. ecModel.eachSeries(function (seriesModel, idx) {
  58971. if (idx < displaySeriesCnt) {
  58972. var seriesLabel = void 0;
  58973. var seriesName = seriesModel.get('name');
  58974. var withName = seriesName ? 'withName' : 'withoutName';
  58975. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  58976. seriesLabel = replace(seriesLabel, {
  58977. seriesId: seriesModel.seriesIndex,
  58978. seriesName: seriesModel.get('name'),
  58979. seriesType: getSeriesTypeName(seriesModel.subType)
  58980. });
  58981. var data = seriesModel.getData();
  58982. if (data.count() > maxDataCnt) {
  58983. // Show part of data
  58984. var partialLabel = labelModel.get(['data', 'partialData']);
  58985. seriesLabel += replace(partialLabel, {
  58986. displayCnt: maxDataCnt
  58987. });
  58988. } else {
  58989. seriesLabel += labelModel.get(['data', 'allData']);
  58990. }
  58991. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  58992. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  58993. var excludeDimensionId_1 = labelModel.get(['data', 'excludeDimensionId']);
  58994. var dataLabels = [];
  58995. for (var i = 0; i < data.count(); i++) {
  58996. if (i < maxDataCnt) {
  58997. var name_1 = data.getName(i);
  58998. var value = !excludeDimensionId_1 ? data.getValues(i) : filter(data.getValues(i), function (v, j) {
  58999. return indexOf(excludeDimensionId_1, j) === -1;
  59000. });
  59001. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  59002. dataLabels.push(replace(dataLabel, {
  59003. name: name_1,
  59004. value: value.join(middleSeparator_1)
  59005. }));
  59006. }
  59007. }
  59008. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  59009. seriesLabels_1.push(seriesLabel);
  59010. }
  59011. });
  59012. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  59013. var middleSeparator = separatorModel.get('middle');
  59014. var endSeparator = separatorModel.get('end');
  59015. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  59016. dom.setAttribute('aria-label', ariaLabel);
  59017. }
  59018. }
  59019. function replace(str, keyValues) {
  59020. if (!isString(str)) {
  59021. return str;
  59022. }
  59023. var result = str;
  59024. each(keyValues, function (value, key) {
  59025. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  59026. });
  59027. return result;
  59028. }
  59029. function getTitle() {
  59030. var title = ecModel.get('title');
  59031. if (title && title.length) {
  59032. title = title[0];
  59033. }
  59034. return title && title.text;
  59035. }
  59036. function getSeriesTypeName(type) {
  59037. var typeNames = ecModel.getLocaleModel().get(['series', 'typeNames']);
  59038. return typeNames[type] || typeNames.chart;
  59039. }
  59040. }
  59041. function ariaPreprocessor(option) {
  59042. if (!option || !option.aria) {
  59043. return;
  59044. }
  59045. var aria = option.aria;
  59046. // aria.show is deprecated and should use aria.enabled instead
  59047. if (aria.show != null) {
  59048. aria.enabled = aria.show;
  59049. }
  59050. aria.label = aria.label || {};
  59051. // move description, general, series, data to be under aria.label
  59052. each(['description', 'general', 'series', 'data'], function (name) {
  59053. if (aria[name] != null) {
  59054. aria.label[name] = aria[name];
  59055. }
  59056. });
  59057. }
  59058. function install$n(registers) {
  59059. registers.registerPreprocessor(ariaPreprocessor);
  59060. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  59061. }
  59062. var DatasetModel = /** @class */function (_super) {
  59063. __extends(DatasetModel, _super);
  59064. function DatasetModel() {
  59065. var _this = _super !== null && _super.apply(this, arguments) || this;
  59066. _this.type = 'dataset';
  59067. return _this;
  59068. }
  59069. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  59070. _super.prototype.init.call(this, option, parentModel, ecModel);
  59071. this._sourceManager = new SourceManager(this);
  59072. disableTransformOptionMerge(this);
  59073. };
  59074. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  59075. _super.prototype.mergeOption.call(this, newOption, ecModel);
  59076. disableTransformOptionMerge(this);
  59077. };
  59078. DatasetModel.prototype.optionUpdated = function () {
  59079. this._sourceManager.dirty();
  59080. };
  59081. DatasetModel.prototype.getSourceManager = function () {
  59082. return this._sourceManager;
  59083. };
  59084. DatasetModel.type = 'dataset';
  59085. DatasetModel.defaultOption = {
  59086. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  59087. };
  59088. return DatasetModel;
  59089. }(ComponentModel);
  59090. var DatasetView = /** @class */function (_super) {
  59091. __extends(DatasetView, _super);
  59092. function DatasetView() {
  59093. var _this = _super !== null && _super.apply(this, arguments) || this;
  59094. _this.type = 'dataset';
  59095. return _this;
  59096. }
  59097. DatasetView.type = 'dataset';
  59098. return DatasetView;
  59099. }(ComponentView);
  59100. function install$o(registers) {
  59101. registers.registerComponentModel(DatasetModel);
  59102. registers.registerComponentView(DatasetView);
  59103. }
  59104. /**
  59105. * @caution
  59106. * Must not export anything except `installScaleBreakHelper`
  59107. */
  59108. var ScaleBreakContextImpl = /** @class */function () {
  59109. function ScaleBreakContextImpl() {
  59110. // [CAVEAT]: Should set only by `ScaleBreakContext#setBreaks`!
  59111. this.breaks = [];
  59112. // [CAVEAT]: Should update only by `ScaleBreakContext#update`!
  59113. // They are the values that scaleExtent[0] and scaleExtent[1] are mapped to a numeric axis
  59114. // that breaks are applied, primarily for optimization of `Scale#normalize`.
  59115. this._elapsedExtent = [Infinity, -Infinity];
  59116. }
  59117. ScaleBreakContextImpl.prototype.setBreaks = function (parsed) {
  59118. // @ts-ignore
  59119. this.breaks = parsed.breaks;
  59120. };
  59121. /**
  59122. * [CAVEAT]: Must be called immediately each time scale extent and breaks are updated!
  59123. */
  59124. ScaleBreakContextImpl.prototype.update = function (scaleExtent) {
  59125. updateAxisBreakGapReal(this, scaleExtent);
  59126. var elapsedExtent = this._elapsedExtent;
  59127. elapsedExtent[0] = this.elapse(scaleExtent[0]);
  59128. elapsedExtent[1] = this.elapse(scaleExtent[1]);
  59129. };
  59130. ScaleBreakContextImpl.prototype.hasBreaks = function () {
  59131. return !!this.breaks.length;
  59132. };
  59133. /**
  59134. * When iteratively generating ticks by nice interval, currently the `interval`, which is
  59135. * calculated by break-elapsed extent span, is probably very small comparing to the original
  59136. * extent, leading to a large number of iteration and tick generation, even over `safeLimit`.
  59137. * Thus stepping over breaks is necessary in that loop.
  59138. *
  59139. * "Nice" should be ensured on ticks when step over the breaks. Thus this method returns
  59140. * a integer multiple of the "nice tick interval".
  59141. *
  59142. * This method does little work; it is just for unifying and restricting the behavior.
  59143. */
  59144. ScaleBreakContextImpl.prototype.calcNiceTickMultiple = function (tickVal, estimateNiceMultiple) {
  59145. for (var idx = 0; idx < this.breaks.length; idx++) {
  59146. var brk = this.breaks[idx];
  59147. if (brk.vmin < tickVal && tickVal < brk.vmax) {
  59148. var multiple = estimateNiceMultiple(tickVal, brk.vmax);
  59149. if ("development" !== 'production') {
  59150. // If not, it may cause dead loop or not nice tick.
  59151. assert(multiple >= 0 && Math.round(multiple) === multiple);
  59152. }
  59153. return multiple;
  59154. }
  59155. }
  59156. return 0;
  59157. };
  59158. ScaleBreakContextImpl.prototype.getExtentSpan = function () {
  59159. return this._elapsedExtent[1] - this._elapsedExtent[0];
  59160. };
  59161. ScaleBreakContextImpl.prototype.normalize = function (val) {
  59162. var elapsedSpan = this._elapsedExtent[1] - this._elapsedExtent[0];
  59163. // The same logic as `Scale#normalize`.
  59164. if (elapsedSpan === 0) {
  59165. return 0.5;
  59166. }
  59167. return (this.elapse(val) - this._elapsedExtent[0]) / elapsedSpan;
  59168. };
  59169. ScaleBreakContextImpl.prototype.scale = function (val) {
  59170. return this.unelapse(val * (this._elapsedExtent[1] - this._elapsedExtent[0]) + this._elapsedExtent[0]);
  59171. };
  59172. /**
  59173. * Suppose:
  59174. * AXIS_BREAK_LAST_BREAK_END_BASE: 0
  59175. * AXIS_BREAK_ELAPSED_BASE: 0
  59176. * breaks: [
  59177. * {start: -400, end: -300, gap: 27},
  59178. * {start: -100, end: 100, gap: 10},
  59179. * {start: 200, end: 400, gap: 300},
  59180. * ]
  59181. * The mapping will be:
  59182. * | |
  59183. * 400 + -> + 237
  59184. * | | | | (gap: 300)
  59185. * 200 + -> + -63
  59186. * | |
  59187. * 100 + -> + -163
  59188. * | | | | (gap: 10)
  59189. * -100 + -> + -173
  59190. * | |
  59191. * -300 + -> + -373
  59192. * | | | | (gap: 27)
  59193. * -400 + -> + -400
  59194. * | |
  59195. * origianl elapsed
  59196. *
  59197. * Note:
  59198. * The mapping has nothing to do with "scale extent".
  59199. */
  59200. ScaleBreakContextImpl.prototype.elapse = function (val) {
  59201. // If the value is in the break, return the normalized value in the break
  59202. var elapsedVal = AXIS_BREAK_ELAPSED_BASE;
  59203. var lastBreakEnd = AXIS_BREAK_LAST_BREAK_END_BASE;
  59204. var stillOver = true;
  59205. for (var i = 0; i < this.breaks.length; i++) {
  59206. var brk = this.breaks[i];
  59207. if (val <= brk.vmax) {
  59208. if (val > brk.vmin) {
  59209. elapsedVal += brk.vmin - lastBreakEnd + (val - brk.vmin) / (brk.vmax - brk.vmin) * brk.gapReal;
  59210. } else {
  59211. elapsedVal += val - lastBreakEnd;
  59212. }
  59213. lastBreakEnd = brk.vmax;
  59214. stillOver = false;
  59215. break;
  59216. }
  59217. elapsedVal += brk.vmin - lastBreakEnd + brk.gapReal;
  59218. lastBreakEnd = brk.vmax;
  59219. }
  59220. if (stillOver) {
  59221. elapsedVal += val - lastBreakEnd;
  59222. }
  59223. return elapsedVal;
  59224. };
  59225. ScaleBreakContextImpl.prototype.unelapse = function (elapsedVal) {
  59226. var lastElapsedEnd = AXIS_BREAK_ELAPSED_BASE;
  59227. var lastBreakEnd = AXIS_BREAK_LAST_BREAK_END_BASE;
  59228. var stillOver = true;
  59229. var unelapsedVal = 0;
  59230. for (var i = 0; i < this.breaks.length; i++) {
  59231. var brk = this.breaks[i];
  59232. var elapsedStart = lastElapsedEnd + brk.vmin - lastBreakEnd;
  59233. var elapsedEnd = elapsedStart + brk.gapReal;
  59234. if (elapsedVal <= elapsedEnd) {
  59235. if (elapsedVal > elapsedStart) {
  59236. unelapsedVal = brk.vmin + (elapsedVal - elapsedStart) / (elapsedEnd - elapsedStart) * (brk.vmax - brk.vmin);
  59237. } else {
  59238. unelapsedVal = lastBreakEnd + elapsedVal - lastElapsedEnd;
  59239. }
  59240. lastBreakEnd = brk.vmax;
  59241. stillOver = false;
  59242. break;
  59243. }
  59244. lastElapsedEnd = elapsedEnd;
  59245. lastBreakEnd = brk.vmax;
  59246. }
  59247. if (stillOver) {
  59248. unelapsedVal = lastBreakEnd + elapsedVal - lastElapsedEnd;
  59249. }
  59250. return unelapsedVal;
  59251. };
  59252. return ScaleBreakContextImpl;
  59253. }();
  59254. function createScaleBreakContext() {
  59255. return new ScaleBreakContextImpl();
  59256. }
  59257. // Both can start with any finite value, and are not necessaryily equal. But they need to
  59258. // be the same in `axisBreakElapse` and `axisBreakUnelapse` respectively.
  59259. var AXIS_BREAK_ELAPSED_BASE = 0;
  59260. var AXIS_BREAK_LAST_BREAK_END_BASE = 0;
  59261. /**
  59262. * `gapReal` in brkCtx.breaks will be calculated.
  59263. */
  59264. function updateAxisBreakGapReal(brkCtx, scaleExtent) {
  59265. // Considered the effect:
  59266. // - Use dataZoom to move some of the breaks outside the extent.
  59267. // - Some scenarios that `series.clip: false`.
  59268. //
  59269. // How to calculate `prctBrksGapRealSum`:
  59270. // Based on the formula:
  59271. // xxx.span = brk.vmax - brk.vmin
  59272. // xxx.tpPrct.val / xxx.tpAbs.val means ParsedAxisBreak['gapParsed']['val']
  59273. // .S/.E means a break that is semi in scaleExtent[0] or scaleExtent[1]
  59274. // valP = (
  59275. // + (fullyInExtBrksSum.tpAbs.gapReal - fullyInExtBrksSum.tpAbs.span)
  59276. // + (semiInExtBrk.S.tpAbs.gapReal - semiInExtBrk.S.tpAbs.span) * semiInExtBrk.S.tpAbs.inExtFrac
  59277. // + (semiInExtBrk.E.tpAbs.gapReal - semiInExtBrk.E.tpAbs.span) * semiInExtBrk.E.tpAbs.inExtFrac
  59278. // )
  59279. // valQ = (
  59280. // - fullyInExtBrksSum.tpPrct.span
  59281. // - semiInExtBrk.S.tpPrct.span * semiInExtBrk.S.tpPrct.inExtFrac
  59282. // - semiInExtBrk.E.tpPrct.span * semiInExtBrk.E.tpPrct.inExtFrac
  59283. // )
  59284. // gapPrctSum = sum(xxx.tpPrct.val)
  59285. // gapPrctSum = prctBrksGapRealSum / (
  59286. // + (scaleExtent[1] - scaleExtent[0]) + valP + valQ
  59287. // + fullyInExtBrksSum.tpPrct.gapReal
  59288. // + semiInExtBrk.S.tpPrct.gapReal * semiInExtBrk.S.tpPrct.inExtFrac
  59289. // + semiInExtBrk.E.tpPrct.gapReal * semiInExtBrk.E.tpPrct.inExtFrac
  59290. // )
  59291. // Assume:
  59292. // xxx.tpPrct.gapReal = xxx.tpPrct.val / gapPrctSum * prctBrksGapRealSum
  59293. // (NOTE: This is not accurate when semi-in-extent break exist because its
  59294. // proportion is not linear, but this assumption approximately works.)
  59295. // Derived as follows:
  59296. // prctBrksGapRealSum = gapPrctSum * ( (scaleExtent[1] - scaleExtent[0]) + valP + valQ )
  59297. // / (1
  59298. // - fullyInExtBrksSum.tpPrct.val
  59299. // - semiInExtBrk.S.tpPrct.val * semiInExtBrk.S.tpPrct.inExtFrac
  59300. // - semiInExtBrk.E.tpPrct.val * semiInExtBrk.E.tpPrct.inExtFrac
  59301. // )
  59302. var gapPrctSum = 0;
  59303. var fullyInExtBrksSum = {
  59304. tpAbs: {
  59305. span: 0,
  59306. val: 0
  59307. },
  59308. tpPrct: {
  59309. span: 0,
  59310. val: 0
  59311. }
  59312. };
  59313. var init = function () {
  59314. return {
  59315. has: false,
  59316. span: NaN,
  59317. inExtFrac: NaN,
  59318. val: NaN
  59319. };
  59320. };
  59321. var semiInExtBrk = {
  59322. S: {
  59323. tpAbs: init(),
  59324. tpPrct: init()
  59325. },
  59326. E: {
  59327. tpAbs: init(),
  59328. tpPrct: init()
  59329. }
  59330. };
  59331. each(brkCtx.breaks, function (brk) {
  59332. var gapParsed = brk.gapParsed;
  59333. if (gapParsed.type === 'tpPrct') {
  59334. gapPrctSum += gapParsed.val;
  59335. }
  59336. var clampedBrk = clampBreakByExtent(brk, scaleExtent);
  59337. if (clampedBrk) {
  59338. var vminClamped = clampedBrk.vmin !== brk.vmin;
  59339. var vmaxClamped = clampedBrk.vmax !== brk.vmax;
  59340. var clampedSpan = clampedBrk.vmax - clampedBrk.vmin;
  59341. if (vminClamped && vmaxClamped) ; else if (vminClamped || vmaxClamped) {
  59342. var sOrE = vminClamped ? 'S' : 'E';
  59343. semiInExtBrk[sOrE][gapParsed.type].has = true;
  59344. semiInExtBrk[sOrE][gapParsed.type].span = clampedSpan;
  59345. semiInExtBrk[sOrE][gapParsed.type].inExtFrac = clampedSpan / (brk.vmax - brk.vmin);
  59346. semiInExtBrk[sOrE][gapParsed.type].val = gapParsed.val;
  59347. } else {
  59348. fullyInExtBrksSum[gapParsed.type].span += clampedSpan;
  59349. fullyInExtBrksSum[gapParsed.type].val += gapParsed.val;
  59350. }
  59351. }
  59352. });
  59353. var prctBrksGapRealSum = gapPrctSum * (0 + (scaleExtent[1] - scaleExtent[0]) + (fullyInExtBrksSum.tpAbs.val - fullyInExtBrksSum.tpAbs.span) + (semiInExtBrk.S.tpAbs.has ? (semiInExtBrk.S.tpAbs.val - semiInExtBrk.S.tpAbs.span) * semiInExtBrk.S.tpAbs.inExtFrac : 0) + (semiInExtBrk.E.tpAbs.has ? (semiInExtBrk.E.tpAbs.val - semiInExtBrk.E.tpAbs.span) * semiInExtBrk.E.tpAbs.inExtFrac : 0) - fullyInExtBrksSum.tpPrct.span - (semiInExtBrk.S.tpPrct.has ? semiInExtBrk.S.tpPrct.span * semiInExtBrk.S.tpPrct.inExtFrac : 0) - (semiInExtBrk.E.tpPrct.has ? semiInExtBrk.E.tpPrct.span * semiInExtBrk.E.tpPrct.inExtFrac : 0)) / (1 - fullyInExtBrksSum.tpPrct.val - (semiInExtBrk.S.tpPrct.has ? semiInExtBrk.S.tpPrct.val * semiInExtBrk.S.tpPrct.inExtFrac : 0) - (semiInExtBrk.E.tpPrct.has ? semiInExtBrk.E.tpPrct.val * semiInExtBrk.E.tpPrct.inExtFrac : 0));
  59354. each(brkCtx.breaks, function (brk) {
  59355. var gapParsed = brk.gapParsed;
  59356. if (gapParsed.type === 'tpPrct') {
  59357. brk.gapReal = gapPrctSum !== 0
  59358. // prctBrksGapRealSum is supposed to be non-negative but add a safe guard
  59359. ? Math.max(prctBrksGapRealSum, 0) * gapParsed.val / gapPrctSum : 0;
  59360. }
  59361. if (gapParsed.type === 'tpAbs') {
  59362. brk.gapReal = gapParsed.val;
  59363. }
  59364. if (brk.gapReal == null) {
  59365. brk.gapReal = 0;
  59366. }
  59367. });
  59368. }
  59369. function pruneTicksByBreak(pruneByBreak, ticks, breaks, getValue, interval, scaleExtent) {
  59370. if (pruneByBreak === 'no') {
  59371. return;
  59372. }
  59373. each(breaks, function (brk) {
  59374. // break.vmin/vmax that out of extent must not impact the visible of
  59375. // normal ticks and labels.
  59376. var clampedBrk = clampBreakByExtent(brk, scaleExtent);
  59377. if (!clampedBrk) {
  59378. return;
  59379. }
  59380. // Remove some normal ticks to avoid zigzag shapes overlapping with split lines
  59381. // and to avoid break labels overlapping with normal tick labels (thouth it can
  59382. // also be avoided by `axisLabel.hideOverlap`).
  59383. // It's OK to O(n^2) since the number of `ticks` are small.
  59384. for (var j = ticks.length - 1; j >= 0; j--) {
  59385. var tick = ticks[j];
  59386. var val = getValue(tick);
  59387. // 1. Ensure there is no ticks inside `break.vmin` and `break.vmax`.
  59388. // 2. Use an empirically gap value here. Theoritically `zigzagAmplitude` is
  59389. // supposed to be involved to provide better precision but it will brings
  59390. // more complexity. The empirically gap value is conservative because break
  59391. // labels and normal tick lables are prone to overlapping.
  59392. var gap = interval * 3 / 4;
  59393. if (val > clampedBrk.vmin - gap && val < clampedBrk.vmax + gap && (pruneByBreak !== 'preserve_extent_bound' || val !== scaleExtent[0] && val !== scaleExtent[1])) {
  59394. ticks.splice(j, 1);
  59395. }
  59396. }
  59397. });
  59398. }
  59399. function addBreaksToTicks(
  59400. // The input ticks should be in accending order.
  59401. ticks, breaks, scaleExtent,
  59402. // Keep the break ends at the same level to avoid an awkward appearance.
  59403. getTimeProps) {
  59404. each(breaks, function (brk) {
  59405. var clampedBrk = clampBreakByExtent(brk, scaleExtent);
  59406. if (!clampedBrk) {
  59407. return;
  59408. }
  59409. // - When neight `break.vmin` nor `break.vmax` is in scale extent,
  59410. // break label should not be displayed and we do not add them to the result.
  59411. // - When only one of `break.vmin` and `break.vmax` is inside the extent and the
  59412. // other is outsite, we comply with the extent and display only part of the breaks area,
  59413. // because the extent might be determined by user settings (such as `axis.min/max`)
  59414. ticks.push({
  59415. value: clampedBrk.vmin,
  59416. "break": {
  59417. type: 'vmin',
  59418. parsedBreak: clampedBrk
  59419. },
  59420. time: getTimeProps ? getTimeProps(clampedBrk) : undefined
  59421. });
  59422. // When gap is 0, start tick overlap with end tick, but we still count both of them. Break
  59423. // area shape can address that overlapping. `axisLabel` need draw both start and end separately,
  59424. // otherwise it brings complexity to the logic of label overlapping resolving (e.g., when label
  59425. // rotated), and introduces inconsistency to users in `axisLabel.formatter` between gap is 0 or not.
  59426. ticks.push({
  59427. value: clampedBrk.vmax,
  59428. "break": {
  59429. type: 'vmax',
  59430. parsedBreak: clampedBrk
  59431. },
  59432. time: getTimeProps ? getTimeProps(clampedBrk) : undefined
  59433. });
  59434. });
  59435. if (breaks.length) {
  59436. ticks.sort(function (a, b) {
  59437. return a.value - b.value;
  59438. });
  59439. }
  59440. }
  59441. /**
  59442. * If break and extent does not intersect, return null/undefined.
  59443. * If the intersection is only a point at scaleExtent[0] or scaleExtent[1], return null/undefined.
  59444. */
  59445. function clampBreakByExtent(brk, scaleExtent) {
  59446. var vmin = Math.max(brk.vmin, scaleExtent[0]);
  59447. var vmax = Math.min(brk.vmax, scaleExtent[1]);
  59448. return vmin < vmax || vmin === vmax && vmin > scaleExtent[0] && vmin < scaleExtent[1] ? {
  59449. vmin: vmin,
  59450. vmax: vmax,
  59451. breakOption: brk.breakOption,
  59452. gapParsed: brk.gapParsed,
  59453. gapReal: brk.gapReal
  59454. } : null;
  59455. }
  59456. function parseAxisBreakOption(
  59457. // raw user input breaks, retrieved from axis model.
  59458. breakOptionList, parse, opt) {
  59459. var parsedBreaks = [];
  59460. if (!breakOptionList) {
  59461. return {
  59462. breaks: parsedBreaks
  59463. };
  59464. }
  59465. function validatePercent(normalizedPercent, msg) {
  59466. if (normalizedPercent >= 0 && normalizedPercent < 1 - 1e-5) {
  59467. // Avoid division error.
  59468. return true;
  59469. }
  59470. if ("development" !== 'production') {
  59471. error(msg + " must be >= 0 and < 1, rather than " + normalizedPercent + " .");
  59472. }
  59473. return false;
  59474. }
  59475. each(breakOptionList, function (brkOption) {
  59476. if (!brkOption || brkOption.start == null || brkOption.end == null) {
  59477. if ("development" !== 'production') {
  59478. error('The input axis breaks start/end should not be empty.');
  59479. }
  59480. return;
  59481. }
  59482. if (brkOption.isExpanded) {
  59483. return;
  59484. }
  59485. var parsedBrk = {
  59486. breakOption: clone(brkOption),
  59487. vmin: parse(brkOption.start),
  59488. vmax: parse(brkOption.end),
  59489. gapParsed: {
  59490. type: 'tpAbs',
  59491. val: 0
  59492. },
  59493. gapReal: null
  59494. };
  59495. if (brkOption.gap != null) {
  59496. var isPrct = false;
  59497. if (isString(brkOption.gap)) {
  59498. var trimmedGap = trim(brkOption.gap);
  59499. if (trimmedGap.match(/%$/)) {
  59500. var normalizedPercent = parseFloat(trimmedGap) / 100;
  59501. if (!validatePercent(normalizedPercent, 'Percent gap')) {
  59502. normalizedPercent = 0;
  59503. }
  59504. parsedBrk.gapParsed.type = 'tpPrct';
  59505. parsedBrk.gapParsed.val = normalizedPercent;
  59506. isPrct = true;
  59507. }
  59508. }
  59509. if (!isPrct) {
  59510. var absolute = parse(brkOption.gap);
  59511. if (!isFinite(absolute) || absolute < 0) {
  59512. if ("development" !== 'production') {
  59513. error("Axis breaks gap must positive finite rather than (" + brkOption.gap + ").");
  59514. }
  59515. absolute = 0;
  59516. }
  59517. parsedBrk.gapParsed.type = 'tpAbs';
  59518. parsedBrk.gapParsed.val = absolute;
  59519. }
  59520. }
  59521. if (parsedBrk.vmin === parsedBrk.vmax) {
  59522. parsedBrk.gapParsed.type = 'tpAbs';
  59523. parsedBrk.gapParsed.val = 0;
  59524. }
  59525. if (opt && opt.noNegative) {
  59526. each(['vmin', 'vmax'], function (se) {
  59527. if (parsedBrk[se] < 0) {
  59528. if ("development" !== 'production') {
  59529. error("Axis break." + se + " must not be negative.");
  59530. }
  59531. parsedBrk[se] = 0;
  59532. }
  59533. });
  59534. }
  59535. // Ascending numerical order is the prerequisite of the calculation in Scale#normalize.
  59536. // User are allowed to input desending vmin/vmax for simplifying the usage.
  59537. if (parsedBrk.vmin > parsedBrk.vmax) {
  59538. var tmp = parsedBrk.vmax;
  59539. parsedBrk.vmax = parsedBrk.vmin;
  59540. parsedBrk.vmin = tmp;
  59541. }
  59542. parsedBreaks.push(parsedBrk);
  59543. });
  59544. // Ascending numerical order is the prerequisite of the calculation in Scale#normalize.
  59545. parsedBreaks.sort(function (item1, item2) {
  59546. return item1.vmin - item2.vmin;
  59547. });
  59548. // Make sure that the intervals in breaks are not overlap.
  59549. var lastEnd = -Infinity;
  59550. each(parsedBreaks, function (brk, idx) {
  59551. if (lastEnd > brk.vmin) {
  59552. if ("development" !== 'production') {
  59553. error('Axis breaks must not overlap.');
  59554. }
  59555. parsedBreaks[idx] = null;
  59556. }
  59557. lastEnd = brk.vmax;
  59558. });
  59559. return {
  59560. breaks: parsedBreaks.filter(function (brk) {
  59561. return !!brk;
  59562. })
  59563. };
  59564. }
  59565. function identifyAxisBreak(brk, identifier) {
  59566. return serializeAxisBreakIdentifier(identifier) === serializeAxisBreakIdentifier(brk);
  59567. }
  59568. function serializeAxisBreakIdentifier(identifier) {
  59569. // We use user input start/end to identify break. Considered cases like `start: new Date(xxx)`,
  59570. // Theoretically `Scale#parse` should be used here, but not used currently to reduce dependencies,
  59571. // since simply converting to string happens to be correct.
  59572. return identifier.start + '_\0_' + identifier.end;
  59573. }
  59574. /**
  59575. * - A break pair represents `[vmin, vmax]`,
  59576. * - Only both vmin and vmax item exist, they are counted as a pair.
  59577. */
  59578. function retrieveAxisBreakPairs(itemList, getVisualAxisBreak, returnIdx) {
  59579. var idxPairList = [];
  59580. each(itemList, function (el, idx) {
  59581. var vBreak = getVisualAxisBreak(el);
  59582. if (vBreak && vBreak.type === 'vmin') {
  59583. idxPairList.push([idx]);
  59584. }
  59585. });
  59586. each(itemList, function (el, idx) {
  59587. var vBreak = getVisualAxisBreak(el);
  59588. if (vBreak && vBreak.type === 'vmax') {
  59589. var idxPair = find(idxPairList,
  59590. // parsedBreak may be changed, can only use breakOption to match them.
  59591. function (pr) {
  59592. return identifyAxisBreak(getVisualAxisBreak(itemList[pr[0]]).parsedBreak.breakOption, vBreak.parsedBreak.breakOption);
  59593. });
  59594. idxPair && idxPair.push(idx);
  59595. }
  59596. });
  59597. var result = [];
  59598. each(idxPairList, function (idxPair) {
  59599. if (idxPair.length === 2) {
  59600. result.push(returnIdx ? idxPair : [itemList[idxPair[0]], itemList[idxPair[1]]]);
  59601. }
  59602. });
  59603. return result;
  59604. }
  59605. function getTicksLogTransformBreak(tick, logBase, logOriginalBreaks, fixRoundingError) {
  59606. var vBreak;
  59607. var brkRoundingCriterion;
  59608. if (tick["break"]) {
  59609. var brk = tick["break"].parsedBreak;
  59610. var originalBreak = find(logOriginalBreaks, function (brk) {
  59611. return identifyAxisBreak(brk.breakOption, tick["break"].parsedBreak.breakOption);
  59612. });
  59613. var vmin = fixRoundingError(Math.pow(logBase, brk.vmin), originalBreak.vmin);
  59614. var vmax = fixRoundingError(Math.pow(logBase, brk.vmax), originalBreak.vmax);
  59615. var gapParsed = {
  59616. type: brk.gapParsed.type,
  59617. val: brk.gapParsed.type === 'tpAbs' ? round(Math.pow(logBase, brk.vmin + brk.gapParsed.val)) - vmin : brk.gapParsed.val
  59618. };
  59619. vBreak = {
  59620. type: tick["break"].type,
  59621. parsedBreak: {
  59622. breakOption: brk.breakOption,
  59623. vmin: vmin,
  59624. vmax: vmax,
  59625. gapParsed: gapParsed,
  59626. gapReal: brk.gapReal
  59627. }
  59628. };
  59629. brkRoundingCriterion = originalBreak[tick["break"].type];
  59630. }
  59631. return {
  59632. brkRoundingCriterion: brkRoundingCriterion,
  59633. vBreak: vBreak
  59634. };
  59635. }
  59636. function logarithmicParseBreaksFromOption(breakOptionList, logBase, parse) {
  59637. var opt = {
  59638. noNegative: true
  59639. };
  59640. var parsedOriginal = parseAxisBreakOption(breakOptionList, parse, opt);
  59641. var parsedLogged = parseAxisBreakOption(breakOptionList, parse, opt);
  59642. var loggedBase = Math.log(logBase);
  59643. parsedLogged.breaks = map(parsedLogged.breaks, function (brk) {
  59644. var vmin = Math.log(brk.vmin) / loggedBase;
  59645. var vmax = Math.log(brk.vmax) / loggedBase;
  59646. var gapParsed = {
  59647. type: brk.gapParsed.type,
  59648. val: brk.gapParsed.type === 'tpAbs' ? Math.log(brk.vmin + brk.gapParsed.val) / loggedBase - vmin : brk.gapParsed.val
  59649. };
  59650. return {
  59651. vmin: vmin,
  59652. vmax: vmax,
  59653. gapParsed: gapParsed,
  59654. gapReal: brk.gapReal,
  59655. breakOption: brk.breakOption
  59656. };
  59657. });
  59658. return {
  59659. parsedOriginal: parsedOriginal,
  59660. parsedLogged: parsedLogged
  59661. };
  59662. }
  59663. var BREAK_MIN_MAX_TO_PARAM = {
  59664. vmin: 'start',
  59665. vmax: 'end'
  59666. };
  59667. function makeAxisLabelFormatterParamBreak(extraParam, vBreak) {
  59668. if (vBreak) {
  59669. extraParam = extraParam || {};
  59670. extraParam["break"] = {
  59671. type: BREAK_MIN_MAX_TO_PARAM[vBreak.type],
  59672. start: vBreak.parsedBreak.vmin,
  59673. end: vBreak.parsedBreak.vmax
  59674. };
  59675. }
  59676. return extraParam;
  59677. }
  59678. function installScaleBreakHelper() {
  59679. registerScaleBreakHelperImpl({
  59680. createScaleBreakContext: createScaleBreakContext,
  59681. pruneTicksByBreak: pruneTicksByBreak,
  59682. addBreaksToTicks: addBreaksToTicks,
  59683. parseAxisBreakOption: parseAxisBreakOption,
  59684. identifyAxisBreak: identifyAxisBreak,
  59685. serializeAxisBreakIdentifier: serializeAxisBreakIdentifier,
  59686. retrieveAxisBreakPairs: retrieveAxisBreakPairs,
  59687. getTicksLogTransformBreak: getTicksLogTransformBreak,
  59688. logarithmicParseBreaksFromOption: logarithmicParseBreaksFromOption,
  59689. makeAxisLabelFormatterParamBreak: makeAxisLabelFormatterParamBreak
  59690. });
  59691. }
  59692. /**
  59693. * @caution
  59694. * Must not export anything except `installAxisBreakHelper`
  59695. */
  59696. /**
  59697. * The zigzag shapes for axis breaks are generated according to some random
  59698. * factors. It should persist as much as possible to avoid constantly
  59699. * changing by every user operation.
  59700. */
  59701. var viewCache = makeInner();
  59702. function ensureVisualInCache(visualList, targetBreak) {
  59703. var visual = find(visualList, function (item) {
  59704. return getScaleBreakHelper().identifyAxisBreak(item.parsedBreak.breakOption, targetBreak.breakOption);
  59705. });
  59706. if (!visual) {
  59707. visualList.push(visual = {
  59708. zigzagRandomList: [],
  59709. parsedBreak: targetBreak,
  59710. shouldRemove: false
  59711. });
  59712. }
  59713. return visual;
  59714. }
  59715. function resetCacheVisualRemoveFlag(visualList) {
  59716. each(visualList, function (item) {
  59717. return item.shouldRemove = true;
  59718. });
  59719. }
  59720. function removeUnusedCacheVisual(visualList) {
  59721. for (var i = visualList.length - 1; i >= 0; i--) {
  59722. if (visualList[i].shouldRemove) {
  59723. visualList.splice(i, 1);
  59724. }
  59725. }
  59726. }
  59727. function rectCoordBuildBreakAxis(axisGroup, axisView, axisModel, coordSysRect, api) {
  59728. var axis = axisModel.axis;
  59729. if (axis.scale.isBlank() || !getScaleBreakHelper()) {
  59730. return;
  59731. }
  59732. var breakPairs = getScaleBreakHelper().retrieveAxisBreakPairs(axis.scale.getTicks({
  59733. breakTicks: 'only_break'
  59734. }), function (tick) {
  59735. return tick["break"];
  59736. }, false);
  59737. if (!breakPairs.length) {
  59738. return;
  59739. }
  59740. var breakAreaModel = axisModel.getModel('breakArea');
  59741. var zigzagAmplitude = breakAreaModel.get('zigzagAmplitude');
  59742. var zigzagMinSpan = breakAreaModel.get('zigzagMinSpan');
  59743. var zigzagMaxSpan = breakAreaModel.get('zigzagMaxSpan');
  59744. // Use arbitrary value to avoid dead loop if user gives inappropriate settings.
  59745. zigzagMinSpan = Math.max(2, zigzagMinSpan || 0);
  59746. zigzagMaxSpan = Math.max(zigzagMinSpan, zigzagMaxSpan || 0);
  59747. var expandOnClick = breakAreaModel.get('expandOnClick');
  59748. var zigzagZ = breakAreaModel.get('zigzagZ');
  59749. var itemStyleModel = breakAreaModel.getModel('itemStyle');
  59750. var itemStyle = itemStyleModel.getItemStyle();
  59751. var borderColor = itemStyle.stroke;
  59752. var borderWidth = itemStyle.lineWidth;
  59753. var borderType = itemStyle.lineDash;
  59754. var color = itemStyle.fill;
  59755. var group = new Group({
  59756. ignoreModelZ: true
  59757. });
  59758. var isAxisHorizontal = axis.isHorizontal();
  59759. var cachedVisualList = viewCache(axisView).visualList || (viewCache(axisView).visualList = []);
  59760. resetCacheVisualRemoveFlag(cachedVisualList);
  59761. var _loop_1 = function (i) {
  59762. var parsedBreak = breakPairs[i][0]["break"].parsedBreak;
  59763. // Even if brk.gap is 0, we should also draw the breakArea because
  59764. // border is sometimes required to be visible (as a line)
  59765. var coords = [];
  59766. coords[0] = axis.toGlobalCoord(axis.dataToCoord(parsedBreak.vmin, true));
  59767. coords[1] = axis.toGlobalCoord(axis.dataToCoord(parsedBreak.vmax, true));
  59768. if (coords[1] < coords[0]) {
  59769. coords.reverse();
  59770. }
  59771. var cachedVisual = ensureVisualInCache(cachedVisualList, parsedBreak);
  59772. cachedVisual.shouldRemove = false;
  59773. var breakGroup = new Group();
  59774. addZigzagShapes(cachedVisual.zigzagRandomList, breakGroup, coords[0], coords[1], isAxisHorizontal, parsedBreak);
  59775. if (expandOnClick) {
  59776. breakGroup.on('click', function () {
  59777. var payload = {
  59778. type: AXIS_BREAK_EXPAND_ACTION_TYPE,
  59779. breaks: [{
  59780. start: parsedBreak.breakOption.start,
  59781. end: parsedBreak.breakOption.end
  59782. }]
  59783. };
  59784. payload[axis.dim + "AxisIndex"] = axisModel.componentIndex;
  59785. api.dispatchAction(payload);
  59786. });
  59787. }
  59788. breakGroup.silent = !expandOnClick;
  59789. group.add(breakGroup);
  59790. };
  59791. for (var i = 0; i < breakPairs.length; i++) {
  59792. _loop_1(i);
  59793. }
  59794. axisGroup.add(group);
  59795. removeUnusedCacheVisual(cachedVisualList);
  59796. function addZigzagShapes(zigzagRandomList, breakGroup, startCoord, endCoord, isAxisHorizontal, trimmedBreak) {
  59797. var polylineStyle = {
  59798. stroke: borderColor,
  59799. lineWidth: borderWidth,
  59800. lineDash: borderType,
  59801. fill: 'none'
  59802. };
  59803. var dimBrk = isAxisHorizontal ? 0 : 1;
  59804. var dimZigzag = 1 - dimBrk;
  59805. var zigzagCoordMax = coordSysRect[XY$1[dimZigzag]] + coordSysRect[WH$1[dimZigzag]];
  59806. // Apply `subPixelOptimizeLine` for alignning with break ticks.
  59807. function subPixelOpt(brkCoord) {
  59808. var pBrk = [];
  59809. var dummyP = [];
  59810. pBrk[dimBrk] = dummyP[dimBrk] = brkCoord;
  59811. pBrk[dimZigzag] = coordSysRect[XY$1[dimZigzag]];
  59812. dummyP[dimZigzag] = zigzagCoordMax;
  59813. var dummyShape = {
  59814. x1: pBrk[0],
  59815. y1: pBrk[1],
  59816. x2: dummyP[0],
  59817. y2: dummyP[1]
  59818. };
  59819. subPixelOptimizeLine(dummyShape, dummyShape, {
  59820. lineWidth: 1
  59821. });
  59822. pBrk[0] = dummyShape.x1;
  59823. pBrk[1] = dummyShape.y1;
  59824. return pBrk[dimBrk];
  59825. }
  59826. startCoord = subPixelOpt(startCoord);
  59827. endCoord = subPixelOpt(endCoord);
  59828. var pointsA = [];
  59829. var pointsB = [];
  59830. var isSwap = true;
  59831. var current = coordSysRect[XY$1[dimZigzag]];
  59832. for (var idx = 0;; idx++) {
  59833. // Use `isFirstPoint` `isLastPoint` to ensure the intersections between zigzag
  59834. // and axis are precise, thus it can join its axis tick correctly.
  59835. var isFirstPoint = current === coordSysRect[XY$1[dimZigzag]];
  59836. var isLastPoint = current >= zigzagCoordMax;
  59837. if (isLastPoint) {
  59838. current = zigzagCoordMax;
  59839. }
  59840. var pA = [];
  59841. var pB = [];
  59842. pA[dimBrk] = startCoord;
  59843. pB[dimBrk] = endCoord;
  59844. if (!isFirstPoint && !isLastPoint) {
  59845. pA[dimBrk] += isSwap ? -zigzagAmplitude : zigzagAmplitude;
  59846. pB[dimBrk] -= !isSwap ? -zigzagAmplitude : zigzagAmplitude;
  59847. }
  59848. pA[dimZigzag] = current;
  59849. pB[dimZigzag] = current;
  59850. pointsA.push(pA);
  59851. pointsB.push(pB);
  59852. var randomVal = void 0;
  59853. if (idx < zigzagRandomList.length) {
  59854. randomVal = zigzagRandomList[idx];
  59855. } else {
  59856. randomVal = Math.random();
  59857. zigzagRandomList.push(randomVal);
  59858. }
  59859. current += randomVal * (zigzagMaxSpan - zigzagMinSpan) + zigzagMinSpan;
  59860. isSwap = !isSwap;
  59861. if (isLastPoint) {
  59862. break;
  59863. }
  59864. }
  59865. var anidSuffix = getScaleBreakHelper().serializeAxisBreakIdentifier(trimmedBreak.breakOption);
  59866. // Create two polylines and add them to the breakGroup
  59867. breakGroup.add(new Polyline({
  59868. anid: "break_a_" + anidSuffix,
  59869. shape: {
  59870. points: pointsA
  59871. },
  59872. style: polylineStyle,
  59873. z: zigzagZ
  59874. }));
  59875. /* Add the second polyline and a polygon only if the gap is not zero
  59876. * Otherwise if the polyline is with dashed line or being opaque,
  59877. * it may not be constant with breaks with non-zero gaps. */
  59878. if (trimmedBreak.gapReal !== 0) {
  59879. breakGroup.add(new Polyline({
  59880. anid: "break_b_" + anidSuffix,
  59881. shape: {
  59882. // Not reverse to keep the dash stable when dragging resizing.
  59883. points: pointsB
  59884. },
  59885. style: polylineStyle,
  59886. z: zigzagZ
  59887. }));
  59888. // Creating the polygon that fills the area between the polylines
  59889. // From end to start for polygon.
  59890. var pointsB2 = pointsB.slice();
  59891. pointsB2.reverse();
  59892. var polygonPoints = pointsA.concat(pointsB2);
  59893. breakGroup.add(new Polygon({
  59894. anid: "break_c_" + anidSuffix,
  59895. shape: {
  59896. points: polygonPoints
  59897. },
  59898. style: {
  59899. fill: color,
  59900. opacity: itemStyle.opacity
  59901. },
  59902. z: zigzagZ
  59903. }));
  59904. }
  59905. }
  59906. }
  59907. function buildAxisBreakLine(axisModel, group, transformGroup, pathBaseProp) {
  59908. var axis = axisModel.axis;
  59909. var transform = transformGroup.transform;
  59910. assert(pathBaseProp.style);
  59911. var extent = axis.getExtent();
  59912. if (axis.inverse) {
  59913. extent = extent.slice();
  59914. extent.reverse();
  59915. }
  59916. var breakPairs = getScaleBreakHelper().retrieveAxisBreakPairs(axis.scale.getTicks({
  59917. breakTicks: 'only_break'
  59918. }), function (tick) {
  59919. return tick["break"];
  59920. }, false);
  59921. var brkLayoutList = map(breakPairs, function (breakPair) {
  59922. var parsedBreak = breakPair[0]["break"].parsedBreak;
  59923. var coordPair = [axis.dataToCoord(parsedBreak.vmin, true), axis.dataToCoord(parsedBreak.vmax, true)];
  59924. coordPair[0] > coordPair[1] && coordPair.reverse();
  59925. return {
  59926. coordPair: coordPair,
  59927. brkId: getScaleBreakHelper().serializeAxisBreakIdentifier(parsedBreak.breakOption)
  59928. };
  59929. });
  59930. brkLayoutList.sort(function (layout1, layout2) {
  59931. return layout1.coordPair[0] - layout2.coordPair[0];
  59932. });
  59933. var ySegMin = extent[0];
  59934. var lastLayout = null;
  59935. for (var idx = 0; idx < brkLayoutList.length; idx++) {
  59936. var layout = brkLayoutList[idx];
  59937. var brkTirmmedMin = Math.max(layout.coordPair[0], extent[0]);
  59938. var brkTirmmedMax = Math.min(layout.coordPair[1], extent[1]);
  59939. if (ySegMin <= brkTirmmedMin) {
  59940. addSeg(ySegMin, brkTirmmedMin, lastLayout, layout);
  59941. }
  59942. ySegMin = brkTirmmedMax;
  59943. lastLayout = layout;
  59944. }
  59945. if (ySegMin <= extent[1]) {
  59946. addSeg(ySegMin, extent[1], lastLayout, null);
  59947. }
  59948. function addSeg(min, max, layout1, layout2) {
  59949. function trans(p1, p2) {
  59950. if (transform) {
  59951. applyTransform(p1, p1, transform);
  59952. applyTransform(p2, p2, transform);
  59953. }
  59954. }
  59955. function subPixelOptimizePP(p1, p2) {
  59956. var shape = {
  59957. x1: p1[0],
  59958. y1: p1[1],
  59959. x2: p2[0],
  59960. y2: p2[1]
  59961. };
  59962. subPixelOptimizeLine(shape, shape, pathBaseProp.style);
  59963. p1[0] = shape.x1;
  59964. p1[1] = shape.y1;
  59965. p2[0] = shape.x2;
  59966. p2[1] = shape.y2;
  59967. }
  59968. var lineP1 = [min, 0];
  59969. var lineP2 = [max, 0];
  59970. // dummy tick is used to align the line segment ends with axis ticks
  59971. // after `subPixelOptimizeLine` being applied.
  59972. var dummyTickEnd1 = [min, 5];
  59973. var dummyTickEnd2 = [max, 5];
  59974. trans(lineP1, dummyTickEnd1);
  59975. subPixelOptimizePP(lineP1, dummyTickEnd1);
  59976. trans(lineP2, dummyTickEnd2);
  59977. subPixelOptimizePP(lineP2, dummyTickEnd2);
  59978. // Apply it keeping the same as the normal axis line.
  59979. subPixelOptimizePP(lineP1, lineP2);
  59980. var seg = new Line(extend({
  59981. shape: {
  59982. x1: lineP1[0],
  59983. y1: lineP1[1],
  59984. x2: lineP2[0],
  59985. y2: lineP2[1]
  59986. }
  59987. }, pathBaseProp));
  59988. group.add(seg);
  59989. // Animation should be precise to be consistent with tick and split line animation.
  59990. seg.anid = "breakLine_" + (layout1 ? layout1.brkId : '\0') + "_\0_" + (layout2 ? layout2.brkId : '\0');
  59991. }
  59992. }
  59993. /**
  59994. * Resolve the overlap of a pair of labels.
  59995. *
  59996. * [CAUTION] Only label.x/y are allowed to change.
  59997. */
  59998. function adjustBreakLabelPair(axisInverse, axisRotation, layoutPair) {
  59999. if (find(layoutPair, function (item) {
  60000. return !item;
  60001. })) {
  60002. return;
  60003. }
  60004. var mtv = new Point();
  60005. if (!labelIntersect(layoutPair[0], layoutPair[1], mtv, {
  60006. // Assert `labelPair` is `[break_min, break_max]`.
  60007. // `axis.inverse: true` means a smaller scale value corresponds to a bigger value in axis.extent.
  60008. // The axisRotation indicates mtv direction of OBB intersecting.
  60009. direction: -(axisInverse ? axisRotation + Math.PI : axisRotation),
  60010. touchThreshold: 0,
  60011. // If need to resovle intersection align axis by moving labels according to MTV,
  60012. // the direction must not be opposite, otherwise cause misleading.
  60013. bidirectional: false
  60014. })) {
  60015. return;
  60016. }
  60017. // Rotate axis back to (1, 0) direction, to be a standard axis.
  60018. var axisStTrans = create$1();
  60019. rotate(axisStTrans, axisStTrans, -axisRotation);
  60020. var labelPairStTrans = map(layoutPair, function (layout) {
  60021. return layout.transform ? mul$1(create$1(), axisStTrans, layout.transform) : axisStTrans;
  60022. });
  60023. function isParallelToAxis(whIdx) {
  60024. // Assert label[0] and label[1] has the same rotation, so only use [0].
  60025. var localRect = layoutPair[0].localRect;
  60026. var labelVec0 = new Point(localRect[WH$1[whIdx]] * labelPairStTrans[0][0], localRect[WH$1[whIdx]] * labelPairStTrans[0][1]);
  60027. return Math.abs(labelVec0.y) < 1e-5;
  60028. }
  60029. // If overlapping, move pair[0] pair[1] apart a little. We need to calculate a ratio k to
  60030. // distribute mtv to pair[0] and pair[1]. This is to place the text gap as close as possible
  60031. // to the center of the break ticks, otherwise it might looks weird or misleading.
  60032. // - When labels' width/height are not parallel to axis (usually by rotation),
  60033. // we can simply treat the k as `0.5`.
  60034. var k = 0.5;
  60035. // - When labels' width/height are parallel to axis, the width/height need to be considered,
  60036. // since they may differ significantly. In this case we keep textAlign as 'center' rather
  60037. // than 'left'/'right', due to considerations of space utilization for wide break.gap.
  60038. // A sample case: break on xAxis(no inverse) is [200, 300000].
  60039. // We calculate k based on the formula below:
  60040. // Rotated axis and labels to the direction of (1, 0).
  60041. // uval = ( (pair[0].insidePt - mtv*k) + (pair[1].insidePt + mtv*(1-k)) ) / 2 - brkCenter
  60042. // 0 <= k <= 1
  60043. // |uval| should be as small as possible.
  60044. // Derived as follows:
  60045. // qval = (pair[0].insidePt + pair[1].insidePt + mtv) / 2 - brkCenter
  60046. // k = (qval - uval) / mtv
  60047. // min(qval, qval-mtv) <= uval <= max(qval, qval-mtv)
  60048. if (isParallelToAxis(0) || isParallelToAxis(1)) {
  60049. var rectSt = map(layoutPair, function (layout, idx) {
  60050. var rect = layout.localRect.clone();
  60051. rect.applyTransform(labelPairStTrans[idx]);
  60052. return rect;
  60053. });
  60054. var brkCenterSt = new Point();
  60055. brkCenterSt.copy(layoutPair[0].label).add(layoutPair[1].label).scale(0.5);
  60056. brkCenterSt.transform(axisStTrans);
  60057. var mtvSt = mtv.clone().transform(axisStTrans);
  60058. var insidePtSum = rectSt[0].x + rectSt[1].x + (mtvSt.x >= 0 ? rectSt[0].width : rectSt[1].width);
  60059. var qval = (insidePtSum + mtvSt.x) / 2 - brkCenterSt.x;
  60060. var uvalMin = Math.min(qval, qval - mtvSt.x);
  60061. var uvalMax = Math.max(qval, qval - mtvSt.x);
  60062. var uval = uvalMax < 0 ? uvalMax : uvalMin > 0 ? uvalMin : 0;
  60063. k = (qval - uval) / mtvSt.x;
  60064. }
  60065. var delta0 = new Point();
  60066. var delta1 = new Point();
  60067. Point.scale(delta0, mtv, -k);
  60068. Point.scale(delta1, mtv, 1 - k);
  60069. labelLayoutApplyTranslation(layoutPair[0], delta0);
  60070. labelLayoutApplyTranslation(layoutPair[1], delta1);
  60071. }
  60072. function updateModelAxisBreak(model, payload) {
  60073. var result = {
  60074. breaks: []
  60075. };
  60076. each(payload.breaks, function (inputBrk) {
  60077. if (!inputBrk) {
  60078. return;
  60079. }
  60080. var breakOption = find(model.get('breaks', true), function (brkOption) {
  60081. return getScaleBreakHelper().identifyAxisBreak(brkOption, inputBrk);
  60082. });
  60083. if (!breakOption) {
  60084. if ("development" !== 'production') {
  60085. warn("Can not find axis break by start: " + inputBrk.start + ", end: " + inputBrk.end);
  60086. }
  60087. return;
  60088. }
  60089. var actionType = payload.type;
  60090. var old = {
  60091. isExpanded: !!breakOption.isExpanded
  60092. };
  60093. breakOption.isExpanded = actionType === AXIS_BREAK_EXPAND_ACTION_TYPE ? true : actionType === AXIS_BREAK_COLLAPSE_ACTION_TYPE ? false : actionType === AXIS_BREAK_TOGGLE_ACTION_TYPE ? !breakOption.isExpanded : breakOption.isExpanded;
  60094. result.breaks.push({
  60095. start: breakOption.start,
  60096. end: breakOption.end,
  60097. isExpanded: !!breakOption.isExpanded,
  60098. old: old
  60099. });
  60100. });
  60101. return result;
  60102. }
  60103. function installAxisBreakHelper() {
  60104. registerAxisBreakHelperImpl({
  60105. adjustBreakLabelPair: adjustBreakLabelPair,
  60106. buildAxisBreakLine: buildAxisBreakLine,
  60107. rectCoordBuildBreakAxis: rectCoordBuildBreakAxis,
  60108. updateModelAxisBreak: updateModelAxisBreak
  60109. });
  60110. }
  60111. function installAxisBreak(registers) {
  60112. registerAction$1(registers);
  60113. installScaleBreakHelper();
  60114. installAxisBreakHelper();
  60115. }
  60116. use([install$1]);
  60117. use([install]);
  60118. use([install$2, install$3, install$4, install$6]);
  60119. 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]);
  60120. // Features
  60121. use([installAxisBreak]);
  60122. exports.Axis = Axis;
  60123. exports.ChartView = ChartView;
  60124. exports.ComponentModel = ComponentModel;
  60125. exports.ComponentView = ComponentView;
  60126. exports.List = SeriesData;
  60127. exports.Model = Model;
  60128. exports.PRIORITY = PRIORITY;
  60129. exports.SeriesModel = SeriesModel;
  60130. exports.color = color;
  60131. exports.connect = connect;
  60132. exports.dataTool = dataTool;
  60133. exports.dependencies = dependencies;
  60134. exports.disConnect = disConnect;
  60135. exports.disconnect = disconnect;
  60136. exports.dispose = dispose$1;
  60137. exports.env = env;
  60138. exports.extendChartView = extendChartView;
  60139. exports.extendComponentModel = extendComponentModel;
  60140. exports.extendComponentView = extendComponentView;
  60141. exports.extendSeriesModel = extendSeriesModel;
  60142. exports.format = format$1;
  60143. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  60144. exports.getInstanceByDom = getInstanceByDom;
  60145. exports.getInstanceById = getInstanceById;
  60146. exports.getMap = getMap;
  60147. exports.graphic = graphic$1;
  60148. exports.helper = helper;
  60149. exports.init = init$1;
  60150. exports.innerDrawElementOnCanvas = brushSingle;
  60151. exports.matrix = matrix;
  60152. exports.number = number;
  60153. exports.parseGeoJSON = parseGeoJSON;
  60154. exports.parseGeoJson = parseGeoJSON;
  60155. exports.registerAction = registerAction;
  60156. exports.registerCoordinateSystem = registerCoordinateSystem;
  60157. exports.registerCustomSeries = registerCustomSeries;
  60158. exports.registerLayout = registerLayout;
  60159. exports.registerLoading = registerLoading;
  60160. exports.registerLocale = registerLocale;
  60161. exports.registerMap = registerMap;
  60162. exports.registerPostInit = registerPostInit;
  60163. exports.registerPostUpdate = registerPostUpdate;
  60164. exports.registerPreprocessor = registerPreprocessor;
  60165. exports.registerProcessor = registerProcessor;
  60166. exports.registerTheme = registerTheme;
  60167. exports.registerTransform = registerTransform;
  60168. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  60169. exports.registerVisual = registerVisual;
  60170. exports.setCanvasCreator = setCanvasCreator;
  60171. exports.setPlatformAPI = setPlatformAPI;
  60172. exports.throttle = throttle;
  60173. exports.time = time;
  60174. exports.use = use;
  60175. exports.util = util$1;
  60176. exports.vector = vector;
  60177. exports.version = version$1;
  60178. exports.zrUtil = util;
  60179. exports.zrender = zrender;
  60180. Object.defineProperty(exports, '__esModule', { value: true });
  60181. })));
  60182. //# sourceMappingURL=echarts.common.js.map