echarts.esm.js 2.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673
  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. /*! *****************************************************************************
  20. Copyright (c) Microsoft Corporation.
  21. Permission to use, copy, modify, and/or distribute this software for any
  22. purpose with or without fee is hereby granted.
  23. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  24. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  25. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  26. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  27. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  28. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  29. PERFORMANCE OF THIS SOFTWARE.
  30. ***************************************************************************** */
  31. /* global Reflect, Promise */
  32. var extendStatics = function(d, b) {
  33. extendStatics = Object.setPrototypeOf ||
  34. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  35. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  36. return extendStatics(d, b);
  37. };
  38. function __extends(d, b) {
  39. if (typeof b !== "function" && b !== null)
  40. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  41. extendStatics(d, b);
  42. function __() { this.constructor = d; }
  43. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  44. }
  45. var Browser = (function () {
  46. function Browser() {
  47. this.firefox = false;
  48. this.ie = false;
  49. this.edge = false;
  50. this.newEdge = false;
  51. this.weChat = false;
  52. }
  53. return Browser;
  54. }());
  55. var Env = (function () {
  56. function Env() {
  57. this.browser = new Browser();
  58. this.node = false;
  59. this.wxa = false;
  60. this.worker = false;
  61. this.svgSupported = false;
  62. this.touchEventsSupported = false;
  63. this.pointerEventsSupported = false;
  64. this.domSupported = false;
  65. this.transformSupported = false;
  66. this.transform3dSupported = false;
  67. this.hasGlobalWindow = typeof window !== 'undefined';
  68. }
  69. return Env;
  70. }());
  71. var env = new Env();
  72. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  73. env.wxa = true;
  74. env.touchEventsSupported = true;
  75. }
  76. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  77. env.worker = true;
  78. }
  79. else if (typeof navigator === 'undefined') {
  80. env.node = true;
  81. env.svgSupported = true;
  82. }
  83. else {
  84. detect(navigator.userAgent, env);
  85. }
  86. function detect(ua, env) {
  87. var browser = env.browser;
  88. var firefox = ua.match(/Firefox\/([\d.]+)/);
  89. var ie = ua.match(/MSIE\s([\d.]+)/)
  90. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  91. var edge = ua.match(/Edge?\/([\d.]+)/);
  92. var weChat = (/micromessenger/i).test(ua);
  93. if (firefox) {
  94. browser.firefox = true;
  95. browser.version = firefox[1];
  96. }
  97. if (ie) {
  98. browser.ie = true;
  99. browser.version = ie[1];
  100. }
  101. if (edge) {
  102. browser.edge = true;
  103. browser.version = edge[1];
  104. browser.newEdge = +edge[1].split('.')[0] > 18;
  105. }
  106. if (weChat) {
  107. browser.weChat = true;
  108. }
  109. env.svgSupported = typeof SVGRect !== 'undefined';
  110. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  111. env.pointerEventsSupported = 'onpointerdown' in window
  112. && (browser.edge || (browser.ie && +browser.version >= 11));
  113. env.domSupported = typeof document !== 'undefined';
  114. var style = document.documentElement.style;
  115. env.transform3dSupported = ((browser.ie && 'transition' in style)
  116. || browser.edge
  117. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  118. || 'MozPerspective' in style)
  119. && !('OTransition' in style);
  120. env.transformSupported = env.transform3dSupported
  121. || (browser.ie && +browser.version >= 9);
  122. }
  123. var DEFAULT_FONT_SIZE = 12;
  124. var DEFAULT_FONT_FAMILY = 'sans-serif';
  125. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  126. var OFFSET = 20;
  127. var SCALE = 100;
  128. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  129. function getTextWidthMap(mapStr) {
  130. var map = {};
  131. if (typeof JSON === 'undefined') {
  132. return map;
  133. }
  134. for (var i = 0; i < mapStr.length; i++) {
  135. var char = String.fromCharCode(i + 32);
  136. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  137. map[char] = size;
  138. }
  139. return map;
  140. }
  141. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  142. var platformApi = {
  143. createCanvas: function () {
  144. return typeof document !== 'undefined'
  145. && document.createElement('canvas');
  146. },
  147. measureText: (function () {
  148. var _ctx;
  149. var _cachedFont;
  150. return function (text, font) {
  151. if (!_ctx) {
  152. var canvas = platformApi.createCanvas();
  153. _ctx = canvas && canvas.getContext('2d');
  154. }
  155. if (_ctx) {
  156. if (_cachedFont !== font) {
  157. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  158. }
  159. return _ctx.measureText(text);
  160. }
  161. else {
  162. text = text || '';
  163. font = font || DEFAULT_FONT;
  164. var res = /(\d+)px/.exec(font);
  165. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  166. var width = 0;
  167. if (font.indexOf('mono') >= 0) {
  168. width = fontSize * text.length;
  169. }
  170. else {
  171. for (var i = 0; i < text.length; i++) {
  172. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  173. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  174. }
  175. }
  176. return { width: width };
  177. }
  178. };
  179. })(),
  180. loadImage: function (src, onload, onerror) {
  181. var image = new Image();
  182. image.onload = onload;
  183. image.onerror = onerror;
  184. image.src = src;
  185. return image;
  186. }
  187. };
  188. function setPlatformAPI(newPlatformApis) {
  189. for (var key in platformApi) {
  190. if (newPlatformApis[key]) {
  191. platformApi[key] = newPlatformApis[key];
  192. }
  193. }
  194. }
  195. var BUILTIN_OBJECT = reduce([
  196. 'Function',
  197. 'RegExp',
  198. 'Date',
  199. 'Error',
  200. 'CanvasGradient',
  201. 'CanvasPattern',
  202. 'Image',
  203. 'Canvas'
  204. ], function (obj, val) {
  205. obj['[object ' + val + ']'] = true;
  206. return obj;
  207. }, {});
  208. var TYPED_ARRAY = reduce([
  209. 'Int8',
  210. 'Uint8',
  211. 'Uint8Clamped',
  212. 'Int16',
  213. 'Uint16',
  214. 'Int32',
  215. 'Uint32',
  216. 'Float32',
  217. 'Float64'
  218. ], function (obj, val) {
  219. obj['[object ' + val + 'Array]'] = true;
  220. return obj;
  221. }, {});
  222. var objToString = Object.prototype.toString;
  223. var arrayProto = Array.prototype;
  224. var nativeForEach = arrayProto.forEach;
  225. var nativeFilter = arrayProto.filter;
  226. var nativeSlice = arrayProto.slice;
  227. var nativeMap = arrayProto.map;
  228. var ctorFunction = function () { }.constructor;
  229. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  230. var protoKey = '__proto__';
  231. var idStart = 0x0907;
  232. function guid() {
  233. return idStart++;
  234. }
  235. function logError() {
  236. var args = [];
  237. for (var _i = 0; _i < arguments.length; _i++) {
  238. args[_i] = arguments[_i];
  239. }
  240. if (typeof console !== 'undefined') {
  241. console.error.apply(console, args);
  242. }
  243. }
  244. function clone(source) {
  245. if (source == null || typeof source !== 'object') {
  246. return source;
  247. }
  248. var result = source;
  249. var typeStr = objToString.call(source);
  250. if (typeStr === '[object Array]') {
  251. if (!isPrimitive(source)) {
  252. result = [];
  253. for (var i = 0, len = source.length; i < len; i++) {
  254. result[i] = clone(source[i]);
  255. }
  256. }
  257. }
  258. else if (TYPED_ARRAY[typeStr]) {
  259. if (!isPrimitive(source)) {
  260. var Ctor = source.constructor;
  261. if (Ctor.from) {
  262. result = Ctor.from(source);
  263. }
  264. else {
  265. result = new Ctor(source.length);
  266. for (var i = 0, len = source.length; i < len; i++) {
  267. result[i] = source[i];
  268. }
  269. }
  270. }
  271. }
  272. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  273. result = {};
  274. for (var key in source) {
  275. if (source.hasOwnProperty(key) && key !== protoKey) {
  276. result[key] = clone(source[key]);
  277. }
  278. }
  279. }
  280. return result;
  281. }
  282. function merge(target, source, overwrite) {
  283. if (!isObject(source) || !isObject(target)) {
  284. return overwrite ? clone(source) : target;
  285. }
  286. for (var key in source) {
  287. if (source.hasOwnProperty(key) && key !== protoKey) {
  288. var targetProp = target[key];
  289. var sourceProp = source[key];
  290. if (isObject(sourceProp)
  291. && isObject(targetProp)
  292. && !isArray(sourceProp)
  293. && !isArray(targetProp)
  294. && !isDom(sourceProp)
  295. && !isDom(targetProp)
  296. && !isBuiltInObject(sourceProp)
  297. && !isBuiltInObject(targetProp)
  298. && !isPrimitive(sourceProp)
  299. && !isPrimitive(targetProp)) {
  300. merge(targetProp, sourceProp, overwrite);
  301. }
  302. else if (overwrite || !(key in target)) {
  303. target[key] = clone(source[key]);
  304. }
  305. }
  306. }
  307. return target;
  308. }
  309. function mergeAll(targetAndSources, overwrite) {
  310. var result = targetAndSources[0];
  311. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  312. result = merge(result, targetAndSources[i], overwrite);
  313. }
  314. return result;
  315. }
  316. function extend(target, source) {
  317. if (Object.assign) {
  318. Object.assign(target, source);
  319. }
  320. else {
  321. for (var key in source) {
  322. if (source.hasOwnProperty(key) && key !== protoKey) {
  323. target[key] = source[key];
  324. }
  325. }
  326. }
  327. return target;
  328. }
  329. function defaults(target, source, overlay) {
  330. var keysArr = keys(source);
  331. for (var i = 0; i < keysArr.length; i++) {
  332. var key = keysArr[i];
  333. if ((overlay ? source[key] != null : target[key] == null)) {
  334. target[key] = source[key];
  335. }
  336. }
  337. return target;
  338. }
  339. var createCanvas = platformApi.createCanvas;
  340. function indexOf(array, value) {
  341. if (array) {
  342. if (array.indexOf) {
  343. return array.indexOf(value);
  344. }
  345. for (var i = 0, len = array.length; i < len; i++) {
  346. if (array[i] === value) {
  347. return i;
  348. }
  349. }
  350. }
  351. return -1;
  352. }
  353. function inherits(clazz, baseClazz) {
  354. var clazzPrototype = clazz.prototype;
  355. function F() { }
  356. F.prototype = baseClazz.prototype;
  357. clazz.prototype = new F();
  358. for (var prop in clazzPrototype) {
  359. if (clazzPrototype.hasOwnProperty(prop)) {
  360. clazz.prototype[prop] = clazzPrototype[prop];
  361. }
  362. }
  363. clazz.prototype.constructor = clazz;
  364. clazz.superClass = baseClazz;
  365. }
  366. function mixin(target, source, override) {
  367. target = 'prototype' in target ? target.prototype : target;
  368. source = 'prototype' in source ? source.prototype : source;
  369. if (Object.getOwnPropertyNames) {
  370. var keyList = Object.getOwnPropertyNames(source);
  371. for (var i = 0; i < keyList.length; i++) {
  372. var key = keyList[i];
  373. if (key !== 'constructor') {
  374. if ((override ? source[key] != null : target[key] == null)) {
  375. target[key] = source[key];
  376. }
  377. }
  378. }
  379. }
  380. else {
  381. defaults(target, source, override);
  382. }
  383. }
  384. function isArrayLike(data) {
  385. if (!data) {
  386. return false;
  387. }
  388. if (typeof data === 'string') {
  389. return false;
  390. }
  391. return typeof data.length === 'number';
  392. }
  393. function each(arr, cb, context) {
  394. if (!(arr && cb)) {
  395. return;
  396. }
  397. if (arr.forEach && arr.forEach === nativeForEach) {
  398. arr.forEach(cb, context);
  399. }
  400. else if (arr.length === +arr.length) {
  401. for (var i = 0, len = arr.length; i < len; i++) {
  402. cb.call(context, arr[i], i, arr);
  403. }
  404. }
  405. else {
  406. for (var key in arr) {
  407. if (arr.hasOwnProperty(key)) {
  408. cb.call(context, arr[key], key, arr);
  409. }
  410. }
  411. }
  412. }
  413. function map(arr, cb, context) {
  414. if (!arr) {
  415. return [];
  416. }
  417. if (!cb) {
  418. return slice(arr);
  419. }
  420. if (arr.map && arr.map === nativeMap) {
  421. return arr.map(cb, context);
  422. }
  423. else {
  424. var result = [];
  425. for (var i = 0, len = arr.length; i < len; i++) {
  426. result.push(cb.call(context, arr[i], i, arr));
  427. }
  428. return result;
  429. }
  430. }
  431. function reduce(arr, cb, memo, context) {
  432. if (!(arr && cb)) {
  433. return;
  434. }
  435. for (var i = 0, len = arr.length; i < len; i++) {
  436. memo = cb.call(context, memo, arr[i], i, arr);
  437. }
  438. return memo;
  439. }
  440. function filter(arr, cb, context) {
  441. if (!arr) {
  442. return [];
  443. }
  444. if (!cb) {
  445. return slice(arr);
  446. }
  447. if (arr.filter && arr.filter === nativeFilter) {
  448. return arr.filter(cb, context);
  449. }
  450. else {
  451. var result = [];
  452. for (var i = 0, len = arr.length; i < len; i++) {
  453. if (cb.call(context, arr[i], i, arr)) {
  454. result.push(arr[i]);
  455. }
  456. }
  457. return result;
  458. }
  459. }
  460. function find(arr, cb, context) {
  461. if (!(arr && cb)) {
  462. return;
  463. }
  464. for (var i = 0, len = arr.length; i < len; i++) {
  465. if (cb.call(context, arr[i], i, arr)) {
  466. return arr[i];
  467. }
  468. }
  469. }
  470. function keys(obj) {
  471. if (!obj) {
  472. return [];
  473. }
  474. if (Object.keys) {
  475. return Object.keys(obj);
  476. }
  477. var keyList = [];
  478. for (var key in obj) {
  479. if (obj.hasOwnProperty(key)) {
  480. keyList.push(key);
  481. }
  482. }
  483. return keyList;
  484. }
  485. function bindPolyfill(func, context) {
  486. var args = [];
  487. for (var _i = 2; _i < arguments.length; _i++) {
  488. args[_i - 2] = arguments[_i];
  489. }
  490. return function () {
  491. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  492. };
  493. }
  494. var bind = (protoFunction && isFunction(protoFunction.bind))
  495. ? protoFunction.call.bind(protoFunction.bind)
  496. : bindPolyfill;
  497. function curry(func) {
  498. var args = [];
  499. for (var _i = 1; _i < arguments.length; _i++) {
  500. args[_i - 1] = arguments[_i];
  501. }
  502. return function () {
  503. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  504. };
  505. }
  506. function isArray(value) {
  507. if (Array.isArray) {
  508. return Array.isArray(value);
  509. }
  510. return objToString.call(value) === '[object Array]';
  511. }
  512. function isFunction(value) {
  513. return typeof value === 'function';
  514. }
  515. function isString(value) {
  516. return typeof value === 'string';
  517. }
  518. function isStringSafe(value) {
  519. return objToString.call(value) === '[object String]';
  520. }
  521. function isNumber(value) {
  522. return typeof value === 'number';
  523. }
  524. function isObject(value) {
  525. var type = typeof value;
  526. return type === 'function' || (!!value && type === 'object');
  527. }
  528. function isBuiltInObject(value) {
  529. return !!BUILTIN_OBJECT[objToString.call(value)];
  530. }
  531. function isTypedArray(value) {
  532. return !!TYPED_ARRAY[objToString.call(value)];
  533. }
  534. function isDom(value) {
  535. return typeof value === 'object'
  536. && typeof value.nodeType === 'number'
  537. && typeof value.ownerDocument === 'object';
  538. }
  539. function isGradientObject(value) {
  540. return value.colorStops != null;
  541. }
  542. function isImagePatternObject(value) {
  543. return value.image != null;
  544. }
  545. function isRegExp(value) {
  546. return objToString.call(value) === '[object RegExp]';
  547. }
  548. function eqNaN(value) {
  549. return value !== value;
  550. }
  551. function retrieve() {
  552. var args = [];
  553. for (var _i = 0; _i < arguments.length; _i++) {
  554. args[_i] = arguments[_i];
  555. }
  556. for (var i = 0, len = args.length; i < len; i++) {
  557. if (args[i] != null) {
  558. return args[i];
  559. }
  560. }
  561. }
  562. function retrieve2(value0, value1) {
  563. return value0 != null
  564. ? value0
  565. : value1;
  566. }
  567. function retrieve3(value0, value1, value2) {
  568. return value0 != null
  569. ? value0
  570. : value1 != null
  571. ? value1
  572. : value2;
  573. }
  574. function slice(arr) {
  575. var args = [];
  576. for (var _i = 1; _i < arguments.length; _i++) {
  577. args[_i - 1] = arguments[_i];
  578. }
  579. return nativeSlice.apply(arr, args);
  580. }
  581. function normalizeCssArray(val) {
  582. if (typeof (val) === 'number') {
  583. return [val, val, val, val];
  584. }
  585. var len = val.length;
  586. if (len === 2) {
  587. return [val[0], val[1], val[0], val[1]];
  588. }
  589. else if (len === 3) {
  590. return [val[0], val[1], val[2], val[1]];
  591. }
  592. return val;
  593. }
  594. function assert(condition, message) {
  595. if (!condition) {
  596. throw new Error(message);
  597. }
  598. }
  599. function trim(str) {
  600. if (str == null) {
  601. return null;
  602. }
  603. else if (typeof str.trim === 'function') {
  604. return str.trim();
  605. }
  606. else {
  607. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  608. }
  609. }
  610. var primitiveKey = '__ec_primitive__';
  611. function setAsPrimitive(obj) {
  612. obj[primitiveKey] = true;
  613. }
  614. function isPrimitive(obj) {
  615. return obj[primitiveKey];
  616. }
  617. var MapPolyfill = (function () {
  618. function MapPolyfill() {
  619. this.data = {};
  620. }
  621. MapPolyfill.prototype["delete"] = function (key) {
  622. var existed = this.has(key);
  623. if (existed) {
  624. delete this.data[key];
  625. }
  626. return existed;
  627. };
  628. MapPolyfill.prototype.has = function (key) {
  629. return this.data.hasOwnProperty(key);
  630. };
  631. MapPolyfill.prototype.get = function (key) {
  632. return this.data[key];
  633. };
  634. MapPolyfill.prototype.set = function (key, value) {
  635. this.data[key] = value;
  636. return this;
  637. };
  638. MapPolyfill.prototype.keys = function () {
  639. return keys(this.data);
  640. };
  641. MapPolyfill.prototype.forEach = function (callback) {
  642. var data = this.data;
  643. for (var key in data) {
  644. if (data.hasOwnProperty(key)) {
  645. callback(data[key], key);
  646. }
  647. }
  648. };
  649. return MapPolyfill;
  650. }());
  651. var isNativeMapSupported = typeof Map === 'function';
  652. function maybeNativeMap() {
  653. return (isNativeMapSupported ? new Map() : new MapPolyfill());
  654. }
  655. var HashMap = (function () {
  656. function HashMap(obj) {
  657. var isArr = isArray(obj);
  658. this.data = maybeNativeMap();
  659. var thisMap = this;
  660. (obj instanceof HashMap)
  661. ? obj.each(visit)
  662. : (obj && each(obj, visit));
  663. function visit(value, key) {
  664. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  665. }
  666. }
  667. HashMap.prototype.hasKey = function (key) {
  668. return this.data.has(key);
  669. };
  670. HashMap.prototype.get = function (key) {
  671. return this.data.get(key);
  672. };
  673. HashMap.prototype.set = function (key, value) {
  674. this.data.set(key, value);
  675. return value;
  676. };
  677. HashMap.prototype.each = function (cb, context) {
  678. this.data.forEach(function (value, key) {
  679. cb.call(context, value, key);
  680. });
  681. };
  682. HashMap.prototype.keys = function () {
  683. var keys = this.data.keys();
  684. return isNativeMapSupported
  685. ? Array.from(keys)
  686. : keys;
  687. };
  688. HashMap.prototype.removeKey = function (key) {
  689. this.data["delete"](key);
  690. };
  691. return HashMap;
  692. }());
  693. function createHashMap(obj) {
  694. return new HashMap(obj);
  695. }
  696. function concatArray(a, b) {
  697. var newArray = new a.constructor(a.length + b.length);
  698. for (var i = 0; i < a.length; i++) {
  699. newArray[i] = a[i];
  700. }
  701. var offset = a.length;
  702. for (var i = 0; i < b.length; i++) {
  703. newArray[i + offset] = b[i];
  704. }
  705. return newArray;
  706. }
  707. function createObject(proto, properties) {
  708. var obj;
  709. if (Object.create) {
  710. obj = Object.create(proto);
  711. }
  712. else {
  713. var StyleCtor = function () { };
  714. StyleCtor.prototype = proto;
  715. obj = new StyleCtor();
  716. }
  717. if (properties) {
  718. extend(obj, properties);
  719. }
  720. return obj;
  721. }
  722. function disableUserSelect(dom) {
  723. var domStyle = dom.style;
  724. domStyle.webkitUserSelect = 'none';
  725. domStyle.userSelect = 'none';
  726. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  727. domStyle['-webkit-touch-callout'] = 'none';
  728. }
  729. function hasOwn(own, prop) {
  730. return own.hasOwnProperty(prop);
  731. }
  732. function noop() { }
  733. var RADIAN_TO_DEGREE = 180 / Math.PI;
  734. var util = /*#__PURE__*/Object.freeze({
  735. __proto__: null,
  736. guid: guid,
  737. logError: logError,
  738. clone: clone,
  739. merge: merge,
  740. mergeAll: mergeAll,
  741. extend: extend,
  742. defaults: defaults,
  743. createCanvas: createCanvas,
  744. indexOf: indexOf,
  745. inherits: inherits,
  746. mixin: mixin,
  747. isArrayLike: isArrayLike,
  748. each: each,
  749. map: map,
  750. reduce: reduce,
  751. filter: filter,
  752. find: find,
  753. keys: keys,
  754. bind: bind,
  755. curry: curry,
  756. isArray: isArray,
  757. isFunction: isFunction,
  758. isString: isString,
  759. isStringSafe: isStringSafe,
  760. isNumber: isNumber,
  761. isObject: isObject,
  762. isBuiltInObject: isBuiltInObject,
  763. isTypedArray: isTypedArray,
  764. isDom: isDom,
  765. isGradientObject: isGradientObject,
  766. isImagePatternObject: isImagePatternObject,
  767. isRegExp: isRegExp,
  768. eqNaN: eqNaN,
  769. retrieve: retrieve,
  770. retrieve2: retrieve2,
  771. retrieve3: retrieve3,
  772. slice: slice,
  773. normalizeCssArray: normalizeCssArray,
  774. assert: assert,
  775. trim: trim,
  776. setAsPrimitive: setAsPrimitive,
  777. isPrimitive: isPrimitive,
  778. HashMap: HashMap,
  779. createHashMap: createHashMap,
  780. concatArray: concatArray,
  781. createObject: createObject,
  782. disableUserSelect: disableUserSelect,
  783. hasOwn: hasOwn,
  784. noop: noop,
  785. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  786. });
  787. function create(x, y) {
  788. if (x == null) {
  789. x = 0;
  790. }
  791. if (y == null) {
  792. y = 0;
  793. }
  794. return [x, y];
  795. }
  796. function copy(out, v) {
  797. out[0] = v[0];
  798. out[1] = v[1];
  799. return out;
  800. }
  801. function clone$1(v) {
  802. return [v[0], v[1]];
  803. }
  804. function set(out, a, b) {
  805. out[0] = a;
  806. out[1] = b;
  807. return out;
  808. }
  809. function add(out, v1, v2) {
  810. out[0] = v1[0] + v2[0];
  811. out[1] = v1[1] + v2[1];
  812. return out;
  813. }
  814. function scaleAndAdd(out, v1, v2, a) {
  815. out[0] = v1[0] + v2[0] * a;
  816. out[1] = v1[1] + v2[1] * a;
  817. return out;
  818. }
  819. function sub(out, v1, v2) {
  820. out[0] = v1[0] - v2[0];
  821. out[1] = v1[1] - v2[1];
  822. return out;
  823. }
  824. function len(v) {
  825. return Math.sqrt(lenSquare(v));
  826. }
  827. var length = len;
  828. function lenSquare(v) {
  829. return v[0] * v[0] + v[1] * v[1];
  830. }
  831. var lengthSquare = lenSquare;
  832. function mul(out, v1, v2) {
  833. out[0] = v1[0] * v2[0];
  834. out[1] = v1[1] * v2[1];
  835. return out;
  836. }
  837. function div(out, v1, v2) {
  838. out[0] = v1[0] / v2[0];
  839. out[1] = v1[1] / v2[1];
  840. return out;
  841. }
  842. function dot(v1, v2) {
  843. return v1[0] * v2[0] + v1[1] * v2[1];
  844. }
  845. function scale(out, v, s) {
  846. out[0] = v[0] * s;
  847. out[1] = v[1] * s;
  848. return out;
  849. }
  850. function normalize(out, v) {
  851. var d = len(v);
  852. if (d === 0) {
  853. out[0] = 0;
  854. out[1] = 0;
  855. }
  856. else {
  857. out[0] = v[0] / d;
  858. out[1] = v[1] / d;
  859. }
  860. return out;
  861. }
  862. function distance(v1, v2) {
  863. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  864. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  865. }
  866. var dist = distance;
  867. function distanceSquare(v1, v2) {
  868. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  869. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  870. }
  871. var distSquare = distanceSquare;
  872. function negate(out, v) {
  873. out[0] = -v[0];
  874. out[1] = -v[1];
  875. return out;
  876. }
  877. function lerp(out, v1, v2, t) {
  878. out[0] = v1[0] + t * (v2[0] - v1[0]);
  879. out[1] = v1[1] + t * (v2[1] - v1[1]);
  880. return out;
  881. }
  882. function applyTransform(out, v, m) {
  883. var x = v[0];
  884. var y = v[1];
  885. out[0] = m[0] * x + m[2] * y + m[4];
  886. out[1] = m[1] * x + m[3] * y + m[5];
  887. return out;
  888. }
  889. function min(out, v1, v2) {
  890. out[0] = Math.min(v1[0], v2[0]);
  891. out[1] = Math.min(v1[1], v2[1]);
  892. return out;
  893. }
  894. function max(out, v1, v2) {
  895. out[0] = Math.max(v1[0], v2[0]);
  896. out[1] = Math.max(v1[1], v2[1]);
  897. return out;
  898. }
  899. var vector = /*#__PURE__*/Object.freeze({
  900. __proto__: null,
  901. create: create,
  902. copy: copy,
  903. clone: clone$1,
  904. set: set,
  905. add: add,
  906. scaleAndAdd: scaleAndAdd,
  907. sub: sub,
  908. len: len,
  909. length: length,
  910. lenSquare: lenSquare,
  911. lengthSquare: lengthSquare,
  912. mul: mul,
  913. div: div,
  914. dot: dot,
  915. scale: scale,
  916. normalize: normalize,
  917. distance: distance,
  918. dist: dist,
  919. distanceSquare: distanceSquare,
  920. distSquare: distSquare,
  921. negate: negate,
  922. lerp: lerp,
  923. applyTransform: applyTransform,
  924. min: min,
  925. max: max
  926. });
  927. var Param = (function () {
  928. function Param(target, e) {
  929. this.target = target;
  930. this.topTarget = e && e.topTarget;
  931. }
  932. return Param;
  933. }());
  934. var Draggable = (function () {
  935. function Draggable(handler) {
  936. this.handler = handler;
  937. handler.on('mousedown', this._dragStart, this);
  938. handler.on('mousemove', this._drag, this);
  939. handler.on('mouseup', this._dragEnd, this);
  940. }
  941. Draggable.prototype._dragStart = function (e) {
  942. var draggingTarget = e.target;
  943. while (draggingTarget && !draggingTarget.draggable) {
  944. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  945. }
  946. if (draggingTarget) {
  947. this._draggingTarget = draggingTarget;
  948. draggingTarget.dragging = true;
  949. this._x = e.offsetX;
  950. this._y = e.offsetY;
  951. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  952. }
  953. };
  954. Draggable.prototype._drag = function (e) {
  955. var draggingTarget = this._draggingTarget;
  956. if (draggingTarget) {
  957. var x = e.offsetX;
  958. var y = e.offsetY;
  959. var dx = x - this._x;
  960. var dy = y - this._y;
  961. this._x = x;
  962. this._y = y;
  963. draggingTarget.drift(dx, dy, e);
  964. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  965. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  966. var lastDropTarget = this._dropTarget;
  967. this._dropTarget = dropTarget;
  968. if (draggingTarget !== dropTarget) {
  969. if (lastDropTarget && dropTarget !== lastDropTarget) {
  970. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  971. }
  972. if (dropTarget && dropTarget !== lastDropTarget) {
  973. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  974. }
  975. }
  976. }
  977. };
  978. Draggable.prototype._dragEnd = function (e) {
  979. var draggingTarget = this._draggingTarget;
  980. if (draggingTarget) {
  981. draggingTarget.dragging = false;
  982. }
  983. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  984. if (this._dropTarget) {
  985. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  986. }
  987. this._draggingTarget = null;
  988. this._dropTarget = null;
  989. };
  990. return Draggable;
  991. }());
  992. var Eventful = (function () {
  993. function Eventful(eventProcessors) {
  994. if (eventProcessors) {
  995. this._$eventProcessor = eventProcessors;
  996. }
  997. }
  998. Eventful.prototype.on = function (event, query, handler, context) {
  999. if (!this._$handlers) {
  1000. this._$handlers = {};
  1001. }
  1002. var _h = this._$handlers;
  1003. if (typeof query === 'function') {
  1004. context = handler;
  1005. handler = query;
  1006. query = null;
  1007. }
  1008. if (!handler || !event) {
  1009. return this;
  1010. }
  1011. var eventProcessor = this._$eventProcessor;
  1012. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1013. query = eventProcessor.normalizeQuery(query);
  1014. }
  1015. if (!_h[event]) {
  1016. _h[event] = [];
  1017. }
  1018. for (var i = 0; i < _h[event].length; i++) {
  1019. if (_h[event][i].h === handler) {
  1020. return this;
  1021. }
  1022. }
  1023. var wrap = {
  1024. h: handler,
  1025. query: query,
  1026. ctx: (context || this),
  1027. callAtLast: handler.zrEventfulCallAtLast
  1028. };
  1029. var lastIndex = _h[event].length - 1;
  1030. var lastWrap = _h[event][lastIndex];
  1031. (lastWrap && lastWrap.callAtLast)
  1032. ? _h[event].splice(lastIndex, 0, wrap)
  1033. : _h[event].push(wrap);
  1034. return this;
  1035. };
  1036. Eventful.prototype.isSilent = function (eventName) {
  1037. var _h = this._$handlers;
  1038. return !_h || !_h[eventName] || !_h[eventName].length;
  1039. };
  1040. Eventful.prototype.off = function (eventType, handler) {
  1041. var _h = this._$handlers;
  1042. if (!_h) {
  1043. return this;
  1044. }
  1045. if (!eventType) {
  1046. this._$handlers = {};
  1047. return this;
  1048. }
  1049. if (handler) {
  1050. if (_h[eventType]) {
  1051. var newList = [];
  1052. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1053. if (_h[eventType][i].h !== handler) {
  1054. newList.push(_h[eventType][i]);
  1055. }
  1056. }
  1057. _h[eventType] = newList;
  1058. }
  1059. if (_h[eventType] && _h[eventType].length === 0) {
  1060. delete _h[eventType];
  1061. }
  1062. }
  1063. else {
  1064. delete _h[eventType];
  1065. }
  1066. return this;
  1067. };
  1068. Eventful.prototype.trigger = function (eventType) {
  1069. var args = [];
  1070. for (var _i = 1; _i < arguments.length; _i++) {
  1071. args[_i - 1] = arguments[_i];
  1072. }
  1073. if (!this._$handlers) {
  1074. return this;
  1075. }
  1076. var _h = this._$handlers[eventType];
  1077. var eventProcessor = this._$eventProcessor;
  1078. if (_h) {
  1079. var argLen = args.length;
  1080. var len = _h.length;
  1081. for (var i = 0; i < len; i++) {
  1082. var hItem = _h[i];
  1083. if (eventProcessor
  1084. && eventProcessor.filter
  1085. && hItem.query != null
  1086. && !eventProcessor.filter(eventType, hItem.query)) {
  1087. continue;
  1088. }
  1089. switch (argLen) {
  1090. case 0:
  1091. hItem.h.call(hItem.ctx);
  1092. break;
  1093. case 1:
  1094. hItem.h.call(hItem.ctx, args[0]);
  1095. break;
  1096. case 2:
  1097. hItem.h.call(hItem.ctx, args[0], args[1]);
  1098. break;
  1099. default:
  1100. hItem.h.apply(hItem.ctx, args);
  1101. break;
  1102. }
  1103. }
  1104. }
  1105. eventProcessor && eventProcessor.afterTrigger
  1106. && eventProcessor.afterTrigger(eventType);
  1107. return this;
  1108. };
  1109. Eventful.prototype.triggerWithContext = function (type) {
  1110. var args = [];
  1111. for (var _i = 1; _i < arguments.length; _i++) {
  1112. args[_i - 1] = arguments[_i];
  1113. }
  1114. if (!this._$handlers) {
  1115. return this;
  1116. }
  1117. var _h = this._$handlers[type];
  1118. var eventProcessor = this._$eventProcessor;
  1119. if (_h) {
  1120. var argLen = args.length;
  1121. var ctx = args[argLen - 1];
  1122. var len = _h.length;
  1123. for (var i = 0; i < len; i++) {
  1124. var hItem = _h[i];
  1125. if (eventProcessor
  1126. && eventProcessor.filter
  1127. && hItem.query != null
  1128. && !eventProcessor.filter(type, hItem.query)) {
  1129. continue;
  1130. }
  1131. switch (argLen) {
  1132. case 0:
  1133. hItem.h.call(ctx);
  1134. break;
  1135. case 1:
  1136. hItem.h.call(ctx, args[0]);
  1137. break;
  1138. case 2:
  1139. hItem.h.call(ctx, args[0], args[1]);
  1140. break;
  1141. default:
  1142. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1143. break;
  1144. }
  1145. }
  1146. }
  1147. eventProcessor && eventProcessor.afterTrigger
  1148. && eventProcessor.afterTrigger(type);
  1149. return this;
  1150. };
  1151. return Eventful;
  1152. }());
  1153. var LN2 = Math.log(2);
  1154. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1155. var cacheKey = rowMask + '-' + colMask;
  1156. var fullRank = rows.length;
  1157. if (detCache.hasOwnProperty(cacheKey)) {
  1158. return detCache[cacheKey];
  1159. }
  1160. if (rank === 1) {
  1161. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1162. return rows[rowStart][colStart];
  1163. }
  1164. var subRowMask = rowMask | (1 << rowStart);
  1165. var subRowStart = rowStart + 1;
  1166. while (rowMask & (1 << subRowStart)) {
  1167. subRowStart++;
  1168. }
  1169. var sum = 0;
  1170. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1171. var colTag = 1 << j;
  1172. if (!(colTag & colMask)) {
  1173. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1174. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1175. colLocalIdx++;
  1176. }
  1177. }
  1178. detCache[cacheKey] = sum;
  1179. return sum;
  1180. }
  1181. function buildTransformer(src, dest) {
  1182. var mA = [
  1183. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1184. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1185. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1186. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1187. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1188. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1189. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1190. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1191. ];
  1192. var detCache = {};
  1193. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1194. if (det === 0) {
  1195. return;
  1196. }
  1197. var vh = [];
  1198. for (var i = 0; i < 8; i++) {
  1199. for (var j = 0; j < 8; j++) {
  1200. vh[j] == null && (vh[j] = 0);
  1201. vh[j] += ((i + j) % 2 ? -1 : 1)
  1202. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1203. / det * dest[i];
  1204. }
  1205. }
  1206. return function (out, srcPointX, srcPointY) {
  1207. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1208. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1209. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1210. };
  1211. }
  1212. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1213. var _calcOut = [];
  1214. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1215. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1216. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1217. }
  1218. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1219. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1220. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1221. var markers = prepareCoordMarkers(el, saved);
  1222. var transformer = preparePointerTransformer(markers, saved, inverse);
  1223. if (transformer) {
  1224. transformer(out, inX, inY);
  1225. return true;
  1226. }
  1227. }
  1228. return false;
  1229. }
  1230. function prepareCoordMarkers(el, saved) {
  1231. var markers = saved.markers;
  1232. if (markers) {
  1233. return markers;
  1234. }
  1235. markers = saved.markers = [];
  1236. var propLR = ['left', 'right'];
  1237. var propTB = ['top', 'bottom'];
  1238. for (var i = 0; i < 4; i++) {
  1239. var marker = document.createElement('div');
  1240. var stl = marker.style;
  1241. var idxLR = i % 2;
  1242. var idxTB = (i >> 1) % 2;
  1243. stl.cssText = [
  1244. 'position: absolute',
  1245. 'visibility: hidden',
  1246. 'padding: 0',
  1247. 'margin: 0',
  1248. 'border-width: 0',
  1249. 'user-select: none',
  1250. 'width:0',
  1251. 'height:0',
  1252. propLR[idxLR] + ':0',
  1253. propTB[idxTB] + ':0',
  1254. propLR[1 - idxLR] + ':auto',
  1255. propTB[1 - idxTB] + ':auto',
  1256. ''
  1257. ].join('!important;');
  1258. el.appendChild(marker);
  1259. markers.push(marker);
  1260. }
  1261. return markers;
  1262. }
  1263. function preparePointerTransformer(markers, saved, inverse) {
  1264. var transformerName = inverse ? 'invTrans' : 'trans';
  1265. var transformer = saved[transformerName];
  1266. var oldSrcCoords = saved.srcCoords;
  1267. var srcCoords = [];
  1268. var destCoords = [];
  1269. var oldCoordTheSame = true;
  1270. for (var i = 0; i < 4; i++) {
  1271. var rect = markers[i].getBoundingClientRect();
  1272. var ii = 2 * i;
  1273. var x = rect.left;
  1274. var y = rect.top;
  1275. srcCoords.push(x, y);
  1276. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1277. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1278. }
  1279. return (oldCoordTheSame && transformer)
  1280. ? transformer
  1281. : (saved.srcCoords = srcCoords,
  1282. saved[transformerName] = inverse
  1283. ? buildTransformer(destCoords, srcCoords)
  1284. : buildTransformer(srcCoords, destCoords));
  1285. }
  1286. function isCanvasEl(el) {
  1287. return el.nodeName.toUpperCase() === 'CANVAS';
  1288. }
  1289. var replaceReg = /([&<>"'])/g;
  1290. var replaceMap = {
  1291. '&': '&amp;',
  1292. '<': '&lt;',
  1293. '>': '&gt;',
  1294. '"': '&quot;',
  1295. '\'': '&#39;'
  1296. };
  1297. function encodeHTML(source) {
  1298. return source == null
  1299. ? ''
  1300. : (source + '').replace(replaceReg, function (str, c) {
  1301. return replaceMap[c];
  1302. });
  1303. }
  1304. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1305. var _calcOut$1 = [];
  1306. var firefoxNotSupportOffsetXY = env.browser.firefox
  1307. && +env.browser.version.split('.')[0] < 39;
  1308. function clientToLocal(el, e, out, calculate) {
  1309. out = out || {};
  1310. if (calculate) {
  1311. calculateZrXY(el, e, out);
  1312. }
  1313. else if (firefoxNotSupportOffsetXY
  1314. && e.layerX != null
  1315. && e.layerX !== e.offsetX) {
  1316. out.zrX = e.layerX;
  1317. out.zrY = e.layerY;
  1318. }
  1319. else if (e.offsetX != null) {
  1320. out.zrX = e.offsetX;
  1321. out.zrY = e.offsetY;
  1322. }
  1323. else {
  1324. calculateZrXY(el, e, out);
  1325. }
  1326. return out;
  1327. }
  1328. function calculateZrXY(el, e, out) {
  1329. if (env.domSupported && el.getBoundingClientRect) {
  1330. var ex = e.clientX;
  1331. var ey = e.clientY;
  1332. if (isCanvasEl(el)) {
  1333. var box = el.getBoundingClientRect();
  1334. out.zrX = ex - box.left;
  1335. out.zrY = ey - box.top;
  1336. return;
  1337. }
  1338. else {
  1339. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1340. out.zrX = _calcOut$1[0];
  1341. out.zrY = _calcOut$1[1];
  1342. return;
  1343. }
  1344. }
  1345. }
  1346. out.zrX = out.zrY = 0;
  1347. }
  1348. function getNativeEvent(e) {
  1349. return e
  1350. || window.event;
  1351. }
  1352. function normalizeEvent(el, e, calculate) {
  1353. e = getNativeEvent(e);
  1354. if (e.zrX != null) {
  1355. return e;
  1356. }
  1357. var eventType = e.type;
  1358. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1359. if (!isTouch) {
  1360. clientToLocal(el, e, e, calculate);
  1361. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1362. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1363. }
  1364. else {
  1365. var touch = eventType !== 'touchend'
  1366. ? e.targetTouches[0]
  1367. : e.changedTouches[0];
  1368. touch && clientToLocal(el, touch, e, calculate);
  1369. }
  1370. var button = e.button;
  1371. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1372. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1373. }
  1374. return e;
  1375. }
  1376. function getWheelDeltaMayPolyfill(e) {
  1377. var rawWheelDelta = e.wheelDelta;
  1378. if (rawWheelDelta) {
  1379. return rawWheelDelta;
  1380. }
  1381. var deltaX = e.deltaX;
  1382. var deltaY = e.deltaY;
  1383. if (deltaX == null || deltaY == null) {
  1384. return rawWheelDelta;
  1385. }
  1386. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1387. var sign = deltaY > 0 ? -1
  1388. : deltaY < 0 ? 1
  1389. : deltaX > 0 ? -1
  1390. : 1;
  1391. return 3 * delta * sign;
  1392. }
  1393. function addEventListener(el, name, handler, opt) {
  1394. el.addEventListener(name, handler, opt);
  1395. }
  1396. function removeEventListener(el, name, handler, opt) {
  1397. el.removeEventListener(name, handler, opt);
  1398. }
  1399. var stop = function (e) {
  1400. e.preventDefault();
  1401. e.stopPropagation();
  1402. e.cancelBubble = true;
  1403. };
  1404. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1405. return e.which === 2 || e.which === 3;
  1406. }
  1407. var GestureMgr = (function () {
  1408. function GestureMgr() {
  1409. this._track = [];
  1410. }
  1411. GestureMgr.prototype.recognize = function (event, target, root) {
  1412. this._doTrack(event, target, root);
  1413. return this._recognize(event);
  1414. };
  1415. GestureMgr.prototype.clear = function () {
  1416. this._track.length = 0;
  1417. return this;
  1418. };
  1419. GestureMgr.prototype._doTrack = function (event, target, root) {
  1420. var touches = event.touches;
  1421. if (!touches) {
  1422. return;
  1423. }
  1424. var trackItem = {
  1425. points: [],
  1426. touches: [],
  1427. target: target,
  1428. event: event
  1429. };
  1430. for (var i = 0, len = touches.length; i < len; i++) {
  1431. var touch = touches[i];
  1432. var pos = clientToLocal(root, touch, {});
  1433. trackItem.points.push([pos.zrX, pos.zrY]);
  1434. trackItem.touches.push(touch);
  1435. }
  1436. this._track.push(trackItem);
  1437. };
  1438. GestureMgr.prototype._recognize = function (event) {
  1439. for (var eventName in recognizers) {
  1440. if (recognizers.hasOwnProperty(eventName)) {
  1441. var gestureInfo = recognizers[eventName](this._track, event);
  1442. if (gestureInfo) {
  1443. return gestureInfo;
  1444. }
  1445. }
  1446. }
  1447. };
  1448. return GestureMgr;
  1449. }());
  1450. function dist$1(pointPair) {
  1451. var dx = pointPair[1][0] - pointPair[0][0];
  1452. var dy = pointPair[1][1] - pointPair[0][1];
  1453. return Math.sqrt(dx * dx + dy * dy);
  1454. }
  1455. function center(pointPair) {
  1456. return [
  1457. (pointPair[0][0] + pointPair[1][0]) / 2,
  1458. (pointPair[0][1] + pointPair[1][1]) / 2
  1459. ];
  1460. }
  1461. var recognizers = {
  1462. pinch: function (tracks, event) {
  1463. var trackLen = tracks.length;
  1464. if (!trackLen) {
  1465. return;
  1466. }
  1467. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1468. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1469. if (pinchPre
  1470. && pinchPre.length > 1
  1471. && pinchEnd
  1472. && pinchEnd.length > 1) {
  1473. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1474. !isFinite(pinchScale) && (pinchScale = 1);
  1475. event.pinchScale = pinchScale;
  1476. var pinchCenter = center(pinchEnd);
  1477. event.pinchX = pinchCenter[0];
  1478. event.pinchY = pinchCenter[1];
  1479. return {
  1480. type: 'pinch',
  1481. target: tracks[0].target,
  1482. event: event
  1483. };
  1484. }
  1485. }
  1486. };
  1487. function create$1() {
  1488. return [1, 0, 0, 1, 0, 0];
  1489. }
  1490. function identity(out) {
  1491. out[0] = 1;
  1492. out[1] = 0;
  1493. out[2] = 0;
  1494. out[3] = 1;
  1495. out[4] = 0;
  1496. out[5] = 0;
  1497. return out;
  1498. }
  1499. function copy$1(out, m) {
  1500. out[0] = m[0];
  1501. out[1] = m[1];
  1502. out[2] = m[2];
  1503. out[3] = m[3];
  1504. out[4] = m[4];
  1505. out[5] = m[5];
  1506. return out;
  1507. }
  1508. function mul$1(out, m1, m2) {
  1509. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1510. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1511. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1512. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1513. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1514. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1515. out[0] = out0;
  1516. out[1] = out1;
  1517. out[2] = out2;
  1518. out[3] = out3;
  1519. out[4] = out4;
  1520. out[5] = out5;
  1521. return out;
  1522. }
  1523. function translate(out, a, v) {
  1524. out[0] = a[0];
  1525. out[1] = a[1];
  1526. out[2] = a[2];
  1527. out[3] = a[3];
  1528. out[4] = a[4] + v[0];
  1529. out[5] = a[5] + v[1];
  1530. return out;
  1531. }
  1532. function rotate(out, a, rad) {
  1533. var aa = a[0];
  1534. var ac = a[2];
  1535. var atx = a[4];
  1536. var ab = a[1];
  1537. var ad = a[3];
  1538. var aty = a[5];
  1539. var st = Math.sin(rad);
  1540. var ct = Math.cos(rad);
  1541. out[0] = aa * ct + ab * st;
  1542. out[1] = -aa * st + ab * ct;
  1543. out[2] = ac * ct + ad * st;
  1544. out[3] = -ac * st + ct * ad;
  1545. out[4] = ct * atx + st * aty;
  1546. out[5] = ct * aty - st * atx;
  1547. return out;
  1548. }
  1549. function scale$1(out, a, v) {
  1550. var vx = v[0];
  1551. var vy = v[1];
  1552. out[0] = a[0] * vx;
  1553. out[1] = a[1] * vy;
  1554. out[2] = a[2] * vx;
  1555. out[3] = a[3] * vy;
  1556. out[4] = a[4] * vx;
  1557. out[5] = a[5] * vy;
  1558. return out;
  1559. }
  1560. function invert(out, a) {
  1561. var aa = a[0];
  1562. var ac = a[2];
  1563. var atx = a[4];
  1564. var ab = a[1];
  1565. var ad = a[3];
  1566. var aty = a[5];
  1567. var det = aa * ad - ab * ac;
  1568. if (!det) {
  1569. return null;
  1570. }
  1571. det = 1.0 / det;
  1572. out[0] = ad * det;
  1573. out[1] = -ab * det;
  1574. out[2] = -ac * det;
  1575. out[3] = aa * det;
  1576. out[4] = (ac * aty - ad * atx) * det;
  1577. out[5] = (ab * atx - aa * aty) * det;
  1578. return out;
  1579. }
  1580. function clone$2(a) {
  1581. var b = create$1();
  1582. copy$1(b, a);
  1583. return b;
  1584. }
  1585. var matrix = /*#__PURE__*/Object.freeze({
  1586. __proto__: null,
  1587. create: create$1,
  1588. identity: identity,
  1589. copy: copy$1,
  1590. mul: mul$1,
  1591. translate: translate,
  1592. rotate: rotate,
  1593. scale: scale$1,
  1594. invert: invert,
  1595. clone: clone$2
  1596. });
  1597. var Point = (function () {
  1598. function Point(x, y) {
  1599. this.x = x || 0;
  1600. this.y = y || 0;
  1601. }
  1602. Point.prototype.copy = function (other) {
  1603. this.x = other.x;
  1604. this.y = other.y;
  1605. return this;
  1606. };
  1607. Point.prototype.clone = function () {
  1608. return new Point(this.x, this.y);
  1609. };
  1610. Point.prototype.set = function (x, y) {
  1611. this.x = x;
  1612. this.y = y;
  1613. return this;
  1614. };
  1615. Point.prototype.equal = function (other) {
  1616. return other.x === this.x && other.y === this.y;
  1617. };
  1618. Point.prototype.add = function (other) {
  1619. this.x += other.x;
  1620. this.y += other.y;
  1621. return this;
  1622. };
  1623. Point.prototype.scale = function (scalar) {
  1624. this.x *= scalar;
  1625. this.y *= scalar;
  1626. };
  1627. Point.prototype.scaleAndAdd = function (other, scalar) {
  1628. this.x += other.x * scalar;
  1629. this.y += other.y * scalar;
  1630. };
  1631. Point.prototype.sub = function (other) {
  1632. this.x -= other.x;
  1633. this.y -= other.y;
  1634. return this;
  1635. };
  1636. Point.prototype.dot = function (other) {
  1637. return this.x * other.x + this.y * other.y;
  1638. };
  1639. Point.prototype.len = function () {
  1640. return Math.sqrt(this.x * this.x + this.y * this.y);
  1641. };
  1642. Point.prototype.lenSquare = function () {
  1643. return this.x * this.x + this.y * this.y;
  1644. };
  1645. Point.prototype.normalize = function () {
  1646. var len = this.len();
  1647. this.x /= len;
  1648. this.y /= len;
  1649. return this;
  1650. };
  1651. Point.prototype.distance = function (other) {
  1652. var dx = this.x - other.x;
  1653. var dy = this.y - other.y;
  1654. return Math.sqrt(dx * dx + dy * dy);
  1655. };
  1656. Point.prototype.distanceSquare = function (other) {
  1657. var dx = this.x - other.x;
  1658. var dy = this.y - other.y;
  1659. return dx * dx + dy * dy;
  1660. };
  1661. Point.prototype.negate = function () {
  1662. this.x = -this.x;
  1663. this.y = -this.y;
  1664. return this;
  1665. };
  1666. Point.prototype.transform = function (m) {
  1667. if (!m) {
  1668. return;
  1669. }
  1670. var x = this.x;
  1671. var y = this.y;
  1672. this.x = m[0] * x + m[2] * y + m[4];
  1673. this.y = m[1] * x + m[3] * y + m[5];
  1674. return this;
  1675. };
  1676. Point.prototype.toArray = function (out) {
  1677. out[0] = this.x;
  1678. out[1] = this.y;
  1679. return out;
  1680. };
  1681. Point.prototype.fromArray = function (input) {
  1682. this.x = input[0];
  1683. this.y = input[1];
  1684. };
  1685. Point.set = function (p, x, y) {
  1686. p.x = x;
  1687. p.y = y;
  1688. };
  1689. Point.copy = function (p, p2) {
  1690. p.x = p2.x;
  1691. p.y = p2.y;
  1692. };
  1693. Point.len = function (p) {
  1694. return Math.sqrt(p.x * p.x + p.y * p.y);
  1695. };
  1696. Point.lenSquare = function (p) {
  1697. return p.x * p.x + p.y * p.y;
  1698. };
  1699. Point.dot = function (p0, p1) {
  1700. return p0.x * p1.x + p0.y * p1.y;
  1701. };
  1702. Point.add = function (out, p0, p1) {
  1703. out.x = p0.x + p1.x;
  1704. out.y = p0.y + p1.y;
  1705. };
  1706. Point.sub = function (out, p0, p1) {
  1707. out.x = p0.x - p1.x;
  1708. out.y = p0.y - p1.y;
  1709. };
  1710. Point.scale = function (out, p0, scalar) {
  1711. out.x = p0.x * scalar;
  1712. out.y = p0.y * scalar;
  1713. };
  1714. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1715. out.x = p0.x + p1.x * scalar;
  1716. out.y = p0.y + p1.y * scalar;
  1717. };
  1718. Point.lerp = function (out, p0, p1, t) {
  1719. var onet = 1 - t;
  1720. out.x = onet * p0.x + t * p1.x;
  1721. out.y = onet * p0.y + t * p1.y;
  1722. };
  1723. return Point;
  1724. }());
  1725. var mathMin = Math.min;
  1726. var mathMax = Math.max;
  1727. var lt = new Point();
  1728. var rb = new Point();
  1729. var lb = new Point();
  1730. var rt = new Point();
  1731. var minTv = new Point();
  1732. var maxTv = new Point();
  1733. var BoundingRect = (function () {
  1734. function BoundingRect(x, y, width, height) {
  1735. if (width < 0) {
  1736. x = x + width;
  1737. width = -width;
  1738. }
  1739. if (height < 0) {
  1740. y = y + height;
  1741. height = -height;
  1742. }
  1743. this.x = x;
  1744. this.y = y;
  1745. this.width = width;
  1746. this.height = height;
  1747. }
  1748. BoundingRect.prototype.union = function (other) {
  1749. var x = mathMin(other.x, this.x);
  1750. var y = mathMin(other.y, this.y);
  1751. if (isFinite(this.x) && isFinite(this.width)) {
  1752. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1753. }
  1754. else {
  1755. this.width = other.width;
  1756. }
  1757. if (isFinite(this.y) && isFinite(this.height)) {
  1758. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1759. }
  1760. else {
  1761. this.height = other.height;
  1762. }
  1763. this.x = x;
  1764. this.y = y;
  1765. };
  1766. BoundingRect.prototype.applyTransform = function (m) {
  1767. BoundingRect.applyTransform(this, this, m);
  1768. };
  1769. BoundingRect.prototype.calculateTransform = function (b) {
  1770. var a = this;
  1771. var sx = b.width / a.width;
  1772. var sy = b.height / a.height;
  1773. var m = create$1();
  1774. translate(m, m, [-a.x, -a.y]);
  1775. scale$1(m, m, [sx, sy]);
  1776. translate(m, m, [b.x, b.y]);
  1777. return m;
  1778. };
  1779. BoundingRect.prototype.intersect = function (b, mtv) {
  1780. if (!b) {
  1781. return false;
  1782. }
  1783. if (!(b instanceof BoundingRect)) {
  1784. b = BoundingRect.create(b);
  1785. }
  1786. var a = this;
  1787. var ax0 = a.x;
  1788. var ax1 = a.x + a.width;
  1789. var ay0 = a.y;
  1790. var ay1 = a.y + a.height;
  1791. var bx0 = b.x;
  1792. var bx1 = b.x + b.width;
  1793. var by0 = b.y;
  1794. var by1 = b.y + b.height;
  1795. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1796. if (mtv) {
  1797. var dMin = Infinity;
  1798. var dMax = 0;
  1799. var d0 = Math.abs(ax1 - bx0);
  1800. var d1 = Math.abs(bx1 - ax0);
  1801. var d2 = Math.abs(ay1 - by0);
  1802. var d3 = Math.abs(by1 - ay0);
  1803. var dx = Math.min(d0, d1);
  1804. var dy = Math.min(d2, d3);
  1805. if (ax1 < bx0 || bx1 < ax0) {
  1806. if (dx > dMax) {
  1807. dMax = dx;
  1808. if (d0 < d1) {
  1809. Point.set(maxTv, -d0, 0);
  1810. }
  1811. else {
  1812. Point.set(maxTv, d1, 0);
  1813. }
  1814. }
  1815. }
  1816. else {
  1817. if (dx < dMin) {
  1818. dMin = dx;
  1819. if (d0 < d1) {
  1820. Point.set(minTv, d0, 0);
  1821. }
  1822. else {
  1823. Point.set(minTv, -d1, 0);
  1824. }
  1825. }
  1826. }
  1827. if (ay1 < by0 || by1 < ay0) {
  1828. if (dy > dMax) {
  1829. dMax = dy;
  1830. if (d2 < d3) {
  1831. Point.set(maxTv, 0, -d2);
  1832. }
  1833. else {
  1834. Point.set(maxTv, 0, d3);
  1835. }
  1836. }
  1837. }
  1838. else {
  1839. if (dx < dMin) {
  1840. dMin = dx;
  1841. if (d2 < d3) {
  1842. Point.set(minTv, 0, d2);
  1843. }
  1844. else {
  1845. Point.set(minTv, 0, -d3);
  1846. }
  1847. }
  1848. }
  1849. }
  1850. if (mtv) {
  1851. Point.copy(mtv, overlap ? minTv : maxTv);
  1852. }
  1853. return overlap;
  1854. };
  1855. BoundingRect.prototype.contain = function (x, y) {
  1856. var rect = this;
  1857. return x >= rect.x
  1858. && x <= (rect.x + rect.width)
  1859. && y >= rect.y
  1860. && y <= (rect.y + rect.height);
  1861. };
  1862. BoundingRect.prototype.clone = function () {
  1863. return new BoundingRect(this.x, this.y, this.width, this.height);
  1864. };
  1865. BoundingRect.prototype.copy = function (other) {
  1866. BoundingRect.copy(this, other);
  1867. };
  1868. BoundingRect.prototype.plain = function () {
  1869. return {
  1870. x: this.x,
  1871. y: this.y,
  1872. width: this.width,
  1873. height: this.height
  1874. };
  1875. };
  1876. BoundingRect.prototype.isFinite = function () {
  1877. return isFinite(this.x)
  1878. && isFinite(this.y)
  1879. && isFinite(this.width)
  1880. && isFinite(this.height);
  1881. };
  1882. BoundingRect.prototype.isZero = function () {
  1883. return this.width === 0 || this.height === 0;
  1884. };
  1885. BoundingRect.create = function (rect) {
  1886. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1887. };
  1888. BoundingRect.copy = function (target, source) {
  1889. target.x = source.x;
  1890. target.y = source.y;
  1891. target.width = source.width;
  1892. target.height = source.height;
  1893. };
  1894. BoundingRect.applyTransform = function (target, source, m) {
  1895. if (!m) {
  1896. if (target !== source) {
  1897. BoundingRect.copy(target, source);
  1898. }
  1899. return;
  1900. }
  1901. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1902. var sx = m[0];
  1903. var sy = m[3];
  1904. var tx = m[4];
  1905. var ty = m[5];
  1906. target.x = source.x * sx + tx;
  1907. target.y = source.y * sy + ty;
  1908. target.width = source.width * sx;
  1909. target.height = source.height * sy;
  1910. if (target.width < 0) {
  1911. target.x += target.width;
  1912. target.width = -target.width;
  1913. }
  1914. if (target.height < 0) {
  1915. target.y += target.height;
  1916. target.height = -target.height;
  1917. }
  1918. return;
  1919. }
  1920. lt.x = lb.x = source.x;
  1921. lt.y = rt.y = source.y;
  1922. rb.x = rt.x = source.x + source.width;
  1923. rb.y = lb.y = source.y + source.height;
  1924. lt.transform(m);
  1925. rt.transform(m);
  1926. rb.transform(m);
  1927. lb.transform(m);
  1928. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1929. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1930. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1931. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1932. target.width = maxX - target.x;
  1933. target.height = maxY - target.y;
  1934. };
  1935. return BoundingRect;
  1936. }());
  1937. var SILENT = 'silent';
  1938. function makeEventPacket(eveType, targetInfo, event) {
  1939. return {
  1940. type: eveType,
  1941. event: event,
  1942. target: targetInfo.target,
  1943. topTarget: targetInfo.topTarget,
  1944. cancelBubble: false,
  1945. offsetX: event.zrX,
  1946. offsetY: event.zrY,
  1947. gestureEvent: event.gestureEvent,
  1948. pinchX: event.pinchX,
  1949. pinchY: event.pinchY,
  1950. pinchScale: event.pinchScale,
  1951. wheelDelta: event.zrDelta,
  1952. zrByTouch: event.zrByTouch,
  1953. which: event.which,
  1954. stop: stopEvent
  1955. };
  1956. }
  1957. function stopEvent() {
  1958. stop(this.event);
  1959. }
  1960. var EmptyProxy = (function (_super) {
  1961. __extends(EmptyProxy, _super);
  1962. function EmptyProxy() {
  1963. var _this = _super !== null && _super.apply(this, arguments) || this;
  1964. _this.handler = null;
  1965. return _this;
  1966. }
  1967. EmptyProxy.prototype.dispose = function () { };
  1968. EmptyProxy.prototype.setCursor = function () { };
  1969. return EmptyProxy;
  1970. }(Eventful));
  1971. var HoveredResult = (function () {
  1972. function HoveredResult(x, y) {
  1973. this.x = x;
  1974. this.y = y;
  1975. }
  1976. return HoveredResult;
  1977. }());
  1978. var handlerNames = [
  1979. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1980. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1981. ];
  1982. var tmpRect = new BoundingRect(0, 0, 0, 0);
  1983. var Handler = (function (_super) {
  1984. __extends(Handler, _super);
  1985. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  1986. var _this = _super.call(this) || this;
  1987. _this._hovered = new HoveredResult(0, 0);
  1988. _this.storage = storage;
  1989. _this.painter = painter;
  1990. _this.painterRoot = painterRoot;
  1991. _this._pointerSize = pointerSize;
  1992. proxy = proxy || new EmptyProxy();
  1993. _this.proxy = null;
  1994. _this.setHandlerProxy(proxy);
  1995. _this._draggingMgr = new Draggable(_this);
  1996. return _this;
  1997. }
  1998. Handler.prototype.setHandlerProxy = function (proxy) {
  1999. if (this.proxy) {
  2000. this.proxy.dispose();
  2001. }
  2002. if (proxy) {
  2003. each(handlerNames, function (name) {
  2004. proxy.on && proxy.on(name, this[name], this);
  2005. }, this);
  2006. proxy.handler = this;
  2007. }
  2008. this.proxy = proxy;
  2009. };
  2010. Handler.prototype.mousemove = function (event) {
  2011. var x = event.zrX;
  2012. var y = event.zrY;
  2013. var isOutside = isOutsideBoundary(this, x, y);
  2014. var lastHovered = this._hovered;
  2015. var lastHoveredTarget = lastHovered.target;
  2016. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2017. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2018. lastHoveredTarget = lastHovered.target;
  2019. }
  2020. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2021. var hoveredTarget = hovered.target;
  2022. var proxy = this.proxy;
  2023. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2024. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2025. this.dispatchToElement(lastHovered, 'mouseout', event);
  2026. }
  2027. this.dispatchToElement(hovered, 'mousemove', event);
  2028. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2029. this.dispatchToElement(hovered, 'mouseover', event);
  2030. }
  2031. };
  2032. Handler.prototype.mouseout = function (event) {
  2033. var eventControl = event.zrEventControl;
  2034. if (eventControl !== 'only_globalout') {
  2035. this.dispatchToElement(this._hovered, 'mouseout', event);
  2036. }
  2037. if (eventControl !== 'no_globalout') {
  2038. this.trigger('globalout', { type: 'globalout', event: event });
  2039. }
  2040. };
  2041. Handler.prototype.resize = function () {
  2042. this._hovered = new HoveredResult(0, 0);
  2043. };
  2044. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2045. var handler = this[eventName];
  2046. handler && handler.call(this, eventArgs);
  2047. };
  2048. Handler.prototype.dispose = function () {
  2049. this.proxy.dispose();
  2050. this.storage = null;
  2051. this.proxy = null;
  2052. this.painter = null;
  2053. };
  2054. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2055. var proxy = this.proxy;
  2056. proxy.setCursor && proxy.setCursor(cursorStyle);
  2057. };
  2058. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2059. targetInfo = targetInfo || {};
  2060. var el = targetInfo.target;
  2061. if (el && el.silent) {
  2062. return;
  2063. }
  2064. var eventKey = ('on' + eventName);
  2065. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2066. while (el) {
  2067. el[eventKey]
  2068. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2069. el.trigger(eventName, eventPacket);
  2070. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2071. if (eventPacket.cancelBubble) {
  2072. break;
  2073. }
  2074. }
  2075. if (!eventPacket.cancelBubble) {
  2076. this.trigger(eventName, eventPacket);
  2077. if (this.painter && this.painter.eachOtherLayer) {
  2078. this.painter.eachOtherLayer(function (layer) {
  2079. if (typeof (layer[eventKey]) === 'function') {
  2080. layer[eventKey].call(layer, eventPacket);
  2081. }
  2082. if (layer.trigger) {
  2083. layer.trigger(eventName, eventPacket);
  2084. }
  2085. });
  2086. }
  2087. }
  2088. };
  2089. Handler.prototype.findHover = function (x, y, exclude) {
  2090. var list = this.storage.getDisplayList();
  2091. var out = new HoveredResult(x, y);
  2092. setHoverTarget(list, out, x, y, exclude);
  2093. if (this._pointerSize && !out.target) {
  2094. var candidates = [];
  2095. var pointerSize = this._pointerSize;
  2096. var targetSizeHalf = pointerSize / 2;
  2097. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2098. for (var i = list.length - 1; i >= 0; i--) {
  2099. var el = list[i];
  2100. if (el !== exclude
  2101. && !el.ignore
  2102. && !el.ignoreCoarsePointer
  2103. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2104. tmpRect.copy(el.getBoundingRect());
  2105. if (el.transform) {
  2106. tmpRect.applyTransform(el.transform);
  2107. }
  2108. if (tmpRect.intersect(pointerRect)) {
  2109. candidates.push(el);
  2110. }
  2111. }
  2112. }
  2113. if (candidates.length) {
  2114. var rStep = 4;
  2115. var thetaStep = Math.PI / 12;
  2116. var PI2 = Math.PI * 2;
  2117. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2118. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2119. var x1 = x + r * Math.cos(theta);
  2120. var y1 = y + r * Math.sin(theta);
  2121. setHoverTarget(candidates, out, x1, y1, exclude);
  2122. if (out.target) {
  2123. return out;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. }
  2129. return out;
  2130. };
  2131. Handler.prototype.processGesture = function (event, stage) {
  2132. if (!this._gestureMgr) {
  2133. this._gestureMgr = new GestureMgr();
  2134. }
  2135. var gestureMgr = this._gestureMgr;
  2136. stage === 'start' && gestureMgr.clear();
  2137. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2138. stage === 'end' && gestureMgr.clear();
  2139. if (gestureInfo) {
  2140. var type = gestureInfo.type;
  2141. event.gestureEvent = type;
  2142. var res = new HoveredResult();
  2143. res.target = gestureInfo.target;
  2144. this.dispatchToElement(res, type, gestureInfo.event);
  2145. }
  2146. };
  2147. return Handler;
  2148. }(Eventful));
  2149. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2150. Handler.prototype[name] = function (event) {
  2151. var x = event.zrX;
  2152. var y = event.zrY;
  2153. var isOutside = isOutsideBoundary(this, x, y);
  2154. var hovered;
  2155. var hoveredTarget;
  2156. if (name !== 'mouseup' || !isOutside) {
  2157. hovered = this.findHover(x, y);
  2158. hoveredTarget = hovered.target;
  2159. }
  2160. if (name === 'mousedown') {
  2161. this._downEl = hoveredTarget;
  2162. this._downPoint = [event.zrX, event.zrY];
  2163. this._upEl = hoveredTarget;
  2164. }
  2165. else if (name === 'mouseup') {
  2166. this._upEl = hoveredTarget;
  2167. }
  2168. else if (name === 'click') {
  2169. if (this._downEl !== this._upEl
  2170. || !this._downPoint
  2171. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2172. return;
  2173. }
  2174. this._downPoint = null;
  2175. }
  2176. this.dispatchToElement(hovered, name, event);
  2177. };
  2178. });
  2179. function isHover(displayable, x, y) {
  2180. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2181. var el = displayable;
  2182. var isSilent = void 0;
  2183. var ignoreClip = false;
  2184. while (el) {
  2185. if (el.ignoreClip) {
  2186. ignoreClip = true;
  2187. }
  2188. if (!ignoreClip) {
  2189. var clipPath = el.getClipPath();
  2190. if (clipPath && !clipPath.contain(x, y)) {
  2191. return false;
  2192. }
  2193. if (el.silent) {
  2194. isSilent = true;
  2195. }
  2196. }
  2197. var hostEl = el.__hostTarget;
  2198. el = hostEl ? hostEl : el.parent;
  2199. }
  2200. return isSilent ? SILENT : true;
  2201. }
  2202. return false;
  2203. }
  2204. function setHoverTarget(list, out, x, y, exclude) {
  2205. for (var i = list.length - 1; i >= 0; i--) {
  2206. var el = list[i];
  2207. var hoverCheckResult = void 0;
  2208. if (el !== exclude
  2209. && !el.ignore
  2210. && (hoverCheckResult = isHover(el, x, y))) {
  2211. !out.topTarget && (out.topTarget = el);
  2212. if (hoverCheckResult !== SILENT) {
  2213. out.target = el;
  2214. break;
  2215. }
  2216. }
  2217. }
  2218. }
  2219. function isOutsideBoundary(handlerInstance, x, y) {
  2220. var painter = handlerInstance.painter;
  2221. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2222. }
  2223. var DEFAULT_MIN_MERGE = 32;
  2224. var DEFAULT_MIN_GALLOPING = 7;
  2225. function minRunLength(n) {
  2226. var r = 0;
  2227. while (n >= DEFAULT_MIN_MERGE) {
  2228. r |= n & 1;
  2229. n >>= 1;
  2230. }
  2231. return n + r;
  2232. }
  2233. function makeAscendingRun(array, lo, hi, compare) {
  2234. var runHi = lo + 1;
  2235. if (runHi === hi) {
  2236. return 1;
  2237. }
  2238. if (compare(array[runHi++], array[lo]) < 0) {
  2239. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2240. runHi++;
  2241. }
  2242. reverseRun(array, lo, runHi);
  2243. }
  2244. else {
  2245. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2246. runHi++;
  2247. }
  2248. }
  2249. return runHi - lo;
  2250. }
  2251. function reverseRun(array, lo, hi) {
  2252. hi--;
  2253. while (lo < hi) {
  2254. var t = array[lo];
  2255. array[lo++] = array[hi];
  2256. array[hi--] = t;
  2257. }
  2258. }
  2259. function binaryInsertionSort(array, lo, hi, start, compare) {
  2260. if (start === lo) {
  2261. start++;
  2262. }
  2263. for (; start < hi; start++) {
  2264. var pivot = array[start];
  2265. var left = lo;
  2266. var right = start;
  2267. var mid;
  2268. while (left < right) {
  2269. mid = left + right >>> 1;
  2270. if (compare(pivot, array[mid]) < 0) {
  2271. right = mid;
  2272. }
  2273. else {
  2274. left = mid + 1;
  2275. }
  2276. }
  2277. var n = start - left;
  2278. switch (n) {
  2279. case 3:
  2280. array[left + 3] = array[left + 2];
  2281. case 2:
  2282. array[left + 2] = array[left + 1];
  2283. case 1:
  2284. array[left + 1] = array[left];
  2285. break;
  2286. default:
  2287. while (n > 0) {
  2288. array[left + n] = array[left + n - 1];
  2289. n--;
  2290. }
  2291. }
  2292. array[left] = pivot;
  2293. }
  2294. }
  2295. function gallopLeft(value, array, start, length, hint, compare) {
  2296. var lastOffset = 0;
  2297. var maxOffset = 0;
  2298. var offset = 1;
  2299. if (compare(value, array[start + hint]) > 0) {
  2300. maxOffset = length - hint;
  2301. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2302. lastOffset = offset;
  2303. offset = (offset << 1) + 1;
  2304. if (offset <= 0) {
  2305. offset = maxOffset;
  2306. }
  2307. }
  2308. if (offset > maxOffset) {
  2309. offset = maxOffset;
  2310. }
  2311. lastOffset += hint;
  2312. offset += hint;
  2313. }
  2314. else {
  2315. maxOffset = hint + 1;
  2316. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2317. lastOffset = offset;
  2318. offset = (offset << 1) + 1;
  2319. if (offset <= 0) {
  2320. offset = maxOffset;
  2321. }
  2322. }
  2323. if (offset > maxOffset) {
  2324. offset = maxOffset;
  2325. }
  2326. var tmp = lastOffset;
  2327. lastOffset = hint - offset;
  2328. offset = hint - tmp;
  2329. }
  2330. lastOffset++;
  2331. while (lastOffset < offset) {
  2332. var m = lastOffset + (offset - lastOffset >>> 1);
  2333. if (compare(value, array[start + m]) > 0) {
  2334. lastOffset = m + 1;
  2335. }
  2336. else {
  2337. offset = m;
  2338. }
  2339. }
  2340. return offset;
  2341. }
  2342. function gallopRight(value, array, start, length, hint, compare) {
  2343. var lastOffset = 0;
  2344. var maxOffset = 0;
  2345. var offset = 1;
  2346. if (compare(value, array[start + hint]) < 0) {
  2347. maxOffset = hint + 1;
  2348. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2349. lastOffset = offset;
  2350. offset = (offset << 1) + 1;
  2351. if (offset <= 0) {
  2352. offset = maxOffset;
  2353. }
  2354. }
  2355. if (offset > maxOffset) {
  2356. offset = maxOffset;
  2357. }
  2358. var tmp = lastOffset;
  2359. lastOffset = hint - offset;
  2360. offset = hint - tmp;
  2361. }
  2362. else {
  2363. maxOffset = length - hint;
  2364. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2365. lastOffset = offset;
  2366. offset = (offset << 1) + 1;
  2367. if (offset <= 0) {
  2368. offset = maxOffset;
  2369. }
  2370. }
  2371. if (offset > maxOffset) {
  2372. offset = maxOffset;
  2373. }
  2374. lastOffset += hint;
  2375. offset += hint;
  2376. }
  2377. lastOffset++;
  2378. while (lastOffset < offset) {
  2379. var m = lastOffset + (offset - lastOffset >>> 1);
  2380. if (compare(value, array[start + m]) < 0) {
  2381. offset = m;
  2382. }
  2383. else {
  2384. lastOffset = m + 1;
  2385. }
  2386. }
  2387. return offset;
  2388. }
  2389. function TimSort(array, compare) {
  2390. var minGallop = DEFAULT_MIN_GALLOPING;
  2391. var length = 0;
  2392. var runStart;
  2393. var runLength;
  2394. var stackSize = 0;
  2395. length = array.length;
  2396. var tmp = [];
  2397. runStart = [];
  2398. runLength = [];
  2399. function pushRun(_runStart, _runLength) {
  2400. runStart[stackSize] = _runStart;
  2401. runLength[stackSize] = _runLength;
  2402. stackSize += 1;
  2403. }
  2404. function mergeRuns() {
  2405. while (stackSize > 1) {
  2406. var n = stackSize - 2;
  2407. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2408. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2409. if (runLength[n - 1] < runLength[n + 1]) {
  2410. n--;
  2411. }
  2412. }
  2413. else if (runLength[n] > runLength[n + 1]) {
  2414. break;
  2415. }
  2416. mergeAt(n);
  2417. }
  2418. }
  2419. function forceMergeRuns() {
  2420. while (stackSize > 1) {
  2421. var n = stackSize - 2;
  2422. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2423. n--;
  2424. }
  2425. mergeAt(n);
  2426. }
  2427. }
  2428. function mergeAt(i) {
  2429. var start1 = runStart[i];
  2430. var length1 = runLength[i];
  2431. var start2 = runStart[i + 1];
  2432. var length2 = runLength[i + 1];
  2433. runLength[i] = length1 + length2;
  2434. if (i === stackSize - 3) {
  2435. runStart[i + 1] = runStart[i + 2];
  2436. runLength[i + 1] = runLength[i + 2];
  2437. }
  2438. stackSize--;
  2439. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2440. start1 += k;
  2441. length1 -= k;
  2442. if (length1 === 0) {
  2443. return;
  2444. }
  2445. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2446. if (length2 === 0) {
  2447. return;
  2448. }
  2449. if (length1 <= length2) {
  2450. mergeLow(start1, length1, start2, length2);
  2451. }
  2452. else {
  2453. mergeHigh(start1, length1, start2, length2);
  2454. }
  2455. }
  2456. function mergeLow(start1, length1, start2, length2) {
  2457. var i = 0;
  2458. for (i = 0; i < length1; i++) {
  2459. tmp[i] = array[start1 + i];
  2460. }
  2461. var cursor1 = 0;
  2462. var cursor2 = start2;
  2463. var dest = start1;
  2464. array[dest++] = array[cursor2++];
  2465. if (--length2 === 0) {
  2466. for (i = 0; i < length1; i++) {
  2467. array[dest + i] = tmp[cursor1 + i];
  2468. }
  2469. return;
  2470. }
  2471. if (length1 === 1) {
  2472. for (i = 0; i < length2; i++) {
  2473. array[dest + i] = array[cursor2 + i];
  2474. }
  2475. array[dest + length2] = tmp[cursor1];
  2476. return;
  2477. }
  2478. var _minGallop = minGallop;
  2479. var count1;
  2480. var count2;
  2481. var exit;
  2482. while (1) {
  2483. count1 = 0;
  2484. count2 = 0;
  2485. exit = false;
  2486. do {
  2487. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2488. array[dest++] = array[cursor2++];
  2489. count2++;
  2490. count1 = 0;
  2491. if (--length2 === 0) {
  2492. exit = true;
  2493. break;
  2494. }
  2495. }
  2496. else {
  2497. array[dest++] = tmp[cursor1++];
  2498. count1++;
  2499. count2 = 0;
  2500. if (--length1 === 1) {
  2501. exit = true;
  2502. break;
  2503. }
  2504. }
  2505. } while ((count1 | count2) < _minGallop);
  2506. if (exit) {
  2507. break;
  2508. }
  2509. do {
  2510. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2511. if (count1 !== 0) {
  2512. for (i = 0; i < count1; i++) {
  2513. array[dest + i] = tmp[cursor1 + i];
  2514. }
  2515. dest += count1;
  2516. cursor1 += count1;
  2517. length1 -= count1;
  2518. if (length1 <= 1) {
  2519. exit = true;
  2520. break;
  2521. }
  2522. }
  2523. array[dest++] = array[cursor2++];
  2524. if (--length2 === 0) {
  2525. exit = true;
  2526. break;
  2527. }
  2528. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2529. if (count2 !== 0) {
  2530. for (i = 0; i < count2; i++) {
  2531. array[dest + i] = array[cursor2 + i];
  2532. }
  2533. dest += count2;
  2534. cursor2 += count2;
  2535. length2 -= count2;
  2536. if (length2 === 0) {
  2537. exit = true;
  2538. break;
  2539. }
  2540. }
  2541. array[dest++] = tmp[cursor1++];
  2542. if (--length1 === 1) {
  2543. exit = true;
  2544. break;
  2545. }
  2546. _minGallop--;
  2547. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2548. if (exit) {
  2549. break;
  2550. }
  2551. if (_minGallop < 0) {
  2552. _minGallop = 0;
  2553. }
  2554. _minGallop += 2;
  2555. }
  2556. minGallop = _minGallop;
  2557. minGallop < 1 && (minGallop = 1);
  2558. if (length1 === 1) {
  2559. for (i = 0; i < length2; i++) {
  2560. array[dest + i] = array[cursor2 + i];
  2561. }
  2562. array[dest + length2] = tmp[cursor1];
  2563. }
  2564. else if (length1 === 0) {
  2565. throw new Error();
  2566. }
  2567. else {
  2568. for (i = 0; i < length1; i++) {
  2569. array[dest + i] = tmp[cursor1 + i];
  2570. }
  2571. }
  2572. }
  2573. function mergeHigh(start1, length1, start2, length2) {
  2574. var i = 0;
  2575. for (i = 0; i < length2; i++) {
  2576. tmp[i] = array[start2 + i];
  2577. }
  2578. var cursor1 = start1 + length1 - 1;
  2579. var cursor2 = length2 - 1;
  2580. var dest = start2 + length2 - 1;
  2581. var customCursor = 0;
  2582. var customDest = 0;
  2583. array[dest--] = array[cursor1--];
  2584. if (--length1 === 0) {
  2585. customCursor = dest - (length2 - 1);
  2586. for (i = 0; i < length2; i++) {
  2587. array[customCursor + i] = tmp[i];
  2588. }
  2589. return;
  2590. }
  2591. if (length2 === 1) {
  2592. dest -= length1;
  2593. cursor1 -= length1;
  2594. customDest = dest + 1;
  2595. customCursor = cursor1 + 1;
  2596. for (i = length1 - 1; i >= 0; i--) {
  2597. array[customDest + i] = array[customCursor + i];
  2598. }
  2599. array[dest] = tmp[cursor2];
  2600. return;
  2601. }
  2602. var _minGallop = minGallop;
  2603. while (true) {
  2604. var count1 = 0;
  2605. var count2 = 0;
  2606. var exit = false;
  2607. do {
  2608. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2609. array[dest--] = array[cursor1--];
  2610. count1++;
  2611. count2 = 0;
  2612. if (--length1 === 0) {
  2613. exit = true;
  2614. break;
  2615. }
  2616. }
  2617. else {
  2618. array[dest--] = tmp[cursor2--];
  2619. count2++;
  2620. count1 = 0;
  2621. if (--length2 === 1) {
  2622. exit = true;
  2623. break;
  2624. }
  2625. }
  2626. } while ((count1 | count2) < _minGallop);
  2627. if (exit) {
  2628. break;
  2629. }
  2630. do {
  2631. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2632. if (count1 !== 0) {
  2633. dest -= count1;
  2634. cursor1 -= count1;
  2635. length1 -= count1;
  2636. customDest = dest + 1;
  2637. customCursor = cursor1 + 1;
  2638. for (i = count1 - 1; i >= 0; i--) {
  2639. array[customDest + i] = array[customCursor + i];
  2640. }
  2641. if (length1 === 0) {
  2642. exit = true;
  2643. break;
  2644. }
  2645. }
  2646. array[dest--] = tmp[cursor2--];
  2647. if (--length2 === 1) {
  2648. exit = true;
  2649. break;
  2650. }
  2651. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2652. if (count2 !== 0) {
  2653. dest -= count2;
  2654. cursor2 -= count2;
  2655. length2 -= count2;
  2656. customDest = dest + 1;
  2657. customCursor = cursor2 + 1;
  2658. for (i = 0; i < count2; i++) {
  2659. array[customDest + i] = tmp[customCursor + i];
  2660. }
  2661. if (length2 <= 1) {
  2662. exit = true;
  2663. break;
  2664. }
  2665. }
  2666. array[dest--] = array[cursor1--];
  2667. if (--length1 === 0) {
  2668. exit = true;
  2669. break;
  2670. }
  2671. _minGallop--;
  2672. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2673. if (exit) {
  2674. break;
  2675. }
  2676. if (_minGallop < 0) {
  2677. _minGallop = 0;
  2678. }
  2679. _minGallop += 2;
  2680. }
  2681. minGallop = _minGallop;
  2682. if (minGallop < 1) {
  2683. minGallop = 1;
  2684. }
  2685. if (length2 === 1) {
  2686. dest -= length1;
  2687. cursor1 -= length1;
  2688. customDest = dest + 1;
  2689. customCursor = cursor1 + 1;
  2690. for (i = length1 - 1; i >= 0; i--) {
  2691. array[customDest + i] = array[customCursor + i];
  2692. }
  2693. array[dest] = tmp[cursor2];
  2694. }
  2695. else if (length2 === 0) {
  2696. throw new Error();
  2697. }
  2698. else {
  2699. customCursor = dest - (length2 - 1);
  2700. for (i = 0; i < length2; i++) {
  2701. array[customCursor + i] = tmp[i];
  2702. }
  2703. }
  2704. }
  2705. return {
  2706. mergeRuns: mergeRuns,
  2707. forceMergeRuns: forceMergeRuns,
  2708. pushRun: pushRun
  2709. };
  2710. }
  2711. function sort(array, compare, lo, hi) {
  2712. if (!lo) {
  2713. lo = 0;
  2714. }
  2715. if (!hi) {
  2716. hi = array.length;
  2717. }
  2718. var remaining = hi - lo;
  2719. if (remaining < 2) {
  2720. return;
  2721. }
  2722. var runLength = 0;
  2723. if (remaining < DEFAULT_MIN_MERGE) {
  2724. runLength = makeAscendingRun(array, lo, hi, compare);
  2725. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2726. return;
  2727. }
  2728. var ts = TimSort(array, compare);
  2729. var minRun = minRunLength(remaining);
  2730. do {
  2731. runLength = makeAscendingRun(array, lo, hi, compare);
  2732. if (runLength < minRun) {
  2733. var force = remaining;
  2734. if (force > minRun) {
  2735. force = minRun;
  2736. }
  2737. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2738. runLength = force;
  2739. }
  2740. ts.pushRun(lo, runLength);
  2741. ts.mergeRuns();
  2742. remaining -= runLength;
  2743. lo += runLength;
  2744. } while (remaining !== 0);
  2745. ts.forceMergeRuns();
  2746. }
  2747. var REDRAW_BIT = 1;
  2748. var STYLE_CHANGED_BIT = 2;
  2749. var SHAPE_CHANGED_BIT = 4;
  2750. var invalidZErrorLogged = false;
  2751. function logInvalidZError() {
  2752. if (invalidZErrorLogged) {
  2753. return;
  2754. }
  2755. invalidZErrorLogged = true;
  2756. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2757. }
  2758. function shapeCompareFunc(a, b) {
  2759. if (a.zlevel === b.zlevel) {
  2760. if (a.z === b.z) {
  2761. return a.z2 - b.z2;
  2762. }
  2763. return a.z - b.z;
  2764. }
  2765. return a.zlevel - b.zlevel;
  2766. }
  2767. var Storage = (function () {
  2768. function Storage() {
  2769. this._roots = [];
  2770. this._displayList = [];
  2771. this._displayListLen = 0;
  2772. this.displayableSortFunc = shapeCompareFunc;
  2773. }
  2774. Storage.prototype.traverse = function (cb, context) {
  2775. for (var i = 0; i < this._roots.length; i++) {
  2776. this._roots[i].traverse(cb, context);
  2777. }
  2778. };
  2779. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2780. includeIgnore = includeIgnore || false;
  2781. var displayList = this._displayList;
  2782. if (update || !displayList.length) {
  2783. this.updateDisplayList(includeIgnore);
  2784. }
  2785. return displayList;
  2786. };
  2787. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2788. this._displayListLen = 0;
  2789. var roots = this._roots;
  2790. var displayList = this._displayList;
  2791. for (var i = 0, len = roots.length; i < len; i++) {
  2792. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2793. }
  2794. displayList.length = this._displayListLen;
  2795. sort(displayList, shapeCompareFunc);
  2796. };
  2797. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2798. if (el.ignore && !includeIgnore) {
  2799. return;
  2800. }
  2801. el.beforeUpdate();
  2802. el.update();
  2803. el.afterUpdate();
  2804. var userSetClipPath = el.getClipPath();
  2805. if (el.ignoreClip) {
  2806. clipPaths = null;
  2807. }
  2808. else if (userSetClipPath) {
  2809. if (clipPaths) {
  2810. clipPaths = clipPaths.slice();
  2811. }
  2812. else {
  2813. clipPaths = [];
  2814. }
  2815. var currentClipPath = userSetClipPath;
  2816. var parentClipPath = el;
  2817. while (currentClipPath) {
  2818. currentClipPath.parent = parentClipPath;
  2819. currentClipPath.updateTransform();
  2820. clipPaths.push(currentClipPath);
  2821. parentClipPath = currentClipPath;
  2822. currentClipPath = currentClipPath.getClipPath();
  2823. }
  2824. }
  2825. if (el.childrenRef) {
  2826. var children = el.childrenRef();
  2827. for (var i = 0; i < children.length; i++) {
  2828. var child = children[i];
  2829. if (el.__dirty) {
  2830. child.__dirty |= REDRAW_BIT;
  2831. }
  2832. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2833. }
  2834. el.__dirty = 0;
  2835. }
  2836. else {
  2837. var disp = el;
  2838. if (clipPaths && clipPaths.length) {
  2839. disp.__clipPaths = clipPaths;
  2840. }
  2841. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2842. disp.__clipPaths = [];
  2843. }
  2844. if (isNaN(disp.z)) {
  2845. logInvalidZError();
  2846. disp.z = 0;
  2847. }
  2848. if (isNaN(disp.z2)) {
  2849. logInvalidZError();
  2850. disp.z2 = 0;
  2851. }
  2852. if (isNaN(disp.zlevel)) {
  2853. logInvalidZError();
  2854. disp.zlevel = 0;
  2855. }
  2856. this._displayList[this._displayListLen++] = disp;
  2857. }
  2858. var decalEl = el.getDecalElement && el.getDecalElement();
  2859. if (decalEl) {
  2860. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2861. }
  2862. var textGuide = el.getTextGuideLine();
  2863. if (textGuide) {
  2864. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2865. }
  2866. var textEl = el.getTextContent();
  2867. if (textEl) {
  2868. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2869. }
  2870. };
  2871. Storage.prototype.addRoot = function (el) {
  2872. if (el.__zr && el.__zr.storage === this) {
  2873. return;
  2874. }
  2875. this._roots.push(el);
  2876. };
  2877. Storage.prototype.delRoot = function (el) {
  2878. if (el instanceof Array) {
  2879. for (var i = 0, l = el.length; i < l; i++) {
  2880. this.delRoot(el[i]);
  2881. }
  2882. return;
  2883. }
  2884. var idx = indexOf(this._roots, el);
  2885. if (idx >= 0) {
  2886. this._roots.splice(idx, 1);
  2887. }
  2888. };
  2889. Storage.prototype.delAllRoots = function () {
  2890. this._roots = [];
  2891. this._displayList = [];
  2892. this._displayListLen = 0;
  2893. return;
  2894. };
  2895. Storage.prototype.getRoots = function () {
  2896. return this._roots;
  2897. };
  2898. Storage.prototype.dispose = function () {
  2899. this._displayList = null;
  2900. this._roots = null;
  2901. };
  2902. return Storage;
  2903. }());
  2904. var requestAnimationFrame;
  2905. requestAnimationFrame = (env.hasGlobalWindow
  2906. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2907. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2908. || window.mozRequestAnimationFrame
  2909. || window.webkitRequestAnimationFrame)) || function (func) {
  2910. return setTimeout(func, 16);
  2911. };
  2912. var requestAnimationFrame$1 = requestAnimationFrame;
  2913. var easingFuncs = {
  2914. linear: function (k) {
  2915. return k;
  2916. },
  2917. quadraticIn: function (k) {
  2918. return k * k;
  2919. },
  2920. quadraticOut: function (k) {
  2921. return k * (2 - k);
  2922. },
  2923. quadraticInOut: function (k) {
  2924. if ((k *= 2) < 1) {
  2925. return 0.5 * k * k;
  2926. }
  2927. return -0.5 * (--k * (k - 2) - 1);
  2928. },
  2929. cubicIn: function (k) {
  2930. return k * k * k;
  2931. },
  2932. cubicOut: function (k) {
  2933. return --k * k * k + 1;
  2934. },
  2935. cubicInOut: function (k) {
  2936. if ((k *= 2) < 1) {
  2937. return 0.5 * k * k * k;
  2938. }
  2939. return 0.5 * ((k -= 2) * k * k + 2);
  2940. },
  2941. quarticIn: function (k) {
  2942. return k * k * k * k;
  2943. },
  2944. quarticOut: function (k) {
  2945. return 1 - (--k * k * k * k);
  2946. },
  2947. quarticInOut: function (k) {
  2948. if ((k *= 2) < 1) {
  2949. return 0.5 * k * k * k * k;
  2950. }
  2951. return -0.5 * ((k -= 2) * k * k * k - 2);
  2952. },
  2953. quinticIn: function (k) {
  2954. return k * k * k * k * k;
  2955. },
  2956. quinticOut: function (k) {
  2957. return --k * k * k * k * k + 1;
  2958. },
  2959. quinticInOut: function (k) {
  2960. if ((k *= 2) < 1) {
  2961. return 0.5 * k * k * k * k * k;
  2962. }
  2963. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2964. },
  2965. sinusoidalIn: function (k) {
  2966. return 1 - Math.cos(k * Math.PI / 2);
  2967. },
  2968. sinusoidalOut: function (k) {
  2969. return Math.sin(k * Math.PI / 2);
  2970. },
  2971. sinusoidalInOut: function (k) {
  2972. return 0.5 * (1 - Math.cos(Math.PI * k));
  2973. },
  2974. exponentialIn: function (k) {
  2975. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2976. },
  2977. exponentialOut: function (k) {
  2978. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2979. },
  2980. exponentialInOut: function (k) {
  2981. if (k === 0) {
  2982. return 0;
  2983. }
  2984. if (k === 1) {
  2985. return 1;
  2986. }
  2987. if ((k *= 2) < 1) {
  2988. return 0.5 * Math.pow(1024, k - 1);
  2989. }
  2990. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2991. },
  2992. circularIn: function (k) {
  2993. return 1 - Math.sqrt(1 - k * k);
  2994. },
  2995. circularOut: function (k) {
  2996. return Math.sqrt(1 - (--k * k));
  2997. },
  2998. circularInOut: function (k) {
  2999. if ((k *= 2) < 1) {
  3000. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3001. }
  3002. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3003. },
  3004. elasticIn: function (k) {
  3005. var s;
  3006. var a = 0.1;
  3007. var p = 0.4;
  3008. if (k === 0) {
  3009. return 0;
  3010. }
  3011. if (k === 1) {
  3012. return 1;
  3013. }
  3014. if (!a || a < 1) {
  3015. a = 1;
  3016. s = p / 4;
  3017. }
  3018. else {
  3019. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3020. }
  3021. return -(a * Math.pow(2, 10 * (k -= 1))
  3022. * Math.sin((k - s) * (2 * Math.PI) / p));
  3023. },
  3024. elasticOut: function (k) {
  3025. var s;
  3026. var a = 0.1;
  3027. var p = 0.4;
  3028. if (k === 0) {
  3029. return 0;
  3030. }
  3031. if (k === 1) {
  3032. return 1;
  3033. }
  3034. if (!a || a < 1) {
  3035. a = 1;
  3036. s = p / 4;
  3037. }
  3038. else {
  3039. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3040. }
  3041. return (a * Math.pow(2, -10 * k)
  3042. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3043. },
  3044. elasticInOut: function (k) {
  3045. var s;
  3046. var a = 0.1;
  3047. var p = 0.4;
  3048. if (k === 0) {
  3049. return 0;
  3050. }
  3051. if (k === 1) {
  3052. return 1;
  3053. }
  3054. if (!a || a < 1) {
  3055. a = 1;
  3056. s = p / 4;
  3057. }
  3058. else {
  3059. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3060. }
  3061. if ((k *= 2) < 1) {
  3062. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3063. * Math.sin((k - s) * (2 * Math.PI) / p));
  3064. }
  3065. return a * Math.pow(2, -10 * (k -= 1))
  3066. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3067. },
  3068. backIn: function (k) {
  3069. var s = 1.70158;
  3070. return k * k * ((s + 1) * k - s);
  3071. },
  3072. backOut: function (k) {
  3073. var s = 1.70158;
  3074. return --k * k * ((s + 1) * k + s) + 1;
  3075. },
  3076. backInOut: function (k) {
  3077. var s = 1.70158 * 1.525;
  3078. if ((k *= 2) < 1) {
  3079. return 0.5 * (k * k * ((s + 1) * k - s));
  3080. }
  3081. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3082. },
  3083. bounceIn: function (k) {
  3084. return 1 - easingFuncs.bounceOut(1 - k);
  3085. },
  3086. bounceOut: function (k) {
  3087. if (k < (1 / 2.75)) {
  3088. return 7.5625 * k * k;
  3089. }
  3090. else if (k < (2 / 2.75)) {
  3091. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3092. }
  3093. else if (k < (2.5 / 2.75)) {
  3094. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3095. }
  3096. else {
  3097. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3098. }
  3099. },
  3100. bounceInOut: function (k) {
  3101. if (k < 0.5) {
  3102. return easingFuncs.bounceIn(k * 2) * 0.5;
  3103. }
  3104. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3105. }
  3106. };
  3107. var mathPow = Math.pow;
  3108. var mathSqrt = Math.sqrt;
  3109. var EPSILON = 1e-8;
  3110. var EPSILON_NUMERIC = 1e-4;
  3111. var THREE_SQRT = mathSqrt(3);
  3112. var ONE_THIRD = 1 / 3;
  3113. var _v0 = create();
  3114. var _v1 = create();
  3115. var _v2 = create();
  3116. function isAroundZero(val) {
  3117. return val > -EPSILON && val < EPSILON;
  3118. }
  3119. function isNotAroundZero(val) {
  3120. return val > EPSILON || val < -EPSILON;
  3121. }
  3122. function cubicAt(p0, p1, p2, p3, t) {
  3123. var onet = 1 - t;
  3124. return onet * onet * (onet * p0 + 3 * t * p1)
  3125. + t * t * (t * p3 + 3 * onet * p2);
  3126. }
  3127. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3128. var onet = 1 - t;
  3129. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3130. + (p3 - p2) * t * t);
  3131. }
  3132. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3133. var a = p3 + 3 * (p1 - p2) - p0;
  3134. var b = 3 * (p2 - p1 * 2 + p0);
  3135. var c = 3 * (p1 - p0);
  3136. var d = p0 - val;
  3137. var A = b * b - 3 * a * c;
  3138. var B = b * c - 9 * a * d;
  3139. var C = c * c - 3 * b * d;
  3140. var n = 0;
  3141. if (isAroundZero(A) && isAroundZero(B)) {
  3142. if (isAroundZero(b)) {
  3143. roots[0] = 0;
  3144. }
  3145. else {
  3146. var t1 = -c / b;
  3147. if (t1 >= 0 && t1 <= 1) {
  3148. roots[n++] = t1;
  3149. }
  3150. }
  3151. }
  3152. else {
  3153. var disc = B * B - 4 * A * C;
  3154. if (isAroundZero(disc)) {
  3155. var K = B / A;
  3156. var t1 = -b / a + K;
  3157. var t2 = -K / 2;
  3158. if (t1 >= 0 && t1 <= 1) {
  3159. roots[n++] = t1;
  3160. }
  3161. if (t2 >= 0 && t2 <= 1) {
  3162. roots[n++] = t2;
  3163. }
  3164. }
  3165. else if (disc > 0) {
  3166. var discSqrt = mathSqrt(disc);
  3167. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3168. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3169. if (Y1 < 0) {
  3170. Y1 = -mathPow(-Y1, ONE_THIRD);
  3171. }
  3172. else {
  3173. Y1 = mathPow(Y1, ONE_THIRD);
  3174. }
  3175. if (Y2 < 0) {
  3176. Y2 = -mathPow(-Y2, ONE_THIRD);
  3177. }
  3178. else {
  3179. Y2 = mathPow(Y2, ONE_THIRD);
  3180. }
  3181. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3182. if (t1 >= 0 && t1 <= 1) {
  3183. roots[n++] = t1;
  3184. }
  3185. }
  3186. else {
  3187. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3188. var theta = Math.acos(T) / 3;
  3189. var ASqrt = mathSqrt(A);
  3190. var tmp = Math.cos(theta);
  3191. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3192. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3193. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3194. if (t1 >= 0 && t1 <= 1) {
  3195. roots[n++] = t1;
  3196. }
  3197. if (t2 >= 0 && t2 <= 1) {
  3198. roots[n++] = t2;
  3199. }
  3200. if (t3 >= 0 && t3 <= 1) {
  3201. roots[n++] = t3;
  3202. }
  3203. }
  3204. }
  3205. return n;
  3206. }
  3207. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3208. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3209. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3210. var c = 3 * p1 - 3 * p0;
  3211. var n = 0;
  3212. if (isAroundZero(a)) {
  3213. if (isNotAroundZero(b)) {
  3214. var t1 = -c / b;
  3215. if (t1 >= 0 && t1 <= 1) {
  3216. extrema[n++] = t1;
  3217. }
  3218. }
  3219. }
  3220. else {
  3221. var disc = b * b - 4 * a * c;
  3222. if (isAroundZero(disc)) {
  3223. extrema[0] = -b / (2 * a);
  3224. }
  3225. else if (disc > 0) {
  3226. var discSqrt = mathSqrt(disc);
  3227. var t1 = (-b + discSqrt) / (2 * a);
  3228. var t2 = (-b - discSqrt) / (2 * a);
  3229. if (t1 >= 0 && t1 <= 1) {
  3230. extrema[n++] = t1;
  3231. }
  3232. if (t2 >= 0 && t2 <= 1) {
  3233. extrema[n++] = t2;
  3234. }
  3235. }
  3236. }
  3237. return n;
  3238. }
  3239. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3240. var p01 = (p1 - p0) * t + p0;
  3241. var p12 = (p2 - p1) * t + p1;
  3242. var p23 = (p3 - p2) * t + p2;
  3243. var p012 = (p12 - p01) * t + p01;
  3244. var p123 = (p23 - p12) * t + p12;
  3245. var p0123 = (p123 - p012) * t + p012;
  3246. out[0] = p0;
  3247. out[1] = p01;
  3248. out[2] = p012;
  3249. out[3] = p0123;
  3250. out[4] = p0123;
  3251. out[5] = p123;
  3252. out[6] = p23;
  3253. out[7] = p3;
  3254. }
  3255. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3256. var t;
  3257. var interval = 0.005;
  3258. var d = Infinity;
  3259. var prev;
  3260. var next;
  3261. var d1;
  3262. var d2;
  3263. _v0[0] = x;
  3264. _v0[1] = y;
  3265. for (var _t = 0; _t < 1; _t += 0.05) {
  3266. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3267. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3268. d1 = distSquare(_v0, _v1);
  3269. if (d1 < d) {
  3270. t = _t;
  3271. d = d1;
  3272. }
  3273. }
  3274. d = Infinity;
  3275. for (var i = 0; i < 32; i++) {
  3276. if (interval < EPSILON_NUMERIC) {
  3277. break;
  3278. }
  3279. prev = t - interval;
  3280. next = t + interval;
  3281. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3282. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3283. d1 = distSquare(_v1, _v0);
  3284. if (prev >= 0 && d1 < d) {
  3285. t = prev;
  3286. d = d1;
  3287. }
  3288. else {
  3289. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3290. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3291. d2 = distSquare(_v2, _v0);
  3292. if (next <= 1 && d2 < d) {
  3293. t = next;
  3294. d = d2;
  3295. }
  3296. else {
  3297. interval *= 0.5;
  3298. }
  3299. }
  3300. }
  3301. if (out) {
  3302. out[0] = cubicAt(x0, x1, x2, x3, t);
  3303. out[1] = cubicAt(y0, y1, y2, y3, t);
  3304. }
  3305. return mathSqrt(d);
  3306. }
  3307. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3308. var px = x0;
  3309. var py = y0;
  3310. var d = 0;
  3311. var step = 1 / iteration;
  3312. for (var i = 1; i <= iteration; i++) {
  3313. var t = i * step;
  3314. var x = cubicAt(x0, x1, x2, x3, t);
  3315. var y = cubicAt(y0, y1, y2, y3, t);
  3316. var dx = x - px;
  3317. var dy = y - py;
  3318. d += Math.sqrt(dx * dx + dy * dy);
  3319. px = x;
  3320. py = y;
  3321. }
  3322. return d;
  3323. }
  3324. function quadraticAt(p0, p1, p2, t) {
  3325. var onet = 1 - t;
  3326. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3327. }
  3328. function quadraticDerivativeAt(p0, p1, p2, t) {
  3329. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3330. }
  3331. function quadraticRootAt(p0, p1, p2, val, roots) {
  3332. var a = p0 - 2 * p1 + p2;
  3333. var b = 2 * (p1 - p0);
  3334. var c = p0 - val;
  3335. var n = 0;
  3336. if (isAroundZero(a)) {
  3337. if (isNotAroundZero(b)) {
  3338. var t1 = -c / b;
  3339. if (t1 >= 0 && t1 <= 1) {
  3340. roots[n++] = t1;
  3341. }
  3342. }
  3343. }
  3344. else {
  3345. var disc = b * b - 4 * a * c;
  3346. if (isAroundZero(disc)) {
  3347. var t1 = -b / (2 * a);
  3348. if (t1 >= 0 && t1 <= 1) {
  3349. roots[n++] = t1;
  3350. }
  3351. }
  3352. else if (disc > 0) {
  3353. var discSqrt = mathSqrt(disc);
  3354. var t1 = (-b + discSqrt) / (2 * a);
  3355. var t2 = (-b - discSqrt) / (2 * a);
  3356. if (t1 >= 0 && t1 <= 1) {
  3357. roots[n++] = t1;
  3358. }
  3359. if (t2 >= 0 && t2 <= 1) {
  3360. roots[n++] = t2;
  3361. }
  3362. }
  3363. }
  3364. return n;
  3365. }
  3366. function quadraticExtremum(p0, p1, p2) {
  3367. var divider = p0 + p2 - 2 * p1;
  3368. if (divider === 0) {
  3369. return 0.5;
  3370. }
  3371. else {
  3372. return (p0 - p1) / divider;
  3373. }
  3374. }
  3375. function quadraticSubdivide(p0, p1, p2, t, out) {
  3376. var p01 = (p1 - p0) * t + p0;
  3377. var p12 = (p2 - p1) * t + p1;
  3378. var p012 = (p12 - p01) * t + p01;
  3379. out[0] = p0;
  3380. out[1] = p01;
  3381. out[2] = p012;
  3382. out[3] = p012;
  3383. out[4] = p12;
  3384. out[5] = p2;
  3385. }
  3386. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3387. var t;
  3388. var interval = 0.005;
  3389. var d = Infinity;
  3390. _v0[0] = x;
  3391. _v0[1] = y;
  3392. for (var _t = 0; _t < 1; _t += 0.05) {
  3393. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3394. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3395. var d1 = distSquare(_v0, _v1);
  3396. if (d1 < d) {
  3397. t = _t;
  3398. d = d1;
  3399. }
  3400. }
  3401. d = Infinity;
  3402. for (var i = 0; i < 32; i++) {
  3403. if (interval < EPSILON_NUMERIC) {
  3404. break;
  3405. }
  3406. var prev = t - interval;
  3407. var next = t + interval;
  3408. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3409. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3410. var d1 = distSquare(_v1, _v0);
  3411. if (prev >= 0 && d1 < d) {
  3412. t = prev;
  3413. d = d1;
  3414. }
  3415. else {
  3416. _v2[0] = quadraticAt(x0, x1, x2, next);
  3417. _v2[1] = quadraticAt(y0, y1, y2, next);
  3418. var d2 = distSquare(_v2, _v0);
  3419. if (next <= 1 && d2 < d) {
  3420. t = next;
  3421. d = d2;
  3422. }
  3423. else {
  3424. interval *= 0.5;
  3425. }
  3426. }
  3427. }
  3428. if (out) {
  3429. out[0] = quadraticAt(x0, x1, x2, t);
  3430. out[1] = quadraticAt(y0, y1, y2, t);
  3431. }
  3432. return mathSqrt(d);
  3433. }
  3434. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3435. var px = x0;
  3436. var py = y0;
  3437. var d = 0;
  3438. var step = 1 / iteration;
  3439. for (var i = 1; i <= iteration; i++) {
  3440. var t = i * step;
  3441. var x = quadraticAt(x0, x1, x2, t);
  3442. var y = quadraticAt(y0, y1, y2, t);
  3443. var dx = x - px;
  3444. var dy = y - py;
  3445. d += Math.sqrt(dx * dx + dy * dy);
  3446. px = x;
  3447. py = y;
  3448. }
  3449. return d;
  3450. }
  3451. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3452. function createCubicEasingFunc(cubicEasingStr) {
  3453. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3454. if (cubic) {
  3455. var points = cubic[1].split(',');
  3456. var a_1 = +trim(points[0]);
  3457. var b_1 = +trim(points[1]);
  3458. var c_1 = +trim(points[2]);
  3459. var d_1 = +trim(points[3]);
  3460. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3461. return;
  3462. }
  3463. var roots_1 = [];
  3464. return function (p) {
  3465. return p <= 0
  3466. ? 0 : p >= 1
  3467. ? 1
  3468. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3469. };
  3470. }
  3471. }
  3472. var Clip = (function () {
  3473. function Clip(opts) {
  3474. this._inited = false;
  3475. this._startTime = 0;
  3476. this._pausedTime = 0;
  3477. this._paused = false;
  3478. this._life = opts.life || 1000;
  3479. this._delay = opts.delay || 0;
  3480. this.loop = opts.loop || false;
  3481. this.onframe = opts.onframe || noop;
  3482. this.ondestroy = opts.ondestroy || noop;
  3483. this.onrestart = opts.onrestart || noop;
  3484. opts.easing && this.setEasing(opts.easing);
  3485. }
  3486. Clip.prototype.step = function (globalTime, deltaTime) {
  3487. if (!this._inited) {
  3488. this._startTime = globalTime + this._delay;
  3489. this._inited = true;
  3490. }
  3491. if (this._paused) {
  3492. this._pausedTime += deltaTime;
  3493. return;
  3494. }
  3495. var life = this._life;
  3496. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3497. var percent = elapsedTime / life;
  3498. if (percent < 0) {
  3499. percent = 0;
  3500. }
  3501. percent = Math.min(percent, 1);
  3502. var easingFunc = this.easingFunc;
  3503. var schedule = easingFunc ? easingFunc(percent) : percent;
  3504. this.onframe(schedule);
  3505. if (percent === 1) {
  3506. if (this.loop) {
  3507. var remainder = elapsedTime % life;
  3508. this._startTime = globalTime - remainder;
  3509. this._pausedTime = 0;
  3510. this.onrestart();
  3511. }
  3512. else {
  3513. return true;
  3514. }
  3515. }
  3516. return false;
  3517. };
  3518. Clip.prototype.pause = function () {
  3519. this._paused = true;
  3520. };
  3521. Clip.prototype.resume = function () {
  3522. this._paused = false;
  3523. };
  3524. Clip.prototype.setEasing = function (easing) {
  3525. this.easing = easing;
  3526. this.easingFunc = isFunction(easing)
  3527. ? easing
  3528. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3529. };
  3530. return Clip;
  3531. }());
  3532. var Entry = (function () {
  3533. function Entry(val) {
  3534. this.value = val;
  3535. }
  3536. return Entry;
  3537. }());
  3538. var LinkedList = (function () {
  3539. function LinkedList() {
  3540. this._len = 0;
  3541. }
  3542. LinkedList.prototype.insert = function (val) {
  3543. var entry = new Entry(val);
  3544. this.insertEntry(entry);
  3545. return entry;
  3546. };
  3547. LinkedList.prototype.insertEntry = function (entry) {
  3548. if (!this.head) {
  3549. this.head = this.tail = entry;
  3550. }
  3551. else {
  3552. this.tail.next = entry;
  3553. entry.prev = this.tail;
  3554. entry.next = null;
  3555. this.tail = entry;
  3556. }
  3557. this._len++;
  3558. };
  3559. LinkedList.prototype.remove = function (entry) {
  3560. var prev = entry.prev;
  3561. var next = entry.next;
  3562. if (prev) {
  3563. prev.next = next;
  3564. }
  3565. else {
  3566. this.head = next;
  3567. }
  3568. if (next) {
  3569. next.prev = prev;
  3570. }
  3571. else {
  3572. this.tail = prev;
  3573. }
  3574. entry.next = entry.prev = null;
  3575. this._len--;
  3576. };
  3577. LinkedList.prototype.len = function () {
  3578. return this._len;
  3579. };
  3580. LinkedList.prototype.clear = function () {
  3581. this.head = this.tail = null;
  3582. this._len = 0;
  3583. };
  3584. return LinkedList;
  3585. }());
  3586. var LRU = (function () {
  3587. function LRU(maxSize) {
  3588. this._list = new LinkedList();
  3589. this._maxSize = 10;
  3590. this._map = {};
  3591. this._maxSize = maxSize;
  3592. }
  3593. LRU.prototype.put = function (key, value) {
  3594. var list = this._list;
  3595. var map = this._map;
  3596. var removed = null;
  3597. if (map[key] == null) {
  3598. var len = list.len();
  3599. var entry = this._lastRemovedEntry;
  3600. if (len >= this._maxSize && len > 0) {
  3601. var leastUsedEntry = list.head;
  3602. list.remove(leastUsedEntry);
  3603. delete map[leastUsedEntry.key];
  3604. removed = leastUsedEntry.value;
  3605. this._lastRemovedEntry = leastUsedEntry;
  3606. }
  3607. if (entry) {
  3608. entry.value = value;
  3609. }
  3610. else {
  3611. entry = new Entry(value);
  3612. }
  3613. entry.key = key;
  3614. list.insertEntry(entry);
  3615. map[key] = entry;
  3616. }
  3617. return removed;
  3618. };
  3619. LRU.prototype.get = function (key) {
  3620. var entry = this._map[key];
  3621. var list = this._list;
  3622. if (entry != null) {
  3623. if (entry !== list.tail) {
  3624. list.remove(entry);
  3625. list.insertEntry(entry);
  3626. }
  3627. return entry.value;
  3628. }
  3629. };
  3630. LRU.prototype.clear = function () {
  3631. this._list.clear();
  3632. this._map = {};
  3633. };
  3634. LRU.prototype.len = function () {
  3635. return this._list.len();
  3636. };
  3637. return LRU;
  3638. }());
  3639. var kCSSColorTable = {
  3640. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3641. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3642. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3643. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3644. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3645. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3646. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3647. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3648. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3649. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3650. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3651. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3652. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3653. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3654. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3655. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3656. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3657. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3658. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3659. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3660. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3661. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3662. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3663. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3664. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3665. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3666. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3667. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3668. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3669. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3670. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3671. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3672. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3673. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3674. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3675. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3676. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3677. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3678. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3679. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3680. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3681. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3682. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3683. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3684. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3685. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3686. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3687. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3688. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3689. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3690. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3691. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3692. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3693. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3694. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3695. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3696. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3697. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3698. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3699. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3700. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3701. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3702. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3703. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3704. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3705. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3706. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3707. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3708. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3709. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3710. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3711. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3712. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3713. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3714. };
  3715. function clampCssByte(i) {
  3716. i = Math.round(i);
  3717. return i < 0 ? 0 : i > 255 ? 255 : i;
  3718. }
  3719. function clampCssAngle(i) {
  3720. i = Math.round(i);
  3721. return i < 0 ? 0 : i > 360 ? 360 : i;
  3722. }
  3723. function clampCssFloat(f) {
  3724. return f < 0 ? 0 : f > 1 ? 1 : f;
  3725. }
  3726. function parseCssInt(val) {
  3727. var str = val;
  3728. if (str.length && str.charAt(str.length - 1) === '%') {
  3729. return clampCssByte(parseFloat(str) / 100 * 255);
  3730. }
  3731. return clampCssByte(parseInt(str, 10));
  3732. }
  3733. function parseCssFloat(val) {
  3734. var str = val;
  3735. if (str.length && str.charAt(str.length - 1) === '%') {
  3736. return clampCssFloat(parseFloat(str) / 100);
  3737. }
  3738. return clampCssFloat(parseFloat(str));
  3739. }
  3740. function cssHueToRgb(m1, m2, h) {
  3741. if (h < 0) {
  3742. h += 1;
  3743. }
  3744. else if (h > 1) {
  3745. h -= 1;
  3746. }
  3747. if (h * 6 < 1) {
  3748. return m1 + (m2 - m1) * h * 6;
  3749. }
  3750. if (h * 2 < 1) {
  3751. return m2;
  3752. }
  3753. if (h * 3 < 2) {
  3754. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3755. }
  3756. return m1;
  3757. }
  3758. function lerpNumber(a, b, p) {
  3759. return a + (b - a) * p;
  3760. }
  3761. function setRgba(out, r, g, b, a) {
  3762. out[0] = r;
  3763. out[1] = g;
  3764. out[2] = b;
  3765. out[3] = a;
  3766. return out;
  3767. }
  3768. function copyRgba(out, a) {
  3769. out[0] = a[0];
  3770. out[1] = a[1];
  3771. out[2] = a[2];
  3772. out[3] = a[3];
  3773. return out;
  3774. }
  3775. var colorCache = new LRU(20);
  3776. var lastRemovedArr = null;
  3777. function putToCache(colorStr, rgbaArr) {
  3778. if (lastRemovedArr) {
  3779. copyRgba(lastRemovedArr, rgbaArr);
  3780. }
  3781. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3782. }
  3783. function parse(colorStr, rgbaArr) {
  3784. if (!colorStr) {
  3785. return;
  3786. }
  3787. rgbaArr = rgbaArr || [];
  3788. var cached = colorCache.get(colorStr);
  3789. if (cached) {
  3790. return copyRgba(rgbaArr, cached);
  3791. }
  3792. colorStr = colorStr + '';
  3793. var str = colorStr.replace(/ /g, '').toLowerCase();
  3794. if (str in kCSSColorTable) {
  3795. copyRgba(rgbaArr, kCSSColorTable[str]);
  3796. putToCache(colorStr, rgbaArr);
  3797. return rgbaArr;
  3798. }
  3799. var strLen = str.length;
  3800. if (str.charAt(0) === '#') {
  3801. if (strLen === 4 || strLen === 5) {
  3802. var iv = parseInt(str.slice(1, 4), 16);
  3803. if (!(iv >= 0 && iv <= 0xfff)) {
  3804. setRgba(rgbaArr, 0, 0, 0, 1);
  3805. return;
  3806. }
  3807. 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);
  3808. putToCache(colorStr, rgbaArr);
  3809. return rgbaArr;
  3810. }
  3811. else if (strLen === 7 || strLen === 9) {
  3812. var iv = parseInt(str.slice(1, 7), 16);
  3813. if (!(iv >= 0 && iv <= 0xffffff)) {
  3814. setRgba(rgbaArr, 0, 0, 0, 1);
  3815. return;
  3816. }
  3817. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3818. putToCache(colorStr, rgbaArr);
  3819. return rgbaArr;
  3820. }
  3821. return;
  3822. }
  3823. var op = str.indexOf('(');
  3824. var ep = str.indexOf(')');
  3825. if (op !== -1 && ep + 1 === strLen) {
  3826. var fname = str.substr(0, op);
  3827. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3828. var alpha = 1;
  3829. switch (fname) {
  3830. case 'rgba':
  3831. if (params.length !== 4) {
  3832. return params.length === 3
  3833. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3834. : setRgba(rgbaArr, 0, 0, 0, 1);
  3835. }
  3836. alpha = parseCssFloat(params.pop());
  3837. case 'rgb':
  3838. if (params.length >= 3) {
  3839. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3840. putToCache(colorStr, rgbaArr);
  3841. return rgbaArr;
  3842. }
  3843. else {
  3844. setRgba(rgbaArr, 0, 0, 0, 1);
  3845. return;
  3846. }
  3847. case 'hsla':
  3848. if (params.length !== 4) {
  3849. setRgba(rgbaArr, 0, 0, 0, 1);
  3850. return;
  3851. }
  3852. params[3] = parseCssFloat(params[3]);
  3853. hsla2rgba(params, rgbaArr);
  3854. putToCache(colorStr, rgbaArr);
  3855. return rgbaArr;
  3856. case 'hsl':
  3857. if (params.length !== 3) {
  3858. setRgba(rgbaArr, 0, 0, 0, 1);
  3859. return;
  3860. }
  3861. hsla2rgba(params, rgbaArr);
  3862. putToCache(colorStr, rgbaArr);
  3863. return rgbaArr;
  3864. default:
  3865. return;
  3866. }
  3867. }
  3868. setRgba(rgbaArr, 0, 0, 0, 1);
  3869. return;
  3870. }
  3871. function hsla2rgba(hsla, rgba) {
  3872. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3873. var s = parseCssFloat(hsla[1]);
  3874. var l = parseCssFloat(hsla[2]);
  3875. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3876. var m1 = l * 2 - m2;
  3877. rgba = rgba || [];
  3878. 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);
  3879. if (hsla.length === 4) {
  3880. rgba[3] = hsla[3];
  3881. }
  3882. return rgba;
  3883. }
  3884. function rgba2hsla(rgba) {
  3885. if (!rgba) {
  3886. return;
  3887. }
  3888. var R = rgba[0] / 255;
  3889. var G = rgba[1] / 255;
  3890. var B = rgba[2] / 255;
  3891. var vMin = Math.min(R, G, B);
  3892. var vMax = Math.max(R, G, B);
  3893. var delta = vMax - vMin;
  3894. var L = (vMax + vMin) / 2;
  3895. var H;
  3896. var S;
  3897. if (delta === 0) {
  3898. H = 0;
  3899. S = 0;
  3900. }
  3901. else {
  3902. if (L < 0.5) {
  3903. S = delta / (vMax + vMin);
  3904. }
  3905. else {
  3906. S = delta / (2 - vMax - vMin);
  3907. }
  3908. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3909. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3910. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3911. if (R === vMax) {
  3912. H = deltaB - deltaG;
  3913. }
  3914. else if (G === vMax) {
  3915. H = (1 / 3) + deltaR - deltaB;
  3916. }
  3917. else if (B === vMax) {
  3918. H = (2 / 3) + deltaG - deltaR;
  3919. }
  3920. if (H < 0) {
  3921. H += 1;
  3922. }
  3923. if (H > 1) {
  3924. H -= 1;
  3925. }
  3926. }
  3927. var hsla = [H * 360, S, L];
  3928. if (rgba[3] != null) {
  3929. hsla.push(rgba[3]);
  3930. }
  3931. return hsla;
  3932. }
  3933. function lift(color, level) {
  3934. var colorArr = parse(color);
  3935. if (colorArr) {
  3936. for (var i = 0; i < 3; i++) {
  3937. if (level < 0) {
  3938. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3939. }
  3940. else {
  3941. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3942. }
  3943. if (colorArr[i] > 255) {
  3944. colorArr[i] = 255;
  3945. }
  3946. else if (colorArr[i] < 0) {
  3947. colorArr[i] = 0;
  3948. }
  3949. }
  3950. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3951. }
  3952. }
  3953. function toHex(color) {
  3954. var colorArr = parse(color);
  3955. if (colorArr) {
  3956. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3957. }
  3958. }
  3959. function fastLerp(normalizedValue, colors, out) {
  3960. if (!(colors && colors.length)
  3961. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3962. return;
  3963. }
  3964. out = out || [];
  3965. var value = normalizedValue * (colors.length - 1);
  3966. var leftIndex = Math.floor(value);
  3967. var rightIndex = Math.ceil(value);
  3968. var leftColor = colors[leftIndex];
  3969. var rightColor = colors[rightIndex];
  3970. var dv = value - leftIndex;
  3971. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3972. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3973. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3974. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3975. return out;
  3976. }
  3977. var fastMapToColor = fastLerp;
  3978. function lerp$1(normalizedValue, colors, fullOutput) {
  3979. if (!(colors && colors.length)
  3980. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3981. return;
  3982. }
  3983. var value = normalizedValue * (colors.length - 1);
  3984. var leftIndex = Math.floor(value);
  3985. var rightIndex = Math.ceil(value);
  3986. var leftColor = parse(colors[leftIndex]);
  3987. var rightColor = parse(colors[rightIndex]);
  3988. var dv = value - leftIndex;
  3989. var color = stringify([
  3990. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3991. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3992. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3993. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3994. ], 'rgba');
  3995. return fullOutput
  3996. ? {
  3997. color: color,
  3998. leftIndex: leftIndex,
  3999. rightIndex: rightIndex,
  4000. value: value
  4001. }
  4002. : color;
  4003. }
  4004. var mapToColor = lerp$1;
  4005. function modifyHSL(color, h, s, l) {
  4006. var colorArr = parse(color);
  4007. if (color) {
  4008. colorArr = rgba2hsla(colorArr);
  4009. h != null && (colorArr[0] = clampCssAngle(h));
  4010. s != null && (colorArr[1] = parseCssFloat(s));
  4011. l != null && (colorArr[2] = parseCssFloat(l));
  4012. return stringify(hsla2rgba(colorArr), 'rgba');
  4013. }
  4014. }
  4015. function modifyAlpha(color, alpha) {
  4016. var colorArr = parse(color);
  4017. if (colorArr && alpha != null) {
  4018. colorArr[3] = clampCssFloat(alpha);
  4019. return stringify(colorArr, 'rgba');
  4020. }
  4021. }
  4022. function stringify(arrColor, type) {
  4023. if (!arrColor || !arrColor.length) {
  4024. return;
  4025. }
  4026. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4027. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4028. colorStr += ',' + arrColor[3];
  4029. }
  4030. return type + '(' + colorStr + ')';
  4031. }
  4032. function lum(color, backgroundLum) {
  4033. var arr = parse(color);
  4034. return arr
  4035. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4036. + (1 - arr[3]) * backgroundLum
  4037. : 0;
  4038. }
  4039. function random() {
  4040. return stringify([
  4041. Math.round(Math.random() * 255),
  4042. Math.round(Math.random() * 255),
  4043. Math.round(Math.random() * 255)
  4044. ], 'rgb');
  4045. }
  4046. var color = /*#__PURE__*/Object.freeze({
  4047. __proto__: null,
  4048. parse: parse,
  4049. lift: lift,
  4050. toHex: toHex,
  4051. fastLerp: fastLerp,
  4052. fastMapToColor: fastMapToColor,
  4053. lerp: lerp$1,
  4054. mapToColor: mapToColor,
  4055. modifyHSL: modifyHSL,
  4056. modifyAlpha: modifyAlpha,
  4057. stringify: stringify,
  4058. lum: lum,
  4059. random: random
  4060. });
  4061. var mathRound = Math.round;
  4062. function normalizeColor(color) {
  4063. var opacity;
  4064. if (!color || color === 'transparent') {
  4065. color = 'none';
  4066. }
  4067. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  4068. var arr = parse(color);
  4069. if (arr) {
  4070. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  4071. opacity = arr[3];
  4072. }
  4073. }
  4074. return {
  4075. color: color,
  4076. opacity: opacity == null ? 1 : opacity
  4077. };
  4078. }
  4079. var EPSILON$1 = 1e-4;
  4080. function isAroundZero$1(transform) {
  4081. return transform < EPSILON$1 && transform > -EPSILON$1;
  4082. }
  4083. function round3(transform) {
  4084. return mathRound(transform * 1e3) / 1e3;
  4085. }
  4086. function round4(transform) {
  4087. return mathRound(transform * 1e4) / 1e4;
  4088. }
  4089. function getMatrixStr(m) {
  4090. return 'matrix('
  4091. + round3(m[0]) + ','
  4092. + round3(m[1]) + ','
  4093. + round3(m[2]) + ','
  4094. + round3(m[3]) + ','
  4095. + round4(m[4]) + ','
  4096. + round4(m[5])
  4097. + ')';
  4098. }
  4099. var TEXT_ALIGN_TO_ANCHOR = {
  4100. left: 'start',
  4101. right: 'end',
  4102. center: 'middle',
  4103. middle: 'middle'
  4104. };
  4105. function adjustTextY(y, lineHeight, textBaseline) {
  4106. if (textBaseline === 'top') {
  4107. y += lineHeight / 2;
  4108. }
  4109. else if (textBaseline === 'bottom') {
  4110. y -= lineHeight / 2;
  4111. }
  4112. return y;
  4113. }
  4114. function hasShadow(style) {
  4115. return style
  4116. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  4117. }
  4118. function getShadowKey(displayable) {
  4119. var style = displayable.style;
  4120. var globalScale = displayable.getGlobalScale();
  4121. return [
  4122. style.shadowColor,
  4123. (style.shadowBlur || 0).toFixed(2),
  4124. (style.shadowOffsetX || 0).toFixed(2),
  4125. (style.shadowOffsetY || 0).toFixed(2),
  4126. globalScale[0],
  4127. globalScale[1]
  4128. ].join(',');
  4129. }
  4130. function isImagePattern(val) {
  4131. return val && (!!val.image);
  4132. }
  4133. function isSVGPattern(val) {
  4134. return val && (!!val.svgElement);
  4135. }
  4136. function isPattern(val) {
  4137. return isImagePattern(val) || isSVGPattern(val);
  4138. }
  4139. function isLinearGradient(val) {
  4140. return val.type === 'linear';
  4141. }
  4142. function isRadialGradient(val) {
  4143. return val.type === 'radial';
  4144. }
  4145. function isGradient(val) {
  4146. return val && (val.type === 'linear'
  4147. || val.type === 'radial');
  4148. }
  4149. function getIdURL(id) {
  4150. return "url(#" + id + ")";
  4151. }
  4152. function getPathPrecision(el) {
  4153. var scale = el.getGlobalScale();
  4154. var size = Math.max(scale[0], scale[1]);
  4155. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  4156. }
  4157. function getSRTTransformString(transform) {
  4158. var x = transform.x || 0;
  4159. var y = transform.y || 0;
  4160. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  4161. var scaleX = retrieve2(transform.scaleX, 1);
  4162. var scaleY = retrieve2(transform.scaleY, 1);
  4163. var skewX = transform.skewX || 0;
  4164. var skewY = transform.skewY || 0;
  4165. var res = [];
  4166. if (x || y) {
  4167. res.push("translate(" + x + "px," + y + "px)");
  4168. }
  4169. if (rotation) {
  4170. res.push("rotate(" + rotation + ")");
  4171. }
  4172. if (scaleX !== 1 || scaleY !== 1) {
  4173. res.push("scale(" + scaleX + "," + scaleY + ")");
  4174. }
  4175. if (skewX || skewY) {
  4176. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  4177. }
  4178. return res.join(' ');
  4179. }
  4180. var encodeBase64 = (function () {
  4181. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  4182. return function (str) {
  4183. return window.btoa(unescape(encodeURIComponent(str)));
  4184. };
  4185. }
  4186. if (typeof Buffer !== 'undefined') {
  4187. return function (str) {
  4188. return Buffer.from(str).toString('base64');
  4189. };
  4190. }
  4191. return function (str) {
  4192. if ("development" !== 'production') {
  4193. logError('Base64 isn\'t natively supported in the current environment.');
  4194. }
  4195. return null;
  4196. };
  4197. })();
  4198. var arraySlice = Array.prototype.slice;
  4199. function interpolateNumber(p0, p1, percent) {
  4200. return (p1 - p0) * percent + p0;
  4201. }
  4202. function interpolate1DArray(out, p0, p1, percent) {
  4203. var len = p0.length;
  4204. for (var i = 0; i < len; i++) {
  4205. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4206. }
  4207. return out;
  4208. }
  4209. function interpolate2DArray(out, p0, p1, percent) {
  4210. var len = p0.length;
  4211. var len2 = len && p0[0].length;
  4212. for (var i = 0; i < len; i++) {
  4213. if (!out[i]) {
  4214. out[i] = [];
  4215. }
  4216. for (var j = 0; j < len2; j++) {
  4217. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4218. }
  4219. }
  4220. return out;
  4221. }
  4222. function add1DArray(out, p0, p1, sign) {
  4223. var len = p0.length;
  4224. for (var i = 0; i < len; i++) {
  4225. out[i] = p0[i] + p1[i] * sign;
  4226. }
  4227. return out;
  4228. }
  4229. function add2DArray(out, p0, p1, sign) {
  4230. var len = p0.length;
  4231. var len2 = len && p0[0].length;
  4232. for (var i = 0; i < len; i++) {
  4233. if (!out[i]) {
  4234. out[i] = [];
  4235. }
  4236. for (var j = 0; j < len2; j++) {
  4237. out[i][j] = p0[i][j] + p1[i][j] * sign;
  4238. }
  4239. }
  4240. return out;
  4241. }
  4242. function fillColorStops(val0, val1) {
  4243. var len0 = val0.length;
  4244. var len1 = val1.length;
  4245. var shorterArr = len0 > len1 ? val1 : val0;
  4246. var shorterLen = Math.min(len0, len1);
  4247. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4248. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4249. shorterArr.push({
  4250. offset: last.offset,
  4251. color: last.color.slice()
  4252. });
  4253. }
  4254. }
  4255. function fillArray(val0, val1, arrDim) {
  4256. var arr0 = val0;
  4257. var arr1 = val1;
  4258. if (!arr0.push || !arr1.push) {
  4259. return;
  4260. }
  4261. var arr0Len = arr0.length;
  4262. var arr1Len = arr1.length;
  4263. if (arr0Len !== arr1Len) {
  4264. var isPreviousLarger = arr0Len > arr1Len;
  4265. if (isPreviousLarger) {
  4266. arr0.length = arr1Len;
  4267. }
  4268. else {
  4269. for (var i = arr0Len; i < arr1Len; i++) {
  4270. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4271. }
  4272. }
  4273. }
  4274. var len2 = arr0[0] && arr0[0].length;
  4275. for (var i = 0; i < arr0.length; i++) {
  4276. if (arrDim === 1) {
  4277. if (isNaN(arr0[i])) {
  4278. arr0[i] = arr1[i];
  4279. }
  4280. }
  4281. else {
  4282. for (var j = 0; j < len2; j++) {
  4283. if (isNaN(arr0[i][j])) {
  4284. arr0[i][j] = arr1[i][j];
  4285. }
  4286. }
  4287. }
  4288. }
  4289. }
  4290. function cloneValue(value) {
  4291. if (isArrayLike(value)) {
  4292. var len = value.length;
  4293. if (isArrayLike(value[0])) {
  4294. var ret = [];
  4295. for (var i = 0; i < len; i++) {
  4296. ret.push(arraySlice.call(value[i]));
  4297. }
  4298. return ret;
  4299. }
  4300. return arraySlice.call(value);
  4301. }
  4302. return value;
  4303. }
  4304. function rgba2String(rgba) {
  4305. rgba[0] = Math.floor(rgba[0]) || 0;
  4306. rgba[1] = Math.floor(rgba[1]) || 0;
  4307. rgba[2] = Math.floor(rgba[2]) || 0;
  4308. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4309. return 'rgba(' + rgba.join(',') + ')';
  4310. }
  4311. function guessArrayDim(value) {
  4312. return isArrayLike(value && value[0]) ? 2 : 1;
  4313. }
  4314. var VALUE_TYPE_NUMBER = 0;
  4315. var VALUE_TYPE_1D_ARRAY = 1;
  4316. var VALUE_TYPE_2D_ARRAY = 2;
  4317. var VALUE_TYPE_COLOR = 3;
  4318. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4319. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4320. var VALUE_TYPE_UNKOWN = 6;
  4321. function isGradientValueType(valType) {
  4322. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4323. }
  4324. function isArrayValueType(valType) {
  4325. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4326. }
  4327. var tmpRgba = [0, 0, 0, 0];
  4328. var Track = (function () {
  4329. function Track(propName) {
  4330. this.keyframes = [];
  4331. this.discrete = false;
  4332. this._invalid = false;
  4333. this._needsSort = false;
  4334. this._lastFr = 0;
  4335. this._lastFrP = 0;
  4336. this.propName = propName;
  4337. }
  4338. Track.prototype.isFinished = function () {
  4339. return this._finished;
  4340. };
  4341. Track.prototype.setFinished = function () {
  4342. this._finished = true;
  4343. if (this._additiveTrack) {
  4344. this._additiveTrack.setFinished();
  4345. }
  4346. };
  4347. Track.prototype.needsAnimate = function () {
  4348. return this.keyframes.length >= 1;
  4349. };
  4350. Track.prototype.getAdditiveTrack = function () {
  4351. return this._additiveTrack;
  4352. };
  4353. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4354. this._needsSort = true;
  4355. var keyframes = this.keyframes;
  4356. var len = keyframes.length;
  4357. var discrete = false;
  4358. var valType = VALUE_TYPE_UNKOWN;
  4359. var value = rawValue;
  4360. if (isArrayLike(rawValue)) {
  4361. var arrayDim = guessArrayDim(rawValue);
  4362. valType = arrayDim;
  4363. if (arrayDim === 1 && !isNumber(rawValue[0])
  4364. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4365. discrete = true;
  4366. }
  4367. }
  4368. else {
  4369. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4370. valType = VALUE_TYPE_NUMBER;
  4371. }
  4372. else if (isString(rawValue)) {
  4373. if (!isNaN(+rawValue)) {
  4374. valType = VALUE_TYPE_NUMBER;
  4375. }
  4376. else {
  4377. var colorArray = parse(rawValue);
  4378. if (colorArray) {
  4379. value = colorArray;
  4380. valType = VALUE_TYPE_COLOR;
  4381. }
  4382. }
  4383. }
  4384. else if (isGradientObject(rawValue)) {
  4385. var parsedGradient = extend({}, value);
  4386. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4387. offset: colorStop.offset,
  4388. color: parse(colorStop.color)
  4389. }); });
  4390. if (isLinearGradient(rawValue)) {
  4391. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4392. }
  4393. else if (isRadialGradient(rawValue)) {
  4394. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4395. }
  4396. value = parsedGradient;
  4397. }
  4398. }
  4399. if (len === 0) {
  4400. this.valType = valType;
  4401. }
  4402. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4403. discrete = true;
  4404. }
  4405. this.discrete = this.discrete || discrete;
  4406. var kf = {
  4407. time: time,
  4408. value: value,
  4409. rawValue: rawValue,
  4410. percent: 0
  4411. };
  4412. if (easing) {
  4413. kf.easing = easing;
  4414. kf.easingFunc = isFunction(easing)
  4415. ? easing
  4416. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4417. }
  4418. keyframes.push(kf);
  4419. return kf;
  4420. };
  4421. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4422. var kfs = this.keyframes;
  4423. if (this._needsSort) {
  4424. kfs.sort(function (a, b) {
  4425. return a.time - b.time;
  4426. });
  4427. }
  4428. var valType = this.valType;
  4429. var kfsLen = kfs.length;
  4430. var lastKf = kfs[kfsLen - 1];
  4431. var isDiscrete = this.discrete;
  4432. var isArr = isArrayValueType(valType);
  4433. var isGradient = isGradientValueType(valType);
  4434. for (var i = 0; i < kfsLen; i++) {
  4435. var kf = kfs[i];
  4436. var value = kf.value;
  4437. var lastValue = lastKf.value;
  4438. kf.percent = kf.time / maxTime;
  4439. if (!isDiscrete) {
  4440. if (isArr && i !== kfsLen - 1) {
  4441. fillArray(value, lastValue, valType);
  4442. }
  4443. else if (isGradient) {
  4444. fillColorStops(value.colorStops, lastValue.colorStops);
  4445. }
  4446. }
  4447. }
  4448. if (!isDiscrete
  4449. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4450. && additiveTrack
  4451. && this.needsAnimate()
  4452. && additiveTrack.needsAnimate()
  4453. && valType === additiveTrack.valType
  4454. && !additiveTrack._finished) {
  4455. this._additiveTrack = additiveTrack;
  4456. var startValue = kfs[0].value;
  4457. for (var i = 0; i < kfsLen; i++) {
  4458. if (valType === VALUE_TYPE_NUMBER) {
  4459. kfs[i].additiveValue = kfs[i].value - startValue;
  4460. }
  4461. else if (valType === VALUE_TYPE_COLOR) {
  4462. kfs[i].additiveValue =
  4463. add1DArray([], kfs[i].value, startValue, -1);
  4464. }
  4465. else if (isArrayValueType(valType)) {
  4466. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4467. ? add1DArray([], kfs[i].value, startValue, -1)
  4468. : add2DArray([], kfs[i].value, startValue, -1);
  4469. }
  4470. }
  4471. }
  4472. };
  4473. Track.prototype.step = function (target, percent) {
  4474. if (this._finished) {
  4475. return;
  4476. }
  4477. if (this._additiveTrack && this._additiveTrack._finished) {
  4478. this._additiveTrack = null;
  4479. }
  4480. var isAdditive = this._additiveTrack != null;
  4481. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4482. var valType = this.valType;
  4483. var keyframes = this.keyframes;
  4484. var kfsNum = keyframes.length;
  4485. var propName = this.propName;
  4486. var isValueColor = valType === VALUE_TYPE_COLOR;
  4487. var frameIdx;
  4488. var lastFrame = this._lastFr;
  4489. var mathMin = Math.min;
  4490. var frame;
  4491. var nextFrame;
  4492. if (kfsNum === 1) {
  4493. frame = nextFrame = keyframes[0];
  4494. }
  4495. else {
  4496. if (percent < 0) {
  4497. frameIdx = 0;
  4498. }
  4499. else if (percent < this._lastFrP) {
  4500. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4501. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4502. if (keyframes[frameIdx].percent <= percent) {
  4503. break;
  4504. }
  4505. }
  4506. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4507. }
  4508. else {
  4509. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4510. if (keyframes[frameIdx].percent > percent) {
  4511. break;
  4512. }
  4513. }
  4514. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4515. }
  4516. nextFrame = keyframes[frameIdx + 1];
  4517. frame = keyframes[frameIdx];
  4518. }
  4519. if (!(frame && nextFrame)) {
  4520. return;
  4521. }
  4522. this._lastFr = frameIdx;
  4523. this._lastFrP = percent;
  4524. var interval = (nextFrame.percent - frame.percent);
  4525. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4526. if (nextFrame.easingFunc) {
  4527. w = nextFrame.easingFunc(w);
  4528. }
  4529. var targetArr = isAdditive ? this._additiveValue
  4530. : (isValueColor ? tmpRgba : target[propName]);
  4531. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4532. targetArr = this._additiveValue = [];
  4533. }
  4534. if (this.discrete) {
  4535. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4536. }
  4537. else if (isArrayValueType(valType)) {
  4538. valType === VALUE_TYPE_1D_ARRAY
  4539. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4540. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4541. }
  4542. else if (isGradientValueType(valType)) {
  4543. var val = frame[valueKey];
  4544. var nextVal_1 = nextFrame[valueKey];
  4545. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4546. target[propName] = {
  4547. type: isLinearGradient_1 ? 'linear' : 'radial',
  4548. x: interpolateNumber(val.x, nextVal_1.x, w),
  4549. y: interpolateNumber(val.y, nextVal_1.y, w),
  4550. colorStops: map(val.colorStops, function (colorStop, idx) {
  4551. var nextColorStop = nextVal_1.colorStops[idx];
  4552. return {
  4553. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4554. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4555. };
  4556. }),
  4557. global: nextVal_1.global
  4558. };
  4559. if (isLinearGradient_1) {
  4560. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4561. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4562. }
  4563. else {
  4564. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4565. }
  4566. }
  4567. else if (isValueColor) {
  4568. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4569. if (!isAdditive) {
  4570. target[propName] = rgba2String(targetArr);
  4571. }
  4572. }
  4573. else {
  4574. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4575. if (isAdditive) {
  4576. this._additiveValue = value;
  4577. }
  4578. else {
  4579. target[propName] = value;
  4580. }
  4581. }
  4582. if (isAdditive) {
  4583. this._addToTarget(target);
  4584. }
  4585. };
  4586. Track.prototype._addToTarget = function (target) {
  4587. var valType = this.valType;
  4588. var propName = this.propName;
  4589. var additiveValue = this._additiveValue;
  4590. if (valType === VALUE_TYPE_NUMBER) {
  4591. target[propName] = target[propName] + additiveValue;
  4592. }
  4593. else if (valType === VALUE_TYPE_COLOR) {
  4594. parse(target[propName], tmpRgba);
  4595. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4596. target[propName] = rgba2String(tmpRgba);
  4597. }
  4598. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4599. add1DArray(target[propName], target[propName], additiveValue, 1);
  4600. }
  4601. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4602. add2DArray(target[propName], target[propName], additiveValue, 1);
  4603. }
  4604. };
  4605. return Track;
  4606. }());
  4607. var Animator = (function () {
  4608. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4609. this._tracks = {};
  4610. this._trackKeys = [];
  4611. this._maxTime = 0;
  4612. this._started = 0;
  4613. this._clip = null;
  4614. this._target = target;
  4615. this._loop = loop;
  4616. if (loop && additiveTo) {
  4617. logError('Can\' use additive animation on looped animation.');
  4618. return;
  4619. }
  4620. this._additiveAnimators = additiveTo;
  4621. this._allowDiscrete = allowDiscreteAnimation;
  4622. }
  4623. Animator.prototype.getMaxTime = function () {
  4624. return this._maxTime;
  4625. };
  4626. Animator.prototype.getDelay = function () {
  4627. return this._delay;
  4628. };
  4629. Animator.prototype.getLoop = function () {
  4630. return this._loop;
  4631. };
  4632. Animator.prototype.getTarget = function () {
  4633. return this._target;
  4634. };
  4635. Animator.prototype.changeTarget = function (target) {
  4636. this._target = target;
  4637. };
  4638. Animator.prototype.when = function (time, props, easing) {
  4639. return this.whenWithKeys(time, props, keys(props), easing);
  4640. };
  4641. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4642. var tracks = this._tracks;
  4643. for (var i = 0; i < propNames.length; i++) {
  4644. var propName = propNames[i];
  4645. var track = tracks[propName];
  4646. if (!track) {
  4647. track = tracks[propName] = new Track(propName);
  4648. var initialValue = void 0;
  4649. var additiveTrack = this._getAdditiveTrack(propName);
  4650. if (additiveTrack) {
  4651. var addtiveTrackKfs = additiveTrack.keyframes;
  4652. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4653. initialValue = lastFinalKf && lastFinalKf.value;
  4654. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4655. initialValue = rgba2String(initialValue);
  4656. }
  4657. }
  4658. else {
  4659. initialValue = this._target[propName];
  4660. }
  4661. if (initialValue == null) {
  4662. continue;
  4663. }
  4664. if (time > 0) {
  4665. track.addKeyframe(0, cloneValue(initialValue), easing);
  4666. }
  4667. this._trackKeys.push(propName);
  4668. }
  4669. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4670. }
  4671. this._maxTime = Math.max(this._maxTime, time);
  4672. return this;
  4673. };
  4674. Animator.prototype.pause = function () {
  4675. this._clip.pause();
  4676. this._paused = true;
  4677. };
  4678. Animator.prototype.resume = function () {
  4679. this._clip.resume();
  4680. this._paused = false;
  4681. };
  4682. Animator.prototype.isPaused = function () {
  4683. return !!this._paused;
  4684. };
  4685. Animator.prototype.duration = function (duration) {
  4686. this._maxTime = duration;
  4687. this._force = true;
  4688. return this;
  4689. };
  4690. Animator.prototype._doneCallback = function () {
  4691. this._setTracksFinished();
  4692. this._clip = null;
  4693. var doneList = this._doneCbs;
  4694. if (doneList) {
  4695. var len = doneList.length;
  4696. for (var i = 0; i < len; i++) {
  4697. doneList[i].call(this);
  4698. }
  4699. }
  4700. };
  4701. Animator.prototype._abortedCallback = function () {
  4702. this._setTracksFinished();
  4703. var animation = this.animation;
  4704. var abortedList = this._abortedCbs;
  4705. if (animation) {
  4706. animation.removeClip(this._clip);
  4707. }
  4708. this._clip = null;
  4709. if (abortedList) {
  4710. for (var i = 0; i < abortedList.length; i++) {
  4711. abortedList[i].call(this);
  4712. }
  4713. }
  4714. };
  4715. Animator.prototype._setTracksFinished = function () {
  4716. var tracks = this._tracks;
  4717. var tracksKeys = this._trackKeys;
  4718. for (var i = 0; i < tracksKeys.length; i++) {
  4719. tracks[tracksKeys[i]].setFinished();
  4720. }
  4721. };
  4722. Animator.prototype._getAdditiveTrack = function (trackName) {
  4723. var additiveTrack;
  4724. var additiveAnimators = this._additiveAnimators;
  4725. if (additiveAnimators) {
  4726. for (var i = 0; i < additiveAnimators.length; i++) {
  4727. var track = additiveAnimators[i].getTrack(trackName);
  4728. if (track) {
  4729. additiveTrack = track;
  4730. }
  4731. }
  4732. }
  4733. return additiveTrack;
  4734. };
  4735. Animator.prototype.start = function (easing) {
  4736. if (this._started > 0) {
  4737. return;
  4738. }
  4739. this._started = 1;
  4740. var self = this;
  4741. var tracks = [];
  4742. var maxTime = this._maxTime || 0;
  4743. for (var i = 0; i < this._trackKeys.length; i++) {
  4744. var propName = this._trackKeys[i];
  4745. var track = this._tracks[propName];
  4746. var additiveTrack = this._getAdditiveTrack(propName);
  4747. var kfs = track.keyframes;
  4748. var kfsNum = kfs.length;
  4749. track.prepare(maxTime, additiveTrack);
  4750. if (track.needsAnimate()) {
  4751. if (!this._allowDiscrete && track.discrete) {
  4752. var lastKf = kfs[kfsNum - 1];
  4753. if (lastKf) {
  4754. self._target[track.propName] = lastKf.rawValue;
  4755. }
  4756. track.setFinished();
  4757. }
  4758. else {
  4759. tracks.push(track);
  4760. }
  4761. }
  4762. }
  4763. if (tracks.length || this._force) {
  4764. var clip = new Clip({
  4765. life: maxTime,
  4766. loop: this._loop,
  4767. delay: this._delay || 0,
  4768. onframe: function (percent) {
  4769. self._started = 2;
  4770. var additiveAnimators = self._additiveAnimators;
  4771. if (additiveAnimators) {
  4772. var stillHasAdditiveAnimator = false;
  4773. for (var i = 0; i < additiveAnimators.length; i++) {
  4774. if (additiveAnimators[i]._clip) {
  4775. stillHasAdditiveAnimator = true;
  4776. break;
  4777. }
  4778. }
  4779. if (!stillHasAdditiveAnimator) {
  4780. self._additiveAnimators = null;
  4781. }
  4782. }
  4783. for (var i = 0; i < tracks.length; i++) {
  4784. tracks[i].step(self._target, percent);
  4785. }
  4786. var onframeList = self._onframeCbs;
  4787. if (onframeList) {
  4788. for (var i = 0; i < onframeList.length; i++) {
  4789. onframeList[i](self._target, percent);
  4790. }
  4791. }
  4792. },
  4793. ondestroy: function () {
  4794. self._doneCallback();
  4795. }
  4796. });
  4797. this._clip = clip;
  4798. if (this.animation) {
  4799. this.animation.addClip(clip);
  4800. }
  4801. if (easing) {
  4802. clip.setEasing(easing);
  4803. }
  4804. }
  4805. else {
  4806. this._doneCallback();
  4807. }
  4808. return this;
  4809. };
  4810. Animator.prototype.stop = function (forwardToLast) {
  4811. if (!this._clip) {
  4812. return;
  4813. }
  4814. var clip = this._clip;
  4815. if (forwardToLast) {
  4816. clip.onframe(1);
  4817. }
  4818. this._abortedCallback();
  4819. };
  4820. Animator.prototype.delay = function (time) {
  4821. this._delay = time;
  4822. return this;
  4823. };
  4824. Animator.prototype.during = function (cb) {
  4825. if (cb) {
  4826. if (!this._onframeCbs) {
  4827. this._onframeCbs = [];
  4828. }
  4829. this._onframeCbs.push(cb);
  4830. }
  4831. return this;
  4832. };
  4833. Animator.prototype.done = function (cb) {
  4834. if (cb) {
  4835. if (!this._doneCbs) {
  4836. this._doneCbs = [];
  4837. }
  4838. this._doneCbs.push(cb);
  4839. }
  4840. return this;
  4841. };
  4842. Animator.prototype.aborted = function (cb) {
  4843. if (cb) {
  4844. if (!this._abortedCbs) {
  4845. this._abortedCbs = [];
  4846. }
  4847. this._abortedCbs.push(cb);
  4848. }
  4849. return this;
  4850. };
  4851. Animator.prototype.getClip = function () {
  4852. return this._clip;
  4853. };
  4854. Animator.prototype.getTrack = function (propName) {
  4855. return this._tracks[propName];
  4856. };
  4857. Animator.prototype.getTracks = function () {
  4858. var _this = this;
  4859. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4860. };
  4861. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4862. if (!propNames.length || !this._clip) {
  4863. return true;
  4864. }
  4865. var tracks = this._tracks;
  4866. var tracksKeys = this._trackKeys;
  4867. for (var i = 0; i < propNames.length; i++) {
  4868. var track = tracks[propNames[i]];
  4869. if (track && !track.isFinished()) {
  4870. if (forwardToLast) {
  4871. track.step(this._target, 1);
  4872. }
  4873. else if (this._started === 1) {
  4874. track.step(this._target, 0);
  4875. }
  4876. track.setFinished();
  4877. }
  4878. }
  4879. var allAborted = true;
  4880. for (var i = 0; i < tracksKeys.length; i++) {
  4881. if (!tracks[tracksKeys[i]].isFinished()) {
  4882. allAborted = false;
  4883. break;
  4884. }
  4885. }
  4886. if (allAborted) {
  4887. this._abortedCallback();
  4888. }
  4889. return allAborted;
  4890. };
  4891. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4892. if (!target) {
  4893. return;
  4894. }
  4895. trackKeys = trackKeys || this._trackKeys;
  4896. for (var i = 0; i < trackKeys.length; i++) {
  4897. var propName = trackKeys[i];
  4898. var track = this._tracks[propName];
  4899. if (!track || track.isFinished()) {
  4900. continue;
  4901. }
  4902. var kfs = track.keyframes;
  4903. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4904. if (kf) {
  4905. target[propName] = cloneValue(kf.rawValue);
  4906. }
  4907. }
  4908. };
  4909. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4910. trackKeys = trackKeys || keys(finalProps);
  4911. for (var i = 0; i < trackKeys.length; i++) {
  4912. var propName = trackKeys[i];
  4913. var track = this._tracks[propName];
  4914. if (!track) {
  4915. continue;
  4916. }
  4917. var kfs = track.keyframes;
  4918. if (kfs.length > 1) {
  4919. var lastKf = kfs.pop();
  4920. track.addKeyframe(lastKf.time, finalProps[propName]);
  4921. track.prepare(this._maxTime, track.getAdditiveTrack());
  4922. }
  4923. }
  4924. };
  4925. return Animator;
  4926. }());
  4927. function getTime() {
  4928. return new Date().getTime();
  4929. }
  4930. var Animation = (function (_super) {
  4931. __extends(Animation, _super);
  4932. function Animation(opts) {
  4933. var _this = _super.call(this) || this;
  4934. _this._running = false;
  4935. _this._time = 0;
  4936. _this._pausedTime = 0;
  4937. _this._pauseStart = 0;
  4938. _this._paused = false;
  4939. opts = opts || {};
  4940. _this.stage = opts.stage || {};
  4941. return _this;
  4942. }
  4943. Animation.prototype.addClip = function (clip) {
  4944. if (clip.animation) {
  4945. this.removeClip(clip);
  4946. }
  4947. if (!this._head) {
  4948. this._head = this._tail = clip;
  4949. }
  4950. else {
  4951. this._tail.next = clip;
  4952. clip.prev = this._tail;
  4953. clip.next = null;
  4954. this._tail = clip;
  4955. }
  4956. clip.animation = this;
  4957. };
  4958. Animation.prototype.addAnimator = function (animator) {
  4959. animator.animation = this;
  4960. var clip = animator.getClip();
  4961. if (clip) {
  4962. this.addClip(clip);
  4963. }
  4964. };
  4965. Animation.prototype.removeClip = function (clip) {
  4966. if (!clip.animation) {
  4967. return;
  4968. }
  4969. var prev = clip.prev;
  4970. var next = clip.next;
  4971. if (prev) {
  4972. prev.next = next;
  4973. }
  4974. else {
  4975. this._head = next;
  4976. }
  4977. if (next) {
  4978. next.prev = prev;
  4979. }
  4980. else {
  4981. this._tail = prev;
  4982. }
  4983. clip.next = clip.prev = clip.animation = null;
  4984. };
  4985. Animation.prototype.removeAnimator = function (animator) {
  4986. var clip = animator.getClip();
  4987. if (clip) {
  4988. this.removeClip(clip);
  4989. }
  4990. animator.animation = null;
  4991. };
  4992. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  4993. var time = getTime() - this._pausedTime;
  4994. var delta = time - this._time;
  4995. var clip = this._head;
  4996. while (clip) {
  4997. var nextClip = clip.next;
  4998. var finished = clip.step(time, delta);
  4999. if (finished) {
  5000. clip.ondestroy();
  5001. this.removeClip(clip);
  5002. clip = nextClip;
  5003. }
  5004. else {
  5005. clip = nextClip;
  5006. }
  5007. }
  5008. this._time = time;
  5009. if (!notTriggerFrameAndStageUpdate) {
  5010. this.trigger('frame', delta);
  5011. this.stage.update && this.stage.update();
  5012. }
  5013. };
  5014. Animation.prototype._startLoop = function () {
  5015. var self = this;
  5016. this._running = true;
  5017. function step() {
  5018. if (self._running) {
  5019. requestAnimationFrame$1(step);
  5020. !self._paused && self.update();
  5021. }
  5022. }
  5023. requestAnimationFrame$1(step);
  5024. };
  5025. Animation.prototype.start = function () {
  5026. if (this._running) {
  5027. return;
  5028. }
  5029. this._time = getTime();
  5030. this._pausedTime = 0;
  5031. this._startLoop();
  5032. };
  5033. Animation.prototype.stop = function () {
  5034. this._running = false;
  5035. };
  5036. Animation.prototype.pause = function () {
  5037. if (!this._paused) {
  5038. this._pauseStart = getTime();
  5039. this._paused = true;
  5040. }
  5041. };
  5042. Animation.prototype.resume = function () {
  5043. if (this._paused) {
  5044. this._pausedTime += getTime() - this._pauseStart;
  5045. this._paused = false;
  5046. }
  5047. };
  5048. Animation.prototype.clear = function () {
  5049. var clip = this._head;
  5050. while (clip) {
  5051. var nextClip = clip.next;
  5052. clip.prev = clip.next = clip.animation = null;
  5053. clip = nextClip;
  5054. }
  5055. this._head = this._tail = null;
  5056. };
  5057. Animation.prototype.isFinished = function () {
  5058. return this._head == null;
  5059. };
  5060. Animation.prototype.animate = function (target, options) {
  5061. options = options || {};
  5062. this.start();
  5063. var animator = new Animator(target, options.loop);
  5064. this.addAnimator(animator);
  5065. return animator;
  5066. };
  5067. return Animation;
  5068. }(Eventful));
  5069. var TOUCH_CLICK_DELAY = 300;
  5070. var globalEventSupported = env.domSupported;
  5071. var localNativeListenerNames = (function () {
  5072. var mouseHandlerNames = [
  5073. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5074. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5075. ];
  5076. var touchHandlerNames = [
  5077. 'touchstart', 'touchend', 'touchmove'
  5078. ];
  5079. var pointerEventNameMap = {
  5080. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5081. };
  5082. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5083. var nm = name.replace('mouse', 'pointer');
  5084. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5085. });
  5086. return {
  5087. mouse: mouseHandlerNames,
  5088. touch: touchHandlerNames,
  5089. pointer: pointerHandlerNames
  5090. };
  5091. })();
  5092. var globalNativeListenerNames = {
  5093. mouse: ['mousemove', 'mouseup'],
  5094. pointer: ['pointermove', 'pointerup']
  5095. };
  5096. var wheelEventSupported = false;
  5097. function isPointerFromTouch(event) {
  5098. var pointerType = event.pointerType;
  5099. return pointerType === 'pen' || pointerType === 'touch';
  5100. }
  5101. function setTouchTimer(scope) {
  5102. scope.touching = true;
  5103. if (scope.touchTimer != null) {
  5104. clearTimeout(scope.touchTimer);
  5105. scope.touchTimer = null;
  5106. }
  5107. scope.touchTimer = setTimeout(function () {
  5108. scope.touching = false;
  5109. scope.touchTimer = null;
  5110. }, 700);
  5111. }
  5112. function markTouch(event) {
  5113. event && (event.zrByTouch = true);
  5114. }
  5115. function normalizeGlobalEvent(instance, event) {
  5116. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5117. }
  5118. function isLocalEl(instance, el) {
  5119. var elTmp = el;
  5120. var isLocal = false;
  5121. while (elTmp && elTmp.nodeType !== 9
  5122. && !(isLocal = elTmp.domBelongToZr
  5123. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5124. elTmp = elTmp.parentNode;
  5125. }
  5126. return isLocal;
  5127. }
  5128. var FakeGlobalEvent = (function () {
  5129. function FakeGlobalEvent(instance, event) {
  5130. this.stopPropagation = noop;
  5131. this.stopImmediatePropagation = noop;
  5132. this.preventDefault = noop;
  5133. this.type = event.type;
  5134. this.target = this.currentTarget = instance.dom;
  5135. this.pointerType = event.pointerType;
  5136. this.clientX = event.clientX;
  5137. this.clientY = event.clientY;
  5138. }
  5139. return FakeGlobalEvent;
  5140. }());
  5141. var localDOMHandlers = {
  5142. mousedown: function (event) {
  5143. event = normalizeEvent(this.dom, event);
  5144. this.__mayPointerCapture = [event.zrX, event.zrY];
  5145. this.trigger('mousedown', event);
  5146. },
  5147. mousemove: function (event) {
  5148. event = normalizeEvent(this.dom, event);
  5149. var downPoint = this.__mayPointerCapture;
  5150. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5151. this.__togglePointerCapture(true);
  5152. }
  5153. this.trigger('mousemove', event);
  5154. },
  5155. mouseup: function (event) {
  5156. event = normalizeEvent(this.dom, event);
  5157. this.__togglePointerCapture(false);
  5158. this.trigger('mouseup', event);
  5159. },
  5160. mouseout: function (event) {
  5161. event = normalizeEvent(this.dom, event);
  5162. var element = event.toElement || event.relatedTarget;
  5163. if (!isLocalEl(this, element)) {
  5164. if (this.__pointerCapturing) {
  5165. event.zrEventControl = 'no_globalout';
  5166. }
  5167. this.trigger('mouseout', event);
  5168. }
  5169. },
  5170. wheel: function (event) {
  5171. wheelEventSupported = true;
  5172. event = normalizeEvent(this.dom, event);
  5173. this.trigger('mousewheel', event);
  5174. },
  5175. mousewheel: function (event) {
  5176. if (wheelEventSupported) {
  5177. return;
  5178. }
  5179. event = normalizeEvent(this.dom, event);
  5180. this.trigger('mousewheel', event);
  5181. },
  5182. touchstart: function (event) {
  5183. event = normalizeEvent(this.dom, event);
  5184. markTouch(event);
  5185. this.__lastTouchMoment = new Date();
  5186. this.handler.processGesture(event, 'start');
  5187. localDOMHandlers.mousemove.call(this, event);
  5188. localDOMHandlers.mousedown.call(this, event);
  5189. },
  5190. touchmove: function (event) {
  5191. event = normalizeEvent(this.dom, event);
  5192. markTouch(event);
  5193. this.handler.processGesture(event, 'change');
  5194. localDOMHandlers.mousemove.call(this, event);
  5195. },
  5196. touchend: function (event) {
  5197. event = normalizeEvent(this.dom, event);
  5198. markTouch(event);
  5199. this.handler.processGesture(event, 'end');
  5200. localDOMHandlers.mouseup.call(this, event);
  5201. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5202. localDOMHandlers.click.call(this, event);
  5203. }
  5204. },
  5205. pointerdown: function (event) {
  5206. localDOMHandlers.mousedown.call(this, event);
  5207. },
  5208. pointermove: function (event) {
  5209. if (!isPointerFromTouch(event)) {
  5210. localDOMHandlers.mousemove.call(this, event);
  5211. }
  5212. },
  5213. pointerup: function (event) {
  5214. localDOMHandlers.mouseup.call(this, event);
  5215. },
  5216. pointerout: function (event) {
  5217. if (!isPointerFromTouch(event)) {
  5218. localDOMHandlers.mouseout.call(this, event);
  5219. }
  5220. }
  5221. };
  5222. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5223. localDOMHandlers[name] = function (event) {
  5224. event = normalizeEvent(this.dom, event);
  5225. this.trigger(name, event);
  5226. };
  5227. });
  5228. var globalDOMHandlers = {
  5229. pointermove: function (event) {
  5230. if (!isPointerFromTouch(event)) {
  5231. globalDOMHandlers.mousemove.call(this, event);
  5232. }
  5233. },
  5234. pointerup: function (event) {
  5235. globalDOMHandlers.mouseup.call(this, event);
  5236. },
  5237. mousemove: function (event) {
  5238. this.trigger('mousemove', event);
  5239. },
  5240. mouseup: function (event) {
  5241. var pointerCaptureReleasing = this.__pointerCapturing;
  5242. this.__togglePointerCapture(false);
  5243. this.trigger('mouseup', event);
  5244. if (pointerCaptureReleasing) {
  5245. event.zrEventControl = 'only_globalout';
  5246. this.trigger('mouseout', event);
  5247. }
  5248. }
  5249. };
  5250. function mountLocalDOMEventListeners(instance, scope) {
  5251. var domHandlers = scope.domHandlers;
  5252. if (env.pointerEventsSupported) {
  5253. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5254. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5255. domHandlers[nativeEventName].call(instance, event);
  5256. });
  5257. });
  5258. }
  5259. else {
  5260. if (env.touchEventsSupported) {
  5261. each(localNativeListenerNames.touch, function (nativeEventName) {
  5262. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5263. domHandlers[nativeEventName].call(instance, event);
  5264. setTouchTimer(scope);
  5265. });
  5266. });
  5267. }
  5268. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5269. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5270. event = getNativeEvent(event);
  5271. if (!scope.touching) {
  5272. domHandlers[nativeEventName].call(instance, event);
  5273. }
  5274. });
  5275. });
  5276. }
  5277. }
  5278. function mountGlobalDOMEventListeners(instance, scope) {
  5279. if (env.pointerEventsSupported) {
  5280. each(globalNativeListenerNames.pointer, mount);
  5281. }
  5282. else if (!env.touchEventsSupported) {
  5283. each(globalNativeListenerNames.mouse, mount);
  5284. }
  5285. function mount(nativeEventName) {
  5286. function nativeEventListener(event) {
  5287. event = getNativeEvent(event);
  5288. if (!isLocalEl(instance, event.target)) {
  5289. event = normalizeGlobalEvent(instance, event);
  5290. scope.domHandlers[nativeEventName].call(instance, event);
  5291. }
  5292. }
  5293. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5294. }
  5295. }
  5296. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5297. scope.mounted[nativeEventName] = listener;
  5298. scope.listenerOpts[nativeEventName] = opt;
  5299. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5300. }
  5301. function unmountDOMEventListeners(scope) {
  5302. var mounted = scope.mounted;
  5303. for (var nativeEventName in mounted) {
  5304. if (mounted.hasOwnProperty(nativeEventName)) {
  5305. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5306. }
  5307. }
  5308. scope.mounted = {};
  5309. }
  5310. var DOMHandlerScope = (function () {
  5311. function DOMHandlerScope(domTarget, domHandlers) {
  5312. this.mounted = {};
  5313. this.listenerOpts = {};
  5314. this.touching = false;
  5315. this.domTarget = domTarget;
  5316. this.domHandlers = domHandlers;
  5317. }
  5318. return DOMHandlerScope;
  5319. }());
  5320. var HandlerDomProxy = (function (_super) {
  5321. __extends(HandlerDomProxy, _super);
  5322. function HandlerDomProxy(dom, painterRoot) {
  5323. var _this = _super.call(this) || this;
  5324. _this.__pointerCapturing = false;
  5325. _this.dom = dom;
  5326. _this.painterRoot = painterRoot;
  5327. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5328. if (globalEventSupported) {
  5329. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5330. }
  5331. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5332. return _this;
  5333. }
  5334. HandlerDomProxy.prototype.dispose = function () {
  5335. unmountDOMEventListeners(this._localHandlerScope);
  5336. if (globalEventSupported) {
  5337. unmountDOMEventListeners(this._globalHandlerScope);
  5338. }
  5339. };
  5340. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5341. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5342. };
  5343. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5344. this.__mayPointerCapture = null;
  5345. if (globalEventSupported
  5346. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5347. this.__pointerCapturing = isPointerCapturing;
  5348. var globalHandlerScope = this._globalHandlerScope;
  5349. isPointerCapturing
  5350. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5351. : unmountDOMEventListeners(globalHandlerScope);
  5352. }
  5353. };
  5354. return HandlerDomProxy;
  5355. }(Eventful));
  5356. var dpr = 1;
  5357. if (env.hasGlobalWindow) {
  5358. dpr = Math.max(window.devicePixelRatio
  5359. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5360. || 1, 1);
  5361. }
  5362. var devicePixelRatio = dpr;
  5363. var DARK_MODE_THRESHOLD = 0.4;
  5364. var DARK_LABEL_COLOR = '#333';
  5365. var LIGHT_LABEL_COLOR = '#ccc';
  5366. var LIGHTER_LABEL_COLOR = '#eee';
  5367. var mIdentity = identity;
  5368. var EPSILON$2 = 5e-5;
  5369. function isNotAroundZero$1(val) {
  5370. return val > EPSILON$2 || val < -EPSILON$2;
  5371. }
  5372. var scaleTmp = [];
  5373. var tmpTransform = [];
  5374. var originTransform = create$1();
  5375. var abs = Math.abs;
  5376. var Transformable = (function () {
  5377. function Transformable() {
  5378. }
  5379. Transformable.prototype.getLocalTransform = function (m) {
  5380. return Transformable.getLocalTransform(this, m);
  5381. };
  5382. Transformable.prototype.setPosition = function (arr) {
  5383. this.x = arr[0];
  5384. this.y = arr[1];
  5385. };
  5386. Transformable.prototype.setScale = function (arr) {
  5387. this.scaleX = arr[0];
  5388. this.scaleY = arr[1];
  5389. };
  5390. Transformable.prototype.setSkew = function (arr) {
  5391. this.skewX = arr[0];
  5392. this.skewY = arr[1];
  5393. };
  5394. Transformable.prototype.setOrigin = function (arr) {
  5395. this.originX = arr[0];
  5396. this.originY = arr[1];
  5397. };
  5398. Transformable.prototype.needLocalTransform = function () {
  5399. return isNotAroundZero$1(this.rotation)
  5400. || isNotAroundZero$1(this.x)
  5401. || isNotAroundZero$1(this.y)
  5402. || isNotAroundZero$1(this.scaleX - 1)
  5403. || isNotAroundZero$1(this.scaleY - 1)
  5404. || isNotAroundZero$1(this.skewX)
  5405. || isNotAroundZero$1(this.skewY);
  5406. };
  5407. Transformable.prototype.updateTransform = function () {
  5408. var parentTransform = this.parent && this.parent.transform;
  5409. var needLocalTransform = this.needLocalTransform();
  5410. var m = this.transform;
  5411. if (!(needLocalTransform || parentTransform)) {
  5412. m && mIdentity(m);
  5413. return;
  5414. }
  5415. m = m || create$1();
  5416. if (needLocalTransform) {
  5417. this.getLocalTransform(m);
  5418. }
  5419. else {
  5420. mIdentity(m);
  5421. }
  5422. if (parentTransform) {
  5423. if (needLocalTransform) {
  5424. mul$1(m, parentTransform, m);
  5425. }
  5426. else {
  5427. copy$1(m, parentTransform);
  5428. }
  5429. }
  5430. this.transform = m;
  5431. this._resolveGlobalScaleRatio(m);
  5432. };
  5433. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5434. var globalScaleRatio = this.globalScaleRatio;
  5435. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5436. this.getGlobalScale(scaleTmp);
  5437. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5438. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5439. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5440. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5441. m[0] *= sx;
  5442. m[1] *= sx;
  5443. m[2] *= sy;
  5444. m[3] *= sy;
  5445. }
  5446. this.invTransform = this.invTransform || create$1();
  5447. invert(this.invTransform, m);
  5448. };
  5449. Transformable.prototype.getComputedTransform = function () {
  5450. var transformNode = this;
  5451. var ancestors = [];
  5452. while (transformNode) {
  5453. ancestors.push(transformNode);
  5454. transformNode = transformNode.parent;
  5455. }
  5456. while (transformNode = ancestors.pop()) {
  5457. transformNode.updateTransform();
  5458. }
  5459. return this.transform;
  5460. };
  5461. Transformable.prototype.setLocalTransform = function (m) {
  5462. if (!m) {
  5463. return;
  5464. }
  5465. var sx = m[0] * m[0] + m[1] * m[1];
  5466. var sy = m[2] * m[2] + m[3] * m[3];
  5467. var rotation = Math.atan2(m[1], m[0]);
  5468. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5469. sy = Math.sqrt(sy) * Math.cos(shearX);
  5470. sx = Math.sqrt(sx);
  5471. this.skewX = shearX;
  5472. this.skewY = 0;
  5473. this.rotation = -rotation;
  5474. this.x = +m[4];
  5475. this.y = +m[5];
  5476. this.scaleX = sx;
  5477. this.scaleY = sy;
  5478. this.originX = 0;
  5479. this.originY = 0;
  5480. };
  5481. Transformable.prototype.decomposeTransform = function () {
  5482. if (!this.transform) {
  5483. return;
  5484. }
  5485. var parent = this.parent;
  5486. var m = this.transform;
  5487. if (parent && parent.transform) {
  5488. mul$1(tmpTransform, parent.invTransform, m);
  5489. m = tmpTransform;
  5490. }
  5491. var ox = this.originX;
  5492. var oy = this.originY;
  5493. if (ox || oy) {
  5494. originTransform[4] = ox;
  5495. originTransform[5] = oy;
  5496. mul$1(tmpTransform, m, originTransform);
  5497. tmpTransform[4] -= ox;
  5498. tmpTransform[5] -= oy;
  5499. m = tmpTransform;
  5500. }
  5501. this.setLocalTransform(m);
  5502. };
  5503. Transformable.prototype.getGlobalScale = function (out) {
  5504. var m = this.transform;
  5505. out = out || [];
  5506. if (!m) {
  5507. out[0] = 1;
  5508. out[1] = 1;
  5509. return out;
  5510. }
  5511. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5512. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5513. if (m[0] < 0) {
  5514. out[0] = -out[0];
  5515. }
  5516. if (m[3] < 0) {
  5517. out[1] = -out[1];
  5518. }
  5519. return out;
  5520. };
  5521. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5522. var v2 = [x, y];
  5523. var invTransform = this.invTransform;
  5524. if (invTransform) {
  5525. applyTransform(v2, v2, invTransform);
  5526. }
  5527. return v2;
  5528. };
  5529. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5530. var v2 = [x, y];
  5531. var transform = this.transform;
  5532. if (transform) {
  5533. applyTransform(v2, v2, transform);
  5534. }
  5535. return v2;
  5536. };
  5537. Transformable.prototype.getLineScale = function () {
  5538. var m = this.transform;
  5539. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5540. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5541. : 1;
  5542. };
  5543. Transformable.prototype.copyTransform = function (source) {
  5544. copyTransform(this, source);
  5545. };
  5546. Transformable.getLocalTransform = function (target, m) {
  5547. m = m || [];
  5548. var ox = target.originX || 0;
  5549. var oy = target.originY || 0;
  5550. var sx = target.scaleX;
  5551. var sy = target.scaleY;
  5552. var ax = target.anchorX;
  5553. var ay = target.anchorY;
  5554. var rotation = target.rotation || 0;
  5555. var x = target.x;
  5556. var y = target.y;
  5557. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5558. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5559. if (ox || oy || ax || ay) {
  5560. var dx = ox + ax;
  5561. var dy = oy + ay;
  5562. m[4] = -dx * sx - skewX * dy * sy;
  5563. m[5] = -dy * sy - skewY * dx * sx;
  5564. }
  5565. else {
  5566. m[4] = m[5] = 0;
  5567. }
  5568. m[0] = sx;
  5569. m[3] = sy;
  5570. m[1] = skewY * sx;
  5571. m[2] = skewX * sy;
  5572. rotation && rotate(m, m, rotation);
  5573. m[4] += ox + x;
  5574. m[5] += oy + y;
  5575. return m;
  5576. };
  5577. Transformable.initDefaultProps = (function () {
  5578. var proto = Transformable.prototype;
  5579. proto.scaleX =
  5580. proto.scaleY =
  5581. proto.globalScaleRatio = 1;
  5582. proto.x =
  5583. proto.y =
  5584. proto.originX =
  5585. proto.originY =
  5586. proto.skewX =
  5587. proto.skewY =
  5588. proto.rotation =
  5589. proto.anchorX =
  5590. proto.anchorY = 0;
  5591. })();
  5592. return Transformable;
  5593. }());
  5594. var TRANSFORMABLE_PROPS = [
  5595. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5596. ];
  5597. function copyTransform(target, source) {
  5598. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5599. var propName = TRANSFORMABLE_PROPS[i];
  5600. target[propName] = source[propName];
  5601. }
  5602. }
  5603. var textWidthCache = {};
  5604. function getWidth(text, font) {
  5605. font = font || DEFAULT_FONT;
  5606. var cacheOfFont = textWidthCache[font];
  5607. if (!cacheOfFont) {
  5608. cacheOfFont = textWidthCache[font] = new LRU(500);
  5609. }
  5610. var width = cacheOfFont.get(text);
  5611. if (width == null) {
  5612. width = platformApi.measureText(text, font).width;
  5613. cacheOfFont.put(text, width);
  5614. }
  5615. return width;
  5616. }
  5617. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5618. var width = getWidth(text, font);
  5619. var height = getLineHeight(font);
  5620. var x = adjustTextX(0, width, textAlign);
  5621. var y = adjustTextY$1(0, height, textBaseline);
  5622. var rect = new BoundingRect(x, y, width, height);
  5623. return rect;
  5624. }
  5625. function getBoundingRect(text, font, textAlign, textBaseline) {
  5626. var textLines = ((text || '') + '').split('\n');
  5627. var len = textLines.length;
  5628. if (len === 1) {
  5629. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5630. }
  5631. else {
  5632. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5633. for (var i = 0; i < textLines.length; i++) {
  5634. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5635. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5636. }
  5637. return uniondRect;
  5638. }
  5639. }
  5640. function adjustTextX(x, width, textAlign) {
  5641. if (textAlign === 'right') {
  5642. x -= width;
  5643. }
  5644. else if (textAlign === 'center') {
  5645. x -= width / 2;
  5646. }
  5647. return x;
  5648. }
  5649. function adjustTextY$1(y, height, verticalAlign) {
  5650. if (verticalAlign === 'middle') {
  5651. y -= height / 2;
  5652. }
  5653. else if (verticalAlign === 'bottom') {
  5654. y -= height;
  5655. }
  5656. return y;
  5657. }
  5658. function getLineHeight(font) {
  5659. return getWidth('国', font);
  5660. }
  5661. function parsePercent(value, maxValue) {
  5662. if (typeof value === 'string') {
  5663. if (value.lastIndexOf('%') >= 0) {
  5664. return parseFloat(value) / 100 * maxValue;
  5665. }
  5666. return parseFloat(value);
  5667. }
  5668. return value;
  5669. }
  5670. function calculateTextPosition(out, opts, rect) {
  5671. var textPosition = opts.position || 'inside';
  5672. var distance = opts.distance != null ? opts.distance : 5;
  5673. var height = rect.height;
  5674. var width = rect.width;
  5675. var halfHeight = height / 2;
  5676. var x = rect.x;
  5677. var y = rect.y;
  5678. var textAlign = 'left';
  5679. var textVerticalAlign = 'top';
  5680. if (textPosition instanceof Array) {
  5681. x += parsePercent(textPosition[0], rect.width);
  5682. y += parsePercent(textPosition[1], rect.height);
  5683. textAlign = null;
  5684. textVerticalAlign = null;
  5685. }
  5686. else {
  5687. switch (textPosition) {
  5688. case 'left':
  5689. x -= distance;
  5690. y += halfHeight;
  5691. textAlign = 'right';
  5692. textVerticalAlign = 'middle';
  5693. break;
  5694. case 'right':
  5695. x += distance + width;
  5696. y += halfHeight;
  5697. textVerticalAlign = 'middle';
  5698. break;
  5699. case 'top':
  5700. x += width / 2;
  5701. y -= distance;
  5702. textAlign = 'center';
  5703. textVerticalAlign = 'bottom';
  5704. break;
  5705. case 'bottom':
  5706. x += width / 2;
  5707. y += height + distance;
  5708. textAlign = 'center';
  5709. break;
  5710. case 'inside':
  5711. x += width / 2;
  5712. y += halfHeight;
  5713. textAlign = 'center';
  5714. textVerticalAlign = 'middle';
  5715. break;
  5716. case 'insideLeft':
  5717. x += distance;
  5718. y += halfHeight;
  5719. textVerticalAlign = 'middle';
  5720. break;
  5721. case 'insideRight':
  5722. x += width - distance;
  5723. y += halfHeight;
  5724. textAlign = 'right';
  5725. textVerticalAlign = 'middle';
  5726. break;
  5727. case 'insideTop':
  5728. x += width / 2;
  5729. y += distance;
  5730. textAlign = 'center';
  5731. break;
  5732. case 'insideBottom':
  5733. x += width / 2;
  5734. y += height - distance;
  5735. textAlign = 'center';
  5736. textVerticalAlign = 'bottom';
  5737. break;
  5738. case 'insideTopLeft':
  5739. x += distance;
  5740. y += distance;
  5741. break;
  5742. case 'insideTopRight':
  5743. x += width - distance;
  5744. y += distance;
  5745. textAlign = 'right';
  5746. break;
  5747. case 'insideBottomLeft':
  5748. x += distance;
  5749. y += height - distance;
  5750. textVerticalAlign = 'bottom';
  5751. break;
  5752. case 'insideBottomRight':
  5753. x += width - distance;
  5754. y += height - distance;
  5755. textAlign = 'right';
  5756. textVerticalAlign = 'bottom';
  5757. break;
  5758. }
  5759. }
  5760. out = out || {};
  5761. out.x = x;
  5762. out.y = y;
  5763. out.align = textAlign;
  5764. out.verticalAlign = textVerticalAlign;
  5765. return out;
  5766. }
  5767. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5768. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5769. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5770. obj[key] = true;
  5771. return obj;
  5772. }, { ignore: false });
  5773. var tmpTextPosCalcRes = {};
  5774. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5775. var Element = (function () {
  5776. function Element(props) {
  5777. this.id = guid();
  5778. this.animators = [];
  5779. this.currentStates = [];
  5780. this.states = {};
  5781. this._init(props);
  5782. }
  5783. Element.prototype._init = function (props) {
  5784. this.attr(props);
  5785. };
  5786. Element.prototype.drift = function (dx, dy, e) {
  5787. switch (this.draggable) {
  5788. case 'horizontal':
  5789. dy = 0;
  5790. break;
  5791. case 'vertical':
  5792. dx = 0;
  5793. break;
  5794. }
  5795. var m = this.transform;
  5796. if (!m) {
  5797. m = this.transform = [1, 0, 0, 1, 0, 0];
  5798. }
  5799. m[4] += dx;
  5800. m[5] += dy;
  5801. this.decomposeTransform();
  5802. this.markRedraw();
  5803. };
  5804. Element.prototype.beforeUpdate = function () { };
  5805. Element.prototype.afterUpdate = function () { };
  5806. Element.prototype.update = function () {
  5807. this.updateTransform();
  5808. if (this.__dirty) {
  5809. this.updateInnerText();
  5810. }
  5811. };
  5812. Element.prototype.updateInnerText = function (forceUpdate) {
  5813. var textEl = this._textContent;
  5814. if (textEl && (!textEl.ignore || forceUpdate)) {
  5815. if (!this.textConfig) {
  5816. this.textConfig = {};
  5817. }
  5818. var textConfig = this.textConfig;
  5819. var isLocal = textConfig.local;
  5820. var innerTransformable = textEl.innerTransformable;
  5821. var textAlign = void 0;
  5822. var textVerticalAlign = void 0;
  5823. var textStyleChanged = false;
  5824. innerTransformable.parent = isLocal ? this : null;
  5825. var innerOrigin = false;
  5826. innerTransformable.copyTransform(textEl);
  5827. if (textConfig.position != null) {
  5828. var layoutRect = tmpBoundingRect;
  5829. if (textConfig.layoutRect) {
  5830. layoutRect.copy(textConfig.layoutRect);
  5831. }
  5832. else {
  5833. layoutRect.copy(this.getBoundingRect());
  5834. }
  5835. if (!isLocal) {
  5836. layoutRect.applyTransform(this.transform);
  5837. }
  5838. if (this.calculateTextPosition) {
  5839. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5840. }
  5841. else {
  5842. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5843. }
  5844. innerTransformable.x = tmpTextPosCalcRes.x;
  5845. innerTransformable.y = tmpTextPosCalcRes.y;
  5846. textAlign = tmpTextPosCalcRes.align;
  5847. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5848. var textOrigin = textConfig.origin;
  5849. if (textOrigin && textConfig.rotation != null) {
  5850. var relOriginX = void 0;
  5851. var relOriginY = void 0;
  5852. if (textOrigin === 'center') {
  5853. relOriginX = layoutRect.width * 0.5;
  5854. relOriginY = layoutRect.height * 0.5;
  5855. }
  5856. else {
  5857. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5858. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5859. }
  5860. innerOrigin = true;
  5861. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5862. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5863. }
  5864. }
  5865. if (textConfig.rotation != null) {
  5866. innerTransformable.rotation = textConfig.rotation;
  5867. }
  5868. var textOffset = textConfig.offset;
  5869. if (textOffset) {
  5870. innerTransformable.x += textOffset[0];
  5871. innerTransformable.y += textOffset[1];
  5872. if (!innerOrigin) {
  5873. innerTransformable.originX = -textOffset[0];
  5874. innerTransformable.originY = -textOffset[1];
  5875. }
  5876. }
  5877. var isInside = textConfig.inside == null
  5878. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5879. : textConfig.inside;
  5880. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5881. var textFill = void 0;
  5882. var textStroke = void 0;
  5883. var autoStroke = void 0;
  5884. if (isInside && this.canBeInsideText()) {
  5885. textFill = textConfig.insideFill;
  5886. textStroke = textConfig.insideStroke;
  5887. if (textFill == null || textFill === 'auto') {
  5888. textFill = this.getInsideTextFill();
  5889. }
  5890. if (textStroke == null || textStroke === 'auto') {
  5891. textStroke = this.getInsideTextStroke(textFill);
  5892. autoStroke = true;
  5893. }
  5894. }
  5895. else {
  5896. textFill = textConfig.outsideFill;
  5897. textStroke = textConfig.outsideStroke;
  5898. if (textFill == null || textFill === 'auto') {
  5899. textFill = this.getOutsideFill();
  5900. }
  5901. if (textStroke == null || textStroke === 'auto') {
  5902. textStroke = this.getOutsideStroke(textFill);
  5903. autoStroke = true;
  5904. }
  5905. }
  5906. textFill = textFill || '#000';
  5907. if (textFill !== innerTextDefaultStyle.fill
  5908. || textStroke !== innerTextDefaultStyle.stroke
  5909. || autoStroke !== innerTextDefaultStyle.autoStroke
  5910. || textAlign !== innerTextDefaultStyle.align
  5911. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5912. textStyleChanged = true;
  5913. innerTextDefaultStyle.fill = textFill;
  5914. innerTextDefaultStyle.stroke = textStroke;
  5915. innerTextDefaultStyle.autoStroke = autoStroke;
  5916. innerTextDefaultStyle.align = textAlign;
  5917. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5918. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5919. }
  5920. textEl.__dirty |= REDRAW_BIT;
  5921. if (textStyleChanged) {
  5922. textEl.dirtyStyle(true);
  5923. }
  5924. }
  5925. };
  5926. Element.prototype.canBeInsideText = function () {
  5927. return true;
  5928. };
  5929. Element.prototype.getInsideTextFill = function () {
  5930. return '#fff';
  5931. };
  5932. Element.prototype.getInsideTextStroke = function (textFill) {
  5933. return '#000';
  5934. };
  5935. Element.prototype.getOutsideFill = function () {
  5936. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5937. };
  5938. Element.prototype.getOutsideStroke = function (textFill) {
  5939. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5940. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5941. if (!colorArr) {
  5942. colorArr = [255, 255, 255, 1];
  5943. }
  5944. var alpha = colorArr[3];
  5945. var isDark = this.__zr.isDarkMode();
  5946. for (var i = 0; i < 3; i++) {
  5947. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5948. }
  5949. colorArr[3] = 1;
  5950. return stringify(colorArr, 'rgba');
  5951. };
  5952. Element.prototype.traverse = function (cb, context) { };
  5953. Element.prototype.attrKV = function (key, value) {
  5954. if (key === 'textConfig') {
  5955. this.setTextConfig(value);
  5956. }
  5957. else if (key === 'textContent') {
  5958. this.setTextContent(value);
  5959. }
  5960. else if (key === 'clipPath') {
  5961. this.setClipPath(value);
  5962. }
  5963. else if (key === 'extra') {
  5964. this.extra = this.extra || {};
  5965. extend(this.extra, value);
  5966. }
  5967. else {
  5968. this[key] = value;
  5969. }
  5970. };
  5971. Element.prototype.hide = function () {
  5972. this.ignore = true;
  5973. this.markRedraw();
  5974. };
  5975. Element.prototype.show = function () {
  5976. this.ignore = false;
  5977. this.markRedraw();
  5978. };
  5979. Element.prototype.attr = function (keyOrObj, value) {
  5980. if (typeof keyOrObj === 'string') {
  5981. this.attrKV(keyOrObj, value);
  5982. }
  5983. else if (isObject(keyOrObj)) {
  5984. var obj = keyOrObj;
  5985. var keysArr = keys(obj);
  5986. for (var i = 0; i < keysArr.length; i++) {
  5987. var key = keysArr[i];
  5988. this.attrKV(key, keyOrObj[key]);
  5989. }
  5990. }
  5991. this.markRedraw();
  5992. return this;
  5993. };
  5994. Element.prototype.saveCurrentToNormalState = function (toState) {
  5995. this._innerSaveToNormal(toState);
  5996. var normalState = this._normalState;
  5997. for (var i = 0; i < this.animators.length; i++) {
  5998. var animator = this.animators[i];
  5999. var fromStateTransition = animator.__fromStateTransition;
  6000. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6001. continue;
  6002. }
  6003. var targetName = animator.targetName;
  6004. var target = targetName
  6005. ? normalState[targetName] : normalState;
  6006. animator.saveTo(target);
  6007. }
  6008. };
  6009. Element.prototype._innerSaveToNormal = function (toState) {
  6010. var normalState = this._normalState;
  6011. if (!normalState) {
  6012. normalState = this._normalState = {};
  6013. }
  6014. if (toState.textConfig && !normalState.textConfig) {
  6015. normalState.textConfig = this.textConfig;
  6016. }
  6017. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6018. };
  6019. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6020. for (var i = 0; i < primaryKeys.length; i++) {
  6021. var key = primaryKeys[i];
  6022. if (toState[key] != null && !(key in normalState)) {
  6023. normalState[key] = this[key];
  6024. }
  6025. }
  6026. };
  6027. Element.prototype.hasState = function () {
  6028. return this.currentStates.length > 0;
  6029. };
  6030. Element.prototype.getState = function (name) {
  6031. return this.states[name];
  6032. };
  6033. Element.prototype.ensureState = function (name) {
  6034. var states = this.states;
  6035. if (!states[name]) {
  6036. states[name] = {};
  6037. }
  6038. return states[name];
  6039. };
  6040. Element.prototype.clearStates = function (noAnimation) {
  6041. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6042. };
  6043. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6044. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6045. var hasStates = this.hasState();
  6046. if (!hasStates && toNormalState) {
  6047. return;
  6048. }
  6049. var currentStates = this.currentStates;
  6050. var animationCfg = this.stateTransition;
  6051. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6052. return;
  6053. }
  6054. var state;
  6055. if (this.stateProxy && !toNormalState) {
  6056. state = this.stateProxy(stateName);
  6057. }
  6058. if (!state) {
  6059. state = (this.states && this.states[stateName]);
  6060. }
  6061. if (!state && !toNormalState) {
  6062. logError("State " + stateName + " not exists.");
  6063. return;
  6064. }
  6065. if (!toNormalState) {
  6066. this.saveCurrentToNormalState(state);
  6067. }
  6068. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6069. if (useHoverLayer) {
  6070. this._toggleHoverLayerFlag(true);
  6071. }
  6072. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6073. var textContent = this._textContent;
  6074. var textGuide = this._textGuide;
  6075. if (textContent) {
  6076. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6077. }
  6078. if (textGuide) {
  6079. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6080. }
  6081. if (toNormalState) {
  6082. this.currentStates = [];
  6083. this._normalState = {};
  6084. }
  6085. else {
  6086. if (!keepCurrentStates) {
  6087. this.currentStates = [stateName];
  6088. }
  6089. else {
  6090. this.currentStates.push(stateName);
  6091. }
  6092. }
  6093. this._updateAnimationTargets();
  6094. this.markRedraw();
  6095. if (!useHoverLayer && this.__inHover) {
  6096. this._toggleHoverLayerFlag(false);
  6097. this.__dirty &= ~REDRAW_BIT;
  6098. }
  6099. return state;
  6100. };
  6101. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6102. if (!states.length) {
  6103. this.clearStates();
  6104. }
  6105. else {
  6106. var stateObjects = [];
  6107. var currentStates = this.currentStates;
  6108. var len = states.length;
  6109. var notChange = len === currentStates.length;
  6110. if (notChange) {
  6111. for (var i = 0; i < len; i++) {
  6112. if (states[i] !== currentStates[i]) {
  6113. notChange = false;
  6114. break;
  6115. }
  6116. }
  6117. }
  6118. if (notChange) {
  6119. return;
  6120. }
  6121. for (var i = 0; i < len; i++) {
  6122. var stateName = states[i];
  6123. var stateObj = void 0;
  6124. if (this.stateProxy) {
  6125. stateObj = this.stateProxy(stateName, states);
  6126. }
  6127. if (!stateObj) {
  6128. stateObj = this.states[stateName];
  6129. }
  6130. if (stateObj) {
  6131. stateObjects.push(stateObj);
  6132. }
  6133. }
  6134. var lastStateObj = stateObjects[len - 1];
  6135. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6136. if (useHoverLayer) {
  6137. this._toggleHoverLayerFlag(true);
  6138. }
  6139. var mergedState = this._mergeStates(stateObjects);
  6140. var animationCfg = this.stateTransition;
  6141. this.saveCurrentToNormalState(mergedState);
  6142. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6143. var textContent = this._textContent;
  6144. var textGuide = this._textGuide;
  6145. if (textContent) {
  6146. textContent.useStates(states, noAnimation, useHoverLayer);
  6147. }
  6148. if (textGuide) {
  6149. textGuide.useStates(states, noAnimation, useHoverLayer);
  6150. }
  6151. this._updateAnimationTargets();
  6152. this.currentStates = states.slice();
  6153. this.markRedraw();
  6154. if (!useHoverLayer && this.__inHover) {
  6155. this._toggleHoverLayerFlag(false);
  6156. this.__dirty &= ~REDRAW_BIT;
  6157. }
  6158. }
  6159. };
  6160. Element.prototype._updateAnimationTargets = function () {
  6161. for (var i = 0; i < this.animators.length; i++) {
  6162. var animator = this.animators[i];
  6163. if (animator.targetName) {
  6164. animator.changeTarget(this[animator.targetName]);
  6165. }
  6166. }
  6167. };
  6168. Element.prototype.removeState = function (state) {
  6169. var idx = indexOf(this.currentStates, state);
  6170. if (idx >= 0) {
  6171. var currentStates = this.currentStates.slice();
  6172. currentStates.splice(idx, 1);
  6173. this.useStates(currentStates);
  6174. }
  6175. };
  6176. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6177. var currentStates = this.currentStates.slice();
  6178. var idx = indexOf(currentStates, oldState);
  6179. var newStateExists = indexOf(currentStates, newState) >= 0;
  6180. if (idx >= 0) {
  6181. if (!newStateExists) {
  6182. currentStates[idx] = newState;
  6183. }
  6184. else {
  6185. currentStates.splice(idx, 1);
  6186. }
  6187. }
  6188. else if (forceAdd && !newStateExists) {
  6189. currentStates.push(newState);
  6190. }
  6191. this.useStates(currentStates);
  6192. };
  6193. Element.prototype.toggleState = function (state, enable) {
  6194. if (enable) {
  6195. this.useState(state, true);
  6196. }
  6197. else {
  6198. this.removeState(state);
  6199. }
  6200. };
  6201. Element.prototype._mergeStates = function (states) {
  6202. var mergedState = {};
  6203. var mergedTextConfig;
  6204. for (var i = 0; i < states.length; i++) {
  6205. var state = states[i];
  6206. extend(mergedState, state);
  6207. if (state.textConfig) {
  6208. mergedTextConfig = mergedTextConfig || {};
  6209. extend(mergedTextConfig, state.textConfig);
  6210. }
  6211. }
  6212. if (mergedTextConfig) {
  6213. mergedState.textConfig = mergedTextConfig;
  6214. }
  6215. return mergedState;
  6216. };
  6217. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6218. var needsRestoreToNormal = !(state && keepCurrentStates);
  6219. if (state && state.textConfig) {
  6220. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6221. extend(this.textConfig, state.textConfig);
  6222. }
  6223. else if (needsRestoreToNormal) {
  6224. if (normalState.textConfig) {
  6225. this.textConfig = normalState.textConfig;
  6226. }
  6227. }
  6228. var transitionTarget = {};
  6229. var hasTransition = false;
  6230. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6231. var key = PRIMARY_STATES_KEYS[i];
  6232. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6233. if (state && state[key] != null) {
  6234. if (propNeedsTransition) {
  6235. hasTransition = true;
  6236. transitionTarget[key] = state[key];
  6237. }
  6238. else {
  6239. this[key] = state[key];
  6240. }
  6241. }
  6242. else if (needsRestoreToNormal) {
  6243. if (normalState[key] != null) {
  6244. if (propNeedsTransition) {
  6245. hasTransition = true;
  6246. transitionTarget[key] = normalState[key];
  6247. }
  6248. else {
  6249. this[key] = normalState[key];
  6250. }
  6251. }
  6252. }
  6253. }
  6254. if (!transition) {
  6255. for (var i = 0; i < this.animators.length; i++) {
  6256. var animator = this.animators[i];
  6257. var targetName = animator.targetName;
  6258. if (!animator.getLoop()) {
  6259. animator.__changeFinalValue(targetName
  6260. ? (state || normalState)[targetName]
  6261. : (state || normalState));
  6262. }
  6263. }
  6264. }
  6265. if (hasTransition) {
  6266. this._transitionState(stateName, transitionTarget, animationCfg);
  6267. }
  6268. };
  6269. Element.prototype._attachComponent = function (componentEl) {
  6270. if (componentEl.__zr && !componentEl.__hostTarget) {
  6271. if ("development" !== 'production') {
  6272. throw new Error('Text element has been added to zrender.');
  6273. }
  6274. return;
  6275. }
  6276. if (componentEl === this) {
  6277. if ("development" !== 'production') {
  6278. throw new Error('Recursive component attachment.');
  6279. }
  6280. return;
  6281. }
  6282. var zr = this.__zr;
  6283. if (zr) {
  6284. componentEl.addSelfToZr(zr);
  6285. }
  6286. componentEl.__zr = zr;
  6287. componentEl.__hostTarget = this;
  6288. };
  6289. Element.prototype._detachComponent = function (componentEl) {
  6290. if (componentEl.__zr) {
  6291. componentEl.removeSelfFromZr(componentEl.__zr);
  6292. }
  6293. componentEl.__zr = null;
  6294. componentEl.__hostTarget = null;
  6295. };
  6296. Element.prototype.getClipPath = function () {
  6297. return this._clipPath;
  6298. };
  6299. Element.prototype.setClipPath = function (clipPath) {
  6300. if (this._clipPath && this._clipPath !== clipPath) {
  6301. this.removeClipPath();
  6302. }
  6303. this._attachComponent(clipPath);
  6304. this._clipPath = clipPath;
  6305. this.markRedraw();
  6306. };
  6307. Element.prototype.removeClipPath = function () {
  6308. var clipPath = this._clipPath;
  6309. if (clipPath) {
  6310. this._detachComponent(clipPath);
  6311. this._clipPath = null;
  6312. this.markRedraw();
  6313. }
  6314. };
  6315. Element.prototype.getTextContent = function () {
  6316. return this._textContent;
  6317. };
  6318. Element.prototype.setTextContent = function (textEl) {
  6319. var previousTextContent = this._textContent;
  6320. if (previousTextContent === textEl) {
  6321. return;
  6322. }
  6323. if (previousTextContent && previousTextContent !== textEl) {
  6324. this.removeTextContent();
  6325. }
  6326. if ("development" !== 'production') {
  6327. if (textEl.__zr && !textEl.__hostTarget) {
  6328. throw new Error('Text element has been added to zrender.');
  6329. }
  6330. }
  6331. textEl.innerTransformable = new Transformable();
  6332. this._attachComponent(textEl);
  6333. this._textContent = textEl;
  6334. this.markRedraw();
  6335. };
  6336. Element.prototype.setTextConfig = function (cfg) {
  6337. if (!this.textConfig) {
  6338. this.textConfig = {};
  6339. }
  6340. extend(this.textConfig, cfg);
  6341. this.markRedraw();
  6342. };
  6343. Element.prototype.removeTextConfig = function () {
  6344. this.textConfig = null;
  6345. this.markRedraw();
  6346. };
  6347. Element.prototype.removeTextContent = function () {
  6348. var textEl = this._textContent;
  6349. if (textEl) {
  6350. textEl.innerTransformable = null;
  6351. this._detachComponent(textEl);
  6352. this._textContent = null;
  6353. this._innerTextDefaultStyle = null;
  6354. this.markRedraw();
  6355. }
  6356. };
  6357. Element.prototype.getTextGuideLine = function () {
  6358. return this._textGuide;
  6359. };
  6360. Element.prototype.setTextGuideLine = function (guideLine) {
  6361. if (this._textGuide && this._textGuide !== guideLine) {
  6362. this.removeTextGuideLine();
  6363. }
  6364. this._attachComponent(guideLine);
  6365. this._textGuide = guideLine;
  6366. this.markRedraw();
  6367. };
  6368. Element.prototype.removeTextGuideLine = function () {
  6369. var textGuide = this._textGuide;
  6370. if (textGuide) {
  6371. this._detachComponent(textGuide);
  6372. this._textGuide = null;
  6373. this.markRedraw();
  6374. }
  6375. };
  6376. Element.prototype.markRedraw = function () {
  6377. this.__dirty |= REDRAW_BIT;
  6378. var zr = this.__zr;
  6379. if (zr) {
  6380. if (this.__inHover) {
  6381. zr.refreshHover();
  6382. }
  6383. else {
  6384. zr.refresh();
  6385. }
  6386. }
  6387. if (this.__hostTarget) {
  6388. this.__hostTarget.markRedraw();
  6389. }
  6390. };
  6391. Element.prototype.dirty = function () {
  6392. this.markRedraw();
  6393. };
  6394. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6395. this.__inHover = inHover;
  6396. var textContent = this._textContent;
  6397. var textGuide = this._textGuide;
  6398. if (textContent) {
  6399. textContent.__inHover = inHover;
  6400. }
  6401. if (textGuide) {
  6402. textGuide.__inHover = inHover;
  6403. }
  6404. };
  6405. Element.prototype.addSelfToZr = function (zr) {
  6406. if (this.__zr === zr) {
  6407. return;
  6408. }
  6409. this.__zr = zr;
  6410. var animators = this.animators;
  6411. if (animators) {
  6412. for (var i = 0; i < animators.length; i++) {
  6413. zr.animation.addAnimator(animators[i]);
  6414. }
  6415. }
  6416. if (this._clipPath) {
  6417. this._clipPath.addSelfToZr(zr);
  6418. }
  6419. if (this._textContent) {
  6420. this._textContent.addSelfToZr(zr);
  6421. }
  6422. if (this._textGuide) {
  6423. this._textGuide.addSelfToZr(zr);
  6424. }
  6425. };
  6426. Element.prototype.removeSelfFromZr = function (zr) {
  6427. if (!this.__zr) {
  6428. return;
  6429. }
  6430. this.__zr = null;
  6431. var animators = this.animators;
  6432. if (animators) {
  6433. for (var i = 0; i < animators.length; i++) {
  6434. zr.animation.removeAnimator(animators[i]);
  6435. }
  6436. }
  6437. if (this._clipPath) {
  6438. this._clipPath.removeSelfFromZr(zr);
  6439. }
  6440. if (this._textContent) {
  6441. this._textContent.removeSelfFromZr(zr);
  6442. }
  6443. if (this._textGuide) {
  6444. this._textGuide.removeSelfFromZr(zr);
  6445. }
  6446. };
  6447. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6448. var target = key ? this[key] : this;
  6449. if ("development" !== 'production') {
  6450. if (!target) {
  6451. logError('Property "'
  6452. + key
  6453. + '" is not existed in element '
  6454. + this.id);
  6455. return;
  6456. }
  6457. }
  6458. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6459. key && (animator.targetName = key);
  6460. this.addAnimator(animator, key);
  6461. return animator;
  6462. };
  6463. Element.prototype.addAnimator = function (animator, key) {
  6464. var zr = this.__zr;
  6465. var el = this;
  6466. animator.during(function () {
  6467. el.updateDuringAnimation(key);
  6468. }).done(function () {
  6469. var animators = el.animators;
  6470. var idx = indexOf(animators, animator);
  6471. if (idx >= 0) {
  6472. animators.splice(idx, 1);
  6473. }
  6474. });
  6475. this.animators.push(animator);
  6476. if (zr) {
  6477. zr.animation.addAnimator(animator);
  6478. }
  6479. zr && zr.wakeUp();
  6480. };
  6481. Element.prototype.updateDuringAnimation = function (key) {
  6482. this.markRedraw();
  6483. };
  6484. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6485. var animators = this.animators;
  6486. var len = animators.length;
  6487. var leftAnimators = [];
  6488. for (var i = 0; i < len; i++) {
  6489. var animator = animators[i];
  6490. if (!scope || scope === animator.scope) {
  6491. animator.stop(forwardToLast);
  6492. }
  6493. else {
  6494. leftAnimators.push(animator);
  6495. }
  6496. }
  6497. this.animators = leftAnimators;
  6498. return this;
  6499. };
  6500. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6501. animateTo(this, target, cfg, animationProps);
  6502. };
  6503. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6504. animateTo(this, target, cfg, animationProps, true);
  6505. };
  6506. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6507. var animators = animateTo(this, target, cfg, animationProps);
  6508. for (var i = 0; i < animators.length; i++) {
  6509. animators[i].__fromStateTransition = stateName;
  6510. }
  6511. };
  6512. Element.prototype.getBoundingRect = function () {
  6513. return null;
  6514. };
  6515. Element.prototype.getPaintRect = function () {
  6516. return null;
  6517. };
  6518. Element.initDefaultProps = (function () {
  6519. var elProto = Element.prototype;
  6520. elProto.type = 'element';
  6521. elProto.name = '';
  6522. elProto.ignore =
  6523. elProto.silent =
  6524. elProto.isGroup =
  6525. elProto.draggable =
  6526. elProto.dragging =
  6527. elProto.ignoreClip =
  6528. elProto.__inHover = false;
  6529. elProto.__dirty = REDRAW_BIT;
  6530. var logs = {};
  6531. function logDeprecatedError(key, xKey, yKey) {
  6532. if (!logs[key + xKey + yKey]) {
  6533. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6534. logs[key + xKey + yKey] = true;
  6535. }
  6536. }
  6537. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6538. Object.defineProperty(elProto, key, {
  6539. get: function () {
  6540. if ("development" !== 'production') {
  6541. logDeprecatedError(key, xKey, yKey);
  6542. }
  6543. if (!this[privateKey]) {
  6544. var pos = this[privateKey] = [];
  6545. enhanceArray(this, pos);
  6546. }
  6547. return this[privateKey];
  6548. },
  6549. set: function (pos) {
  6550. if ("development" !== 'production') {
  6551. logDeprecatedError(key, xKey, yKey);
  6552. }
  6553. this[xKey] = pos[0];
  6554. this[yKey] = pos[1];
  6555. this[privateKey] = pos;
  6556. enhanceArray(this, pos);
  6557. }
  6558. });
  6559. function enhanceArray(self, pos) {
  6560. Object.defineProperty(pos, 0, {
  6561. get: function () {
  6562. return self[xKey];
  6563. },
  6564. set: function (val) {
  6565. self[xKey] = val;
  6566. }
  6567. });
  6568. Object.defineProperty(pos, 1, {
  6569. get: function () {
  6570. return self[yKey];
  6571. },
  6572. set: function (val) {
  6573. self[yKey] = val;
  6574. }
  6575. });
  6576. }
  6577. }
  6578. if (Object.defineProperty) {
  6579. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6580. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6581. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6582. }
  6583. })();
  6584. return Element;
  6585. }());
  6586. mixin(Element, Eventful);
  6587. mixin(Element, Transformable);
  6588. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6589. cfg = cfg || {};
  6590. var animators = [];
  6591. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6592. var finishCount = animators.length;
  6593. var doneHappened = false;
  6594. var cfgDone = cfg.done;
  6595. var cfgAborted = cfg.aborted;
  6596. var doneCb = function () {
  6597. doneHappened = true;
  6598. finishCount--;
  6599. if (finishCount <= 0) {
  6600. doneHappened
  6601. ? (cfgDone && cfgDone())
  6602. : (cfgAborted && cfgAborted());
  6603. }
  6604. };
  6605. var abortedCb = function () {
  6606. finishCount--;
  6607. if (finishCount <= 0) {
  6608. doneHappened
  6609. ? (cfgDone && cfgDone())
  6610. : (cfgAborted && cfgAborted());
  6611. }
  6612. };
  6613. if (!finishCount) {
  6614. cfgDone && cfgDone();
  6615. }
  6616. if (animators.length > 0 && cfg.during) {
  6617. animators[0].during(function (target, percent) {
  6618. cfg.during(percent);
  6619. });
  6620. }
  6621. for (var i = 0; i < animators.length; i++) {
  6622. var animator = animators[i];
  6623. if (doneCb) {
  6624. animator.done(doneCb);
  6625. }
  6626. if (abortedCb) {
  6627. animator.aborted(abortedCb);
  6628. }
  6629. if (cfg.force) {
  6630. animator.duration(cfg.duration);
  6631. }
  6632. animator.start(cfg.easing);
  6633. }
  6634. return animators;
  6635. }
  6636. function copyArrShallow(source, target, len) {
  6637. for (var i = 0; i < len; i++) {
  6638. source[i] = target[i];
  6639. }
  6640. }
  6641. function is2DArray(value) {
  6642. return isArrayLike(value[0]);
  6643. }
  6644. function copyValue(target, source, key) {
  6645. if (isArrayLike(source[key])) {
  6646. if (!isArrayLike(target[key])) {
  6647. target[key] = [];
  6648. }
  6649. if (isTypedArray(source[key])) {
  6650. var len = source[key].length;
  6651. if (target[key].length !== len) {
  6652. target[key] = new (source[key].constructor)(len);
  6653. copyArrShallow(target[key], source[key], len);
  6654. }
  6655. }
  6656. else {
  6657. var sourceArr = source[key];
  6658. var targetArr = target[key];
  6659. var len0 = sourceArr.length;
  6660. if (is2DArray(sourceArr)) {
  6661. var len1 = sourceArr[0].length;
  6662. for (var i = 0; i < len0; i++) {
  6663. if (!targetArr[i]) {
  6664. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6665. }
  6666. else {
  6667. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6668. }
  6669. }
  6670. }
  6671. else {
  6672. copyArrShallow(targetArr, sourceArr, len0);
  6673. }
  6674. targetArr.length = sourceArr.length;
  6675. }
  6676. }
  6677. else {
  6678. target[key] = source[key];
  6679. }
  6680. }
  6681. function isValueSame(val1, val2) {
  6682. return val1 === val2
  6683. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6684. }
  6685. function is1DArraySame(arr0, arr1) {
  6686. var len = arr0.length;
  6687. if (len !== arr1.length) {
  6688. return false;
  6689. }
  6690. for (var i = 0; i < len; i++) {
  6691. if (arr0[i] !== arr1[i]) {
  6692. return false;
  6693. }
  6694. }
  6695. return true;
  6696. }
  6697. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6698. var targetKeys = keys(target);
  6699. var duration = cfg.duration;
  6700. var delay = cfg.delay;
  6701. var additive = cfg.additive;
  6702. var setToFinal = cfg.setToFinal;
  6703. var animateAll = !isObject(animationProps);
  6704. var existsAnimators = animatable.animators;
  6705. var animationKeys = [];
  6706. for (var k = 0; k < targetKeys.length; k++) {
  6707. var innerKey = targetKeys[k];
  6708. var targetVal = target[innerKey];
  6709. if (targetVal != null && animateObj[innerKey] != null
  6710. && (animateAll || animationProps[innerKey])) {
  6711. if (isObject(targetVal)
  6712. && !isArrayLike(targetVal)
  6713. && !isGradientObject(targetVal)) {
  6714. if (topKey) {
  6715. if (!reverse) {
  6716. animateObj[innerKey] = targetVal;
  6717. animatable.updateDuringAnimation(topKey);
  6718. }
  6719. continue;
  6720. }
  6721. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6722. }
  6723. else {
  6724. animationKeys.push(innerKey);
  6725. }
  6726. }
  6727. else if (!reverse) {
  6728. animateObj[innerKey] = targetVal;
  6729. animatable.updateDuringAnimation(topKey);
  6730. animationKeys.push(innerKey);
  6731. }
  6732. }
  6733. var keyLen = animationKeys.length;
  6734. if (!additive && keyLen) {
  6735. for (var i = 0; i < existsAnimators.length; i++) {
  6736. var animator = existsAnimators[i];
  6737. if (animator.targetName === topKey) {
  6738. var allAborted = animator.stopTracks(animationKeys);
  6739. if (allAborted) {
  6740. var idx = indexOf(existsAnimators, animator);
  6741. existsAnimators.splice(idx, 1);
  6742. }
  6743. }
  6744. }
  6745. }
  6746. if (!cfg.force) {
  6747. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6748. keyLen = animationKeys.length;
  6749. }
  6750. if (keyLen > 0
  6751. || (cfg.force && !animators.length)) {
  6752. var revertedSource = void 0;
  6753. var reversedTarget = void 0;
  6754. var sourceClone = void 0;
  6755. if (reverse) {
  6756. reversedTarget = {};
  6757. if (setToFinal) {
  6758. revertedSource = {};
  6759. }
  6760. for (var i = 0; i < keyLen; i++) {
  6761. var innerKey = animationKeys[i];
  6762. reversedTarget[innerKey] = animateObj[innerKey];
  6763. if (setToFinal) {
  6764. revertedSource[innerKey] = target[innerKey];
  6765. }
  6766. else {
  6767. animateObj[innerKey] = target[innerKey];
  6768. }
  6769. }
  6770. }
  6771. else if (setToFinal) {
  6772. sourceClone = {};
  6773. for (var i = 0; i < keyLen; i++) {
  6774. var innerKey = animationKeys[i];
  6775. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6776. copyValue(animateObj, target, innerKey);
  6777. }
  6778. }
  6779. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6780. animator.targetName = topKey;
  6781. if (cfg.scope) {
  6782. animator.scope = cfg.scope;
  6783. }
  6784. if (setToFinal && revertedSource) {
  6785. animator.whenWithKeys(0, revertedSource, animationKeys);
  6786. }
  6787. if (sourceClone) {
  6788. animator.whenWithKeys(0, sourceClone, animationKeys);
  6789. }
  6790. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6791. animatable.addAnimator(animator, topKey);
  6792. animators.push(animator);
  6793. }
  6794. }
  6795. var Group = (function (_super) {
  6796. __extends(Group, _super);
  6797. function Group(opts) {
  6798. var _this = _super.call(this) || this;
  6799. _this.isGroup = true;
  6800. _this._children = [];
  6801. _this.attr(opts);
  6802. return _this;
  6803. }
  6804. Group.prototype.childrenRef = function () {
  6805. return this._children;
  6806. };
  6807. Group.prototype.children = function () {
  6808. return this._children.slice();
  6809. };
  6810. Group.prototype.childAt = function (idx) {
  6811. return this._children[idx];
  6812. };
  6813. Group.prototype.childOfName = function (name) {
  6814. var children = this._children;
  6815. for (var i = 0; i < children.length; i++) {
  6816. if (children[i].name === name) {
  6817. return children[i];
  6818. }
  6819. }
  6820. };
  6821. Group.prototype.childCount = function () {
  6822. return this._children.length;
  6823. };
  6824. Group.prototype.add = function (child) {
  6825. if (child) {
  6826. if (child !== this && child.parent !== this) {
  6827. this._children.push(child);
  6828. this._doAdd(child);
  6829. }
  6830. if ("development" !== 'production') {
  6831. if (child.__hostTarget) {
  6832. throw 'This elemenet has been used as an attachment';
  6833. }
  6834. }
  6835. }
  6836. return this;
  6837. };
  6838. Group.prototype.addBefore = function (child, nextSibling) {
  6839. if (child && child !== this && child.parent !== this
  6840. && nextSibling && nextSibling.parent === this) {
  6841. var children = this._children;
  6842. var idx = children.indexOf(nextSibling);
  6843. if (idx >= 0) {
  6844. children.splice(idx, 0, child);
  6845. this._doAdd(child);
  6846. }
  6847. }
  6848. return this;
  6849. };
  6850. Group.prototype.replace = function (oldChild, newChild) {
  6851. var idx = indexOf(this._children, oldChild);
  6852. if (idx >= 0) {
  6853. this.replaceAt(newChild, idx);
  6854. }
  6855. return this;
  6856. };
  6857. Group.prototype.replaceAt = function (child, index) {
  6858. var children = this._children;
  6859. var old = children[index];
  6860. if (child && child !== this && child.parent !== this && child !== old) {
  6861. children[index] = child;
  6862. old.parent = null;
  6863. var zr = this.__zr;
  6864. if (zr) {
  6865. old.removeSelfFromZr(zr);
  6866. }
  6867. this._doAdd(child);
  6868. }
  6869. return this;
  6870. };
  6871. Group.prototype._doAdd = function (child) {
  6872. if (child.parent) {
  6873. child.parent.remove(child);
  6874. }
  6875. child.parent = this;
  6876. var zr = this.__zr;
  6877. if (zr && zr !== child.__zr) {
  6878. child.addSelfToZr(zr);
  6879. }
  6880. zr && zr.refresh();
  6881. };
  6882. Group.prototype.remove = function (child) {
  6883. var zr = this.__zr;
  6884. var children = this._children;
  6885. var idx = indexOf(children, child);
  6886. if (idx < 0) {
  6887. return this;
  6888. }
  6889. children.splice(idx, 1);
  6890. child.parent = null;
  6891. if (zr) {
  6892. child.removeSelfFromZr(zr);
  6893. }
  6894. zr && zr.refresh();
  6895. return this;
  6896. };
  6897. Group.prototype.removeAll = function () {
  6898. var children = this._children;
  6899. var zr = this.__zr;
  6900. for (var i = 0; i < children.length; i++) {
  6901. var child = children[i];
  6902. if (zr) {
  6903. child.removeSelfFromZr(zr);
  6904. }
  6905. child.parent = null;
  6906. }
  6907. children.length = 0;
  6908. return this;
  6909. };
  6910. Group.prototype.eachChild = function (cb, context) {
  6911. var children = this._children;
  6912. for (var i = 0; i < children.length; i++) {
  6913. var child = children[i];
  6914. cb.call(context, child, i);
  6915. }
  6916. return this;
  6917. };
  6918. Group.prototype.traverse = function (cb, context) {
  6919. for (var i = 0; i < this._children.length; i++) {
  6920. var child = this._children[i];
  6921. var stopped = cb.call(context, child);
  6922. if (child.isGroup && !stopped) {
  6923. child.traverse(cb, context);
  6924. }
  6925. }
  6926. return this;
  6927. };
  6928. Group.prototype.addSelfToZr = function (zr) {
  6929. _super.prototype.addSelfToZr.call(this, zr);
  6930. for (var i = 0; i < this._children.length; i++) {
  6931. var child = this._children[i];
  6932. child.addSelfToZr(zr);
  6933. }
  6934. };
  6935. Group.prototype.removeSelfFromZr = function (zr) {
  6936. _super.prototype.removeSelfFromZr.call(this, zr);
  6937. for (var i = 0; i < this._children.length; i++) {
  6938. var child = this._children[i];
  6939. child.removeSelfFromZr(zr);
  6940. }
  6941. };
  6942. Group.prototype.getBoundingRect = function (includeChildren) {
  6943. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6944. var children = includeChildren || this._children;
  6945. var tmpMat = [];
  6946. var rect = null;
  6947. for (var i = 0; i < children.length; i++) {
  6948. var child = children[i];
  6949. if (child.ignore || child.invisible) {
  6950. continue;
  6951. }
  6952. var childRect = child.getBoundingRect();
  6953. var transform = child.getLocalTransform(tmpMat);
  6954. if (transform) {
  6955. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6956. rect = rect || tmpRect.clone();
  6957. rect.union(tmpRect);
  6958. }
  6959. else {
  6960. rect = rect || childRect.clone();
  6961. rect.union(childRect);
  6962. }
  6963. }
  6964. return rect || tmpRect;
  6965. };
  6966. return Group;
  6967. }(Element));
  6968. Group.prototype.type = 'group';
  6969. /*!
  6970. * ZRender, a high performance 2d drawing library.
  6971. *
  6972. * Copyright (c) 2013, Baidu Inc.
  6973. * All rights reserved.
  6974. *
  6975. * LICENSE
  6976. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6977. */
  6978. var painterCtors = {};
  6979. var instances = {};
  6980. function delInstance(id) {
  6981. delete instances[id];
  6982. }
  6983. function isDarkMode(backgroundColor) {
  6984. if (!backgroundColor) {
  6985. return false;
  6986. }
  6987. if (typeof backgroundColor === 'string') {
  6988. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6989. }
  6990. else if (backgroundColor.colorStops) {
  6991. var colorStops = backgroundColor.colorStops;
  6992. var totalLum = 0;
  6993. var len = colorStops.length;
  6994. for (var i = 0; i < len; i++) {
  6995. totalLum += lum(colorStops[i].color, 1);
  6996. }
  6997. totalLum /= len;
  6998. return totalLum < DARK_MODE_THRESHOLD;
  6999. }
  7000. return false;
  7001. }
  7002. var ZRender = (function () {
  7003. function ZRender(id, dom, opts) {
  7004. var _this = this;
  7005. this._sleepAfterStill = 10;
  7006. this._stillFrameAccum = 0;
  7007. this._needsRefresh = true;
  7008. this._needsRefreshHover = true;
  7009. this._darkMode = false;
  7010. opts = opts || {};
  7011. this.dom = dom;
  7012. this.id = id;
  7013. var storage = new Storage();
  7014. var rendererType = opts.renderer || 'canvas';
  7015. if (!painterCtors[rendererType]) {
  7016. rendererType = keys(painterCtors)[0];
  7017. }
  7018. if ("development" !== 'production') {
  7019. if (!painterCtors[rendererType]) {
  7020. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7021. }
  7022. }
  7023. opts.useDirtyRect = opts.useDirtyRect == null
  7024. ? false
  7025. : opts.useDirtyRect;
  7026. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7027. var ssrMode = opts.ssr || painter.ssrOnly;
  7028. this.storage = storage;
  7029. this.painter = painter;
  7030. var handerProxy = (!env.node && !env.worker && !ssrMode)
  7031. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7032. : null;
  7033. var useCoarsePointer = opts.useCoarsePointer;
  7034. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7035. ? env.touchEventsSupported
  7036. : !!useCoarsePointer;
  7037. var defaultPointerSize = 44;
  7038. var pointerSize;
  7039. if (usePointerSize) {
  7040. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7041. }
  7042. this.handler = new Handler(storage, painter, handerProxy, painter.root, pointerSize);
  7043. this.animation = new Animation({
  7044. stage: {
  7045. update: ssrMode ? null : function () { return _this._flush(true); }
  7046. }
  7047. });
  7048. if (!ssrMode) {
  7049. this.animation.start();
  7050. }
  7051. }
  7052. ZRender.prototype.add = function (el) {
  7053. if (!el) {
  7054. return;
  7055. }
  7056. this.storage.addRoot(el);
  7057. el.addSelfToZr(this);
  7058. this.refresh();
  7059. };
  7060. ZRender.prototype.remove = function (el) {
  7061. if (!el) {
  7062. return;
  7063. }
  7064. this.storage.delRoot(el);
  7065. el.removeSelfFromZr(this);
  7066. this.refresh();
  7067. };
  7068. ZRender.prototype.configLayer = function (zLevel, config) {
  7069. if (this.painter.configLayer) {
  7070. this.painter.configLayer(zLevel, config);
  7071. }
  7072. this.refresh();
  7073. };
  7074. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7075. if (this.painter.setBackgroundColor) {
  7076. this.painter.setBackgroundColor(backgroundColor);
  7077. }
  7078. this.refresh();
  7079. this._backgroundColor = backgroundColor;
  7080. this._darkMode = isDarkMode(backgroundColor);
  7081. };
  7082. ZRender.prototype.getBackgroundColor = function () {
  7083. return this._backgroundColor;
  7084. };
  7085. ZRender.prototype.setDarkMode = function (darkMode) {
  7086. this._darkMode = darkMode;
  7087. };
  7088. ZRender.prototype.isDarkMode = function () {
  7089. return this._darkMode;
  7090. };
  7091. ZRender.prototype.refreshImmediately = function (fromInside) {
  7092. if (!fromInside) {
  7093. this.animation.update(true);
  7094. }
  7095. this._needsRefresh = false;
  7096. this.painter.refresh();
  7097. this._needsRefresh = false;
  7098. };
  7099. ZRender.prototype.refresh = function () {
  7100. this._needsRefresh = true;
  7101. this.animation.start();
  7102. };
  7103. ZRender.prototype.flush = function () {
  7104. this._flush(false);
  7105. };
  7106. ZRender.prototype._flush = function (fromInside) {
  7107. var triggerRendered;
  7108. var start = getTime();
  7109. if (this._needsRefresh) {
  7110. triggerRendered = true;
  7111. this.refreshImmediately(fromInside);
  7112. }
  7113. if (this._needsRefreshHover) {
  7114. triggerRendered = true;
  7115. this.refreshHoverImmediately();
  7116. }
  7117. var end = getTime();
  7118. if (triggerRendered) {
  7119. this._stillFrameAccum = 0;
  7120. this.trigger('rendered', {
  7121. elapsedTime: end - start
  7122. });
  7123. }
  7124. else if (this._sleepAfterStill > 0) {
  7125. this._stillFrameAccum++;
  7126. if (this._stillFrameAccum > this._sleepAfterStill) {
  7127. this.animation.stop();
  7128. }
  7129. }
  7130. };
  7131. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7132. this._sleepAfterStill = stillFramesCount;
  7133. };
  7134. ZRender.prototype.wakeUp = function () {
  7135. this.animation.start();
  7136. this._stillFrameAccum = 0;
  7137. };
  7138. ZRender.prototype.refreshHover = function () {
  7139. this._needsRefreshHover = true;
  7140. };
  7141. ZRender.prototype.refreshHoverImmediately = function () {
  7142. this._needsRefreshHover = false;
  7143. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7144. this.painter.refreshHover();
  7145. }
  7146. };
  7147. ZRender.prototype.resize = function (opts) {
  7148. opts = opts || {};
  7149. this.painter.resize(opts.width, opts.height);
  7150. this.handler.resize();
  7151. };
  7152. ZRender.prototype.clearAnimation = function () {
  7153. this.animation.clear();
  7154. };
  7155. ZRender.prototype.getWidth = function () {
  7156. return this.painter.getWidth();
  7157. };
  7158. ZRender.prototype.getHeight = function () {
  7159. return this.painter.getHeight();
  7160. };
  7161. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7162. this.handler.setCursorStyle(cursorStyle);
  7163. };
  7164. ZRender.prototype.findHover = function (x, y) {
  7165. return this.handler.findHover(x, y);
  7166. };
  7167. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7168. this.handler.on(eventName, eventHandler, context);
  7169. return this;
  7170. };
  7171. ZRender.prototype.off = function (eventName, eventHandler) {
  7172. this.handler.off(eventName, eventHandler);
  7173. };
  7174. ZRender.prototype.trigger = function (eventName, event) {
  7175. this.handler.trigger(eventName, event);
  7176. };
  7177. ZRender.prototype.clear = function () {
  7178. var roots = this.storage.getRoots();
  7179. for (var i = 0; i < roots.length; i++) {
  7180. if (roots[i] instanceof Group) {
  7181. roots[i].removeSelfFromZr(this);
  7182. }
  7183. }
  7184. this.storage.delAllRoots();
  7185. this.painter.clear();
  7186. };
  7187. ZRender.prototype.dispose = function () {
  7188. this.animation.stop();
  7189. this.clear();
  7190. this.storage.dispose();
  7191. this.painter.dispose();
  7192. this.handler.dispose();
  7193. this.animation =
  7194. this.storage =
  7195. this.painter =
  7196. this.handler = null;
  7197. delInstance(this.id);
  7198. };
  7199. return ZRender;
  7200. }());
  7201. function init(dom, opts) {
  7202. var zr = new ZRender(guid(), dom, opts);
  7203. instances[zr.id] = zr;
  7204. return zr;
  7205. }
  7206. function dispose(zr) {
  7207. zr.dispose();
  7208. }
  7209. function disposeAll() {
  7210. for (var key in instances) {
  7211. if (instances.hasOwnProperty(key)) {
  7212. instances[key].dispose();
  7213. }
  7214. }
  7215. instances = {};
  7216. }
  7217. function getInstance(id) {
  7218. return instances[id];
  7219. }
  7220. function registerPainter(name, Ctor) {
  7221. painterCtors[name] = Ctor;
  7222. }
  7223. var version = '5.4.3';
  7224. var zrender = /*#__PURE__*/Object.freeze({
  7225. __proto__: null,
  7226. init: init,
  7227. dispose: dispose,
  7228. disposeAll: disposeAll,
  7229. getInstance: getInstance,
  7230. registerPainter: registerPainter,
  7231. version: version
  7232. });
  7233. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  7234. // we sill follow the spec for compatibility.
  7235. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7236. function _trim(str) {
  7237. return str.replace(/^\s+|\s+$/g, '');
  7238. }
  7239. /**
  7240. * Linear mapping a value from domain to range
  7241. * @param val
  7242. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7243. * @param range Range extent range[0] can be bigger than range[1]
  7244. * @param clamp Default to be false
  7245. */
  7246. function linearMap(val, domain, range, clamp) {
  7247. var d0 = domain[0];
  7248. var d1 = domain[1];
  7249. var r0 = range[0];
  7250. var r1 = range[1];
  7251. var subDomain = d1 - d0;
  7252. var subRange = r1 - r0;
  7253. if (subDomain === 0) {
  7254. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7255. } // Avoid accuracy problem in edge, such as
  7256. // 146.39 - 62.83 === 83.55999999999999.
  7257. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7258. // It is a little verbose for efficiency considering this method
  7259. // is a hotspot.
  7260. if (clamp) {
  7261. if (subDomain > 0) {
  7262. if (val <= d0) {
  7263. return r0;
  7264. } else if (val >= d1) {
  7265. return r1;
  7266. }
  7267. } else {
  7268. if (val >= d0) {
  7269. return r0;
  7270. } else if (val <= d1) {
  7271. return r1;
  7272. }
  7273. }
  7274. } else {
  7275. if (val === d0) {
  7276. return r0;
  7277. }
  7278. if (val === d1) {
  7279. return r1;
  7280. }
  7281. }
  7282. return (val - d0) / subDomain * subRange + r0;
  7283. }
  7284. /**
  7285. * Convert a percent string to absolute number.
  7286. * Returns NaN if percent is not a valid string or number
  7287. */
  7288. function parsePercent$1(percent, all) {
  7289. switch (percent) {
  7290. case 'center':
  7291. case 'middle':
  7292. percent = '50%';
  7293. break;
  7294. case 'left':
  7295. case 'top':
  7296. percent = '0%';
  7297. break;
  7298. case 'right':
  7299. case 'bottom':
  7300. percent = '100%';
  7301. break;
  7302. }
  7303. if (isString(percent)) {
  7304. if (_trim(percent).match(/%$/)) {
  7305. return parseFloat(percent) / 100 * all;
  7306. }
  7307. return parseFloat(percent);
  7308. }
  7309. return percent == null ? NaN : +percent;
  7310. }
  7311. function round(x, precision, returnStr) {
  7312. if (precision == null) {
  7313. precision = 10;
  7314. } // Avoid range error
  7315. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7316. x = (+x).toFixed(precision);
  7317. return returnStr ? x : +x;
  7318. }
  7319. /**
  7320. * Inplacd asc sort arr.
  7321. * The input arr will be modified.
  7322. */
  7323. function asc(arr) {
  7324. arr.sort(function (a, b) {
  7325. return a - b;
  7326. });
  7327. return arr;
  7328. }
  7329. /**
  7330. * Get precision.
  7331. */
  7332. function getPrecision(val) {
  7333. val = +val;
  7334. if (isNaN(val)) {
  7335. return 0;
  7336. } // It is much faster than methods converting number to string as follows
  7337. // let tmp = val.toString();
  7338. // return tmp.length - 1 - tmp.indexOf('.');
  7339. // especially when precision is low
  7340. // Notice:
  7341. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7342. // (see https://jsbench.me/2vkpcekkvw/1)
  7343. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7344. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7345. if (val > 1e-14) {
  7346. var e = 1;
  7347. for (var i = 0; i < 15; i++, e *= 10) {
  7348. if (Math.round(val * e) / e === val) {
  7349. return i;
  7350. }
  7351. }
  7352. }
  7353. return getPrecisionSafe(val);
  7354. }
  7355. /**
  7356. * Get precision with slow but safe method
  7357. */
  7358. function getPrecisionSafe(val) {
  7359. // toLowerCase for: '3.4E-12'
  7360. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  7361. var eIndex = str.indexOf('e');
  7362. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7363. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7364. var dotIndex = str.indexOf('.');
  7365. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7366. return Math.max(0, decimalPartLen - exp);
  7367. }
  7368. /**
  7369. * Minimal dicernible data precisioin according to a single pixel.
  7370. */
  7371. function getPixelPrecision(dataExtent, pixelExtent) {
  7372. var log = Math.log;
  7373. var LN10 = Math.LN10;
  7374. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7375. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  7376. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7377. return !isFinite(precision) ? 20 : precision;
  7378. }
  7379. /**
  7380. * Get a data of given precision, assuring the sum of percentages
  7381. * in valueList is 1.
  7382. * The largest remainder method is used.
  7383. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7384. *
  7385. * @param valueList a list of all data
  7386. * @param idx index of the data to be processed in valueList
  7387. * @param precision integer number showing digits of precision
  7388. * @return percent ranging from 0 to 100
  7389. */
  7390. function getPercentWithPrecision(valueList, idx, precision) {
  7391. if (!valueList[idx]) {
  7392. return 0;
  7393. }
  7394. var seats = getPercentSeats(valueList, precision);
  7395. return seats[idx] || 0;
  7396. }
  7397. /**
  7398. * Get a data of given precision, assuring the sum of percentages
  7399. * in valueList is 1.
  7400. * The largest remainder method is used.
  7401. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7402. *
  7403. * @param valueList a list of all data
  7404. * @param precision integer number showing digits of precision
  7405. * @return {Array<number>}
  7406. */
  7407. function getPercentSeats(valueList, precision) {
  7408. var sum = reduce(valueList, function (acc, val) {
  7409. return acc + (isNaN(val) ? 0 : val);
  7410. }, 0);
  7411. if (sum === 0) {
  7412. return [];
  7413. }
  7414. var digits = Math.pow(10, precision);
  7415. var votesPerQuota = map(valueList, function (val) {
  7416. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7417. });
  7418. var targetSeats = digits * 100;
  7419. var seats = map(votesPerQuota, function (votes) {
  7420. // Assign automatic seats.
  7421. return Math.floor(votes);
  7422. });
  7423. var currentSum = reduce(seats, function (acc, val) {
  7424. return acc + val;
  7425. }, 0);
  7426. var remainder = map(votesPerQuota, function (votes, idx) {
  7427. return votes - seats[idx];
  7428. }); // Has remainding votes.
  7429. while (currentSum < targetSeats) {
  7430. // Find next largest remainder.
  7431. var max = Number.NEGATIVE_INFINITY;
  7432. var maxId = null;
  7433. for (var i = 0, len = remainder.length; i < len; ++i) {
  7434. if (remainder[i] > max) {
  7435. max = remainder[i];
  7436. maxId = i;
  7437. }
  7438. } // Add a vote to max remainder.
  7439. ++seats[maxId];
  7440. remainder[maxId] = 0;
  7441. ++currentSum;
  7442. }
  7443. return map(seats, function (seat) {
  7444. return seat / digits;
  7445. });
  7446. }
  7447. /**
  7448. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7449. * See <http://0.30000000000000004.com/>
  7450. */
  7451. function addSafe(val0, val1) {
  7452. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  7453. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7454. var sum = val0 + val1; // // PENDING: support more?
  7455. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7456. } // Number.MAX_SAFE_INTEGER, ie do not support.
  7457. var MAX_SAFE_INTEGER = 9007199254740991;
  7458. /**
  7459. * To 0 - 2 * PI, considering negative radian.
  7460. */
  7461. function remRadian(radian) {
  7462. var pi2 = Math.PI * 2;
  7463. return (radian % pi2 + pi2) % pi2;
  7464. }
  7465. /**
  7466. * @param {type} radian
  7467. * @return {boolean}
  7468. */
  7469. function isRadianAroundZero(val) {
  7470. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7471. } // eslint-disable-next-line
  7472. 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
  7473. /**
  7474. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7475. * These values can be accepted:
  7476. * + An instance of Date, represent a time in its own time zone.
  7477. * + Or string in a subset of ISO 8601, only including:
  7478. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7479. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7480. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7481. * all of which will be treated as local time if time zone is not specified
  7482. * (see <https://momentjs.com/>).
  7483. * + Or other string format, including (all of which will be treated as local time):
  7484. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7485. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7486. * + a timestamp, which represent a time in UTC.
  7487. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7488. */
  7489. function parseDate(value) {
  7490. if (value instanceof Date) {
  7491. return value;
  7492. } else if (isString(value)) {
  7493. // Different browsers parse date in different way, so we parse it manually.
  7494. // Some other issues:
  7495. // new Date('1970-01-01') is UTC,
  7496. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7497. // See issue #3623
  7498. var match = TIME_REG.exec(value);
  7499. if (!match) {
  7500. // return Invalid Date.
  7501. return new Date(NaN);
  7502. } // Use local time when no timezone offset is specified.
  7503. if (!match[8]) {
  7504. // match[n] can only be string or undefined.
  7505. // But take care of '12' + 1 => '121'.
  7506. 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);
  7507. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7508. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7509. // For example, system timezone is set as "Time Zone: America/Toronto",
  7510. // then these code will get different result:
  7511. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7512. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7513. // So we should not use `new Date`, but use `Date.UTC`.
  7514. else {
  7515. var hour = +match[4] || 0;
  7516. if (match[8].toUpperCase() !== 'Z') {
  7517. hour -= +match[8].slice(0, 3);
  7518. }
  7519. 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));
  7520. }
  7521. } else if (value == null) {
  7522. return new Date(NaN);
  7523. }
  7524. return new Date(Math.round(value));
  7525. }
  7526. /**
  7527. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7528. *
  7529. * @param val
  7530. * @return
  7531. */
  7532. function quantity(val) {
  7533. return Math.pow(10, quantityExponent(val));
  7534. }
  7535. /**
  7536. * Exponent of the quantity of a number
  7537. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7538. *
  7539. * @param val non-negative value
  7540. * @return
  7541. */
  7542. function quantityExponent(val) {
  7543. if (val === 0) {
  7544. return 0;
  7545. }
  7546. var exp = Math.floor(Math.log(val) / Math.LN10);
  7547. /**
  7548. * exp is expected to be the rounded-down result of the base-10 log of val.
  7549. * But due to the precision loss with Math.log(val), we need to restore it
  7550. * using 10^exp to make sure we can get val back from exp. #11249
  7551. */
  7552. if (val / Math.pow(10, exp) >= 10) {
  7553. exp++;
  7554. }
  7555. return exp;
  7556. }
  7557. /**
  7558. * find a “nice” number approximately equal to x. Round the number if round = true,
  7559. * take ceiling if round = false. The primary observation is that the “nicest”
  7560. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7561. *
  7562. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7563. *
  7564. * @param val Non-negative value.
  7565. * @param round
  7566. * @return Niced number
  7567. */
  7568. function nice(val, round) {
  7569. var exponent = quantityExponent(val);
  7570. var exp10 = Math.pow(10, exponent);
  7571. var f = val / exp10; // 1 <= f < 10
  7572. var nf;
  7573. if (round) {
  7574. if (f < 1.5) {
  7575. nf = 1;
  7576. } else if (f < 2.5) {
  7577. nf = 2;
  7578. } else if (f < 4) {
  7579. nf = 3;
  7580. } else if (f < 7) {
  7581. nf = 5;
  7582. } else {
  7583. nf = 10;
  7584. }
  7585. } else {
  7586. if (f < 1) {
  7587. nf = 1;
  7588. } else if (f < 2) {
  7589. nf = 2;
  7590. } else if (f < 3) {
  7591. nf = 3;
  7592. } else if (f < 5) {
  7593. nf = 5;
  7594. } else {
  7595. nf = 10;
  7596. }
  7597. }
  7598. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7599. // 20 is the uppper bound of toFixed.
  7600. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7601. }
  7602. /**
  7603. * This code was copied from "d3.js"
  7604. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7605. * See the license statement at the head of this file.
  7606. * @param ascArr
  7607. */
  7608. function quantile(ascArr, p) {
  7609. var H = (ascArr.length - 1) * p + 1;
  7610. var h = Math.floor(H);
  7611. var v = +ascArr[h - 1];
  7612. var e = H - h;
  7613. return e ? v + e * (ascArr[h] - v) : v;
  7614. }
  7615. /**
  7616. * Order intervals asc, and split them when overlap.
  7617. * expect(numberUtil.reformIntervals([
  7618. * {interval: [18, 62], close: [1, 1]},
  7619. * {interval: [-Infinity, -70], close: [0, 0]},
  7620. * {interval: [-70, -26], close: [1, 1]},
  7621. * {interval: [-26, 18], close: [1, 1]},
  7622. * {interval: [62, 150], close: [1, 1]},
  7623. * {interval: [106, 150], close: [1, 1]},
  7624. * {interval: [150, Infinity], close: [0, 0]}
  7625. * ])).toEqual([
  7626. * {interval: [-Infinity, -70], close: [0, 0]},
  7627. * {interval: [-70, -26], close: [1, 1]},
  7628. * {interval: [-26, 18], close: [0, 1]},
  7629. * {interval: [18, 62], close: [0, 1]},
  7630. * {interval: [62, 150], close: [0, 1]},
  7631. * {interval: [150, Infinity], close: [0, 0]}
  7632. * ]);
  7633. * @param list, where `close` mean open or close
  7634. * of the interval, and Infinity can be used.
  7635. * @return The origin list, which has been reformed.
  7636. */
  7637. function reformIntervals(list) {
  7638. list.sort(function (a, b) {
  7639. return littleThan(a, b, 0) ? -1 : 1;
  7640. });
  7641. var curr = -Infinity;
  7642. var currClose = 1;
  7643. for (var i = 0; i < list.length;) {
  7644. var interval = list[i].interval;
  7645. var close_1 = list[i].close;
  7646. for (var lg = 0; lg < 2; lg++) {
  7647. if (interval[lg] <= curr) {
  7648. interval[lg] = curr;
  7649. close_1[lg] = !lg ? 1 - currClose : 1;
  7650. }
  7651. curr = interval[lg];
  7652. currClose = close_1[lg];
  7653. }
  7654. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7655. list.splice(i, 1);
  7656. } else {
  7657. i++;
  7658. }
  7659. }
  7660. return list;
  7661. function littleThan(a, b, lg) {
  7662. 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));
  7663. }
  7664. }
  7665. /**
  7666. * [Numeric is defined as]:
  7667. * `parseFloat(val) == val`
  7668. * For example:
  7669. * numeric:
  7670. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7671. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7672. * not-numeric:
  7673. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7674. * empty string, string with only white-spaces or line-terminal (see es spec),
  7675. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7676. * non-string, ...
  7677. *
  7678. * @test See full test cases in `test/ut/spec/util/number.js`.
  7679. * @return Must be a typeof number. If not numeric, return NaN.
  7680. */
  7681. function numericToNumber(val) {
  7682. var valFloat = parseFloat(val);
  7683. return valFloat == val // eslint-disable-line eqeqeq
  7684. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7685. ? valFloat : NaN;
  7686. }
  7687. /**
  7688. * Definition of "numeric": see `numericToNumber`.
  7689. */
  7690. function isNumeric(val) {
  7691. return !isNaN(numericToNumber(val));
  7692. }
  7693. /**
  7694. * Use random base to prevent users hard code depending on
  7695. * this auto generated marker id.
  7696. * @return An positive integer.
  7697. */
  7698. function getRandomIdBase() {
  7699. return Math.round(Math.random() * 9);
  7700. }
  7701. /**
  7702. * Get the greatest common divisor.
  7703. *
  7704. * @param {number} a one number
  7705. * @param {number} b the other number
  7706. */
  7707. function getGreatestCommonDividor(a, b) {
  7708. if (b === 0) {
  7709. return a;
  7710. }
  7711. return getGreatestCommonDividor(b, a % b);
  7712. }
  7713. /**
  7714. * Get the least common multiple.
  7715. *
  7716. * @param {number} a one number
  7717. * @param {number} b the other number
  7718. */
  7719. function getLeastCommonMultiple(a, b) {
  7720. if (a == null) {
  7721. return b;
  7722. }
  7723. if (b == null) {
  7724. return a;
  7725. }
  7726. return a * b / getGreatestCommonDividor(a, b);
  7727. }
  7728. var ECHARTS_PREFIX = '[ECharts] ';
  7729. var storedLogs = {};
  7730. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7731. && console.warn && console.log;
  7732. function outputLog(type, str, onlyOnce) {
  7733. if (hasConsole) {
  7734. if (onlyOnce) {
  7735. if (storedLogs[str]) {
  7736. return;
  7737. }
  7738. storedLogs[str] = true;
  7739. } // eslint-disable-next-line
  7740. console[type](ECHARTS_PREFIX + str);
  7741. }
  7742. }
  7743. function log(str, onlyOnce) {
  7744. outputLog('log', str, onlyOnce);
  7745. }
  7746. function warn(str, onlyOnce) {
  7747. outputLog('warn', str, onlyOnce);
  7748. }
  7749. function error(str, onlyOnce) {
  7750. outputLog('error', str, onlyOnce);
  7751. }
  7752. function deprecateLog(str) {
  7753. if ("development" !== 'production') {
  7754. // Not display duplicate message.
  7755. outputLog('warn', 'DEPRECATED: ' + str, true);
  7756. }
  7757. }
  7758. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7759. if ("development" !== 'production') {
  7760. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7761. }
  7762. }
  7763. /**
  7764. * If in __DEV__ environment, get console printable message for users hint.
  7765. * Parameters are separated by ' '.
  7766. * @usage
  7767. * makePrintable('This is an error on', someVar, someObj);
  7768. *
  7769. * @param hintInfo anything about the current execution context to hint users.
  7770. * @throws Error
  7771. */
  7772. function makePrintable() {
  7773. var hintInfo = [];
  7774. for (var _i = 0; _i < arguments.length; _i++) {
  7775. hintInfo[_i] = arguments[_i];
  7776. }
  7777. var msg = '';
  7778. if ("development" !== 'production') {
  7779. // Fuzzy stringify for print.
  7780. // This code only exist in dev environment.
  7781. var makePrintableStringIfPossible_1 = function (val) {
  7782. 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;
  7783. };
  7784. msg = map(hintInfo, function (arg) {
  7785. if (isString(arg)) {
  7786. // Print without quotation mark for some statement.
  7787. return arg;
  7788. } else {
  7789. var printableStr = makePrintableStringIfPossible_1(arg);
  7790. if (printableStr != null) {
  7791. return printableStr;
  7792. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7793. try {
  7794. return JSON.stringify(arg, function (n, val) {
  7795. var printableStr = makePrintableStringIfPossible_1(val);
  7796. return printableStr == null ? val : printableStr;
  7797. }); // In most cases the info object is small, so do not line break.
  7798. } catch (err) {
  7799. return '?';
  7800. }
  7801. } else {
  7802. return '?';
  7803. }
  7804. }
  7805. }).join(' ');
  7806. }
  7807. return msg;
  7808. }
  7809. /**
  7810. * @throws Error
  7811. */
  7812. function throwError(msg) {
  7813. throw new Error(msg);
  7814. }
  7815. function interpolateNumber$1(p0, p1, percent) {
  7816. return (p1 - p0) * percent + p0;
  7817. }
  7818. /**
  7819. * Make the name displayable. But we should
  7820. * make sure it is not duplicated with user
  7821. * specified name, so use '\0';
  7822. */
  7823. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7824. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7825. /**
  7826. * If value is not array, then translate it to array.
  7827. * @param {*} value
  7828. * @return {Array} [value] or value
  7829. */
  7830. function normalizeToArray(value) {
  7831. return value instanceof Array ? value : value == null ? [] : [value];
  7832. }
  7833. /**
  7834. * Sync default option between normal and emphasis like `position` and `show`
  7835. * In case some one will write code like
  7836. * label: {
  7837. * show: false,
  7838. * position: 'outside',
  7839. * fontSize: 18
  7840. * },
  7841. * emphasis: {
  7842. * label: { show: true }
  7843. * }
  7844. */
  7845. function defaultEmphasis(opt, key, subOpts) {
  7846. // Caution: performance sensitive.
  7847. if (opt) {
  7848. opt[key] = opt[key] || {};
  7849. opt.emphasis = opt.emphasis || {};
  7850. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7851. for (var i = 0, len = subOpts.length; i < len; i++) {
  7852. var subOptName = subOpts[i];
  7853. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7854. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7855. }
  7856. }
  7857. }
  7858. }
  7859. var TEXT_STYLE_OPTIONS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7860. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7861. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7862. // // FIXME: deprecated, check and remove it.
  7863. // 'textStyle'
  7864. // ]);
  7865. /**
  7866. * The method does not ensure performance.
  7867. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7868. * This helper method retrieves value from data.
  7869. */
  7870. function getDataItemValue(dataItem) {
  7871. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7872. }
  7873. /**
  7874. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7875. * This helper method determine if dataItem has extra option besides value
  7876. */
  7877. function isDataItemOption(dataItem) {
  7878. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7879. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7880. }
  7881. /**
  7882. * Mapping to existings for merge.
  7883. *
  7884. * Mode "normalMege":
  7885. * The mapping result (merge result) will keep the order of the existing
  7886. * component, rather than the order of new option. Because we should ensure
  7887. * some specified index reference (like xAxisIndex) keep work.
  7888. * And in most cases, "merge option" is used to update partial option but not
  7889. * be expected to change the order.
  7890. *
  7891. * Mode "replaceMege":
  7892. * (1) Only the id mapped components will be merged.
  7893. * (2) Other existing components (except internal components) will be removed.
  7894. * (3) Other new options will be used to create new component.
  7895. * (4) The index of the existing components will not be modified.
  7896. * That means their might be "hole" after the removal.
  7897. * The new components are created first at those available index.
  7898. *
  7899. * Mode "replaceAll":
  7900. * This mode try to support that reproduce an echarts instance from another
  7901. * echarts instance (via `getOption`) in some simple cases.
  7902. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7903. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  7904. * the "hole" in `newCmptOptions` will also be kept.
  7905. * On the contrary, other modes try best to eliminate holes.
  7906. * PENDING: This is an experimental mode yet.
  7907. *
  7908. * @return See the comment of <MappingResult>.
  7909. */
  7910. function mappingToExists(existings, newCmptOptions, mode) {
  7911. var isNormalMergeMode = mode === 'normalMerge';
  7912. var isReplaceMergeMode = mode === 'replaceMerge';
  7913. var isReplaceAllMode = mode === 'replaceAll';
  7914. existings = existings || [];
  7915. newCmptOptions = (newCmptOptions || []).slice();
  7916. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7917. each(newCmptOptions, function (cmptOption, index) {
  7918. if (!isObject(cmptOption)) {
  7919. newCmptOptions[index] = null;
  7920. return;
  7921. }
  7922. if ("development" !== 'production') {
  7923. // There is some legacy case that name is set as `false`.
  7924. // But should work normally rather than throw error.
  7925. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7926. warnInvalidateIdOrName(cmptOption.id);
  7927. }
  7928. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7929. warnInvalidateIdOrName(cmptOption.name);
  7930. }
  7931. }
  7932. });
  7933. var result = prepareResult(existings, existingIdIdxMap, mode);
  7934. if (isNormalMergeMode || isReplaceMergeMode) {
  7935. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7936. }
  7937. if (isNormalMergeMode) {
  7938. mappingByName(result, newCmptOptions);
  7939. }
  7940. if (isNormalMergeMode || isReplaceMergeMode) {
  7941. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7942. } else if (isReplaceAllMode) {
  7943. mappingInReplaceAllMode(result, newCmptOptions);
  7944. }
  7945. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7946. // forEach will omit those items and result in incorrect result.
  7947. return result;
  7948. }
  7949. function prepareResult(existings, existingIdIdxMap, mode) {
  7950. var result = [];
  7951. if (mode === 'replaceAll') {
  7952. return result;
  7953. } // Do not use native `map` to in case that the array `existings`
  7954. // contains elided items, which will be omitted.
  7955. for (var index = 0; index < existings.length; index++) {
  7956. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7957. if (existing && existing.id != null) {
  7958. existingIdIdxMap.set(existing.id, index);
  7959. } // For non-internal-componnets:
  7960. // Mode "normalMerge": all existings kept.
  7961. // Mode "replaceMerge": all existing removed unless mapped by id.
  7962. // For internal-components:
  7963. // go with "replaceMerge" approach in both mode.
  7964. result.push({
  7965. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7966. newOption: null,
  7967. keyInfo: null,
  7968. brandNew: null
  7969. });
  7970. }
  7971. return result;
  7972. }
  7973. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7974. // Mapping by id if specified.
  7975. each(newCmptOptions, function (cmptOption, index) {
  7976. if (!cmptOption || cmptOption.id == null) {
  7977. return;
  7978. }
  7979. var optionId = makeComparableKey(cmptOption.id);
  7980. var existingIdx = existingIdIdxMap.get(optionId);
  7981. if (existingIdx != null) {
  7982. var resultItem = result[existingIdx];
  7983. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7984. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7985. // the existings rather than creating new component model.
  7986. resultItem.existing = existings[existingIdx];
  7987. newCmptOptions[index] = null;
  7988. }
  7989. });
  7990. }
  7991. function mappingByName(result, newCmptOptions) {
  7992. // Mapping by name if specified.
  7993. each(newCmptOptions, function (cmptOption, index) {
  7994. if (!cmptOption || cmptOption.name == null) {
  7995. return;
  7996. }
  7997. for (var i = 0; i < result.length; i++) {
  7998. var existing = result[i].existing;
  7999. if (!result[i].newOption // Consider name: two map to one.
  8000. // Can not match when both ids existing but different.
  8001. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8002. result[i].newOption = cmptOption;
  8003. newCmptOptions[index] = null;
  8004. return;
  8005. }
  8006. }
  8007. });
  8008. }
  8009. function mappingByIndex(result, newCmptOptions, brandNew) {
  8010. each(newCmptOptions, function (cmptOption) {
  8011. if (!cmptOption) {
  8012. return;
  8013. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  8014. var resultItem;
  8015. var nextIdx = 0;
  8016. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  8017. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  8018. // after mapping performed, model will always be assigned with an id if user not given.
  8019. // After that all models have id.
  8020. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8021. // not be merged to the existings with different id. Because id should not be overwritten.
  8022. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8023. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8024. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8025. nextIdx++;
  8026. }
  8027. if (resultItem) {
  8028. resultItem.newOption = cmptOption;
  8029. resultItem.brandNew = brandNew;
  8030. } else {
  8031. result.push({
  8032. newOption: cmptOption,
  8033. brandNew: brandNew,
  8034. existing: null,
  8035. keyInfo: null
  8036. });
  8037. }
  8038. nextIdx++;
  8039. });
  8040. }
  8041. function mappingInReplaceAllMode(result, newCmptOptions) {
  8042. each(newCmptOptions, function (cmptOption) {
  8043. // The feature "reproduce" requires "hole" will also reproduced
  8044. // in case that component index referring are broken.
  8045. result.push({
  8046. newOption: cmptOption,
  8047. brandNew: true,
  8048. existing: null,
  8049. keyInfo: null
  8050. });
  8051. });
  8052. }
  8053. /**
  8054. * Make id and name for mapping result (result of mappingToExists)
  8055. * into `keyInfo` field.
  8056. */
  8057. function makeIdAndName(mapResult) {
  8058. // We use this id to hash component models and view instances
  8059. // in echarts. id can be specified by user, or auto generated.
  8060. // The id generation rule ensures new view instance are able
  8061. // to mapped to old instance when setOption are called in
  8062. // no-merge mode. So we generate model id by name and plus
  8063. // type in view id.
  8064. // name can be duplicated among components, which is convenient
  8065. // to specify multi components (like series) by one name.
  8066. // Ensure that each id is distinct.
  8067. var idMap = createHashMap();
  8068. each(mapResult, function (item) {
  8069. var existing = item.existing;
  8070. existing && idMap.set(existing.id, item);
  8071. });
  8072. each(mapResult, function (item) {
  8073. var opt = item.newOption; // Force ensure id not duplicated.
  8074. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8075. opt && opt.id != null && idMap.set(opt.id, item);
  8076. !item.keyInfo && (item.keyInfo = {});
  8077. }); // Make name and id.
  8078. each(mapResult, function (item, index) {
  8079. var existing = item.existing;
  8080. var opt = item.newOption;
  8081. var keyInfo = item.keyInfo;
  8082. if (!isObject(opt)) {
  8083. return;
  8084. } // Name can be overwritten. Consider case: axis.name = '20km'.
  8085. // But id generated by name will not be changed, which affect
  8086. // only in that case: setOption with 'not merge mode' and view
  8087. // instance will be recreated, which can be accepted.
  8088. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid that different series has the same name,
  8089. // because name may be used like in color pallet.
  8090. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8091. if (existing) {
  8092. keyInfo.id = makeComparableKey(existing.id);
  8093. } else if (opt.id != null) {
  8094. keyInfo.id = makeComparableKey(opt.id);
  8095. } else {
  8096. // Consider this situatoin:
  8097. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8098. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8099. // Series with the same name between optionA and optionB
  8100. // should be mapped.
  8101. var idNum = 0;
  8102. do {
  8103. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8104. } while (idMap.get(keyInfo.id));
  8105. }
  8106. idMap.set(keyInfo.id, item);
  8107. });
  8108. }
  8109. function keyExistAndEqual(attr, obj1, obj2) {
  8110. var key1 = convertOptionIdName(obj1[attr], null);
  8111. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8112. return key1 != null && key2 != null && key1 === key2;
  8113. }
  8114. /**
  8115. * @return return null if not exist.
  8116. */
  8117. function makeComparableKey(val) {
  8118. if ("development" !== 'production') {
  8119. if (val == null) {
  8120. throw new Error();
  8121. }
  8122. }
  8123. return convertOptionIdName(val, '');
  8124. }
  8125. function convertOptionIdName(idOrName, defaultValue) {
  8126. if (idOrName == null) {
  8127. return defaultValue;
  8128. }
  8129. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8130. }
  8131. function warnInvalidateIdOrName(idOrName) {
  8132. if ("development" !== 'production') {
  8133. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8134. }
  8135. }
  8136. function isValidIdOrName(idOrName) {
  8137. return isStringSafe(idOrName) || isNumeric(idOrName);
  8138. }
  8139. function isNameSpecified(componentModel) {
  8140. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  8141. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8142. }
  8143. /**
  8144. * @public
  8145. * @param {Object} cmptOption
  8146. * @return {boolean}
  8147. */
  8148. function isComponentIdInternal(cmptOption) {
  8149. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8150. }
  8151. function makeInternalComponentId(idSuffix) {
  8152. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8153. }
  8154. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8155. // Set mainType and complete subType.
  8156. each(mappingResult, function (item) {
  8157. var newOption = item.newOption;
  8158. if (isObject(newOption)) {
  8159. item.keyInfo.mainType = mainType;
  8160. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8161. }
  8162. });
  8163. }
  8164. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8165. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  8166. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  8167. return subType;
  8168. }
  8169. /**
  8170. * A helper for removing duplicate items between batchA and batchB,
  8171. * and in themselves, and categorize by series.
  8172. *
  8173. * @param batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  8174. * @param batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  8175. * @return result: [resultBatchA, resultBatchB]
  8176. */
  8177. function compressBatches(batchA, batchB) {
  8178. var mapA = {};
  8179. var mapB = {};
  8180. makeMap(batchA || [], mapA);
  8181. makeMap(batchB || [], mapB, mapA);
  8182. return [mapToArray(mapA), mapToArray(mapB)];
  8183. function makeMap(sourceBatch, map, otherMap) {
  8184. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  8185. var seriesId = convertOptionIdName(sourceBatch[i].seriesId, null);
  8186. if (seriesId == null) {
  8187. return;
  8188. }
  8189. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  8190. var otherDataIndices = otherMap && otherMap[seriesId];
  8191. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  8192. var dataIndex = dataIndices[j];
  8193. if (otherDataIndices && otherDataIndices[dataIndex]) {
  8194. otherDataIndices[dataIndex] = null;
  8195. } else {
  8196. (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1;
  8197. }
  8198. }
  8199. }
  8200. }
  8201. function mapToArray(map, isData) {
  8202. var result = [];
  8203. for (var i in map) {
  8204. if (map.hasOwnProperty(i) && map[i] != null) {
  8205. if (isData) {
  8206. result.push(+i);
  8207. } else {
  8208. var dataIndices = mapToArray(map[i], true);
  8209. dataIndices.length && result.push({
  8210. seriesId: i,
  8211. dataIndex: dataIndices
  8212. });
  8213. }
  8214. }
  8215. }
  8216. return result;
  8217. }
  8218. }
  8219. /**
  8220. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8221. * each of which can be Array or primary type.
  8222. * @return dataIndex If not found, return undefined/null.
  8223. */
  8224. function queryDataIndex(data, payload) {
  8225. if (payload.dataIndexInside != null) {
  8226. return payload.dataIndexInside;
  8227. } else if (payload.dataIndex != null) {
  8228. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8229. return data.indexOfRawIndex(value);
  8230. }) : data.indexOfRawIndex(payload.dataIndex);
  8231. } else if (payload.name != null) {
  8232. return isArray(payload.name) ? map(payload.name, function (value) {
  8233. return data.indexOfName(value);
  8234. }) : data.indexOfName(payload.name);
  8235. }
  8236. }
  8237. /**
  8238. * Enable property storage to any host object.
  8239. * Notice: Serialization is not supported.
  8240. *
  8241. * For example:
  8242. * let inner = zrUitl.makeInner();
  8243. *
  8244. * function some1(hostObj) {
  8245. * inner(hostObj).someProperty = 1212;
  8246. * ...
  8247. * }
  8248. * function some2() {
  8249. * let fields = inner(this);
  8250. * fields.someProperty1 = 1212;
  8251. * fields.someProperty2 = 'xx';
  8252. * ...
  8253. * }
  8254. *
  8255. * @return {Function}
  8256. */
  8257. function makeInner() {
  8258. var key = '__ec_inner_' + innerUniqueIndex++;
  8259. return function (hostObj) {
  8260. return hostObj[key] || (hostObj[key] = {});
  8261. };
  8262. }
  8263. var innerUniqueIndex = getRandomIdBase();
  8264. /**
  8265. * The same behavior as `component.getReferringComponents`.
  8266. */
  8267. function parseFinder(ecModel, finderInput, opt) {
  8268. var _a = preParseFinder(finderInput, opt),
  8269. mainTypeSpecified = _a.mainTypeSpecified,
  8270. queryOptionMap = _a.queryOptionMap,
  8271. others = _a.others;
  8272. var result = others;
  8273. var defaultMainType = opt ? opt.defaultMainType : null;
  8274. if (!mainTypeSpecified && defaultMainType) {
  8275. queryOptionMap.set(defaultMainType, {});
  8276. }
  8277. queryOptionMap.each(function (queryOption, mainType) {
  8278. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8279. useDefault: defaultMainType === mainType,
  8280. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8281. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8282. });
  8283. result[mainType + 'Models'] = queryResult.models;
  8284. result[mainType + 'Model'] = queryResult.models[0];
  8285. });
  8286. return result;
  8287. }
  8288. function preParseFinder(finderInput, opt) {
  8289. var finder;
  8290. if (isString(finderInput)) {
  8291. var obj = {};
  8292. obj[finderInput + 'Index'] = 0;
  8293. finder = obj;
  8294. } else {
  8295. finder = finderInput;
  8296. }
  8297. var queryOptionMap = createHashMap();
  8298. var others = {};
  8299. var mainTypeSpecified = false;
  8300. each(finder, function (value, key) {
  8301. // Exclude 'dataIndex' and other illgal keys.
  8302. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8303. others[key] = value;
  8304. return;
  8305. }
  8306. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8307. var mainType = parsedKey[1];
  8308. var queryType = (parsedKey[2] || '').toLowerCase();
  8309. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8310. return;
  8311. }
  8312. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8313. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8314. queryOption[queryType] = value;
  8315. });
  8316. return {
  8317. mainTypeSpecified: mainTypeSpecified,
  8318. queryOptionMap: queryOptionMap,
  8319. others: others
  8320. };
  8321. }
  8322. var SINGLE_REFERRING = {
  8323. useDefault: true,
  8324. enableAll: false,
  8325. enableNone: false
  8326. };
  8327. var MULTIPLE_REFERRING = {
  8328. useDefault: false,
  8329. enableAll: true,
  8330. enableNone: true
  8331. };
  8332. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8333. opt = opt || SINGLE_REFERRING;
  8334. var indexOption = userOption.index;
  8335. var idOption = userOption.id;
  8336. var nameOption = userOption.name;
  8337. var result = {
  8338. models: null,
  8339. specified: indexOption != null || idOption != null || nameOption != null
  8340. };
  8341. if (!result.specified) {
  8342. // Use the first as default if `useDefault`.
  8343. var firstCmpt = void 0;
  8344. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8345. return result;
  8346. }
  8347. if (indexOption === 'none' || indexOption === false) {
  8348. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8349. result.models = [];
  8350. return result;
  8351. } // `queryComponents` will return all components if
  8352. // both all of index/id/name are null/undefined.
  8353. if (indexOption === 'all') {
  8354. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8355. indexOption = idOption = nameOption = null;
  8356. }
  8357. result.models = ecModel.queryComponents({
  8358. mainType: mainType,
  8359. index: indexOption,
  8360. id: idOption,
  8361. name: nameOption
  8362. });
  8363. return result;
  8364. }
  8365. function setAttribute(dom, key, value) {
  8366. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8367. }
  8368. function getAttribute(dom, key) {
  8369. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8370. }
  8371. function getTooltipRenderMode(renderModeOption) {
  8372. if (renderModeOption === 'auto') {
  8373. // Using html when `document` exists, use richText otherwise
  8374. return env.domSupported ? 'html' : 'richText';
  8375. } else {
  8376. return renderModeOption || 'html';
  8377. }
  8378. }
  8379. /**
  8380. * Group a list by key.
  8381. */
  8382. function groupData(array, getKey // return key
  8383. ) {
  8384. var buckets = createHashMap();
  8385. var keys = [];
  8386. each(array, function (item) {
  8387. var key = getKey(item);
  8388. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  8389. });
  8390. return {
  8391. keys: keys,
  8392. buckets: buckets
  8393. };
  8394. }
  8395. /**
  8396. * Interpolate raw values of a series with percent
  8397. *
  8398. * @param data data
  8399. * @param labelModel label model of the text element
  8400. * @param sourceValue start value. May be null/undefined when init.
  8401. * @param targetValue end value
  8402. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8403. * @return interpolated values
  8404. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8405. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8406. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8407. * Other cases do not supported.
  8408. */
  8409. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8410. var isAutoPrecision = precision == null || precision === 'auto';
  8411. if (targetValue == null) {
  8412. return targetValue;
  8413. }
  8414. if (isNumber(targetValue)) {
  8415. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8416. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8417. } else if (isString(targetValue)) {
  8418. return percent < 1 ? sourceValue : targetValue;
  8419. } else {
  8420. var interpolated = [];
  8421. var leftArr = sourceValue;
  8422. var rightArr = targetValue;
  8423. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8424. for (var i = 0; i < length_1; ++i) {
  8425. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  8426. if (info && info.type === 'ordinal') {
  8427. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8428. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8429. } else {
  8430. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8431. var rightVal = rightArr[i];
  8432. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8433. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8434. }
  8435. }
  8436. return interpolated;
  8437. }
  8438. }
  8439. var TYPE_DELIMITER = '.';
  8440. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8441. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8442. /**
  8443. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8444. * @public
  8445. */
  8446. function parseClassType(componentType) {
  8447. var ret = {
  8448. main: '',
  8449. sub: ''
  8450. };
  8451. if (componentType) {
  8452. var typeArr = componentType.split(TYPE_DELIMITER);
  8453. ret.main = typeArr[0] || '';
  8454. ret.sub = typeArr[1] || '';
  8455. }
  8456. return ret;
  8457. }
  8458. /**
  8459. * @public
  8460. */
  8461. function checkClassType(componentType) {
  8462. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8463. }
  8464. function isExtendedClass(clz) {
  8465. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8466. }
  8467. /**
  8468. * Implements `ExtendableConstructor` for `rootClz`.
  8469. *
  8470. * @usage
  8471. * ```ts
  8472. * class Xxx {}
  8473. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8474. * enableClassExtend(Xxx as XxxConstructor);
  8475. * ```
  8476. */
  8477. function enableClassExtend(rootClz, mandatoryMethods) {
  8478. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8479. rootClz.extend = function (proto) {
  8480. if ("development" !== 'production') {
  8481. each(mandatoryMethods, function (method) {
  8482. if (!proto[method]) {
  8483. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8484. }
  8485. });
  8486. }
  8487. var superClass = this;
  8488. var ExtendedClass;
  8489. if (isESClass(superClass)) {
  8490. ExtendedClass =
  8491. /** @class */
  8492. function (_super) {
  8493. __extends(class_1, _super);
  8494. function class_1() {
  8495. return _super.apply(this, arguments) || this;
  8496. }
  8497. return class_1;
  8498. }(superClass);
  8499. } else {
  8500. // For backward compat, we both support ts class inheritance and this
  8501. // "extend" approach.
  8502. // The constructor should keep the same behavior as ts class inheritance:
  8503. // If this constructor/$constructor is not declared, auto invoke the super
  8504. // constructor.
  8505. // If this constructor/$constructor is declared, it is responsible for
  8506. // calling the super constructor.
  8507. ExtendedClass = function () {
  8508. (proto.$constructor || superClass).apply(this, arguments);
  8509. };
  8510. inherits(ExtendedClass, this);
  8511. }
  8512. extend(ExtendedClass.prototype, proto);
  8513. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8514. ExtendedClass.extend = this.extend;
  8515. ExtendedClass.superCall = superCall;
  8516. ExtendedClass.superApply = superApply;
  8517. ExtendedClass.superClass = superClass;
  8518. return ExtendedClass;
  8519. };
  8520. }
  8521. function isESClass(fn) {
  8522. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8523. }
  8524. /**
  8525. * A work around to both support ts extend and this extend mechanism.
  8526. * on sub-class.
  8527. * @usage
  8528. * ```ts
  8529. * class Component { ... }
  8530. * classUtil.enableClassExtend(Component);
  8531. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8532. *
  8533. * class Series extends Component { ... }
  8534. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8535. * Component.markExtend(Series);
  8536. * ```
  8537. */
  8538. function mountExtend(SubClz, SupperClz) {
  8539. SubClz.extend = SupperClz.extend;
  8540. } // A random offset.
  8541. var classBase = Math.round(Math.random() * 10);
  8542. /**
  8543. * Implements `CheckableConstructor` for `target`.
  8544. * Can not use instanceof, consider different scope by
  8545. * cross domain or es module import in ec extensions.
  8546. * Mount a method "isInstance()" to Clz.
  8547. *
  8548. * @usage
  8549. * ```ts
  8550. * class Xxx {}
  8551. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8552. * enableClassCheck(Xxx as XxxConstructor)
  8553. * ```
  8554. */
  8555. function enableClassCheck(target) {
  8556. var classAttr = ['__\0is_clz', classBase++].join('_');
  8557. target.prototype[classAttr] = true;
  8558. if ("development" !== 'production') {
  8559. assert(!target.isInstance, 'The method "is" can not be defined.');
  8560. }
  8561. target.isInstance = function (obj) {
  8562. return !!(obj && obj[classAttr]);
  8563. };
  8564. } // superCall should have class info, which can not be fetched from 'this'.
  8565. // Consider this case:
  8566. // class A has method f,
  8567. // class B inherits class A, overrides method f, f call superApply('f'),
  8568. // class C inherits class B, does not override method f,
  8569. // then when method of class C is called, dead loop occurred.
  8570. function superCall(context, methodName) {
  8571. var args = [];
  8572. for (var _i = 2; _i < arguments.length; _i++) {
  8573. args[_i - 2] = arguments[_i];
  8574. }
  8575. return this.superClass.prototype[methodName].apply(context, args);
  8576. }
  8577. function superApply(context, methodName, args) {
  8578. return this.superClass.prototype[methodName].apply(context, args);
  8579. }
  8580. /**
  8581. * Implements `ClassManager` for `target`
  8582. *
  8583. * @usage
  8584. * ```ts
  8585. * class Xxx {}
  8586. * type XxxConstructor = typeof Xxx & ClassManager
  8587. * enableClassManagement(Xxx as XxxConstructor);
  8588. * ```
  8589. */
  8590. function enableClassManagement(target) {
  8591. /**
  8592. * Component model classes
  8593. * key: componentType,
  8594. * value:
  8595. * componentClass, when componentType is 'a'
  8596. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8597. */
  8598. var storage = {};
  8599. target.registerClass = function (clz) {
  8600. // `type` should not be a "instance member".
  8601. // If using TS class, should better declared as `static type = 'series.pie'`.
  8602. // otherwise users have to mount `type` on prototype manually.
  8603. // For backward compat and enable instance visit type via `this.type`,
  8604. // we still support fetch `type` from prototype.
  8605. var componentFullType = clz.type || clz.prototype.type;
  8606. if (componentFullType) {
  8607. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  8608. clz.prototype.type = componentFullType;
  8609. var componentTypeInfo = parseClassType(componentFullType);
  8610. if (!componentTypeInfo.sub) {
  8611. if ("development" !== 'production') {
  8612. if (storage[componentTypeInfo.main]) {
  8613. console.warn(componentTypeInfo.main + ' exists.');
  8614. }
  8615. }
  8616. storage[componentTypeInfo.main] = clz;
  8617. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8618. var container = makeContainer(componentTypeInfo);
  8619. container[componentTypeInfo.sub] = clz;
  8620. }
  8621. }
  8622. return clz;
  8623. };
  8624. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8625. var clz = storage[mainType];
  8626. if (clz && clz[IS_CONTAINER]) {
  8627. clz = subType ? clz[subType] : null;
  8628. }
  8629. if (throwWhenNotFound && !clz) {
  8630. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8631. }
  8632. return clz;
  8633. };
  8634. target.getClassesByMainType = function (componentType) {
  8635. var componentTypeInfo = parseClassType(componentType);
  8636. var result = [];
  8637. var obj = storage[componentTypeInfo.main];
  8638. if (obj && obj[IS_CONTAINER]) {
  8639. each(obj, function (o, type) {
  8640. type !== IS_CONTAINER && result.push(o);
  8641. });
  8642. } else {
  8643. result.push(obj);
  8644. }
  8645. return result;
  8646. };
  8647. target.hasClass = function (componentType) {
  8648. // Just consider componentType.main.
  8649. var componentTypeInfo = parseClassType(componentType);
  8650. return !!storage[componentTypeInfo.main];
  8651. };
  8652. /**
  8653. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8654. */
  8655. target.getAllClassMainTypes = function () {
  8656. var types = [];
  8657. each(storage, function (obj, type) {
  8658. types.push(type);
  8659. });
  8660. return types;
  8661. };
  8662. /**
  8663. * If a main type is container and has sub types
  8664. */
  8665. target.hasSubTypes = function (componentType) {
  8666. var componentTypeInfo = parseClassType(componentType);
  8667. var obj = storage[componentTypeInfo.main];
  8668. return obj && obj[IS_CONTAINER];
  8669. };
  8670. function makeContainer(componentTypeInfo) {
  8671. var container = storage[componentTypeInfo.main];
  8672. if (!container || !container[IS_CONTAINER]) {
  8673. container = storage[componentTypeInfo.main] = {};
  8674. container[IS_CONTAINER] = true;
  8675. }
  8676. return container;
  8677. }
  8678. } // /**
  8679. // * @param {string|Array.<string>} properties
  8680. // */
  8681. // export function setReadOnly(obj, properties) {
  8682. // FIXME It seems broken in IE8 simulation of IE11
  8683. // if (!zrUtil.isArray(properties)) {
  8684. // properties = properties != null ? [properties] : [];
  8685. // }
  8686. // zrUtil.each(properties, function (prop) {
  8687. // let value = obj[prop];
  8688. // Object.defineProperty
  8689. // && Object.defineProperty(obj, prop, {
  8690. // value: value, writable: false
  8691. // });
  8692. // zrUtil.isArray(obj[prop])
  8693. // && Object.freeze
  8694. // && Object.freeze(obj[prop]);
  8695. // });
  8696. // }
  8697. function makeStyleMapper(properties, ignoreParent) {
  8698. // Normalize
  8699. for (var i = 0; i < properties.length; i++) {
  8700. if (!properties[i][1]) {
  8701. properties[i][1] = properties[i][0];
  8702. }
  8703. }
  8704. ignoreParent = ignoreParent || false;
  8705. return function (model, excludes, includes) {
  8706. var style = {};
  8707. for (var i = 0; i < properties.length; i++) {
  8708. var propName = properties[i][1];
  8709. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8710. continue;
  8711. }
  8712. var val = model.getShallow(propName, ignoreParent);
  8713. if (val != null) {
  8714. style[properties[i][0]] = val;
  8715. }
  8716. } // TODO Text or image?
  8717. return style;
  8718. };
  8719. }
  8720. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8721. // So do not transfer decal directly.
  8722. ];
  8723. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8724. var AreaStyleMixin =
  8725. /** @class */
  8726. function () {
  8727. function AreaStyleMixin() {}
  8728. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8729. return getAreaStyle(this, excludes, includes);
  8730. };
  8731. return AreaStyleMixin;
  8732. }();
  8733. var globalImageCache = new LRU(50);
  8734. function findExistImage(newImageOrSrc) {
  8735. if (typeof newImageOrSrc === 'string') {
  8736. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8737. return cachedImgObj && cachedImgObj.image;
  8738. }
  8739. else {
  8740. return newImageOrSrc;
  8741. }
  8742. }
  8743. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8744. if (!newImageOrSrc) {
  8745. return image;
  8746. }
  8747. else if (typeof newImageOrSrc === 'string') {
  8748. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8749. return image;
  8750. }
  8751. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8752. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8753. if (cachedImgObj) {
  8754. image = cachedImgObj.image;
  8755. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8756. }
  8757. else {
  8758. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8759. image.__zrImageSrc = newImageOrSrc;
  8760. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8761. image: image,
  8762. pending: [pendingWrap]
  8763. });
  8764. }
  8765. return image;
  8766. }
  8767. else {
  8768. return newImageOrSrc;
  8769. }
  8770. }
  8771. function imageOnLoad() {
  8772. var cachedImgObj = this.__cachedImgObj;
  8773. this.onload = this.onerror = this.__cachedImgObj = null;
  8774. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8775. var pendingWrap = cachedImgObj.pending[i];
  8776. var cb = pendingWrap.cb;
  8777. cb && cb(this, pendingWrap.cbPayload);
  8778. pendingWrap.hostEl.dirty();
  8779. }
  8780. cachedImgObj.pending.length = 0;
  8781. }
  8782. function isImageReady(image) {
  8783. return image && image.width && image.height;
  8784. }
  8785. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8786. function truncateText(text, containerWidth, font, ellipsis, options) {
  8787. if (!containerWidth) {
  8788. return '';
  8789. }
  8790. var textLines = (text + '').split('\n');
  8791. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8792. for (var i = 0, len = textLines.length; i < len; i++) {
  8793. textLines[i] = truncateSingleLine(textLines[i], options);
  8794. }
  8795. return textLines.join('\n');
  8796. }
  8797. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8798. options = options || {};
  8799. var preparedOpts = extend({}, options);
  8800. preparedOpts.font = font;
  8801. ellipsis = retrieve2(ellipsis, '...');
  8802. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8803. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8804. preparedOpts.cnCharWidth = getWidth('国', font);
  8805. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8806. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8807. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8808. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8809. contentWidth -= ascCharWidth;
  8810. }
  8811. var ellipsisWidth = getWidth(ellipsis, font);
  8812. if (ellipsisWidth > contentWidth) {
  8813. ellipsis = '';
  8814. ellipsisWidth = 0;
  8815. }
  8816. contentWidth = containerWidth - ellipsisWidth;
  8817. preparedOpts.ellipsis = ellipsis;
  8818. preparedOpts.ellipsisWidth = ellipsisWidth;
  8819. preparedOpts.contentWidth = contentWidth;
  8820. preparedOpts.containerWidth = containerWidth;
  8821. return preparedOpts;
  8822. }
  8823. function truncateSingleLine(textLine, options) {
  8824. var containerWidth = options.containerWidth;
  8825. var font = options.font;
  8826. var contentWidth = options.contentWidth;
  8827. if (!containerWidth) {
  8828. return '';
  8829. }
  8830. var lineWidth = getWidth(textLine, font);
  8831. if (lineWidth <= containerWidth) {
  8832. return textLine;
  8833. }
  8834. for (var j = 0;; j++) {
  8835. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8836. textLine += options.ellipsis;
  8837. break;
  8838. }
  8839. var subLength = j === 0
  8840. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8841. : lineWidth > 0
  8842. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8843. : 0;
  8844. textLine = textLine.substr(0, subLength);
  8845. lineWidth = getWidth(textLine, font);
  8846. }
  8847. if (textLine === '') {
  8848. textLine = options.placeholder;
  8849. }
  8850. return textLine;
  8851. }
  8852. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8853. var width = 0;
  8854. var i = 0;
  8855. for (var len = text.length; i < len && width < contentWidth; i++) {
  8856. var charCode = text.charCodeAt(i);
  8857. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8858. }
  8859. return i;
  8860. }
  8861. function parsePlainText(text, style) {
  8862. text != null && (text += '');
  8863. var overflow = style.overflow;
  8864. var padding = style.padding;
  8865. var font = style.font;
  8866. var truncate = overflow === 'truncate';
  8867. var calculatedLineHeight = getLineHeight(font);
  8868. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8869. var bgColorDrawn = !!(style.backgroundColor);
  8870. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8871. var width = style.width;
  8872. var lines;
  8873. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8874. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8875. }
  8876. else {
  8877. lines = text ? text.split('\n') : [];
  8878. }
  8879. var contentHeight = lines.length * lineHeight;
  8880. var height = retrieve2(style.height, contentHeight);
  8881. if (contentHeight > height && truncateLineOverflow) {
  8882. var lineCount = Math.floor(height / lineHeight);
  8883. lines = lines.slice(0, lineCount);
  8884. }
  8885. if (text && truncate && width != null) {
  8886. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8887. minChar: style.truncateMinChar,
  8888. placeholder: style.placeholder
  8889. });
  8890. for (var i = 0; i < lines.length; i++) {
  8891. lines[i] = truncateSingleLine(lines[i], options);
  8892. }
  8893. }
  8894. var outerHeight = height;
  8895. var contentWidth = 0;
  8896. for (var i = 0; i < lines.length; i++) {
  8897. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8898. }
  8899. if (width == null) {
  8900. width = contentWidth;
  8901. }
  8902. var outerWidth = contentWidth;
  8903. if (padding) {
  8904. outerHeight += padding[0] + padding[2];
  8905. outerWidth += padding[1] + padding[3];
  8906. width += padding[1] + padding[3];
  8907. }
  8908. if (bgColorDrawn) {
  8909. outerWidth = width;
  8910. }
  8911. return {
  8912. lines: lines,
  8913. height: height,
  8914. outerWidth: outerWidth,
  8915. outerHeight: outerHeight,
  8916. lineHeight: lineHeight,
  8917. calculatedLineHeight: calculatedLineHeight,
  8918. contentWidth: contentWidth,
  8919. contentHeight: contentHeight,
  8920. width: width
  8921. };
  8922. }
  8923. var RichTextToken = (function () {
  8924. function RichTextToken() {
  8925. }
  8926. return RichTextToken;
  8927. }());
  8928. var RichTextLine = (function () {
  8929. function RichTextLine(tokens) {
  8930. this.tokens = [];
  8931. if (tokens) {
  8932. this.tokens = tokens;
  8933. }
  8934. }
  8935. return RichTextLine;
  8936. }());
  8937. var RichTextContentBlock = (function () {
  8938. function RichTextContentBlock() {
  8939. this.width = 0;
  8940. this.height = 0;
  8941. this.contentWidth = 0;
  8942. this.contentHeight = 0;
  8943. this.outerWidth = 0;
  8944. this.outerHeight = 0;
  8945. this.lines = [];
  8946. }
  8947. return RichTextContentBlock;
  8948. }());
  8949. function parseRichText(text, style) {
  8950. var contentBlock = new RichTextContentBlock();
  8951. text != null && (text += '');
  8952. if (!text) {
  8953. return contentBlock;
  8954. }
  8955. var topWidth = style.width;
  8956. var topHeight = style.height;
  8957. var overflow = style.overflow;
  8958. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8959. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8960. : null;
  8961. var lastIndex = STYLE_REG.lastIndex = 0;
  8962. var result;
  8963. while ((result = STYLE_REG.exec(text)) != null) {
  8964. var matchedIndex = result.index;
  8965. if (matchedIndex > lastIndex) {
  8966. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8967. }
  8968. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8969. lastIndex = STYLE_REG.lastIndex;
  8970. }
  8971. if (lastIndex < text.length) {
  8972. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8973. }
  8974. var pendingList = [];
  8975. var calculatedHeight = 0;
  8976. var calculatedWidth = 0;
  8977. var stlPadding = style.padding;
  8978. var truncate = overflow === 'truncate';
  8979. var truncateLine = style.lineOverflow === 'truncate';
  8980. function finishLine(line, lineWidth, lineHeight) {
  8981. line.width = lineWidth;
  8982. line.lineHeight = lineHeight;
  8983. calculatedHeight += lineHeight;
  8984. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8985. }
  8986. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8987. var line = contentBlock.lines[i];
  8988. var lineHeight = 0;
  8989. var lineWidth = 0;
  8990. for (var j = 0; j < line.tokens.length; j++) {
  8991. var token = line.tokens[j];
  8992. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8993. var textPadding = token.textPadding = tokenStyle.padding;
  8994. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8995. var font = token.font = tokenStyle.font || style.font;
  8996. token.contentHeight = getLineHeight(font);
  8997. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8998. token.innerHeight = tokenHeight;
  8999. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  9000. token.height = tokenHeight;
  9001. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  9002. token.align = tokenStyle && tokenStyle.align || style.align;
  9003. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  9004. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  9005. if (j > 0) {
  9006. line.tokens = line.tokens.slice(0, j);
  9007. finishLine(line, lineWidth, lineHeight);
  9008. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  9009. }
  9010. else {
  9011. contentBlock.lines = contentBlock.lines.slice(0, i);
  9012. }
  9013. break outer;
  9014. }
  9015. var styleTokenWidth = tokenStyle.width;
  9016. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  9017. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  9018. token.percentWidth = styleTokenWidth;
  9019. pendingList.push(token);
  9020. token.contentWidth = getWidth(token.text, font);
  9021. }
  9022. else {
  9023. if (tokenWidthNotSpecified) {
  9024. var textBackgroundColor = tokenStyle.backgroundColor;
  9025. var bgImg = textBackgroundColor && textBackgroundColor.image;
  9026. if (bgImg) {
  9027. bgImg = findExistImage(bgImg);
  9028. if (isImageReady(bgImg)) {
  9029. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  9030. }
  9031. }
  9032. }
  9033. var remainTruncWidth = truncate && topWidth != null
  9034. ? topWidth - lineWidth : null;
  9035. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  9036. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  9037. token.text = '';
  9038. token.width = token.contentWidth = 0;
  9039. }
  9040. else {
  9041. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  9042. token.width = token.contentWidth = getWidth(token.text, font);
  9043. }
  9044. }
  9045. else {
  9046. token.contentWidth = getWidth(token.text, font);
  9047. }
  9048. }
  9049. token.width += paddingH;
  9050. lineWidth += token.width;
  9051. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  9052. }
  9053. finishLine(line, lineWidth, lineHeight);
  9054. }
  9055. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  9056. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  9057. contentBlock.contentHeight = calculatedHeight;
  9058. contentBlock.contentWidth = calculatedWidth;
  9059. if (stlPadding) {
  9060. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  9061. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  9062. }
  9063. for (var i = 0; i < pendingList.length; i++) {
  9064. var token = pendingList[i];
  9065. var percentWidth = token.percentWidth;
  9066. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9067. }
  9068. return contentBlock;
  9069. }
  9070. function pushTokens(block, str, style, wrapInfo, styleName) {
  9071. var isEmptyStr = str === '';
  9072. var tokenStyle = styleName && style.rich[styleName] || {};
  9073. var lines = block.lines;
  9074. var font = tokenStyle.font || style.font;
  9075. var newLine = false;
  9076. var strLines;
  9077. var linesWidths;
  9078. if (wrapInfo) {
  9079. var tokenPadding = tokenStyle.padding;
  9080. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9081. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9082. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9083. if (lines.length > 0) {
  9084. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9085. strLines = str.split('\n');
  9086. newLine = true;
  9087. }
  9088. }
  9089. wrapInfo.accumWidth = outerWidth_1;
  9090. }
  9091. else {
  9092. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9093. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9094. linesWidths = res.linesWidths;
  9095. strLines = res.lines;
  9096. }
  9097. }
  9098. else {
  9099. strLines = str.split('\n');
  9100. }
  9101. for (var i = 0; i < strLines.length; i++) {
  9102. var text = strLines[i];
  9103. var token = new RichTextToken();
  9104. token.styleName = styleName;
  9105. token.text = text;
  9106. token.isLineHolder = !text && !isEmptyStr;
  9107. if (typeof tokenStyle.width === 'number') {
  9108. token.width = tokenStyle.width;
  9109. }
  9110. else {
  9111. token.width = linesWidths
  9112. ? linesWidths[i]
  9113. : getWidth(text, font);
  9114. }
  9115. if (!i && !newLine) {
  9116. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9117. var tokensLen = tokens.length;
  9118. (tokensLen === 1 && tokens[0].isLineHolder)
  9119. ? (tokens[0] = token)
  9120. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9121. }
  9122. else {
  9123. lines.push(new RichTextLine([token]));
  9124. }
  9125. }
  9126. }
  9127. function isAlphabeticLetter(ch) {
  9128. var code = ch.charCodeAt(0);
  9129. return code >= 0x20 && code <= 0x24F
  9130. || code >= 0x370 && code <= 0x10FF
  9131. || code >= 0x1200 && code <= 0x13FF
  9132. || code >= 0x1E00 && code <= 0x206F;
  9133. }
  9134. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9135. obj[ch] = true;
  9136. return obj;
  9137. }, {});
  9138. function isWordBreakChar(ch) {
  9139. if (isAlphabeticLetter(ch)) {
  9140. if (breakCharMap[ch]) {
  9141. return true;
  9142. }
  9143. return false;
  9144. }
  9145. return true;
  9146. }
  9147. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9148. var lines = [];
  9149. var linesWidths = [];
  9150. var line = '';
  9151. var currentWord = '';
  9152. var currentWordWidth = 0;
  9153. var accumWidth = 0;
  9154. for (var i = 0; i < text.length; i++) {
  9155. var ch = text.charAt(i);
  9156. if (ch === '\n') {
  9157. if (currentWord) {
  9158. line += currentWord;
  9159. accumWidth += currentWordWidth;
  9160. }
  9161. lines.push(line);
  9162. linesWidths.push(accumWidth);
  9163. line = '';
  9164. currentWord = '';
  9165. currentWordWidth = 0;
  9166. accumWidth = 0;
  9167. continue;
  9168. }
  9169. var chWidth = getWidth(ch, font);
  9170. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9171. if (!lines.length
  9172. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9173. : accumWidth + chWidth > lineWidth) {
  9174. if (!accumWidth) {
  9175. if (inWord) {
  9176. lines.push(currentWord);
  9177. linesWidths.push(currentWordWidth);
  9178. currentWord = ch;
  9179. currentWordWidth = chWidth;
  9180. }
  9181. else {
  9182. lines.push(ch);
  9183. linesWidths.push(chWidth);
  9184. }
  9185. }
  9186. else if (line || currentWord) {
  9187. if (inWord) {
  9188. if (!line) {
  9189. line = currentWord;
  9190. currentWord = '';
  9191. currentWordWidth = 0;
  9192. accumWidth = currentWordWidth;
  9193. }
  9194. lines.push(line);
  9195. linesWidths.push(accumWidth - currentWordWidth);
  9196. currentWord += ch;
  9197. currentWordWidth += chWidth;
  9198. line = '';
  9199. accumWidth = currentWordWidth;
  9200. }
  9201. else {
  9202. if (currentWord) {
  9203. line += currentWord;
  9204. currentWord = '';
  9205. currentWordWidth = 0;
  9206. }
  9207. lines.push(line);
  9208. linesWidths.push(accumWidth);
  9209. line = ch;
  9210. accumWidth = chWidth;
  9211. }
  9212. }
  9213. continue;
  9214. }
  9215. accumWidth += chWidth;
  9216. if (inWord) {
  9217. currentWord += ch;
  9218. currentWordWidth += chWidth;
  9219. }
  9220. else {
  9221. if (currentWord) {
  9222. line += currentWord;
  9223. currentWord = '';
  9224. currentWordWidth = 0;
  9225. }
  9226. line += ch;
  9227. }
  9228. }
  9229. if (!lines.length && !line) {
  9230. line = text;
  9231. currentWord = '';
  9232. currentWordWidth = 0;
  9233. }
  9234. if (currentWord) {
  9235. line += currentWord;
  9236. }
  9237. if (line) {
  9238. lines.push(line);
  9239. linesWidths.push(accumWidth);
  9240. }
  9241. if (lines.length === 1) {
  9242. accumWidth += lastAccumWidth;
  9243. }
  9244. return {
  9245. accumWidth: accumWidth,
  9246. lines: lines,
  9247. linesWidths: linesWidths
  9248. };
  9249. }
  9250. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9251. var DEFAULT_COMMON_STYLE = {
  9252. shadowBlur: 0,
  9253. shadowOffsetX: 0,
  9254. shadowOffsetY: 0,
  9255. shadowColor: '#000',
  9256. opacity: 1,
  9257. blend: 'source-over'
  9258. };
  9259. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9260. style: {
  9261. shadowBlur: true,
  9262. shadowOffsetX: true,
  9263. shadowOffsetY: true,
  9264. shadowColor: true,
  9265. opacity: true
  9266. }
  9267. };
  9268. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9269. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9270. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9271. var Displayable = (function (_super) {
  9272. __extends(Displayable, _super);
  9273. function Displayable(props) {
  9274. return _super.call(this, props) || this;
  9275. }
  9276. Displayable.prototype._init = function (props) {
  9277. var keysArr = keys(props);
  9278. for (var i = 0; i < keysArr.length; i++) {
  9279. var key = keysArr[i];
  9280. if (key === 'style') {
  9281. this.useStyle(props[key]);
  9282. }
  9283. else {
  9284. _super.prototype.attrKV.call(this, key, props[key]);
  9285. }
  9286. }
  9287. if (!this.style) {
  9288. this.useStyle({});
  9289. }
  9290. };
  9291. Displayable.prototype.beforeBrush = function () { };
  9292. Displayable.prototype.afterBrush = function () { };
  9293. Displayable.prototype.innerBeforeBrush = function () { };
  9294. Displayable.prototype.innerAfterBrush = function () { };
  9295. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9296. var m = this.transform;
  9297. if (this.ignore
  9298. || this.invisible
  9299. || this.style.opacity === 0
  9300. || (this.culling
  9301. && isDisplayableCulled(this, viewWidth, viewHeight))
  9302. || (m && !m[0] && !m[3])) {
  9303. return false;
  9304. }
  9305. if (considerClipPath && this.__clipPaths) {
  9306. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9307. if (this.__clipPaths[i].isZeroArea()) {
  9308. return false;
  9309. }
  9310. }
  9311. }
  9312. if (considerAncestors && this.parent) {
  9313. var parent_1 = this.parent;
  9314. while (parent_1) {
  9315. if (parent_1.ignore) {
  9316. return false;
  9317. }
  9318. parent_1 = parent_1.parent;
  9319. }
  9320. }
  9321. return true;
  9322. };
  9323. Displayable.prototype.contain = function (x, y) {
  9324. return this.rectContain(x, y);
  9325. };
  9326. Displayable.prototype.traverse = function (cb, context) {
  9327. cb.call(context, this);
  9328. };
  9329. Displayable.prototype.rectContain = function (x, y) {
  9330. var coord = this.transformCoordToLocal(x, y);
  9331. var rect = this.getBoundingRect();
  9332. return rect.contain(coord[0], coord[1]);
  9333. };
  9334. Displayable.prototype.getPaintRect = function () {
  9335. var rect = this._paintRect;
  9336. if (!this._paintRect || this.__dirty) {
  9337. var transform = this.transform;
  9338. var elRect = this.getBoundingRect();
  9339. var style = this.style;
  9340. var shadowSize = style.shadowBlur || 0;
  9341. var shadowOffsetX = style.shadowOffsetX || 0;
  9342. var shadowOffsetY = style.shadowOffsetY || 0;
  9343. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9344. if (transform) {
  9345. BoundingRect.applyTransform(rect, elRect, transform);
  9346. }
  9347. else {
  9348. rect.copy(elRect);
  9349. }
  9350. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9351. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9352. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9353. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9354. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9355. }
  9356. var tolerance = this.dirtyRectTolerance;
  9357. if (!rect.isZero()) {
  9358. rect.x = Math.floor(rect.x - tolerance);
  9359. rect.y = Math.floor(rect.y - tolerance);
  9360. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9361. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9362. }
  9363. }
  9364. return rect;
  9365. };
  9366. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9367. if (paintRect) {
  9368. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9369. this._prevPaintRect.copy(paintRect);
  9370. }
  9371. else {
  9372. this._prevPaintRect = null;
  9373. }
  9374. };
  9375. Displayable.prototype.getPrevPaintRect = function () {
  9376. return this._prevPaintRect;
  9377. };
  9378. Displayable.prototype.animateStyle = function (loop) {
  9379. return this.animate('style', loop);
  9380. };
  9381. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9382. if (targetKey === 'style') {
  9383. this.dirtyStyle();
  9384. }
  9385. else {
  9386. this.markRedraw();
  9387. }
  9388. };
  9389. Displayable.prototype.attrKV = function (key, value) {
  9390. if (key !== 'style') {
  9391. _super.prototype.attrKV.call(this, key, value);
  9392. }
  9393. else {
  9394. if (!this.style) {
  9395. this.useStyle(value);
  9396. }
  9397. else {
  9398. this.setStyle(value);
  9399. }
  9400. }
  9401. };
  9402. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9403. if (typeof keyOrObj === 'string') {
  9404. this.style[keyOrObj] = value;
  9405. }
  9406. else {
  9407. extend(this.style, keyOrObj);
  9408. }
  9409. this.dirtyStyle();
  9410. return this;
  9411. };
  9412. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9413. if (!notRedraw) {
  9414. this.markRedraw();
  9415. }
  9416. this.__dirty |= STYLE_CHANGED_BIT;
  9417. if (this._rect) {
  9418. this._rect = null;
  9419. }
  9420. };
  9421. Displayable.prototype.dirty = function () {
  9422. this.dirtyStyle();
  9423. };
  9424. Displayable.prototype.styleChanged = function () {
  9425. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9426. };
  9427. Displayable.prototype.styleUpdated = function () {
  9428. this.__dirty &= ~STYLE_CHANGED_BIT;
  9429. };
  9430. Displayable.prototype.createStyle = function (obj) {
  9431. return createObject(DEFAULT_COMMON_STYLE, obj);
  9432. };
  9433. Displayable.prototype.useStyle = function (obj) {
  9434. if (!obj[STYLE_MAGIC_KEY]) {
  9435. obj = this.createStyle(obj);
  9436. }
  9437. if (this.__inHover) {
  9438. this.__hoverStyle = obj;
  9439. }
  9440. else {
  9441. this.style = obj;
  9442. }
  9443. this.dirtyStyle();
  9444. };
  9445. Displayable.prototype.isStyleObject = function (obj) {
  9446. return obj[STYLE_MAGIC_KEY];
  9447. };
  9448. Displayable.prototype._innerSaveToNormal = function (toState) {
  9449. _super.prototype._innerSaveToNormal.call(this, toState);
  9450. var normalState = this._normalState;
  9451. if (toState.style && !normalState.style) {
  9452. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9453. }
  9454. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9455. };
  9456. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9457. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9458. var needsRestoreToNormal = !(state && keepCurrentStates);
  9459. var targetStyle;
  9460. if (state && state.style) {
  9461. if (transition) {
  9462. if (keepCurrentStates) {
  9463. targetStyle = state.style;
  9464. }
  9465. else {
  9466. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9467. this._mergeStyle(targetStyle, state.style);
  9468. }
  9469. }
  9470. else {
  9471. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9472. this._mergeStyle(targetStyle, state.style);
  9473. }
  9474. }
  9475. else if (needsRestoreToNormal) {
  9476. targetStyle = normalState.style;
  9477. }
  9478. if (targetStyle) {
  9479. if (transition) {
  9480. var sourceStyle = this.style;
  9481. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9482. if (needsRestoreToNormal) {
  9483. var changedKeys = keys(sourceStyle);
  9484. for (var i = 0; i < changedKeys.length; i++) {
  9485. var key = changedKeys[i];
  9486. if (key in targetStyle) {
  9487. targetStyle[key] = targetStyle[key];
  9488. this.style[key] = sourceStyle[key];
  9489. }
  9490. }
  9491. }
  9492. var targetKeys = keys(targetStyle);
  9493. for (var i = 0; i < targetKeys.length; i++) {
  9494. var key = targetKeys[i];
  9495. this.style[key] = this.style[key];
  9496. }
  9497. this._transitionState(stateName, {
  9498. style: targetStyle
  9499. }, animationCfg, this.getAnimationStyleProps());
  9500. }
  9501. else {
  9502. this.useStyle(targetStyle);
  9503. }
  9504. }
  9505. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9506. for (var i = 0; i < statesKeys.length; i++) {
  9507. var key = statesKeys[i];
  9508. if (state && state[key] != null) {
  9509. this[key] = state[key];
  9510. }
  9511. else if (needsRestoreToNormal) {
  9512. if (normalState[key] != null) {
  9513. this[key] = normalState[key];
  9514. }
  9515. }
  9516. }
  9517. };
  9518. Displayable.prototype._mergeStates = function (states) {
  9519. var mergedState = _super.prototype._mergeStates.call(this, states);
  9520. var mergedStyle;
  9521. for (var i = 0; i < states.length; i++) {
  9522. var state = states[i];
  9523. if (state.style) {
  9524. mergedStyle = mergedStyle || {};
  9525. this._mergeStyle(mergedStyle, state.style);
  9526. }
  9527. }
  9528. if (mergedStyle) {
  9529. mergedState.style = mergedStyle;
  9530. }
  9531. return mergedState;
  9532. };
  9533. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9534. extend(targetStyle, sourceStyle);
  9535. return targetStyle;
  9536. };
  9537. Displayable.prototype.getAnimationStyleProps = function () {
  9538. return DEFAULT_COMMON_ANIMATION_PROPS;
  9539. };
  9540. Displayable.initDefaultProps = (function () {
  9541. var dispProto = Displayable.prototype;
  9542. dispProto.type = 'displayable';
  9543. dispProto.invisible = false;
  9544. dispProto.z = 0;
  9545. dispProto.z2 = 0;
  9546. dispProto.zlevel = 0;
  9547. dispProto.culling = false;
  9548. dispProto.cursor = 'pointer';
  9549. dispProto.rectHover = false;
  9550. dispProto.incremental = false;
  9551. dispProto._rect = null;
  9552. dispProto.dirtyRectTolerance = 0;
  9553. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9554. })();
  9555. return Displayable;
  9556. }(Element));
  9557. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9558. var viewRect = new BoundingRect(0, 0, 0, 0);
  9559. function isDisplayableCulled(el, width, height) {
  9560. tmpRect$1.copy(el.getBoundingRect());
  9561. if (el.transform) {
  9562. tmpRect$1.applyTransform(el.transform);
  9563. }
  9564. viewRect.width = width;
  9565. viewRect.height = height;
  9566. return !tmpRect$1.intersect(viewRect);
  9567. }
  9568. var mathMin$1 = Math.min;
  9569. var mathMax$1 = Math.max;
  9570. var mathSin = Math.sin;
  9571. var mathCos = Math.cos;
  9572. var PI2 = Math.PI * 2;
  9573. var start = create();
  9574. var end = create();
  9575. var extremity = create();
  9576. function fromPoints(points, min, max) {
  9577. if (points.length === 0) {
  9578. return;
  9579. }
  9580. var p = points[0];
  9581. var left = p[0];
  9582. var right = p[0];
  9583. var top = p[1];
  9584. var bottom = p[1];
  9585. for (var i = 1; i < points.length; i++) {
  9586. p = points[i];
  9587. left = mathMin$1(left, p[0]);
  9588. right = mathMax$1(right, p[0]);
  9589. top = mathMin$1(top, p[1]);
  9590. bottom = mathMax$1(bottom, p[1]);
  9591. }
  9592. min[0] = left;
  9593. min[1] = top;
  9594. max[0] = right;
  9595. max[1] = bottom;
  9596. }
  9597. function fromLine(x0, y0, x1, y1, min, max) {
  9598. min[0] = mathMin$1(x0, x1);
  9599. min[1] = mathMin$1(y0, y1);
  9600. max[0] = mathMax$1(x0, x1);
  9601. max[1] = mathMax$1(y0, y1);
  9602. }
  9603. var xDim = [];
  9604. var yDim = [];
  9605. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9606. var cubicExtrema$1 = cubicExtrema;
  9607. var cubicAt$1 = cubicAt;
  9608. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9609. min[0] = Infinity;
  9610. min[1] = Infinity;
  9611. max[0] = -Infinity;
  9612. max[1] = -Infinity;
  9613. for (var i = 0; i < n; i++) {
  9614. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9615. min[0] = mathMin$1(x, min[0]);
  9616. max[0] = mathMax$1(x, max[0]);
  9617. }
  9618. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9619. for (var i = 0; i < n; i++) {
  9620. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9621. min[1] = mathMin$1(y, min[1]);
  9622. max[1] = mathMax$1(y, max[1]);
  9623. }
  9624. min[0] = mathMin$1(x0, min[0]);
  9625. max[0] = mathMax$1(x0, max[0]);
  9626. min[0] = mathMin$1(x3, min[0]);
  9627. max[0] = mathMax$1(x3, max[0]);
  9628. min[1] = mathMin$1(y0, min[1]);
  9629. max[1] = mathMax$1(y0, max[1]);
  9630. min[1] = mathMin$1(y3, min[1]);
  9631. max[1] = mathMax$1(y3, max[1]);
  9632. }
  9633. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9634. var quadraticExtremum$1 = quadraticExtremum;
  9635. var quadraticAt$1 = quadraticAt;
  9636. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9637. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9638. var x = quadraticAt$1(x0, x1, x2, tx);
  9639. var y = quadraticAt$1(y0, y1, y2, ty);
  9640. min[0] = mathMin$1(x0, x2, x);
  9641. min[1] = mathMin$1(y0, y2, y);
  9642. max[0] = mathMax$1(x0, x2, x);
  9643. max[1] = mathMax$1(y0, y2, y);
  9644. }
  9645. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9646. var vec2Min = min;
  9647. var vec2Max = max;
  9648. var diff = Math.abs(startAngle - endAngle);
  9649. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9650. min$1[0] = x - rx;
  9651. min$1[1] = y - ry;
  9652. max$1[0] = x + rx;
  9653. max$1[1] = y + ry;
  9654. return;
  9655. }
  9656. start[0] = mathCos(startAngle) * rx + x;
  9657. start[1] = mathSin(startAngle) * ry + y;
  9658. end[0] = mathCos(endAngle) * rx + x;
  9659. end[1] = mathSin(endAngle) * ry + y;
  9660. vec2Min(min$1, start, end);
  9661. vec2Max(max$1, start, end);
  9662. startAngle = startAngle % (PI2);
  9663. if (startAngle < 0) {
  9664. startAngle = startAngle + PI2;
  9665. }
  9666. endAngle = endAngle % (PI2);
  9667. if (endAngle < 0) {
  9668. endAngle = endAngle + PI2;
  9669. }
  9670. if (startAngle > endAngle && !anticlockwise) {
  9671. endAngle += PI2;
  9672. }
  9673. else if (startAngle < endAngle && anticlockwise) {
  9674. startAngle += PI2;
  9675. }
  9676. if (anticlockwise) {
  9677. var tmp = endAngle;
  9678. endAngle = startAngle;
  9679. startAngle = tmp;
  9680. }
  9681. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9682. if (angle > startAngle) {
  9683. extremity[0] = mathCos(angle) * rx + x;
  9684. extremity[1] = mathSin(angle) * ry + y;
  9685. vec2Min(min$1, extremity, min$1);
  9686. vec2Max(max$1, extremity, max$1);
  9687. }
  9688. }
  9689. }
  9690. var CMD = {
  9691. M: 1,
  9692. L: 2,
  9693. C: 3,
  9694. Q: 4,
  9695. A: 5,
  9696. Z: 6,
  9697. R: 7
  9698. };
  9699. var tmpOutX = [];
  9700. var tmpOutY = [];
  9701. var min$1 = [];
  9702. var max$1 = [];
  9703. var min2 = [];
  9704. var max2 = [];
  9705. var mathMin$2 = Math.min;
  9706. var mathMax$2 = Math.max;
  9707. var mathCos$1 = Math.cos;
  9708. var mathSin$1 = Math.sin;
  9709. var mathAbs = Math.abs;
  9710. var PI = Math.PI;
  9711. var PI2$1 = PI * 2;
  9712. var hasTypedArray = typeof Float32Array !== 'undefined';
  9713. var tmpAngles = [];
  9714. function modPI2(radian) {
  9715. var n = Math.round(radian / PI * 1e8) / 1e8;
  9716. return (n % 2) * PI;
  9717. }
  9718. function normalizeArcAngles(angles, anticlockwise) {
  9719. var newStartAngle = modPI2(angles[0]);
  9720. if (newStartAngle < 0) {
  9721. newStartAngle += PI2$1;
  9722. }
  9723. var delta = newStartAngle - angles[0];
  9724. var newEndAngle = angles[1];
  9725. newEndAngle += delta;
  9726. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9727. newEndAngle = newStartAngle + PI2$1;
  9728. }
  9729. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9730. newEndAngle = newStartAngle - PI2$1;
  9731. }
  9732. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9733. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9734. }
  9735. else if (anticlockwise && newStartAngle < newEndAngle) {
  9736. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9737. }
  9738. angles[0] = newStartAngle;
  9739. angles[1] = newEndAngle;
  9740. }
  9741. var PathProxy = (function () {
  9742. function PathProxy(notSaveData) {
  9743. this.dpr = 1;
  9744. this._xi = 0;
  9745. this._yi = 0;
  9746. this._x0 = 0;
  9747. this._y0 = 0;
  9748. this._len = 0;
  9749. if (notSaveData) {
  9750. this._saveData = false;
  9751. }
  9752. if (this._saveData) {
  9753. this.data = [];
  9754. }
  9755. }
  9756. PathProxy.prototype.increaseVersion = function () {
  9757. this._version++;
  9758. };
  9759. PathProxy.prototype.getVersion = function () {
  9760. return this._version;
  9761. };
  9762. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9763. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9764. if (segmentIgnoreThreshold > 0) {
  9765. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9766. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9767. }
  9768. };
  9769. PathProxy.prototype.setDPR = function (dpr) {
  9770. this.dpr = dpr;
  9771. };
  9772. PathProxy.prototype.setContext = function (ctx) {
  9773. this._ctx = ctx;
  9774. };
  9775. PathProxy.prototype.getContext = function () {
  9776. return this._ctx;
  9777. };
  9778. PathProxy.prototype.beginPath = function () {
  9779. this._ctx && this._ctx.beginPath();
  9780. this.reset();
  9781. return this;
  9782. };
  9783. PathProxy.prototype.reset = function () {
  9784. if (this._saveData) {
  9785. this._len = 0;
  9786. }
  9787. if (this._pathSegLen) {
  9788. this._pathSegLen = null;
  9789. this._pathLen = 0;
  9790. }
  9791. this._version++;
  9792. };
  9793. PathProxy.prototype.moveTo = function (x, y) {
  9794. this._drawPendingPt();
  9795. this.addData(CMD.M, x, y);
  9796. this._ctx && this._ctx.moveTo(x, y);
  9797. this._x0 = x;
  9798. this._y0 = y;
  9799. this._xi = x;
  9800. this._yi = y;
  9801. return this;
  9802. };
  9803. PathProxy.prototype.lineTo = function (x, y) {
  9804. var dx = mathAbs(x - this._xi);
  9805. var dy = mathAbs(y - this._yi);
  9806. var exceedUnit = dx > this._ux || dy > this._uy;
  9807. this.addData(CMD.L, x, y);
  9808. if (this._ctx && exceedUnit) {
  9809. this._ctx.lineTo(x, y);
  9810. }
  9811. if (exceedUnit) {
  9812. this._xi = x;
  9813. this._yi = y;
  9814. this._pendingPtDist = 0;
  9815. }
  9816. else {
  9817. var d2 = dx * dx + dy * dy;
  9818. if (d2 > this._pendingPtDist) {
  9819. this._pendingPtX = x;
  9820. this._pendingPtY = y;
  9821. this._pendingPtDist = d2;
  9822. }
  9823. }
  9824. return this;
  9825. };
  9826. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9827. this._drawPendingPt();
  9828. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9829. if (this._ctx) {
  9830. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9831. }
  9832. this._xi = x3;
  9833. this._yi = y3;
  9834. return this;
  9835. };
  9836. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9837. this._drawPendingPt();
  9838. this.addData(CMD.Q, x1, y1, x2, y2);
  9839. if (this._ctx) {
  9840. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9841. }
  9842. this._xi = x2;
  9843. this._yi = y2;
  9844. return this;
  9845. };
  9846. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9847. this._drawPendingPt();
  9848. tmpAngles[0] = startAngle;
  9849. tmpAngles[1] = endAngle;
  9850. normalizeArcAngles(tmpAngles, anticlockwise);
  9851. startAngle = tmpAngles[0];
  9852. endAngle = tmpAngles[1];
  9853. var delta = endAngle - startAngle;
  9854. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9855. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9856. this._xi = mathCos$1(endAngle) * r + cx;
  9857. this._yi = mathSin$1(endAngle) * r + cy;
  9858. return this;
  9859. };
  9860. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9861. this._drawPendingPt();
  9862. if (this._ctx) {
  9863. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9864. }
  9865. return this;
  9866. };
  9867. PathProxy.prototype.rect = function (x, y, w, h) {
  9868. this._drawPendingPt();
  9869. this._ctx && this._ctx.rect(x, y, w, h);
  9870. this.addData(CMD.R, x, y, w, h);
  9871. return this;
  9872. };
  9873. PathProxy.prototype.closePath = function () {
  9874. this._drawPendingPt();
  9875. this.addData(CMD.Z);
  9876. var ctx = this._ctx;
  9877. var x0 = this._x0;
  9878. var y0 = this._y0;
  9879. if (ctx) {
  9880. ctx.closePath();
  9881. }
  9882. this._xi = x0;
  9883. this._yi = y0;
  9884. return this;
  9885. };
  9886. PathProxy.prototype.fill = function (ctx) {
  9887. ctx && ctx.fill();
  9888. this.toStatic();
  9889. };
  9890. PathProxy.prototype.stroke = function (ctx) {
  9891. ctx && ctx.stroke();
  9892. this.toStatic();
  9893. };
  9894. PathProxy.prototype.len = function () {
  9895. return this._len;
  9896. };
  9897. PathProxy.prototype.setData = function (data) {
  9898. var len = data.length;
  9899. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9900. this.data = new Float32Array(len);
  9901. }
  9902. for (var i = 0; i < len; i++) {
  9903. this.data[i] = data[i];
  9904. }
  9905. this._len = len;
  9906. };
  9907. PathProxy.prototype.appendPath = function (path) {
  9908. if (!(path instanceof Array)) {
  9909. path = [path];
  9910. }
  9911. var len = path.length;
  9912. var appendSize = 0;
  9913. var offset = this._len;
  9914. for (var i = 0; i < len; i++) {
  9915. appendSize += path[i].len();
  9916. }
  9917. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9918. this.data = new Float32Array(offset + appendSize);
  9919. }
  9920. for (var i = 0; i < len; i++) {
  9921. var appendPathData = path[i].data;
  9922. for (var k = 0; k < appendPathData.length; k++) {
  9923. this.data[offset++] = appendPathData[k];
  9924. }
  9925. }
  9926. this._len = offset;
  9927. };
  9928. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9929. if (!this._saveData) {
  9930. return;
  9931. }
  9932. var data = this.data;
  9933. if (this._len + arguments.length > data.length) {
  9934. this._expandData();
  9935. data = this.data;
  9936. }
  9937. for (var i = 0; i < arguments.length; i++) {
  9938. data[this._len++] = arguments[i];
  9939. }
  9940. };
  9941. PathProxy.prototype._drawPendingPt = function () {
  9942. if (this._pendingPtDist > 0) {
  9943. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9944. this._pendingPtDist = 0;
  9945. }
  9946. };
  9947. PathProxy.prototype._expandData = function () {
  9948. if (!(this.data instanceof Array)) {
  9949. var newData = [];
  9950. for (var i = 0; i < this._len; i++) {
  9951. newData[i] = this.data[i];
  9952. }
  9953. this.data = newData;
  9954. }
  9955. };
  9956. PathProxy.prototype.toStatic = function () {
  9957. if (!this._saveData) {
  9958. return;
  9959. }
  9960. this._drawPendingPt();
  9961. var data = this.data;
  9962. if (data instanceof Array) {
  9963. data.length = this._len;
  9964. if (hasTypedArray && this._len > 11) {
  9965. this.data = new Float32Array(data);
  9966. }
  9967. }
  9968. };
  9969. PathProxy.prototype.getBoundingRect = function () {
  9970. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9971. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9972. var data = this.data;
  9973. var xi = 0;
  9974. var yi = 0;
  9975. var x0 = 0;
  9976. var y0 = 0;
  9977. var i;
  9978. for (i = 0; i < this._len;) {
  9979. var cmd = data[i++];
  9980. var isFirst = i === 1;
  9981. if (isFirst) {
  9982. xi = data[i];
  9983. yi = data[i + 1];
  9984. x0 = xi;
  9985. y0 = yi;
  9986. }
  9987. switch (cmd) {
  9988. case CMD.M:
  9989. xi = x0 = data[i++];
  9990. yi = y0 = data[i++];
  9991. min2[0] = x0;
  9992. min2[1] = y0;
  9993. max2[0] = x0;
  9994. max2[1] = y0;
  9995. break;
  9996. case CMD.L:
  9997. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9998. xi = data[i++];
  9999. yi = data[i++];
  10000. break;
  10001. case CMD.C:
  10002. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10003. xi = data[i++];
  10004. yi = data[i++];
  10005. break;
  10006. case CMD.Q:
  10007. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10008. xi = data[i++];
  10009. yi = data[i++];
  10010. break;
  10011. case CMD.A:
  10012. var cx = data[i++];
  10013. var cy = data[i++];
  10014. var rx = data[i++];
  10015. var ry = data[i++];
  10016. var startAngle = data[i++];
  10017. var endAngle = data[i++] + startAngle;
  10018. i += 1;
  10019. var anticlockwise = !data[i++];
  10020. if (isFirst) {
  10021. x0 = mathCos$1(startAngle) * rx + cx;
  10022. y0 = mathSin$1(startAngle) * ry + cy;
  10023. }
  10024. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  10025. xi = mathCos$1(endAngle) * rx + cx;
  10026. yi = mathSin$1(endAngle) * ry + cy;
  10027. break;
  10028. case CMD.R:
  10029. x0 = xi = data[i++];
  10030. y0 = yi = data[i++];
  10031. var width = data[i++];
  10032. var height = data[i++];
  10033. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10034. break;
  10035. case CMD.Z:
  10036. xi = x0;
  10037. yi = y0;
  10038. break;
  10039. }
  10040. min(min$1, min$1, min2);
  10041. max(max$1, max$1, max2);
  10042. }
  10043. if (i === 0) {
  10044. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10045. }
  10046. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  10047. };
  10048. PathProxy.prototype._calculateLength = function () {
  10049. var data = this.data;
  10050. var len = this._len;
  10051. var ux = this._ux;
  10052. var uy = this._uy;
  10053. var xi = 0;
  10054. var yi = 0;
  10055. var x0 = 0;
  10056. var y0 = 0;
  10057. if (!this._pathSegLen) {
  10058. this._pathSegLen = [];
  10059. }
  10060. var pathSegLen = this._pathSegLen;
  10061. var pathTotalLen = 0;
  10062. var segCount = 0;
  10063. for (var i = 0; i < len;) {
  10064. var cmd = data[i++];
  10065. var isFirst = i === 1;
  10066. if (isFirst) {
  10067. xi = data[i];
  10068. yi = data[i + 1];
  10069. x0 = xi;
  10070. y0 = yi;
  10071. }
  10072. var l = -1;
  10073. switch (cmd) {
  10074. case CMD.M:
  10075. xi = x0 = data[i++];
  10076. yi = y0 = data[i++];
  10077. break;
  10078. case CMD.L: {
  10079. var x2 = data[i++];
  10080. var y2 = data[i++];
  10081. var dx = x2 - xi;
  10082. var dy = y2 - yi;
  10083. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  10084. l = Math.sqrt(dx * dx + dy * dy);
  10085. xi = x2;
  10086. yi = y2;
  10087. }
  10088. break;
  10089. }
  10090. case CMD.C: {
  10091. var x1 = data[i++];
  10092. var y1 = data[i++];
  10093. var x2 = data[i++];
  10094. var y2 = data[i++];
  10095. var x3 = data[i++];
  10096. var y3 = data[i++];
  10097. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10098. xi = x3;
  10099. yi = y3;
  10100. break;
  10101. }
  10102. case CMD.Q: {
  10103. var x1 = data[i++];
  10104. var y1 = data[i++];
  10105. var x2 = data[i++];
  10106. var y2 = data[i++];
  10107. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10108. xi = x2;
  10109. yi = y2;
  10110. break;
  10111. }
  10112. case CMD.A:
  10113. var cx = data[i++];
  10114. var cy = data[i++];
  10115. var rx = data[i++];
  10116. var ry = data[i++];
  10117. var startAngle = data[i++];
  10118. var delta = data[i++];
  10119. var endAngle = delta + startAngle;
  10120. i += 1;
  10121. var anticlockwise = !data[i++];
  10122. if (isFirst) {
  10123. x0 = mathCos$1(startAngle) * rx + cx;
  10124. y0 = mathSin$1(startAngle) * ry + cy;
  10125. }
  10126. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10127. xi = mathCos$1(endAngle) * rx + cx;
  10128. yi = mathSin$1(endAngle) * ry + cy;
  10129. break;
  10130. case CMD.R: {
  10131. x0 = xi = data[i++];
  10132. y0 = yi = data[i++];
  10133. var width = data[i++];
  10134. var height = data[i++];
  10135. l = width * 2 + height * 2;
  10136. break;
  10137. }
  10138. case CMD.Z: {
  10139. var dx = x0 - xi;
  10140. var dy = y0 - yi;
  10141. l = Math.sqrt(dx * dx + dy * dy);
  10142. xi = x0;
  10143. yi = y0;
  10144. break;
  10145. }
  10146. }
  10147. if (l >= 0) {
  10148. pathSegLen[segCount++] = l;
  10149. pathTotalLen += l;
  10150. }
  10151. }
  10152. this._pathLen = pathTotalLen;
  10153. return pathTotalLen;
  10154. };
  10155. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10156. var d = this.data;
  10157. var ux = this._ux;
  10158. var uy = this._uy;
  10159. var len = this._len;
  10160. var x0;
  10161. var y0;
  10162. var xi;
  10163. var yi;
  10164. var x;
  10165. var y;
  10166. var drawPart = percent < 1;
  10167. var pathSegLen;
  10168. var pathTotalLen;
  10169. var accumLength = 0;
  10170. var segCount = 0;
  10171. var displayedLength;
  10172. var pendingPtDist = 0;
  10173. var pendingPtX;
  10174. var pendingPtY;
  10175. if (drawPart) {
  10176. if (!this._pathSegLen) {
  10177. this._calculateLength();
  10178. }
  10179. pathSegLen = this._pathSegLen;
  10180. pathTotalLen = this._pathLen;
  10181. displayedLength = percent * pathTotalLen;
  10182. if (!displayedLength) {
  10183. return;
  10184. }
  10185. }
  10186. lo: for (var i = 0; i < len;) {
  10187. var cmd = d[i++];
  10188. var isFirst = i === 1;
  10189. if (isFirst) {
  10190. xi = d[i];
  10191. yi = d[i + 1];
  10192. x0 = xi;
  10193. y0 = yi;
  10194. }
  10195. if (cmd !== CMD.L && pendingPtDist > 0) {
  10196. ctx.lineTo(pendingPtX, pendingPtY);
  10197. pendingPtDist = 0;
  10198. }
  10199. switch (cmd) {
  10200. case CMD.M:
  10201. x0 = xi = d[i++];
  10202. y0 = yi = d[i++];
  10203. ctx.moveTo(xi, yi);
  10204. break;
  10205. case CMD.L: {
  10206. x = d[i++];
  10207. y = d[i++];
  10208. var dx = mathAbs(x - xi);
  10209. var dy = mathAbs(y - yi);
  10210. if (dx > ux || dy > uy) {
  10211. if (drawPart) {
  10212. var l = pathSegLen[segCount++];
  10213. if (accumLength + l > displayedLength) {
  10214. var t = (displayedLength - accumLength) / l;
  10215. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10216. break lo;
  10217. }
  10218. accumLength += l;
  10219. }
  10220. ctx.lineTo(x, y);
  10221. xi = x;
  10222. yi = y;
  10223. pendingPtDist = 0;
  10224. }
  10225. else {
  10226. var d2 = dx * dx + dy * dy;
  10227. if (d2 > pendingPtDist) {
  10228. pendingPtX = x;
  10229. pendingPtY = y;
  10230. pendingPtDist = d2;
  10231. }
  10232. }
  10233. break;
  10234. }
  10235. case CMD.C: {
  10236. var x1 = d[i++];
  10237. var y1 = d[i++];
  10238. var x2 = d[i++];
  10239. var y2 = d[i++];
  10240. var x3 = d[i++];
  10241. var y3 = d[i++];
  10242. if (drawPart) {
  10243. var l = pathSegLen[segCount++];
  10244. if (accumLength + l > displayedLength) {
  10245. var t = (displayedLength - accumLength) / l;
  10246. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10247. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10248. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10249. break lo;
  10250. }
  10251. accumLength += l;
  10252. }
  10253. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10254. xi = x3;
  10255. yi = y3;
  10256. break;
  10257. }
  10258. case CMD.Q: {
  10259. var x1 = d[i++];
  10260. var y1 = d[i++];
  10261. var x2 = d[i++];
  10262. var y2 = d[i++];
  10263. if (drawPart) {
  10264. var l = pathSegLen[segCount++];
  10265. if (accumLength + l > displayedLength) {
  10266. var t = (displayedLength - accumLength) / l;
  10267. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10268. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10269. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10270. break lo;
  10271. }
  10272. accumLength += l;
  10273. }
  10274. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10275. xi = x2;
  10276. yi = y2;
  10277. break;
  10278. }
  10279. case CMD.A:
  10280. var cx = d[i++];
  10281. var cy = d[i++];
  10282. var rx = d[i++];
  10283. var ry = d[i++];
  10284. var startAngle = d[i++];
  10285. var delta = d[i++];
  10286. var psi = d[i++];
  10287. var anticlockwise = !d[i++];
  10288. var r = (rx > ry) ? rx : ry;
  10289. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10290. var endAngle = startAngle + delta;
  10291. var breakBuild = false;
  10292. if (drawPart) {
  10293. var l = pathSegLen[segCount++];
  10294. if (accumLength + l > displayedLength) {
  10295. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10296. breakBuild = true;
  10297. }
  10298. accumLength += l;
  10299. }
  10300. if (isEllipse && ctx.ellipse) {
  10301. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10302. }
  10303. else {
  10304. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10305. }
  10306. if (breakBuild) {
  10307. break lo;
  10308. }
  10309. if (isFirst) {
  10310. x0 = mathCos$1(startAngle) * rx + cx;
  10311. y0 = mathSin$1(startAngle) * ry + cy;
  10312. }
  10313. xi = mathCos$1(endAngle) * rx + cx;
  10314. yi = mathSin$1(endAngle) * ry + cy;
  10315. break;
  10316. case CMD.R:
  10317. x0 = xi = d[i];
  10318. y0 = yi = d[i + 1];
  10319. x = d[i++];
  10320. y = d[i++];
  10321. var width = d[i++];
  10322. var height = d[i++];
  10323. if (drawPart) {
  10324. var l = pathSegLen[segCount++];
  10325. if (accumLength + l > displayedLength) {
  10326. var d_1 = displayedLength - accumLength;
  10327. ctx.moveTo(x, y);
  10328. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10329. d_1 -= width;
  10330. if (d_1 > 0) {
  10331. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10332. }
  10333. d_1 -= height;
  10334. if (d_1 > 0) {
  10335. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10336. }
  10337. d_1 -= width;
  10338. if (d_1 > 0) {
  10339. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10340. }
  10341. break lo;
  10342. }
  10343. accumLength += l;
  10344. }
  10345. ctx.rect(x, y, width, height);
  10346. break;
  10347. case CMD.Z:
  10348. if (drawPart) {
  10349. var l = pathSegLen[segCount++];
  10350. if (accumLength + l > displayedLength) {
  10351. var t = (displayedLength - accumLength) / l;
  10352. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10353. break lo;
  10354. }
  10355. accumLength += l;
  10356. }
  10357. ctx.closePath();
  10358. xi = x0;
  10359. yi = y0;
  10360. }
  10361. }
  10362. };
  10363. PathProxy.prototype.clone = function () {
  10364. var newProxy = new PathProxy();
  10365. var data = this.data;
  10366. newProxy.data = data.slice ? data.slice()
  10367. : Array.prototype.slice.call(data);
  10368. newProxy._len = this._len;
  10369. return newProxy;
  10370. };
  10371. PathProxy.CMD = CMD;
  10372. PathProxy.initDefaultProps = (function () {
  10373. var proto = PathProxy.prototype;
  10374. proto._saveData = true;
  10375. proto._ux = 0;
  10376. proto._uy = 0;
  10377. proto._pendingPtDist = 0;
  10378. proto._version = 0;
  10379. })();
  10380. return PathProxy;
  10381. }());
  10382. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10383. if (lineWidth === 0) {
  10384. return false;
  10385. }
  10386. var _l = lineWidth;
  10387. var _a = 0;
  10388. var _b = x0;
  10389. if ((y > y0 + _l && y > y1 + _l)
  10390. || (y < y0 - _l && y < y1 - _l)
  10391. || (x > x0 + _l && x > x1 + _l)
  10392. || (x < x0 - _l && x < x1 - _l)) {
  10393. return false;
  10394. }
  10395. if (x0 !== x1) {
  10396. _a = (y0 - y1) / (x0 - x1);
  10397. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10398. }
  10399. else {
  10400. return Math.abs(x - x0) <= _l / 2;
  10401. }
  10402. var tmp = _a * x - y + _b;
  10403. var _s = tmp * tmp / (_a * _a + 1);
  10404. return _s <= _l / 2 * _l / 2;
  10405. }
  10406. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10407. if (lineWidth === 0) {
  10408. return false;
  10409. }
  10410. var _l = lineWidth;
  10411. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10412. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10413. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10414. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10415. return false;
  10416. }
  10417. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10418. return d <= _l / 2;
  10419. }
  10420. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10421. if (lineWidth === 0) {
  10422. return false;
  10423. }
  10424. var _l = lineWidth;
  10425. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10426. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10427. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10428. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10429. return false;
  10430. }
  10431. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10432. return d <= _l / 2;
  10433. }
  10434. var PI2$2 = Math.PI * 2;
  10435. function normalizeRadian(angle) {
  10436. angle %= PI2$2;
  10437. if (angle < 0) {
  10438. angle += PI2$2;
  10439. }
  10440. return angle;
  10441. }
  10442. var PI2$3 = Math.PI * 2;
  10443. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10444. if (lineWidth === 0) {
  10445. return false;
  10446. }
  10447. var _l = lineWidth;
  10448. x -= cx;
  10449. y -= cy;
  10450. var d = Math.sqrt(x * x + y * y);
  10451. if ((d - _l > r) || (d + _l < r)) {
  10452. return false;
  10453. }
  10454. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10455. return true;
  10456. }
  10457. if (anticlockwise) {
  10458. var tmp = startAngle;
  10459. startAngle = normalizeRadian(endAngle);
  10460. endAngle = normalizeRadian(tmp);
  10461. }
  10462. else {
  10463. startAngle = normalizeRadian(startAngle);
  10464. endAngle = normalizeRadian(endAngle);
  10465. }
  10466. if (startAngle > endAngle) {
  10467. endAngle += PI2$3;
  10468. }
  10469. var angle = Math.atan2(y, x);
  10470. if (angle < 0) {
  10471. angle += PI2$3;
  10472. }
  10473. return (angle >= startAngle && angle <= endAngle)
  10474. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10475. }
  10476. function windingLine(x0, y0, x1, y1, x, y) {
  10477. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10478. return 0;
  10479. }
  10480. if (y1 === y0) {
  10481. return 0;
  10482. }
  10483. var t = (y - y0) / (y1 - y0);
  10484. var dir = y1 < y0 ? 1 : -1;
  10485. if (t === 1 || t === 0) {
  10486. dir = y1 < y0 ? 0.5 : -0.5;
  10487. }
  10488. var x_ = t * (x1 - x0) + x0;
  10489. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10490. }
  10491. var CMD$1 = PathProxy.CMD;
  10492. var PI2$4 = Math.PI * 2;
  10493. var EPSILON$3 = 1e-4;
  10494. function isAroundEqual(a, b) {
  10495. return Math.abs(a - b) < EPSILON$3;
  10496. }
  10497. var roots = [-1, -1, -1];
  10498. var extrema = [-1, -1];
  10499. function swapExtrema() {
  10500. var tmp = extrema[0];
  10501. extrema[0] = extrema[1];
  10502. extrema[1] = tmp;
  10503. }
  10504. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10505. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10506. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10507. return 0;
  10508. }
  10509. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10510. if (nRoots === 0) {
  10511. return 0;
  10512. }
  10513. else {
  10514. var w = 0;
  10515. var nExtrema = -1;
  10516. var y0_ = void 0;
  10517. var y1_ = void 0;
  10518. for (var i = 0; i < nRoots; i++) {
  10519. var t = roots[i];
  10520. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10521. var x_ = cubicAt(x0, x1, x2, x3, t);
  10522. if (x_ < x) {
  10523. continue;
  10524. }
  10525. if (nExtrema < 0) {
  10526. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10527. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10528. swapExtrema();
  10529. }
  10530. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10531. if (nExtrema > 1) {
  10532. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10533. }
  10534. }
  10535. if (nExtrema === 2) {
  10536. if (t < extrema[0]) {
  10537. w += y0_ < y0 ? unit : -unit;
  10538. }
  10539. else if (t < extrema[1]) {
  10540. w += y1_ < y0_ ? unit : -unit;
  10541. }
  10542. else {
  10543. w += y3 < y1_ ? unit : -unit;
  10544. }
  10545. }
  10546. else {
  10547. if (t < extrema[0]) {
  10548. w += y0_ < y0 ? unit : -unit;
  10549. }
  10550. else {
  10551. w += y3 < y0_ ? unit : -unit;
  10552. }
  10553. }
  10554. }
  10555. return w;
  10556. }
  10557. }
  10558. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10559. if ((y > y0 && y > y1 && y > y2)
  10560. || (y < y0 && y < y1 && y < y2)) {
  10561. return 0;
  10562. }
  10563. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10564. if (nRoots === 0) {
  10565. return 0;
  10566. }
  10567. else {
  10568. var t = quadraticExtremum(y0, y1, y2);
  10569. if (t >= 0 && t <= 1) {
  10570. var w = 0;
  10571. var y_ = quadraticAt(y0, y1, y2, t);
  10572. for (var i = 0; i < nRoots; i++) {
  10573. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10574. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10575. if (x_ < x) {
  10576. continue;
  10577. }
  10578. if (roots[i] < t) {
  10579. w += y_ < y0 ? unit : -unit;
  10580. }
  10581. else {
  10582. w += y2 < y_ ? unit : -unit;
  10583. }
  10584. }
  10585. return w;
  10586. }
  10587. else {
  10588. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10589. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10590. if (x_ < x) {
  10591. return 0;
  10592. }
  10593. return y2 < y0 ? unit : -unit;
  10594. }
  10595. }
  10596. }
  10597. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10598. y -= cy;
  10599. if (y > r || y < -r) {
  10600. return 0;
  10601. }
  10602. var tmp = Math.sqrt(r * r - y * y);
  10603. roots[0] = -tmp;
  10604. roots[1] = tmp;
  10605. var dTheta = Math.abs(startAngle - endAngle);
  10606. if (dTheta < 1e-4) {
  10607. return 0;
  10608. }
  10609. if (dTheta >= PI2$4 - 1e-4) {
  10610. startAngle = 0;
  10611. endAngle = PI2$4;
  10612. var dir = anticlockwise ? 1 : -1;
  10613. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10614. return dir;
  10615. }
  10616. else {
  10617. return 0;
  10618. }
  10619. }
  10620. if (startAngle > endAngle) {
  10621. var tmp_1 = startAngle;
  10622. startAngle = endAngle;
  10623. endAngle = tmp_1;
  10624. }
  10625. if (startAngle < 0) {
  10626. startAngle += PI2$4;
  10627. endAngle += PI2$4;
  10628. }
  10629. var w = 0;
  10630. for (var i = 0; i < 2; i++) {
  10631. var x_ = roots[i];
  10632. if (x_ + cx > x) {
  10633. var angle = Math.atan2(y, x_);
  10634. var dir = anticlockwise ? 1 : -1;
  10635. if (angle < 0) {
  10636. angle = PI2$4 + angle;
  10637. }
  10638. if ((angle >= startAngle && angle <= endAngle)
  10639. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10640. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10641. dir = -dir;
  10642. }
  10643. w += dir;
  10644. }
  10645. }
  10646. }
  10647. return w;
  10648. }
  10649. function containPath(path, lineWidth, isStroke, x, y) {
  10650. var data = path.data;
  10651. var len = path.len();
  10652. var w = 0;
  10653. var xi = 0;
  10654. var yi = 0;
  10655. var x0 = 0;
  10656. var y0 = 0;
  10657. var x1;
  10658. var y1;
  10659. for (var i = 0; i < len;) {
  10660. var cmd = data[i++];
  10661. var isFirst = i === 1;
  10662. if (cmd === CMD$1.M && i > 1) {
  10663. if (!isStroke) {
  10664. w += windingLine(xi, yi, x0, y0, x, y);
  10665. }
  10666. }
  10667. if (isFirst) {
  10668. xi = data[i];
  10669. yi = data[i + 1];
  10670. x0 = xi;
  10671. y0 = yi;
  10672. }
  10673. switch (cmd) {
  10674. case CMD$1.M:
  10675. x0 = data[i++];
  10676. y0 = data[i++];
  10677. xi = x0;
  10678. yi = y0;
  10679. break;
  10680. case CMD$1.L:
  10681. if (isStroke) {
  10682. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10683. return true;
  10684. }
  10685. }
  10686. else {
  10687. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10688. }
  10689. xi = data[i++];
  10690. yi = data[i++];
  10691. break;
  10692. case CMD$1.C:
  10693. if (isStroke) {
  10694. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10695. return true;
  10696. }
  10697. }
  10698. else {
  10699. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10700. }
  10701. xi = data[i++];
  10702. yi = data[i++];
  10703. break;
  10704. case CMD$1.Q:
  10705. if (isStroke) {
  10706. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10707. return true;
  10708. }
  10709. }
  10710. else {
  10711. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10712. }
  10713. xi = data[i++];
  10714. yi = data[i++];
  10715. break;
  10716. case CMD$1.A:
  10717. var cx = data[i++];
  10718. var cy = data[i++];
  10719. var rx = data[i++];
  10720. var ry = data[i++];
  10721. var theta = data[i++];
  10722. var dTheta = data[i++];
  10723. i += 1;
  10724. var anticlockwise = !!(1 - data[i++]);
  10725. x1 = Math.cos(theta) * rx + cx;
  10726. y1 = Math.sin(theta) * ry + cy;
  10727. if (!isFirst) {
  10728. w += windingLine(xi, yi, x1, y1, x, y);
  10729. }
  10730. else {
  10731. x0 = x1;
  10732. y0 = y1;
  10733. }
  10734. var _x = (x - cx) * ry / rx + cx;
  10735. if (isStroke) {
  10736. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10737. return true;
  10738. }
  10739. }
  10740. else {
  10741. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10742. }
  10743. xi = Math.cos(theta + dTheta) * rx + cx;
  10744. yi = Math.sin(theta + dTheta) * ry + cy;
  10745. break;
  10746. case CMD$1.R:
  10747. x0 = xi = data[i++];
  10748. y0 = yi = data[i++];
  10749. var width = data[i++];
  10750. var height = data[i++];
  10751. x1 = x0 + width;
  10752. y1 = y0 + height;
  10753. if (isStroke) {
  10754. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10755. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10756. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10757. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10758. return true;
  10759. }
  10760. }
  10761. else {
  10762. w += windingLine(x1, y0, x1, y1, x, y);
  10763. w += windingLine(x0, y1, x0, y0, x, y);
  10764. }
  10765. break;
  10766. case CMD$1.Z:
  10767. if (isStroke) {
  10768. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10769. return true;
  10770. }
  10771. }
  10772. else {
  10773. w += windingLine(xi, yi, x0, y0, x, y);
  10774. }
  10775. xi = x0;
  10776. yi = y0;
  10777. break;
  10778. }
  10779. }
  10780. if (!isStroke && !isAroundEqual(yi, y0)) {
  10781. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10782. }
  10783. return w !== 0;
  10784. }
  10785. function contain(pathProxy, x, y) {
  10786. return containPath(pathProxy, 0, false, x, y);
  10787. }
  10788. function containStroke$4(pathProxy, lineWidth, x, y) {
  10789. return containPath(pathProxy, lineWidth, true, x, y);
  10790. }
  10791. var DEFAULT_PATH_STYLE = defaults({
  10792. fill: '#000',
  10793. stroke: null,
  10794. strokePercent: 1,
  10795. fillOpacity: 1,
  10796. strokeOpacity: 1,
  10797. lineDashOffset: 0,
  10798. lineWidth: 1,
  10799. lineCap: 'butt',
  10800. miterLimit: 10,
  10801. strokeNoScale: false,
  10802. strokeFirst: false
  10803. }, DEFAULT_COMMON_STYLE);
  10804. var DEFAULT_PATH_ANIMATION_PROPS = {
  10805. style: defaults({
  10806. fill: true,
  10807. stroke: true,
  10808. strokePercent: true,
  10809. fillOpacity: true,
  10810. strokeOpacity: true,
  10811. lineDashOffset: true,
  10812. lineWidth: true,
  10813. miterLimit: true
  10814. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10815. };
  10816. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10817. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10818. ]);
  10819. var Path = (function (_super) {
  10820. __extends(Path, _super);
  10821. function Path(opts) {
  10822. return _super.call(this, opts) || this;
  10823. }
  10824. Path.prototype.update = function () {
  10825. var _this = this;
  10826. _super.prototype.update.call(this);
  10827. var style = this.style;
  10828. if (style.decal) {
  10829. var decalEl = this._decalEl = this._decalEl || new Path();
  10830. if (decalEl.buildPath === Path.prototype.buildPath) {
  10831. decalEl.buildPath = function (ctx) {
  10832. _this.buildPath(ctx, _this.shape);
  10833. };
  10834. }
  10835. decalEl.silent = true;
  10836. var decalElStyle = decalEl.style;
  10837. for (var key in style) {
  10838. if (decalElStyle[key] !== style[key]) {
  10839. decalElStyle[key] = style[key];
  10840. }
  10841. }
  10842. decalElStyle.fill = style.fill ? style.decal : null;
  10843. decalElStyle.decal = null;
  10844. decalElStyle.shadowColor = null;
  10845. style.strokeFirst && (decalElStyle.stroke = null);
  10846. for (var i = 0; i < pathCopyParams.length; ++i) {
  10847. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10848. }
  10849. decalEl.__dirty |= REDRAW_BIT;
  10850. }
  10851. else if (this._decalEl) {
  10852. this._decalEl = null;
  10853. }
  10854. };
  10855. Path.prototype.getDecalElement = function () {
  10856. return this._decalEl;
  10857. };
  10858. Path.prototype._init = function (props) {
  10859. var keysArr = keys(props);
  10860. this.shape = this.getDefaultShape();
  10861. var defaultStyle = this.getDefaultStyle();
  10862. if (defaultStyle) {
  10863. this.useStyle(defaultStyle);
  10864. }
  10865. for (var i = 0; i < keysArr.length; i++) {
  10866. var key = keysArr[i];
  10867. var value = props[key];
  10868. if (key === 'style') {
  10869. if (!this.style) {
  10870. this.useStyle(value);
  10871. }
  10872. else {
  10873. extend(this.style, value);
  10874. }
  10875. }
  10876. else if (key === 'shape') {
  10877. extend(this.shape, value);
  10878. }
  10879. else {
  10880. _super.prototype.attrKV.call(this, key, value);
  10881. }
  10882. }
  10883. if (!this.style) {
  10884. this.useStyle({});
  10885. }
  10886. };
  10887. Path.prototype.getDefaultStyle = function () {
  10888. return null;
  10889. };
  10890. Path.prototype.getDefaultShape = function () {
  10891. return {};
  10892. };
  10893. Path.prototype.canBeInsideText = function () {
  10894. return this.hasFill();
  10895. };
  10896. Path.prototype.getInsideTextFill = function () {
  10897. var pathFill = this.style.fill;
  10898. if (pathFill !== 'none') {
  10899. if (isString(pathFill)) {
  10900. var fillLum = lum(pathFill, 0);
  10901. if (fillLum > 0.5) {
  10902. return DARK_LABEL_COLOR;
  10903. }
  10904. else if (fillLum > 0.2) {
  10905. return LIGHTER_LABEL_COLOR;
  10906. }
  10907. return LIGHT_LABEL_COLOR;
  10908. }
  10909. else if (pathFill) {
  10910. return LIGHT_LABEL_COLOR;
  10911. }
  10912. }
  10913. return DARK_LABEL_COLOR;
  10914. };
  10915. Path.prototype.getInsideTextStroke = function (textFill) {
  10916. var pathFill = this.style.fill;
  10917. if (isString(pathFill)) {
  10918. var zr = this.__zr;
  10919. var isDarkMode = !!(zr && zr.isDarkMode());
  10920. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10921. if (isDarkMode === isDarkLabel) {
  10922. return pathFill;
  10923. }
  10924. }
  10925. };
  10926. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10927. Path.prototype.pathUpdated = function () {
  10928. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10929. };
  10930. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10931. !this.path && this.createPathProxy();
  10932. this.path.beginPath();
  10933. this.buildPath(this.path, this.shape, inBatch);
  10934. return this.path;
  10935. };
  10936. Path.prototype.createPathProxy = function () {
  10937. this.path = new PathProxy(false);
  10938. };
  10939. Path.prototype.hasStroke = function () {
  10940. var style = this.style;
  10941. var stroke = style.stroke;
  10942. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10943. };
  10944. Path.prototype.hasFill = function () {
  10945. var style = this.style;
  10946. var fill = style.fill;
  10947. return fill != null && fill !== 'none';
  10948. };
  10949. Path.prototype.getBoundingRect = function () {
  10950. var rect = this._rect;
  10951. var style = this.style;
  10952. var needsUpdateRect = !rect;
  10953. if (needsUpdateRect) {
  10954. var firstInvoke = false;
  10955. if (!this.path) {
  10956. firstInvoke = true;
  10957. this.createPathProxy();
  10958. }
  10959. var path = this.path;
  10960. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10961. path.beginPath();
  10962. this.buildPath(path, this.shape, false);
  10963. this.pathUpdated();
  10964. }
  10965. rect = path.getBoundingRect();
  10966. }
  10967. this._rect = rect;
  10968. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10969. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10970. if (this.__dirty || needsUpdateRect) {
  10971. rectStroke.copy(rect);
  10972. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10973. var w = style.lineWidth;
  10974. if (!this.hasFill()) {
  10975. var strokeContainThreshold = this.strokeContainThreshold;
  10976. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10977. }
  10978. if (lineScale > 1e-10) {
  10979. rectStroke.width += w / lineScale;
  10980. rectStroke.height += w / lineScale;
  10981. rectStroke.x -= w / lineScale / 2;
  10982. rectStroke.y -= w / lineScale / 2;
  10983. }
  10984. }
  10985. return rectStroke;
  10986. }
  10987. return rect;
  10988. };
  10989. Path.prototype.contain = function (x, y) {
  10990. var localPos = this.transformCoordToLocal(x, y);
  10991. var rect = this.getBoundingRect();
  10992. var style = this.style;
  10993. x = localPos[0];
  10994. y = localPos[1];
  10995. if (rect.contain(x, y)) {
  10996. var pathProxy = this.path;
  10997. if (this.hasStroke()) {
  10998. var lineWidth = style.lineWidth;
  10999. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11000. if (lineScale > 1e-10) {
  11001. if (!this.hasFill()) {
  11002. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11003. }
  11004. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  11005. return true;
  11006. }
  11007. }
  11008. }
  11009. if (this.hasFill()) {
  11010. return contain(pathProxy, x, y);
  11011. }
  11012. }
  11013. return false;
  11014. };
  11015. Path.prototype.dirtyShape = function () {
  11016. this.__dirty |= SHAPE_CHANGED_BIT;
  11017. if (this._rect) {
  11018. this._rect = null;
  11019. }
  11020. if (this._decalEl) {
  11021. this._decalEl.dirtyShape();
  11022. }
  11023. this.markRedraw();
  11024. };
  11025. Path.prototype.dirty = function () {
  11026. this.dirtyStyle();
  11027. this.dirtyShape();
  11028. };
  11029. Path.prototype.animateShape = function (loop) {
  11030. return this.animate('shape', loop);
  11031. };
  11032. Path.prototype.updateDuringAnimation = function (targetKey) {
  11033. if (targetKey === 'style') {
  11034. this.dirtyStyle();
  11035. }
  11036. else if (targetKey === 'shape') {
  11037. this.dirtyShape();
  11038. }
  11039. else {
  11040. this.markRedraw();
  11041. }
  11042. };
  11043. Path.prototype.attrKV = function (key, value) {
  11044. if (key === 'shape') {
  11045. this.setShape(value);
  11046. }
  11047. else {
  11048. _super.prototype.attrKV.call(this, key, value);
  11049. }
  11050. };
  11051. Path.prototype.setShape = function (keyOrObj, value) {
  11052. var shape = this.shape;
  11053. if (!shape) {
  11054. shape = this.shape = {};
  11055. }
  11056. if (typeof keyOrObj === 'string') {
  11057. shape[keyOrObj] = value;
  11058. }
  11059. else {
  11060. extend(shape, keyOrObj);
  11061. }
  11062. this.dirtyShape();
  11063. return this;
  11064. };
  11065. Path.prototype.shapeChanged = function () {
  11066. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  11067. };
  11068. Path.prototype.createStyle = function (obj) {
  11069. return createObject(DEFAULT_PATH_STYLE, obj);
  11070. };
  11071. Path.prototype._innerSaveToNormal = function (toState) {
  11072. _super.prototype._innerSaveToNormal.call(this, toState);
  11073. var normalState = this._normalState;
  11074. if (toState.shape && !normalState.shape) {
  11075. normalState.shape = extend({}, this.shape);
  11076. }
  11077. };
  11078. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  11079. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  11080. var needsRestoreToNormal = !(state && keepCurrentStates);
  11081. var targetShape;
  11082. if (state && state.shape) {
  11083. if (transition) {
  11084. if (keepCurrentStates) {
  11085. targetShape = state.shape;
  11086. }
  11087. else {
  11088. targetShape = extend({}, normalState.shape);
  11089. extend(targetShape, state.shape);
  11090. }
  11091. }
  11092. else {
  11093. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11094. extend(targetShape, state.shape);
  11095. }
  11096. }
  11097. else if (needsRestoreToNormal) {
  11098. targetShape = normalState.shape;
  11099. }
  11100. if (targetShape) {
  11101. if (transition) {
  11102. this.shape = extend({}, this.shape);
  11103. var targetShapePrimaryProps = {};
  11104. var shapeKeys = keys(targetShape);
  11105. for (var i = 0; i < shapeKeys.length; i++) {
  11106. var key = shapeKeys[i];
  11107. if (typeof targetShape[key] === 'object') {
  11108. this.shape[key] = targetShape[key];
  11109. }
  11110. else {
  11111. targetShapePrimaryProps[key] = targetShape[key];
  11112. }
  11113. }
  11114. this._transitionState(stateName, {
  11115. shape: targetShapePrimaryProps
  11116. }, animationCfg);
  11117. }
  11118. else {
  11119. this.shape = targetShape;
  11120. this.dirtyShape();
  11121. }
  11122. }
  11123. };
  11124. Path.prototype._mergeStates = function (states) {
  11125. var mergedState = _super.prototype._mergeStates.call(this, states);
  11126. var mergedShape;
  11127. for (var i = 0; i < states.length; i++) {
  11128. var state = states[i];
  11129. if (state.shape) {
  11130. mergedShape = mergedShape || {};
  11131. this._mergeStyle(mergedShape, state.shape);
  11132. }
  11133. }
  11134. if (mergedShape) {
  11135. mergedState.shape = mergedShape;
  11136. }
  11137. return mergedState;
  11138. };
  11139. Path.prototype.getAnimationStyleProps = function () {
  11140. return DEFAULT_PATH_ANIMATION_PROPS;
  11141. };
  11142. Path.prototype.isZeroArea = function () {
  11143. return false;
  11144. };
  11145. Path.extend = function (defaultProps) {
  11146. var Sub = (function (_super) {
  11147. __extends(Sub, _super);
  11148. function Sub(opts) {
  11149. var _this = _super.call(this, opts) || this;
  11150. defaultProps.init && defaultProps.init.call(_this, opts);
  11151. return _this;
  11152. }
  11153. Sub.prototype.getDefaultStyle = function () {
  11154. return clone(defaultProps.style);
  11155. };
  11156. Sub.prototype.getDefaultShape = function () {
  11157. return clone(defaultProps.shape);
  11158. };
  11159. return Sub;
  11160. }(Path));
  11161. for (var key in defaultProps) {
  11162. if (typeof defaultProps[key] === 'function') {
  11163. Sub.prototype[key] = defaultProps[key];
  11164. }
  11165. }
  11166. return Sub;
  11167. };
  11168. Path.initDefaultProps = (function () {
  11169. var pathProto = Path.prototype;
  11170. pathProto.type = 'path';
  11171. pathProto.strokeContainThreshold = 5;
  11172. pathProto.segmentIgnoreThreshold = 0;
  11173. pathProto.subPixelOptimize = false;
  11174. pathProto.autoBatch = false;
  11175. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11176. })();
  11177. return Path;
  11178. }(Displayable));
  11179. var DEFAULT_TSPAN_STYLE = defaults({
  11180. strokeFirst: true,
  11181. font: DEFAULT_FONT,
  11182. x: 0,
  11183. y: 0,
  11184. textAlign: 'left',
  11185. textBaseline: 'top',
  11186. miterLimit: 2
  11187. }, DEFAULT_PATH_STYLE);
  11188. var TSpan = (function (_super) {
  11189. __extends(TSpan, _super);
  11190. function TSpan() {
  11191. return _super !== null && _super.apply(this, arguments) || this;
  11192. }
  11193. TSpan.prototype.hasStroke = function () {
  11194. var style = this.style;
  11195. var stroke = style.stroke;
  11196. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11197. };
  11198. TSpan.prototype.hasFill = function () {
  11199. var style = this.style;
  11200. var fill = style.fill;
  11201. return fill != null && fill !== 'none';
  11202. };
  11203. TSpan.prototype.createStyle = function (obj) {
  11204. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11205. };
  11206. TSpan.prototype.setBoundingRect = function (rect) {
  11207. this._rect = rect;
  11208. };
  11209. TSpan.prototype.getBoundingRect = function () {
  11210. var style = this.style;
  11211. if (!this._rect) {
  11212. var text = style.text;
  11213. text != null ? (text += '') : (text = '');
  11214. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11215. rect.x += style.x || 0;
  11216. rect.y += style.y || 0;
  11217. if (this.hasStroke()) {
  11218. var w = style.lineWidth;
  11219. rect.x -= w / 2;
  11220. rect.y -= w / 2;
  11221. rect.width += w;
  11222. rect.height += w;
  11223. }
  11224. this._rect = rect;
  11225. }
  11226. return this._rect;
  11227. };
  11228. TSpan.initDefaultProps = (function () {
  11229. var tspanProto = TSpan.prototype;
  11230. tspanProto.dirtyRectTolerance = 10;
  11231. })();
  11232. return TSpan;
  11233. }(Displayable));
  11234. TSpan.prototype.type = 'tspan';
  11235. var DEFAULT_IMAGE_STYLE = defaults({
  11236. x: 0,
  11237. y: 0
  11238. }, DEFAULT_COMMON_STYLE);
  11239. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11240. style: defaults({
  11241. x: true,
  11242. y: true,
  11243. width: true,
  11244. height: true,
  11245. sx: true,
  11246. sy: true,
  11247. sWidth: true,
  11248. sHeight: true
  11249. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11250. };
  11251. function isImageLike(source) {
  11252. return !!(source
  11253. && typeof source !== 'string'
  11254. && source.width && source.height);
  11255. }
  11256. var ZRImage = (function (_super) {
  11257. __extends(ZRImage, _super);
  11258. function ZRImage() {
  11259. return _super !== null && _super.apply(this, arguments) || this;
  11260. }
  11261. ZRImage.prototype.createStyle = function (obj) {
  11262. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11263. };
  11264. ZRImage.prototype._getSize = function (dim) {
  11265. var style = this.style;
  11266. var size = style[dim];
  11267. if (size != null) {
  11268. return size;
  11269. }
  11270. var imageSource = isImageLike(style.image)
  11271. ? style.image : this.__image;
  11272. if (!imageSource) {
  11273. return 0;
  11274. }
  11275. var otherDim = dim === 'width' ? 'height' : 'width';
  11276. var otherDimSize = style[otherDim];
  11277. if (otherDimSize == null) {
  11278. return imageSource[dim];
  11279. }
  11280. else {
  11281. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11282. }
  11283. };
  11284. ZRImage.prototype.getWidth = function () {
  11285. return this._getSize('width');
  11286. };
  11287. ZRImage.prototype.getHeight = function () {
  11288. return this._getSize('height');
  11289. };
  11290. ZRImage.prototype.getAnimationStyleProps = function () {
  11291. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11292. };
  11293. ZRImage.prototype.getBoundingRect = function () {
  11294. var style = this.style;
  11295. if (!this._rect) {
  11296. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11297. }
  11298. return this._rect;
  11299. };
  11300. return ZRImage;
  11301. }(Displayable));
  11302. ZRImage.prototype.type = 'image';
  11303. function buildPath(ctx, shape) {
  11304. var x = shape.x;
  11305. var y = shape.y;
  11306. var width = shape.width;
  11307. var height = shape.height;
  11308. var r = shape.r;
  11309. var r1;
  11310. var r2;
  11311. var r3;
  11312. var r4;
  11313. if (width < 0) {
  11314. x = x + width;
  11315. width = -width;
  11316. }
  11317. if (height < 0) {
  11318. y = y + height;
  11319. height = -height;
  11320. }
  11321. if (typeof r === 'number') {
  11322. r1 = r2 = r3 = r4 = r;
  11323. }
  11324. else if (r instanceof Array) {
  11325. if (r.length === 1) {
  11326. r1 = r2 = r3 = r4 = r[0];
  11327. }
  11328. else if (r.length === 2) {
  11329. r1 = r3 = r[0];
  11330. r2 = r4 = r[1];
  11331. }
  11332. else if (r.length === 3) {
  11333. r1 = r[0];
  11334. r2 = r4 = r[1];
  11335. r3 = r[2];
  11336. }
  11337. else {
  11338. r1 = r[0];
  11339. r2 = r[1];
  11340. r3 = r[2];
  11341. r4 = r[3];
  11342. }
  11343. }
  11344. else {
  11345. r1 = r2 = r3 = r4 = 0;
  11346. }
  11347. var total;
  11348. if (r1 + r2 > width) {
  11349. total = r1 + r2;
  11350. r1 *= width / total;
  11351. r2 *= width / total;
  11352. }
  11353. if (r3 + r4 > width) {
  11354. total = r3 + r4;
  11355. r3 *= width / total;
  11356. r4 *= width / total;
  11357. }
  11358. if (r2 + r3 > height) {
  11359. total = r2 + r3;
  11360. r2 *= height / total;
  11361. r3 *= height / total;
  11362. }
  11363. if (r1 + r4 > height) {
  11364. total = r1 + r4;
  11365. r1 *= height / total;
  11366. r4 *= height / total;
  11367. }
  11368. ctx.moveTo(x + r1, y);
  11369. ctx.lineTo(x + width - r2, y);
  11370. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11371. ctx.lineTo(x + width, y + height - r3);
  11372. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11373. ctx.lineTo(x + r4, y + height);
  11374. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11375. ctx.lineTo(x, y + r1);
  11376. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11377. }
  11378. var round$1 = Math.round;
  11379. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11380. if (!inputShape) {
  11381. return;
  11382. }
  11383. var x1 = inputShape.x1;
  11384. var x2 = inputShape.x2;
  11385. var y1 = inputShape.y1;
  11386. var y2 = inputShape.y2;
  11387. outputShape.x1 = x1;
  11388. outputShape.x2 = x2;
  11389. outputShape.y1 = y1;
  11390. outputShape.y2 = y2;
  11391. var lineWidth = style && style.lineWidth;
  11392. if (!lineWidth) {
  11393. return outputShape;
  11394. }
  11395. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11396. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11397. }
  11398. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11399. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11400. }
  11401. return outputShape;
  11402. }
  11403. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11404. if (!inputShape) {
  11405. return;
  11406. }
  11407. var originX = inputShape.x;
  11408. var originY = inputShape.y;
  11409. var originWidth = inputShape.width;
  11410. var originHeight = inputShape.height;
  11411. outputShape.x = originX;
  11412. outputShape.y = originY;
  11413. outputShape.width = originWidth;
  11414. outputShape.height = originHeight;
  11415. var lineWidth = style && style.lineWidth;
  11416. if (!lineWidth) {
  11417. return outputShape;
  11418. }
  11419. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11420. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11421. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11422. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11423. return outputShape;
  11424. }
  11425. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11426. if (!lineWidth) {
  11427. return position;
  11428. }
  11429. var doubledPosition = round$1(position * 2);
  11430. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11431. ? doubledPosition / 2
  11432. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11433. }
  11434. var RectShape = (function () {
  11435. function RectShape() {
  11436. this.x = 0;
  11437. this.y = 0;
  11438. this.width = 0;
  11439. this.height = 0;
  11440. }
  11441. return RectShape;
  11442. }());
  11443. var subPixelOptimizeOutputShape = {};
  11444. var Rect = (function (_super) {
  11445. __extends(Rect, _super);
  11446. function Rect(opts) {
  11447. return _super.call(this, opts) || this;
  11448. }
  11449. Rect.prototype.getDefaultShape = function () {
  11450. return new RectShape();
  11451. };
  11452. Rect.prototype.buildPath = function (ctx, shape) {
  11453. var x;
  11454. var y;
  11455. var width;
  11456. var height;
  11457. if (this.subPixelOptimize) {
  11458. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11459. x = optimizedShape.x;
  11460. y = optimizedShape.y;
  11461. width = optimizedShape.width;
  11462. height = optimizedShape.height;
  11463. optimizedShape.r = shape.r;
  11464. shape = optimizedShape;
  11465. }
  11466. else {
  11467. x = shape.x;
  11468. y = shape.y;
  11469. width = shape.width;
  11470. height = shape.height;
  11471. }
  11472. if (!shape.r) {
  11473. ctx.rect(x, y, width, height);
  11474. }
  11475. else {
  11476. buildPath(ctx, shape);
  11477. }
  11478. };
  11479. Rect.prototype.isZeroArea = function () {
  11480. return !this.shape.width || !this.shape.height;
  11481. };
  11482. return Rect;
  11483. }(Path));
  11484. Rect.prototype.type = 'rect';
  11485. var DEFAULT_RICH_TEXT_COLOR = {
  11486. fill: '#000'
  11487. };
  11488. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11489. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11490. style: defaults({
  11491. fill: true,
  11492. stroke: true,
  11493. fillOpacity: true,
  11494. strokeOpacity: true,
  11495. lineWidth: true,
  11496. fontSize: true,
  11497. lineHeight: true,
  11498. width: true,
  11499. height: true,
  11500. textShadowColor: true,
  11501. textShadowBlur: true,
  11502. textShadowOffsetX: true,
  11503. textShadowOffsetY: true,
  11504. backgroundColor: true,
  11505. padding: true,
  11506. borderColor: true,
  11507. borderWidth: true,
  11508. borderRadius: true
  11509. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11510. };
  11511. var ZRText = (function (_super) {
  11512. __extends(ZRText, _super);
  11513. function ZRText(opts) {
  11514. var _this = _super.call(this) || this;
  11515. _this.type = 'text';
  11516. _this._children = [];
  11517. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11518. _this.attr(opts);
  11519. return _this;
  11520. }
  11521. ZRText.prototype.childrenRef = function () {
  11522. return this._children;
  11523. };
  11524. ZRText.prototype.update = function () {
  11525. _super.prototype.update.call(this);
  11526. if (this.styleChanged()) {
  11527. this._updateSubTexts();
  11528. }
  11529. for (var i = 0; i < this._children.length; i++) {
  11530. var child = this._children[i];
  11531. child.zlevel = this.zlevel;
  11532. child.z = this.z;
  11533. child.z2 = this.z2;
  11534. child.culling = this.culling;
  11535. child.cursor = this.cursor;
  11536. child.invisible = this.invisible;
  11537. }
  11538. };
  11539. ZRText.prototype.updateTransform = function () {
  11540. var innerTransformable = this.innerTransformable;
  11541. if (innerTransformable) {
  11542. innerTransformable.updateTransform();
  11543. if (innerTransformable.transform) {
  11544. this.transform = innerTransformable.transform;
  11545. }
  11546. }
  11547. else {
  11548. _super.prototype.updateTransform.call(this);
  11549. }
  11550. };
  11551. ZRText.prototype.getLocalTransform = function (m) {
  11552. var innerTransformable = this.innerTransformable;
  11553. return innerTransformable
  11554. ? innerTransformable.getLocalTransform(m)
  11555. : _super.prototype.getLocalTransform.call(this, m);
  11556. };
  11557. ZRText.prototype.getComputedTransform = function () {
  11558. if (this.__hostTarget) {
  11559. this.__hostTarget.getComputedTransform();
  11560. this.__hostTarget.updateInnerText(true);
  11561. }
  11562. return _super.prototype.getComputedTransform.call(this);
  11563. };
  11564. ZRText.prototype._updateSubTexts = function () {
  11565. this._childCursor = 0;
  11566. normalizeTextStyle(this.style);
  11567. this.style.rich
  11568. ? this._updateRichTexts()
  11569. : this._updatePlainTexts();
  11570. this._children.length = this._childCursor;
  11571. this.styleUpdated();
  11572. };
  11573. ZRText.prototype.addSelfToZr = function (zr) {
  11574. _super.prototype.addSelfToZr.call(this, zr);
  11575. for (var i = 0; i < this._children.length; i++) {
  11576. this._children[i].__zr = zr;
  11577. }
  11578. };
  11579. ZRText.prototype.removeSelfFromZr = function (zr) {
  11580. _super.prototype.removeSelfFromZr.call(this, zr);
  11581. for (var i = 0; i < this._children.length; i++) {
  11582. this._children[i].__zr = null;
  11583. }
  11584. };
  11585. ZRText.prototype.getBoundingRect = function () {
  11586. if (this.styleChanged()) {
  11587. this._updateSubTexts();
  11588. }
  11589. if (!this._rect) {
  11590. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11591. var children = this._children;
  11592. var tmpMat = [];
  11593. var rect = null;
  11594. for (var i = 0; i < children.length; i++) {
  11595. var child = children[i];
  11596. var childRect = child.getBoundingRect();
  11597. var transform = child.getLocalTransform(tmpMat);
  11598. if (transform) {
  11599. tmpRect.copy(childRect);
  11600. tmpRect.applyTransform(transform);
  11601. rect = rect || tmpRect.clone();
  11602. rect.union(tmpRect);
  11603. }
  11604. else {
  11605. rect = rect || childRect.clone();
  11606. rect.union(childRect);
  11607. }
  11608. }
  11609. this._rect = rect || tmpRect;
  11610. }
  11611. return this._rect;
  11612. };
  11613. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11614. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11615. };
  11616. ZRText.prototype.setTextContent = function (textContent) {
  11617. if ("development" !== 'production') {
  11618. throw new Error('Can\'t attach text on another text');
  11619. }
  11620. };
  11621. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11622. if (!sourceStyle) {
  11623. return targetStyle;
  11624. }
  11625. var sourceRich = sourceStyle.rich;
  11626. var targetRich = targetStyle.rich || (sourceRich && {});
  11627. extend(targetStyle, sourceStyle);
  11628. if (sourceRich && targetRich) {
  11629. this._mergeRich(targetRich, sourceRich);
  11630. targetStyle.rich = targetRich;
  11631. }
  11632. else if (targetRich) {
  11633. targetStyle.rich = targetRich;
  11634. }
  11635. return targetStyle;
  11636. };
  11637. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11638. var richNames = keys(sourceRich);
  11639. for (var i = 0; i < richNames.length; i++) {
  11640. var richName = richNames[i];
  11641. targetRich[richName] = targetRich[richName] || {};
  11642. extend(targetRich[richName], sourceRich[richName]);
  11643. }
  11644. };
  11645. ZRText.prototype.getAnimationStyleProps = function () {
  11646. return DEFAULT_TEXT_ANIMATION_PROPS;
  11647. };
  11648. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11649. var child = this._children[this._childCursor];
  11650. if (!child || !(child instanceof Ctor)) {
  11651. child = new Ctor();
  11652. }
  11653. this._children[this._childCursor++] = child;
  11654. child.__zr = this.__zr;
  11655. child.parent = this;
  11656. return child;
  11657. };
  11658. ZRText.prototype._updatePlainTexts = function () {
  11659. var style = this.style;
  11660. var textFont = style.font || DEFAULT_FONT;
  11661. var textPadding = style.padding;
  11662. var text = getStyleText(style);
  11663. var contentBlock = parsePlainText(text, style);
  11664. var needDrawBg = needDrawBackground(style);
  11665. var bgColorDrawn = !!(style.backgroundColor);
  11666. var outerHeight = contentBlock.outerHeight;
  11667. var outerWidth = contentBlock.outerWidth;
  11668. var contentWidth = contentBlock.contentWidth;
  11669. var textLines = contentBlock.lines;
  11670. var lineHeight = contentBlock.lineHeight;
  11671. var defaultStyle = this._defaultStyle;
  11672. var baseX = style.x || 0;
  11673. var baseY = style.y || 0;
  11674. var textAlign = style.align || defaultStyle.align || 'left';
  11675. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11676. var textX = baseX;
  11677. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11678. if (needDrawBg || textPadding) {
  11679. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11680. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11681. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11682. }
  11683. textY += lineHeight / 2;
  11684. if (textPadding) {
  11685. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11686. if (verticalAlign === 'top') {
  11687. textY += textPadding[0];
  11688. }
  11689. else if (verticalAlign === 'bottom') {
  11690. textY -= textPadding[2];
  11691. }
  11692. }
  11693. var defaultLineWidth = 0;
  11694. var useDefaultFill = false;
  11695. var textFill = getFill('fill' in style
  11696. ? style.fill
  11697. : (useDefaultFill = true, defaultStyle.fill));
  11698. var textStroke = getStroke('stroke' in style
  11699. ? style.stroke
  11700. : (!bgColorDrawn
  11701. && (!defaultStyle.autoStroke || useDefaultFill))
  11702. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11703. : null);
  11704. var hasShadow = style.textShadowBlur > 0;
  11705. var fixedBoundingRect = style.width != null
  11706. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11707. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11708. for (var i = 0; i < textLines.length; i++) {
  11709. var el = this._getOrCreateChild(TSpan);
  11710. var subElStyle = el.createStyle();
  11711. el.useStyle(subElStyle);
  11712. subElStyle.text = textLines[i];
  11713. subElStyle.x = textX;
  11714. subElStyle.y = textY;
  11715. if (textAlign) {
  11716. subElStyle.textAlign = textAlign;
  11717. }
  11718. subElStyle.textBaseline = 'middle';
  11719. subElStyle.opacity = style.opacity;
  11720. subElStyle.strokeFirst = true;
  11721. if (hasShadow) {
  11722. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11723. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11724. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11725. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11726. }
  11727. subElStyle.stroke = textStroke;
  11728. subElStyle.fill = textFill;
  11729. if (textStroke) {
  11730. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11731. subElStyle.lineDash = style.lineDash;
  11732. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11733. }
  11734. subElStyle.font = textFont;
  11735. setSeparateFont(subElStyle, style);
  11736. textY += lineHeight;
  11737. if (fixedBoundingRect) {
  11738. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11739. }
  11740. }
  11741. };
  11742. ZRText.prototype._updateRichTexts = function () {
  11743. var style = this.style;
  11744. var text = getStyleText(style);
  11745. var contentBlock = parseRichText(text, style);
  11746. var contentWidth = contentBlock.width;
  11747. var outerWidth = contentBlock.outerWidth;
  11748. var outerHeight = contentBlock.outerHeight;
  11749. var textPadding = style.padding;
  11750. var baseX = style.x || 0;
  11751. var baseY = style.y || 0;
  11752. var defaultStyle = this._defaultStyle;
  11753. var textAlign = style.align || defaultStyle.align;
  11754. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11755. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11756. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11757. var xLeft = boxX;
  11758. var lineTop = boxY;
  11759. if (textPadding) {
  11760. xLeft += textPadding[3];
  11761. lineTop += textPadding[0];
  11762. }
  11763. var xRight = xLeft + contentWidth;
  11764. if (needDrawBackground(style)) {
  11765. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11766. }
  11767. var bgColorDrawn = !!(style.backgroundColor);
  11768. for (var i = 0; i < contentBlock.lines.length; i++) {
  11769. var line = contentBlock.lines[i];
  11770. var tokens = line.tokens;
  11771. var tokenCount = tokens.length;
  11772. var lineHeight = line.lineHeight;
  11773. var remainedWidth = line.width;
  11774. var leftIndex = 0;
  11775. var lineXLeft = xLeft;
  11776. var lineXRight = xRight;
  11777. var rightIndex = tokenCount - 1;
  11778. var token = void 0;
  11779. while (leftIndex < tokenCount
  11780. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11781. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11782. remainedWidth -= token.width;
  11783. lineXLeft += token.width;
  11784. leftIndex++;
  11785. }
  11786. while (rightIndex >= 0
  11787. && (token = tokens[rightIndex], token.align === 'right')) {
  11788. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11789. remainedWidth -= token.width;
  11790. lineXRight -= token.width;
  11791. rightIndex--;
  11792. }
  11793. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11794. while (leftIndex <= rightIndex) {
  11795. token = tokens[leftIndex];
  11796. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11797. lineXLeft += token.width;
  11798. leftIndex++;
  11799. }
  11800. lineTop += lineHeight;
  11801. }
  11802. };
  11803. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11804. var tokenStyle = style.rich[token.styleName] || {};
  11805. tokenStyle.text = token.text;
  11806. var verticalAlign = token.verticalAlign;
  11807. var y = lineTop + lineHeight / 2;
  11808. if (verticalAlign === 'top') {
  11809. y = lineTop + token.height / 2;
  11810. }
  11811. else if (verticalAlign === 'bottom') {
  11812. y = lineTop + lineHeight - token.height / 2;
  11813. }
  11814. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11815. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11816. ? x - token.width
  11817. : textAlign === 'center'
  11818. ? x - token.width / 2
  11819. : x, y - token.height / 2, token.width, token.height);
  11820. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11821. var textPadding = token.textPadding;
  11822. if (textPadding) {
  11823. x = getTextXForPadding(x, textAlign, textPadding);
  11824. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11825. }
  11826. var el = this._getOrCreateChild(TSpan);
  11827. var subElStyle = el.createStyle();
  11828. el.useStyle(subElStyle);
  11829. var defaultStyle = this._defaultStyle;
  11830. var useDefaultFill = false;
  11831. var defaultLineWidth = 0;
  11832. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11833. : 'fill' in style ? style.fill
  11834. : (useDefaultFill = true, defaultStyle.fill));
  11835. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11836. : 'stroke' in style ? style.stroke
  11837. : (!bgColorDrawn
  11838. && !parentBgColorDrawn
  11839. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11840. : null);
  11841. var hasShadow = tokenStyle.textShadowBlur > 0
  11842. || style.textShadowBlur > 0;
  11843. subElStyle.text = token.text;
  11844. subElStyle.x = x;
  11845. subElStyle.y = y;
  11846. if (hasShadow) {
  11847. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11848. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11849. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11850. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11851. }
  11852. subElStyle.textAlign = textAlign;
  11853. subElStyle.textBaseline = 'middle';
  11854. subElStyle.font = token.font || DEFAULT_FONT;
  11855. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11856. setSeparateFont(subElStyle, tokenStyle);
  11857. if (textStroke) {
  11858. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11859. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11860. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11861. subElStyle.stroke = textStroke;
  11862. }
  11863. if (textFill) {
  11864. subElStyle.fill = textFill;
  11865. }
  11866. var textWidth = token.contentWidth;
  11867. var textHeight = token.contentHeight;
  11868. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11869. };
  11870. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11871. var textBackgroundColor = style.backgroundColor;
  11872. var textBorderWidth = style.borderWidth;
  11873. var textBorderColor = style.borderColor;
  11874. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11875. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11876. var textBorderRadius = style.borderRadius;
  11877. var self = this;
  11878. var rectEl;
  11879. var imgEl;
  11880. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11881. rectEl = this._getOrCreateChild(Rect);
  11882. rectEl.useStyle(rectEl.createStyle());
  11883. rectEl.style.fill = null;
  11884. var rectShape = rectEl.shape;
  11885. rectShape.x = x;
  11886. rectShape.y = y;
  11887. rectShape.width = width;
  11888. rectShape.height = height;
  11889. rectShape.r = textBorderRadius;
  11890. rectEl.dirtyShape();
  11891. }
  11892. if (isPlainOrGradientBg) {
  11893. var rectStyle = rectEl.style;
  11894. rectStyle.fill = textBackgroundColor || null;
  11895. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11896. }
  11897. else if (isImageBg) {
  11898. imgEl = this._getOrCreateChild(ZRImage);
  11899. imgEl.onload = function () {
  11900. self.dirtyStyle();
  11901. };
  11902. var imgStyle = imgEl.style;
  11903. imgStyle.image = textBackgroundColor.image;
  11904. imgStyle.x = x;
  11905. imgStyle.y = y;
  11906. imgStyle.width = width;
  11907. imgStyle.height = height;
  11908. }
  11909. if (textBorderWidth && textBorderColor) {
  11910. var rectStyle = rectEl.style;
  11911. rectStyle.lineWidth = textBorderWidth;
  11912. rectStyle.stroke = textBorderColor;
  11913. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11914. rectStyle.lineDash = style.borderDash;
  11915. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11916. rectEl.strokeContainThreshold = 0;
  11917. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11918. rectStyle.strokeFirst = true;
  11919. rectStyle.lineWidth *= 2;
  11920. }
  11921. }
  11922. var commonStyle = (rectEl || imgEl).style;
  11923. commonStyle.shadowBlur = style.shadowBlur || 0;
  11924. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11925. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11926. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11927. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11928. };
  11929. ZRText.makeFont = function (style) {
  11930. var font = '';
  11931. if (hasSeparateFont(style)) {
  11932. font = [
  11933. style.fontStyle,
  11934. style.fontWeight,
  11935. parseFontSize(style.fontSize),
  11936. style.fontFamily || 'sans-serif'
  11937. ].join(' ');
  11938. }
  11939. return font && trim(font) || style.textFont || style.font;
  11940. };
  11941. return ZRText;
  11942. }(Displayable));
  11943. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11944. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11945. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11946. function parseFontSize(fontSize) {
  11947. if (typeof fontSize === 'string'
  11948. && (fontSize.indexOf('px') !== -1
  11949. || fontSize.indexOf('rem') !== -1
  11950. || fontSize.indexOf('em') !== -1)) {
  11951. return fontSize;
  11952. }
  11953. else if (!isNaN(+fontSize)) {
  11954. return fontSize + 'px';
  11955. }
  11956. else {
  11957. return DEFAULT_FONT_SIZE + 'px';
  11958. }
  11959. }
  11960. function setSeparateFont(targetStyle, sourceStyle) {
  11961. for (var i = 0; i < FONT_PARTS.length; i++) {
  11962. var fontProp = FONT_PARTS[i];
  11963. var val = sourceStyle[fontProp];
  11964. if (val != null) {
  11965. targetStyle[fontProp] = val;
  11966. }
  11967. }
  11968. }
  11969. function hasSeparateFont(style) {
  11970. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11971. }
  11972. function normalizeTextStyle(style) {
  11973. normalizeStyle(style);
  11974. each(style.rich, normalizeStyle);
  11975. return style;
  11976. }
  11977. function normalizeStyle(style) {
  11978. if (style) {
  11979. style.font = ZRText.makeFont(style);
  11980. var textAlign = style.align;
  11981. textAlign === 'middle' && (textAlign = 'center');
  11982. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11983. var verticalAlign = style.verticalAlign;
  11984. verticalAlign === 'center' && (verticalAlign = 'middle');
  11985. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11986. var textPadding = style.padding;
  11987. if (textPadding) {
  11988. style.padding = normalizeCssArray(style.padding);
  11989. }
  11990. }
  11991. }
  11992. function getStroke(stroke, lineWidth) {
  11993. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11994. ? null
  11995. : (stroke.image || stroke.colorStops)
  11996. ? '#000'
  11997. : stroke;
  11998. }
  11999. function getFill(fill) {
  12000. return (fill == null || fill === 'none')
  12001. ? null
  12002. : (fill.image || fill.colorStops)
  12003. ? '#000'
  12004. : fill;
  12005. }
  12006. function getTextXForPadding(x, textAlign, textPadding) {
  12007. return textAlign === 'right'
  12008. ? (x - textPadding[1])
  12009. : textAlign === 'center'
  12010. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  12011. : (x + textPadding[3]);
  12012. }
  12013. function getStyleText(style) {
  12014. var text = style.text;
  12015. text != null && (text += '');
  12016. return text;
  12017. }
  12018. function needDrawBackground(style) {
  12019. return !!(style.backgroundColor
  12020. || style.lineHeight
  12021. || (style.borderWidth && style.borderColor));
  12022. }
  12023. var getECData = makeInner();
  12024. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  12025. if (el) {
  12026. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  12027. // Useful in tooltip
  12028. ecData.dataIndex = dataIdx;
  12029. ecData.dataType = dataType;
  12030. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  12031. if (el.type === 'group') {
  12032. el.traverse(function (child) {
  12033. var childECData = getECData(child);
  12034. childECData.seriesIndex = seriesIndex;
  12035. childECData.dataIndex = dataIdx;
  12036. childECData.dataType = dataType;
  12037. });
  12038. }
  12039. }
  12040. };
  12041. var _highlightNextDigit = 1;
  12042. var _highlightKeyMap = {};
  12043. var getSavedStates = makeInner();
  12044. var getComponentStates = makeInner();
  12045. var HOVER_STATE_NORMAL = 0;
  12046. var HOVER_STATE_BLUR = 1;
  12047. var HOVER_STATE_EMPHASIS = 2;
  12048. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  12049. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  12050. var Z2_EMPHASIS_LIFT = 10;
  12051. var Z2_SELECT_LIFT = 9;
  12052. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  12053. var DOWNPLAY_ACTION_TYPE = 'downplay';
  12054. var SELECT_ACTION_TYPE = 'select';
  12055. var UNSELECT_ACTION_TYPE = 'unselect';
  12056. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  12057. function hasFillOrStroke(fillOrStroke) {
  12058. return fillOrStroke != null && fillOrStroke !== 'none';
  12059. } // Most lifted color are duplicated.
  12060. var liftedColorCache = new LRU(100);
  12061. function liftColor(color$1) {
  12062. if (isString(color$1)) {
  12063. var liftedColor = liftedColorCache.get(color$1);
  12064. if (!liftedColor) {
  12065. liftedColor = lift(color$1, -0.1);
  12066. liftedColorCache.put(color$1, liftedColor);
  12067. }
  12068. return liftedColor;
  12069. } else if (isGradientObject(color$1)) {
  12070. var ret = extend({}, color$1);
  12071. ret.colorStops = map(color$1.colorStops, function (stop) {
  12072. return {
  12073. offset: stop.offset,
  12074. color: lift(stop.color, -0.1)
  12075. };
  12076. });
  12077. return ret;
  12078. } // Change nothing.
  12079. return color$1;
  12080. }
  12081. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12082. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12083. el.onHoverStateChange(stateName);
  12084. }
  12085. el.hoverState = hoverStateEnum;
  12086. }
  12087. function singleEnterEmphasis(el) {
  12088. // Only mark the flag.
  12089. // States will be applied in the echarts.ts in next frame.
  12090. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12091. }
  12092. function singleLeaveEmphasis(el) {
  12093. // Only mark the flag.
  12094. // States will be applied in the echarts.ts in next frame.
  12095. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12096. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12097. }
  12098. }
  12099. function singleEnterBlur(el) {
  12100. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12101. }
  12102. function singleLeaveBlur(el) {
  12103. if (el.hoverState === HOVER_STATE_BLUR) {
  12104. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12105. }
  12106. }
  12107. function singleEnterSelect(el) {
  12108. el.selected = true;
  12109. }
  12110. function singleLeaveSelect(el) {
  12111. el.selected = false;
  12112. }
  12113. function updateElementState(el, updater, commonParam) {
  12114. updater(el, commonParam);
  12115. }
  12116. function traverseUpdateState(el, updater, commonParam) {
  12117. updateElementState(el, updater, commonParam);
  12118. el.isGroup && el.traverse(function (child) {
  12119. updateElementState(child, updater, commonParam);
  12120. });
  12121. }
  12122. function setStatesFlag(el, stateName) {
  12123. switch (stateName) {
  12124. case 'emphasis':
  12125. el.hoverState = HOVER_STATE_EMPHASIS;
  12126. break;
  12127. case 'normal':
  12128. el.hoverState = HOVER_STATE_NORMAL;
  12129. break;
  12130. case 'blur':
  12131. el.hoverState = HOVER_STATE_BLUR;
  12132. break;
  12133. case 'select':
  12134. el.selected = true;
  12135. }
  12136. }
  12137. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12138. var style = el.style;
  12139. var fromState = {};
  12140. for (var i = 0; i < props.length; i++) {
  12141. var propName = props[i];
  12142. var val = style[propName];
  12143. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12144. }
  12145. for (var i = 0; i < el.animators.length; i++) {
  12146. var animator = el.animators[i];
  12147. if (animator.__fromStateTransition // Don't consider the animation to emphasis state.
  12148. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12149. animator.saveTo(fromState, props);
  12150. }
  12151. }
  12152. return fromState;
  12153. }
  12154. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12155. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12156. var cloned = false;
  12157. if (el instanceof Path) {
  12158. var store = getSavedStates(el);
  12159. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12160. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12161. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12162. state = state || {};
  12163. var emphasisStyle = state.style || {}; // inherit case
  12164. if (emphasisStyle.fill === 'inherit') {
  12165. cloned = true;
  12166. state = extend({}, state);
  12167. emphasisStyle = extend({}, emphasisStyle);
  12168. emphasisStyle.fill = fromFill;
  12169. } // Apply default color lift
  12170. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12171. cloned = true; // Not modify the original value.
  12172. state = extend({}, state);
  12173. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  12174. emphasisStyle.fill = liftColor(fromFill);
  12175. } // Not highlight stroke if fill has been highlighted.
  12176. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12177. if (!cloned) {
  12178. state = extend({}, state);
  12179. emphasisStyle = extend({}, emphasisStyle);
  12180. }
  12181. emphasisStyle.stroke = liftColor(fromStroke);
  12182. }
  12183. state.style = emphasisStyle;
  12184. }
  12185. }
  12186. if (state) {
  12187. // TODO Share with textContent?
  12188. if (state.z2 == null) {
  12189. if (!cloned) {
  12190. state = extend({}, state);
  12191. }
  12192. var z2EmphasisLift = el.z2EmphasisLift;
  12193. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12194. }
  12195. }
  12196. return state;
  12197. }
  12198. function createSelectDefaultState(el, stateName, state) {
  12199. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12200. if (state) {
  12201. // TODO Share with textContent?
  12202. if (state.z2 == null) {
  12203. state = extend({}, state);
  12204. var z2SelectLift = el.z2SelectLift;
  12205. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12206. }
  12207. }
  12208. return state;
  12209. }
  12210. function createBlurDefaultState(el, stateName, state) {
  12211. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12212. var currentOpacity = el.style.opacity;
  12213. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12214. opacity: 1
  12215. }) : null;
  12216. state = state || {};
  12217. var blurStyle = state.style || {};
  12218. if (blurStyle.opacity == null) {
  12219. // clone state
  12220. state = extend({}, state);
  12221. blurStyle = extend({
  12222. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12223. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12224. }, blurStyle);
  12225. state.style = blurStyle;
  12226. }
  12227. return state;
  12228. }
  12229. function elementStateProxy(stateName, targetStates) {
  12230. var state = this.states[stateName];
  12231. if (this.style) {
  12232. if (stateName === 'emphasis') {
  12233. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12234. } else if (stateName === 'blur') {
  12235. return createBlurDefaultState(this, stateName, state);
  12236. } else if (stateName === 'select') {
  12237. return createSelectDefaultState(this, stateName, state);
  12238. }
  12239. }
  12240. return state;
  12241. }
  12242. /**
  12243. * Set hover style (namely "emphasis style") of element.
  12244. * @param el Should not be `zrender/graphic/Group`.
  12245. * @param focus 'self' | 'selfInSeries' | 'series'
  12246. */
  12247. function setDefaultStateProxy(el) {
  12248. el.stateProxy = elementStateProxy;
  12249. var textContent = el.getTextContent();
  12250. var textGuide = el.getTextGuideLine();
  12251. if (textContent) {
  12252. textContent.stateProxy = elementStateProxy;
  12253. }
  12254. if (textGuide) {
  12255. textGuide.stateProxy = elementStateProxy;
  12256. }
  12257. }
  12258. function enterEmphasisWhenMouseOver(el, e) {
  12259. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12260. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12261. }
  12262. function leaveEmphasisWhenMouseOut(el, e) {
  12263. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12264. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12265. }
  12266. function enterEmphasis(el, highlightDigit) {
  12267. el.__highByOuter |= 1 << (highlightDigit || 0);
  12268. traverseUpdateState(el, singleEnterEmphasis);
  12269. }
  12270. function leaveEmphasis(el, highlightDigit) {
  12271. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12272. }
  12273. function enterBlur(el) {
  12274. traverseUpdateState(el, singleEnterBlur);
  12275. }
  12276. function leaveBlur(el) {
  12277. traverseUpdateState(el, singleLeaveBlur);
  12278. }
  12279. function enterSelect(el) {
  12280. traverseUpdateState(el, singleEnterSelect);
  12281. }
  12282. function leaveSelect(el) {
  12283. traverseUpdateState(el, singleLeaveSelect);
  12284. }
  12285. function shouldSilent(el, e) {
  12286. return el.__highDownSilentOnTouch && e.zrByTouch;
  12287. }
  12288. function allLeaveBlur(api) {
  12289. var model = api.getModel();
  12290. var leaveBlurredSeries = [];
  12291. var allComponentViews = [];
  12292. model.eachComponent(function (componentType, componentModel) {
  12293. var componentStates = getComponentStates(componentModel);
  12294. var isSeries = componentType === 'series';
  12295. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12296. !isSeries && allComponentViews.push(view);
  12297. if (componentStates.isBlured) {
  12298. // Leave blur anyway
  12299. view.group.traverse(function (child) {
  12300. singleLeaveBlur(child);
  12301. });
  12302. isSeries && leaveBlurredSeries.push(componentModel);
  12303. }
  12304. componentStates.isBlured = false;
  12305. });
  12306. each(allComponentViews, function (view) {
  12307. if (view && view.toggleBlurSeries) {
  12308. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12309. }
  12310. });
  12311. }
  12312. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12313. var ecModel = api.getModel();
  12314. blurScope = blurScope || 'coordinateSystem';
  12315. function leaveBlurOfIndices(data, dataIndices) {
  12316. for (var i = 0; i < dataIndices.length; i++) {
  12317. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12318. itemEl && leaveBlur(itemEl);
  12319. }
  12320. }
  12321. if (targetSeriesIndex == null) {
  12322. return;
  12323. }
  12324. if (!focus || focus === 'none') {
  12325. return;
  12326. }
  12327. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12328. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12329. if (targetCoordSys && targetCoordSys.master) {
  12330. targetCoordSys = targetCoordSys.master;
  12331. }
  12332. var blurredSeries = [];
  12333. ecModel.eachSeries(function (seriesModel) {
  12334. var sameSeries = targetSeriesModel === seriesModel;
  12335. var coordSys = seriesModel.coordinateSystem;
  12336. if (coordSys && coordSys.master) {
  12337. coordSys = coordSys.master;
  12338. }
  12339. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12340. if (!( // Not blur other series if blurScope series
  12341. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  12342. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  12343. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  12344. )) {
  12345. var view = api.getViewOfSeriesModel(seriesModel);
  12346. view.group.traverse(function (child) {
  12347. singleEnterBlur(child);
  12348. });
  12349. if (isArrayLike(focus)) {
  12350. leaveBlurOfIndices(seriesModel.getData(), focus);
  12351. } else if (isObject(focus)) {
  12352. var dataTypes = keys(focus);
  12353. for (var d = 0; d < dataTypes.length; d++) {
  12354. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12355. }
  12356. }
  12357. blurredSeries.push(seriesModel);
  12358. getComponentStates(seriesModel).isBlured = true;
  12359. }
  12360. });
  12361. ecModel.eachComponent(function (componentType, componentModel) {
  12362. if (componentType === 'series') {
  12363. return;
  12364. }
  12365. var view = api.getViewOfComponentModel(componentModel);
  12366. if (view && view.toggleBlurSeries) {
  12367. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12368. }
  12369. });
  12370. }
  12371. function blurComponent(componentMainType, componentIndex, api) {
  12372. if (componentMainType == null || componentIndex == null) {
  12373. return;
  12374. }
  12375. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12376. if (!componentModel) {
  12377. return;
  12378. }
  12379. getComponentStates(componentModel).isBlured = true;
  12380. var view = api.getViewOfComponentModel(componentModel);
  12381. if (!view || !view.focusBlurEnabled) {
  12382. return;
  12383. }
  12384. view.group.traverse(function (child) {
  12385. singleEnterBlur(child);
  12386. });
  12387. }
  12388. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12389. var seriesIndex = seriesModel.seriesIndex;
  12390. var data = seriesModel.getData(payload.dataType);
  12391. if (!data) {
  12392. if ("development" !== 'production') {
  12393. error("Unknown dataType " + payload.dataType);
  12394. }
  12395. return;
  12396. }
  12397. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12398. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12399. var el = data.getItemGraphicEl(dataIndex);
  12400. if (!el) {
  12401. var count = data.count();
  12402. var current = 0; // If data on dataIndex is NaN.
  12403. while (!el && current < count) {
  12404. el = data.getItemGraphicEl(current++);
  12405. }
  12406. }
  12407. if (el) {
  12408. var ecData = getECData(el);
  12409. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12410. } else {
  12411. // If there is no element put on the data. Try getting it from raw option
  12412. // TODO Should put it on seriesModel?
  12413. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12414. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12415. if (focus_1 != null) {
  12416. blurSeries(seriesIndex, focus_1, blurScope, api);
  12417. }
  12418. }
  12419. }
  12420. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12421. var ret = {
  12422. focusSelf: false,
  12423. dispatchers: null
  12424. };
  12425. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12426. return ret;
  12427. }
  12428. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12429. if (!componentModel) {
  12430. return ret;
  12431. }
  12432. var view = api.getViewOfComponentModel(componentModel);
  12433. if (!view || !view.findHighDownDispatchers) {
  12434. return ret;
  12435. }
  12436. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12437. // So we do not use `blurScope` in component.
  12438. var focusSelf;
  12439. for (var i = 0; i < dispatchers.length; i++) {
  12440. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12441. error('param should be highDownDispatcher');
  12442. }
  12443. if (getECData(dispatchers[i]).focus === 'self') {
  12444. focusSelf = true;
  12445. break;
  12446. }
  12447. }
  12448. return {
  12449. focusSelf: focusSelf,
  12450. dispatchers: dispatchers
  12451. };
  12452. }
  12453. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12454. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12455. error('param should be highDownDispatcher');
  12456. }
  12457. var ecData = getECData(dispatcher);
  12458. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12459. dispatchers = _a.dispatchers,
  12460. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12461. // highlight/downplay elements with the same name.
  12462. if (dispatchers) {
  12463. if (focusSelf) {
  12464. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12465. }
  12466. each(dispatchers, function (dispatcher) {
  12467. return enterEmphasisWhenMouseOver(dispatcher, e);
  12468. });
  12469. } else {
  12470. // Try blur all in the related series. Then emphasis the hoverred.
  12471. // TODO. progressive mode.
  12472. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12473. if (ecData.focus === 'self') {
  12474. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12475. } // Other than series, component that not support `findHighDownDispatcher` will
  12476. // also use it. But in this case, highlight/downplay are only supported in
  12477. // mouse hover but not in dispatchAction.
  12478. enterEmphasisWhenMouseOver(dispatcher, e);
  12479. }
  12480. }
  12481. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12482. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12483. error('param should be highDownDispatcher');
  12484. }
  12485. allLeaveBlur(api);
  12486. var ecData = getECData(dispatcher);
  12487. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12488. if (dispatchers) {
  12489. each(dispatchers, function (dispatcher) {
  12490. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12491. });
  12492. } else {
  12493. leaveEmphasisWhenMouseOut(dispatcher, e);
  12494. }
  12495. }
  12496. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12497. if (!isSelectChangePayload(payload)) {
  12498. return;
  12499. }
  12500. var dataType = payload.dataType;
  12501. var data = seriesModel.getData(dataType);
  12502. var dataIndex = queryDataIndex(data, payload);
  12503. if (!isArray(dataIndex)) {
  12504. dataIndex = [dataIndex];
  12505. }
  12506. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12507. }
  12508. function updateSeriesElementSelection(seriesModel) {
  12509. var allData = seriesModel.getAllData();
  12510. each(allData, function (_a) {
  12511. var data = _a.data,
  12512. type = _a.type;
  12513. data.eachItemGraphicEl(function (el, idx) {
  12514. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12515. });
  12516. });
  12517. }
  12518. function getAllSelectedIndices(ecModel) {
  12519. var ret = [];
  12520. ecModel.eachSeries(function (seriesModel) {
  12521. var allData = seriesModel.getAllData();
  12522. each(allData, function (_a) {
  12523. var data = _a.data,
  12524. type = _a.type;
  12525. var dataIndices = seriesModel.getSelectedDataIndices();
  12526. if (dataIndices.length > 0) {
  12527. var item = {
  12528. dataIndex: dataIndices,
  12529. seriesIndex: seriesModel.seriesIndex
  12530. };
  12531. if (type != null) {
  12532. item.dataType = type;
  12533. }
  12534. ret.push(item);
  12535. }
  12536. });
  12537. });
  12538. return ret;
  12539. }
  12540. /**
  12541. * Enable the function that mouseover will trigger the emphasis state.
  12542. *
  12543. * NOTE:
  12544. * This function should be used on the element with dataIndex, seriesIndex.
  12545. *
  12546. */
  12547. function enableHoverEmphasis(el, focus, blurScope) {
  12548. setAsHighDownDispatcher(el, true);
  12549. traverseUpdateState(el, setDefaultStateProxy);
  12550. enableHoverFocus(el, focus, blurScope);
  12551. }
  12552. function disableHoverEmphasis(el) {
  12553. setAsHighDownDispatcher(el, false);
  12554. }
  12555. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12556. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12557. }
  12558. function enableHoverFocus(el, focus, blurScope) {
  12559. var ecData = getECData(el);
  12560. if (focus != null) {
  12561. // TODO dataIndex may be set after this function. This check is not useful.
  12562. // if (ecData.dataIndex == null) {
  12563. // if (__DEV__) {
  12564. // console.warn('focus can only been set on element with dataIndex');
  12565. // }
  12566. // }
  12567. // else {
  12568. ecData.focus = focus;
  12569. ecData.blurScope = blurScope; // }
  12570. } else if (ecData.focus) {
  12571. ecData.focus = null;
  12572. }
  12573. }
  12574. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12575. var defaultStyleGetterMap = {
  12576. itemStyle: 'getItemStyle',
  12577. lineStyle: 'getLineStyle',
  12578. areaStyle: 'getAreaStyle'
  12579. };
  12580. /**
  12581. * Set emphasis/blur/selected states of element.
  12582. */
  12583. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12584. getter) {
  12585. styleType = styleType || 'itemStyle';
  12586. for (var i = 0; i < OTHER_STATES.length; i++) {
  12587. var stateName = OTHER_STATES[i];
  12588. var model = itemModel.getModel([stateName, styleType]);
  12589. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12590. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12591. }
  12592. }
  12593. /**
  12594. *
  12595. * Set element as highlight / downplay dispatcher.
  12596. * It will be checked when element received mouseover event or from highlight action.
  12597. * It's in change of all highlight/downplay behavior of it's children.
  12598. *
  12599. * @param el
  12600. * @param el.highDownSilentOnTouch
  12601. * In touch device, mouseover event will be trigger on touchstart event
  12602. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12603. * conveniently use hoverStyle when tap on touch screen without additional
  12604. * code for compatibility.
  12605. * But if the chart/component has select feature, which usually also use
  12606. * hoverStyle, there might be conflict between 'select-highlight' and
  12607. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12608. * In this case, `highDownSilentOnTouch` should be used to disable
  12609. * hover-highlight on touch device.
  12610. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12611. */
  12612. function setAsHighDownDispatcher(el, asDispatcher) {
  12613. var disable = asDispatcher === false;
  12614. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12615. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12616. if (el.highDownSilentOnTouch) {
  12617. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12618. } // Simple optimize, since this method might be
  12619. // called for each elements of a group in some cases.
  12620. if (!disable || extendedEl.__highDownDispatcher) {
  12621. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12622. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12623. // Also keep previous record.
  12624. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12625. extendedEl.__highDownDispatcher = !disable;
  12626. }
  12627. }
  12628. function isHighDownDispatcher(el) {
  12629. return !!(el && el.__highDownDispatcher);
  12630. }
  12631. /**
  12632. * Enable component highlight/downplay features:
  12633. * + hover link (within the same name)
  12634. * + focus blur in component
  12635. */
  12636. function enableComponentHighDownFeatures(el, componentModel, componentHighDownName) {
  12637. var ecData = getECData(el);
  12638. ecData.componentMainType = componentModel.mainType;
  12639. ecData.componentIndex = componentModel.componentIndex;
  12640. ecData.componentHighDownName = componentHighDownName;
  12641. }
  12642. /**
  12643. * Support highlight/downplay record on each elements.
  12644. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12645. * user triggered highlight/downplay should not conflict.
  12646. * Only all of the highlightDigit cleared, return to normal.
  12647. * @param {string} highlightKey
  12648. * @return {number} highlightDigit
  12649. */
  12650. function getHighlightDigit(highlightKey) {
  12651. var highlightDigit = _highlightKeyMap[highlightKey];
  12652. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12653. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12654. }
  12655. return highlightDigit;
  12656. }
  12657. function isSelectChangePayload(payload) {
  12658. var payloadType = payload.type;
  12659. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12660. }
  12661. function isHighDownPayload(payload) {
  12662. var payloadType = payload.type;
  12663. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12664. }
  12665. function savePathStates(el) {
  12666. var store = getSavedStates(el);
  12667. store.normalFill = el.style.fill;
  12668. store.normalStroke = el.style.stroke;
  12669. var selectState = el.states.select || {};
  12670. store.selectFill = selectState.style && selectState.style.fill || null;
  12671. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12672. }
  12673. var CMD$2 = PathProxy.CMD;
  12674. var points = [[], [], []];
  12675. var mathSqrt$1 = Math.sqrt;
  12676. var mathAtan2 = Math.atan2;
  12677. function transformPath(path, m) {
  12678. if (!m) {
  12679. return;
  12680. }
  12681. var data = path.data;
  12682. var len = path.len();
  12683. var cmd;
  12684. var nPoint;
  12685. var i;
  12686. var j;
  12687. var k;
  12688. var p;
  12689. var M = CMD$2.M;
  12690. var C = CMD$2.C;
  12691. var L = CMD$2.L;
  12692. var R = CMD$2.R;
  12693. var A = CMD$2.A;
  12694. var Q = CMD$2.Q;
  12695. for (i = 0, j = 0; i < len;) {
  12696. cmd = data[i++];
  12697. j = i;
  12698. nPoint = 0;
  12699. switch (cmd) {
  12700. case M:
  12701. nPoint = 1;
  12702. break;
  12703. case L:
  12704. nPoint = 1;
  12705. break;
  12706. case C:
  12707. nPoint = 3;
  12708. break;
  12709. case Q:
  12710. nPoint = 2;
  12711. break;
  12712. case A:
  12713. var x = m[4];
  12714. var y = m[5];
  12715. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12716. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12717. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12718. data[i] *= sx;
  12719. data[i++] += x;
  12720. data[i] *= sy;
  12721. data[i++] += y;
  12722. data[i++] *= sx;
  12723. data[i++] *= sy;
  12724. data[i++] += angle;
  12725. data[i++] += angle;
  12726. i += 2;
  12727. j = i;
  12728. break;
  12729. case R:
  12730. p[0] = data[i++];
  12731. p[1] = data[i++];
  12732. applyTransform(p, p, m);
  12733. data[j++] = p[0];
  12734. data[j++] = p[1];
  12735. p[0] += data[i++];
  12736. p[1] += data[i++];
  12737. applyTransform(p, p, m);
  12738. data[j++] = p[0];
  12739. data[j++] = p[1];
  12740. }
  12741. for (k = 0; k < nPoint; k++) {
  12742. var p_1 = points[k];
  12743. p_1[0] = data[i++];
  12744. p_1[1] = data[i++];
  12745. applyTransform(p_1, p_1, m);
  12746. data[j++] = p_1[0];
  12747. data[j++] = p_1[1];
  12748. }
  12749. }
  12750. path.increaseVersion();
  12751. }
  12752. var mathSqrt$2 = Math.sqrt;
  12753. var mathSin$2 = Math.sin;
  12754. var mathCos$2 = Math.cos;
  12755. var PI$1 = Math.PI;
  12756. function vMag(v) {
  12757. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12758. }
  12759. function vRatio(u, v) {
  12760. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12761. }
  12762. function vAngle(u, v) {
  12763. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12764. * Math.acos(vRatio(u, v));
  12765. }
  12766. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12767. var psi = psiDeg * (PI$1 / 180.0);
  12768. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12769. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12770. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12771. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12772. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12773. if (lambda > 1) {
  12774. rx *= mathSqrt$2(lambda);
  12775. ry *= mathSqrt$2(lambda);
  12776. }
  12777. var f = (fa === fs ? -1 : 1)
  12778. * mathSqrt$2((((rx * rx) * (ry * ry))
  12779. - ((rx * rx) * (yp * yp))
  12780. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12781. + (ry * ry) * (xp * xp))) || 0;
  12782. var cxp = f * rx * yp / ry;
  12783. var cyp = f * -ry * xp / rx;
  12784. var cx = (x1 + x2) / 2.0
  12785. + mathCos$2(psi) * cxp
  12786. - mathSin$2(psi) * cyp;
  12787. var cy = (y1 + y2) / 2.0
  12788. + mathSin$2(psi) * cxp
  12789. + mathCos$2(psi) * cyp;
  12790. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12791. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12792. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12793. var dTheta = vAngle(u, v);
  12794. if (vRatio(u, v) <= -1) {
  12795. dTheta = PI$1;
  12796. }
  12797. if (vRatio(u, v) >= 1) {
  12798. dTheta = 0;
  12799. }
  12800. if (dTheta < 0) {
  12801. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12802. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12803. }
  12804. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12805. }
  12806. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12807. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12808. function createPathProxyFromString(data) {
  12809. var path = new PathProxy();
  12810. if (!data) {
  12811. return path;
  12812. }
  12813. var cpx = 0;
  12814. var cpy = 0;
  12815. var subpathX = cpx;
  12816. var subpathY = cpy;
  12817. var prevCmd;
  12818. var CMD = PathProxy.CMD;
  12819. var cmdList = data.match(commandReg);
  12820. if (!cmdList) {
  12821. return path;
  12822. }
  12823. for (var l = 0; l < cmdList.length; l++) {
  12824. var cmdText = cmdList[l];
  12825. var cmdStr = cmdText.charAt(0);
  12826. var cmd = void 0;
  12827. var p = cmdText.match(numberReg) || [];
  12828. var pLen = p.length;
  12829. for (var i = 0; i < pLen; i++) {
  12830. p[i] = parseFloat(p[i]);
  12831. }
  12832. var off = 0;
  12833. while (off < pLen) {
  12834. var ctlPtx = void 0;
  12835. var ctlPty = void 0;
  12836. var rx = void 0;
  12837. var ry = void 0;
  12838. var psi = void 0;
  12839. var fa = void 0;
  12840. var fs = void 0;
  12841. var x1 = cpx;
  12842. var y1 = cpy;
  12843. var len = void 0;
  12844. var pathData = void 0;
  12845. switch (cmdStr) {
  12846. case 'l':
  12847. cpx += p[off++];
  12848. cpy += p[off++];
  12849. cmd = CMD.L;
  12850. path.addData(cmd, cpx, cpy);
  12851. break;
  12852. case 'L':
  12853. cpx = p[off++];
  12854. cpy = p[off++];
  12855. cmd = CMD.L;
  12856. path.addData(cmd, cpx, cpy);
  12857. break;
  12858. case 'm':
  12859. cpx += p[off++];
  12860. cpy += p[off++];
  12861. cmd = CMD.M;
  12862. path.addData(cmd, cpx, cpy);
  12863. subpathX = cpx;
  12864. subpathY = cpy;
  12865. cmdStr = 'l';
  12866. break;
  12867. case 'M':
  12868. cpx = p[off++];
  12869. cpy = p[off++];
  12870. cmd = CMD.M;
  12871. path.addData(cmd, cpx, cpy);
  12872. subpathX = cpx;
  12873. subpathY = cpy;
  12874. cmdStr = 'L';
  12875. break;
  12876. case 'h':
  12877. cpx += p[off++];
  12878. cmd = CMD.L;
  12879. path.addData(cmd, cpx, cpy);
  12880. break;
  12881. case 'H':
  12882. cpx = p[off++];
  12883. cmd = CMD.L;
  12884. path.addData(cmd, cpx, cpy);
  12885. break;
  12886. case 'v':
  12887. cpy += p[off++];
  12888. cmd = CMD.L;
  12889. path.addData(cmd, cpx, cpy);
  12890. break;
  12891. case 'V':
  12892. cpy = p[off++];
  12893. cmd = CMD.L;
  12894. path.addData(cmd, cpx, cpy);
  12895. break;
  12896. case 'C':
  12897. cmd = CMD.C;
  12898. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12899. cpx = p[off - 2];
  12900. cpy = p[off - 1];
  12901. break;
  12902. case 'c':
  12903. cmd = CMD.C;
  12904. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12905. cpx += p[off - 2];
  12906. cpy += p[off - 1];
  12907. break;
  12908. case 'S':
  12909. ctlPtx = cpx;
  12910. ctlPty = cpy;
  12911. len = path.len();
  12912. pathData = path.data;
  12913. if (prevCmd === CMD.C) {
  12914. ctlPtx += cpx - pathData[len - 4];
  12915. ctlPty += cpy - pathData[len - 3];
  12916. }
  12917. cmd = CMD.C;
  12918. x1 = p[off++];
  12919. y1 = p[off++];
  12920. cpx = p[off++];
  12921. cpy = p[off++];
  12922. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12923. break;
  12924. case 's':
  12925. ctlPtx = cpx;
  12926. ctlPty = cpy;
  12927. len = path.len();
  12928. pathData = path.data;
  12929. if (prevCmd === CMD.C) {
  12930. ctlPtx += cpx - pathData[len - 4];
  12931. ctlPty += cpy - pathData[len - 3];
  12932. }
  12933. cmd = CMD.C;
  12934. x1 = cpx + p[off++];
  12935. y1 = cpy + p[off++];
  12936. cpx += p[off++];
  12937. cpy += p[off++];
  12938. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12939. break;
  12940. case 'Q':
  12941. x1 = p[off++];
  12942. y1 = p[off++];
  12943. cpx = p[off++];
  12944. cpy = p[off++];
  12945. cmd = CMD.Q;
  12946. path.addData(cmd, x1, y1, cpx, cpy);
  12947. break;
  12948. case 'q':
  12949. x1 = p[off++] + cpx;
  12950. y1 = p[off++] + cpy;
  12951. cpx += p[off++];
  12952. cpy += p[off++];
  12953. cmd = CMD.Q;
  12954. path.addData(cmd, x1, y1, cpx, cpy);
  12955. break;
  12956. case 'T':
  12957. ctlPtx = cpx;
  12958. ctlPty = cpy;
  12959. len = path.len();
  12960. pathData = path.data;
  12961. if (prevCmd === CMD.Q) {
  12962. ctlPtx += cpx - pathData[len - 4];
  12963. ctlPty += cpy - pathData[len - 3];
  12964. }
  12965. cpx = p[off++];
  12966. cpy = p[off++];
  12967. cmd = CMD.Q;
  12968. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12969. break;
  12970. case 't':
  12971. ctlPtx = cpx;
  12972. ctlPty = cpy;
  12973. len = path.len();
  12974. pathData = path.data;
  12975. if (prevCmd === CMD.Q) {
  12976. ctlPtx += cpx - pathData[len - 4];
  12977. ctlPty += cpy - pathData[len - 3];
  12978. }
  12979. cpx += p[off++];
  12980. cpy += p[off++];
  12981. cmd = CMD.Q;
  12982. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12983. break;
  12984. case 'A':
  12985. rx = p[off++];
  12986. ry = p[off++];
  12987. psi = p[off++];
  12988. fa = p[off++];
  12989. fs = p[off++];
  12990. x1 = cpx, y1 = cpy;
  12991. cpx = p[off++];
  12992. cpy = p[off++];
  12993. cmd = CMD.A;
  12994. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12995. break;
  12996. case 'a':
  12997. rx = p[off++];
  12998. ry = p[off++];
  12999. psi = p[off++];
  13000. fa = p[off++];
  13001. fs = p[off++];
  13002. x1 = cpx, y1 = cpy;
  13003. cpx += p[off++];
  13004. cpy += p[off++];
  13005. cmd = CMD.A;
  13006. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13007. break;
  13008. }
  13009. }
  13010. if (cmdStr === 'z' || cmdStr === 'Z') {
  13011. cmd = CMD.Z;
  13012. path.addData(cmd);
  13013. cpx = subpathX;
  13014. cpy = subpathY;
  13015. }
  13016. prevCmd = cmd;
  13017. }
  13018. path.toStatic();
  13019. return path;
  13020. }
  13021. var SVGPath = (function (_super) {
  13022. __extends(SVGPath, _super);
  13023. function SVGPath() {
  13024. return _super !== null && _super.apply(this, arguments) || this;
  13025. }
  13026. SVGPath.prototype.applyTransform = function (m) { };
  13027. return SVGPath;
  13028. }(Path));
  13029. function isPathProxy(path) {
  13030. return path.setData != null;
  13031. }
  13032. function createPathOptions(str, opts) {
  13033. var pathProxy = createPathProxyFromString(str);
  13034. var innerOpts = extend({}, opts);
  13035. innerOpts.buildPath = function (path) {
  13036. if (isPathProxy(path)) {
  13037. path.setData(pathProxy.data);
  13038. var ctx = path.getContext();
  13039. if (ctx) {
  13040. path.rebuildPath(ctx, 1);
  13041. }
  13042. }
  13043. else {
  13044. var ctx = path;
  13045. pathProxy.rebuildPath(ctx, 1);
  13046. }
  13047. };
  13048. innerOpts.applyTransform = function (m) {
  13049. transformPath(pathProxy, m);
  13050. this.dirtyShape();
  13051. };
  13052. return innerOpts;
  13053. }
  13054. function createFromString(str, opts) {
  13055. return new SVGPath(createPathOptions(str, opts));
  13056. }
  13057. function extendFromString(str, defaultOpts) {
  13058. var innerOpts = createPathOptions(str, defaultOpts);
  13059. var Sub = (function (_super) {
  13060. __extends(Sub, _super);
  13061. function Sub(opts) {
  13062. var _this = _super.call(this, opts) || this;
  13063. _this.applyTransform = innerOpts.applyTransform;
  13064. _this.buildPath = innerOpts.buildPath;
  13065. return _this;
  13066. }
  13067. return Sub;
  13068. }(SVGPath));
  13069. return Sub;
  13070. }
  13071. function mergePath(pathEls, opts) {
  13072. var pathList = [];
  13073. var len = pathEls.length;
  13074. for (var i = 0; i < len; i++) {
  13075. var pathEl = pathEls[i];
  13076. pathList.push(pathEl.getUpdatedPathProxy(true));
  13077. }
  13078. var pathBundle = new Path(opts);
  13079. pathBundle.createPathProxy();
  13080. pathBundle.buildPath = function (path) {
  13081. if (isPathProxy(path)) {
  13082. path.appendPath(pathList);
  13083. var ctx = path.getContext();
  13084. if (ctx) {
  13085. path.rebuildPath(ctx, 1);
  13086. }
  13087. }
  13088. };
  13089. return pathBundle;
  13090. }
  13091. function clonePath(sourcePath, opts) {
  13092. opts = opts || {};
  13093. var path = new Path();
  13094. if (sourcePath.shape) {
  13095. path.setShape(sourcePath.shape);
  13096. }
  13097. path.setStyle(sourcePath.style);
  13098. if (opts.bakeTransform) {
  13099. transformPath(path.path, sourcePath.getComputedTransform());
  13100. }
  13101. else {
  13102. if (opts.toLocal) {
  13103. path.setLocalTransform(sourcePath.getComputedTransform());
  13104. }
  13105. else {
  13106. path.copyTransform(sourcePath);
  13107. }
  13108. }
  13109. path.buildPath = sourcePath.buildPath;
  13110. path.applyTransform = path.applyTransform;
  13111. path.z = sourcePath.z;
  13112. path.z2 = sourcePath.z2;
  13113. path.zlevel = sourcePath.zlevel;
  13114. return path;
  13115. }
  13116. var CircleShape = (function () {
  13117. function CircleShape() {
  13118. this.cx = 0;
  13119. this.cy = 0;
  13120. this.r = 0;
  13121. }
  13122. return CircleShape;
  13123. }());
  13124. var Circle = (function (_super) {
  13125. __extends(Circle, _super);
  13126. function Circle(opts) {
  13127. return _super.call(this, opts) || this;
  13128. }
  13129. Circle.prototype.getDefaultShape = function () {
  13130. return new CircleShape();
  13131. };
  13132. Circle.prototype.buildPath = function (ctx, shape) {
  13133. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13134. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13135. };
  13136. return Circle;
  13137. }(Path));
  13138. Circle.prototype.type = 'circle';
  13139. var EllipseShape = (function () {
  13140. function EllipseShape() {
  13141. this.cx = 0;
  13142. this.cy = 0;
  13143. this.rx = 0;
  13144. this.ry = 0;
  13145. }
  13146. return EllipseShape;
  13147. }());
  13148. var Ellipse = (function (_super) {
  13149. __extends(Ellipse, _super);
  13150. function Ellipse(opts) {
  13151. return _super.call(this, opts) || this;
  13152. }
  13153. Ellipse.prototype.getDefaultShape = function () {
  13154. return new EllipseShape();
  13155. };
  13156. Ellipse.prototype.buildPath = function (ctx, shape) {
  13157. var k = 0.5522848;
  13158. var x = shape.cx;
  13159. var y = shape.cy;
  13160. var a = shape.rx;
  13161. var b = shape.ry;
  13162. var ox = a * k;
  13163. var oy = b * k;
  13164. ctx.moveTo(x - a, y);
  13165. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13166. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13167. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13168. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13169. ctx.closePath();
  13170. };
  13171. return Ellipse;
  13172. }(Path));
  13173. Ellipse.prototype.type = 'ellipse';
  13174. var PI$2 = Math.PI;
  13175. var PI2$5 = PI$2 * 2;
  13176. var mathSin$3 = Math.sin;
  13177. var mathCos$3 = Math.cos;
  13178. var mathACos = Math.acos;
  13179. var mathATan2 = Math.atan2;
  13180. var mathAbs$1 = Math.abs;
  13181. var mathSqrt$3 = Math.sqrt;
  13182. var mathMax$3 = Math.max;
  13183. var mathMin$3 = Math.min;
  13184. var e = 1e-4;
  13185. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13186. var dx10 = x1 - x0;
  13187. var dy10 = y1 - y0;
  13188. var dx32 = x3 - x2;
  13189. var dy32 = y3 - y2;
  13190. var t = dy32 * dx10 - dx32 * dy10;
  13191. if (t * t < e) {
  13192. return;
  13193. }
  13194. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13195. return [x0 + t * dx10, y0 + t * dy10];
  13196. }
  13197. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13198. var x01 = x0 - x1;
  13199. var y01 = y0 - y1;
  13200. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13201. var ox = lo * y01;
  13202. var oy = -lo * x01;
  13203. var x11 = x0 + ox;
  13204. var y11 = y0 + oy;
  13205. var x10 = x1 + ox;
  13206. var y10 = y1 + oy;
  13207. var x00 = (x11 + x10) / 2;
  13208. var y00 = (y11 + y10) / 2;
  13209. var dx = x10 - x11;
  13210. var dy = y10 - y11;
  13211. var d2 = dx * dx + dy * dy;
  13212. var r = radius - cr;
  13213. var s = x11 * y10 - x10 * y11;
  13214. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13215. var cx0 = (s * dy - dx * d) / d2;
  13216. var cy0 = (-s * dx - dy * d) / d2;
  13217. var cx1 = (s * dy + dx * d) / d2;
  13218. var cy1 = (-s * dx + dy * d) / d2;
  13219. var dx0 = cx0 - x00;
  13220. var dy0 = cy0 - y00;
  13221. var dx1 = cx1 - x00;
  13222. var dy1 = cy1 - y00;
  13223. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13224. cx0 = cx1;
  13225. cy0 = cy1;
  13226. }
  13227. return {
  13228. cx: cx0,
  13229. cy: cy0,
  13230. x0: -ox,
  13231. y0: -oy,
  13232. x1: cx0 * (radius / r - 1),
  13233. y1: cy0 * (radius / r - 1)
  13234. };
  13235. }
  13236. function normalizeCornerRadius(cr) {
  13237. var arr;
  13238. if (isArray(cr)) {
  13239. var len = cr.length;
  13240. if (!len) {
  13241. return cr;
  13242. }
  13243. if (len === 1) {
  13244. arr = [cr[0], cr[0], 0, 0];
  13245. }
  13246. else if (len === 2) {
  13247. arr = [cr[0], cr[0], cr[1], cr[1]];
  13248. }
  13249. else if (len === 3) {
  13250. arr = cr.concat(cr[2]);
  13251. }
  13252. else {
  13253. arr = cr;
  13254. }
  13255. }
  13256. else {
  13257. arr = [cr, cr, cr, cr];
  13258. }
  13259. return arr;
  13260. }
  13261. function buildPath$1(ctx, shape) {
  13262. var _a;
  13263. var radius = mathMax$3(shape.r, 0);
  13264. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13265. var hasRadius = radius > 0;
  13266. var hasInnerRadius = innerRadius > 0;
  13267. if (!hasRadius && !hasInnerRadius) {
  13268. return;
  13269. }
  13270. if (!hasRadius) {
  13271. radius = innerRadius;
  13272. innerRadius = 0;
  13273. }
  13274. if (innerRadius > radius) {
  13275. var tmp = radius;
  13276. radius = innerRadius;
  13277. innerRadius = tmp;
  13278. }
  13279. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13280. if (isNaN(startAngle) || isNaN(endAngle)) {
  13281. return;
  13282. }
  13283. var cx = shape.cx, cy = shape.cy;
  13284. var clockwise = !!shape.clockwise;
  13285. var arc = mathAbs$1(endAngle - startAngle);
  13286. var mod = arc > PI2$5 && arc % PI2$5;
  13287. mod > e && (arc = mod);
  13288. if (!(radius > e)) {
  13289. ctx.moveTo(cx, cy);
  13290. }
  13291. else if (arc > PI2$5 - e) {
  13292. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13293. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13294. if (innerRadius > e) {
  13295. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13296. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13297. }
  13298. }
  13299. else {
  13300. var icrStart = void 0;
  13301. var icrEnd = void 0;
  13302. var ocrStart = void 0;
  13303. var ocrEnd = void 0;
  13304. var ocrs = void 0;
  13305. var ocre = void 0;
  13306. var icrs = void 0;
  13307. var icre = void 0;
  13308. var ocrMax = void 0;
  13309. var icrMax = void 0;
  13310. var limitedOcrMax = void 0;
  13311. var limitedIcrMax = void 0;
  13312. var xre = void 0;
  13313. var yre = void 0;
  13314. var xirs = void 0;
  13315. var yirs = void 0;
  13316. var xrs = radius * mathCos$3(startAngle);
  13317. var yrs = radius * mathSin$3(startAngle);
  13318. var xire = innerRadius * mathCos$3(endAngle);
  13319. var yire = innerRadius * mathSin$3(endAngle);
  13320. var hasArc = arc > e;
  13321. if (hasArc) {
  13322. var cornerRadius = shape.cornerRadius;
  13323. if (cornerRadius) {
  13324. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13325. }
  13326. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13327. ocrs = mathMin$3(halfRd, ocrStart);
  13328. ocre = mathMin$3(halfRd, ocrEnd);
  13329. icrs = mathMin$3(halfRd, icrStart);
  13330. icre = mathMin$3(halfRd, icrEnd);
  13331. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13332. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13333. if (ocrMax > e || icrMax > e) {
  13334. xre = radius * mathCos$3(endAngle);
  13335. yre = radius * mathSin$3(endAngle);
  13336. xirs = innerRadius * mathCos$3(startAngle);
  13337. yirs = innerRadius * mathSin$3(startAngle);
  13338. if (arc < PI$2) {
  13339. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13340. if (it_1) {
  13341. var x0 = xrs - it_1[0];
  13342. var y0 = yrs - it_1[1];
  13343. var x1 = xre - it_1[0];
  13344. var y1 = yre - it_1[1];
  13345. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13346. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13347. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13348. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13349. }
  13350. }
  13351. }
  13352. }
  13353. if (!hasArc) {
  13354. ctx.moveTo(cx + xrs, cy + yrs);
  13355. }
  13356. else if (limitedOcrMax > e) {
  13357. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13358. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13359. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13360. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13361. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13362. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13363. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13364. }
  13365. else {
  13366. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13367. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13368. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13369. }
  13370. }
  13371. else {
  13372. ctx.moveTo(cx + xrs, cy + yrs);
  13373. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13374. }
  13375. if (!(innerRadius > e) || !hasArc) {
  13376. ctx.lineTo(cx + xire, cy + yire);
  13377. }
  13378. else if (limitedIcrMax > e) {
  13379. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13380. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13381. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13382. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13383. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13384. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13385. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13386. }
  13387. else {
  13388. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13389. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13390. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13391. }
  13392. }
  13393. else {
  13394. ctx.lineTo(cx + xire, cy + yire);
  13395. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13396. }
  13397. }
  13398. ctx.closePath();
  13399. }
  13400. var SectorShape = (function () {
  13401. function SectorShape() {
  13402. this.cx = 0;
  13403. this.cy = 0;
  13404. this.r0 = 0;
  13405. this.r = 0;
  13406. this.startAngle = 0;
  13407. this.endAngle = Math.PI * 2;
  13408. this.clockwise = true;
  13409. this.cornerRadius = 0;
  13410. }
  13411. return SectorShape;
  13412. }());
  13413. var Sector = (function (_super) {
  13414. __extends(Sector, _super);
  13415. function Sector(opts) {
  13416. return _super.call(this, opts) || this;
  13417. }
  13418. Sector.prototype.getDefaultShape = function () {
  13419. return new SectorShape();
  13420. };
  13421. Sector.prototype.buildPath = function (ctx, shape) {
  13422. buildPath$1(ctx, shape);
  13423. };
  13424. Sector.prototype.isZeroArea = function () {
  13425. return this.shape.startAngle === this.shape.endAngle
  13426. || this.shape.r === this.shape.r0;
  13427. };
  13428. return Sector;
  13429. }(Path));
  13430. Sector.prototype.type = 'sector';
  13431. var RingShape = (function () {
  13432. function RingShape() {
  13433. this.cx = 0;
  13434. this.cy = 0;
  13435. this.r = 0;
  13436. this.r0 = 0;
  13437. }
  13438. return RingShape;
  13439. }());
  13440. var Ring = (function (_super) {
  13441. __extends(Ring, _super);
  13442. function Ring(opts) {
  13443. return _super.call(this, opts) || this;
  13444. }
  13445. Ring.prototype.getDefaultShape = function () {
  13446. return new RingShape();
  13447. };
  13448. Ring.prototype.buildPath = function (ctx, shape) {
  13449. var x = shape.cx;
  13450. var y = shape.cy;
  13451. var PI2 = Math.PI * 2;
  13452. ctx.moveTo(x + shape.r, y);
  13453. ctx.arc(x, y, shape.r, 0, PI2, false);
  13454. ctx.moveTo(x + shape.r0, y);
  13455. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13456. };
  13457. return Ring;
  13458. }(Path));
  13459. Ring.prototype.type = 'ring';
  13460. function smoothBezier(points, smooth, isLoop, constraint) {
  13461. var cps = [];
  13462. var v = [];
  13463. var v1 = [];
  13464. var v2 = [];
  13465. var prevPoint;
  13466. var nextPoint;
  13467. var min$1;
  13468. var max$1;
  13469. if (constraint) {
  13470. min$1 = [Infinity, Infinity];
  13471. max$1 = [-Infinity, -Infinity];
  13472. for (var i = 0, len = points.length; i < len; i++) {
  13473. min(min$1, min$1, points[i]);
  13474. max(max$1, max$1, points[i]);
  13475. }
  13476. min(min$1, min$1, constraint[0]);
  13477. max(max$1, max$1, constraint[1]);
  13478. }
  13479. for (var i = 0, len = points.length; i < len; i++) {
  13480. var point = points[i];
  13481. if (isLoop) {
  13482. prevPoint = points[i ? i - 1 : len - 1];
  13483. nextPoint = points[(i + 1) % len];
  13484. }
  13485. else {
  13486. if (i === 0 || i === len - 1) {
  13487. cps.push(clone$1(points[i]));
  13488. continue;
  13489. }
  13490. else {
  13491. prevPoint = points[i - 1];
  13492. nextPoint = points[i + 1];
  13493. }
  13494. }
  13495. sub(v, nextPoint, prevPoint);
  13496. scale(v, v, smooth);
  13497. var d0 = distance(point, prevPoint);
  13498. var d1 = distance(point, nextPoint);
  13499. var sum = d0 + d1;
  13500. if (sum !== 0) {
  13501. d0 /= sum;
  13502. d1 /= sum;
  13503. }
  13504. scale(v1, v, -d0);
  13505. scale(v2, v, d1);
  13506. var cp0 = add([], point, v1);
  13507. var cp1 = add([], point, v2);
  13508. if (constraint) {
  13509. max(cp0, cp0, min$1);
  13510. min(cp0, cp0, max$1);
  13511. max(cp1, cp1, min$1);
  13512. min(cp1, cp1, max$1);
  13513. }
  13514. cps.push(cp0);
  13515. cps.push(cp1);
  13516. }
  13517. if (isLoop) {
  13518. cps.push(cps.shift());
  13519. }
  13520. return cps;
  13521. }
  13522. function buildPath$2(ctx, shape, closePath) {
  13523. var smooth = shape.smooth;
  13524. var points = shape.points;
  13525. if (points && points.length >= 2) {
  13526. if (smooth) {
  13527. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13528. ctx.moveTo(points[0][0], points[0][1]);
  13529. var len = points.length;
  13530. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13531. var cp1 = controlPoints[i * 2];
  13532. var cp2 = controlPoints[i * 2 + 1];
  13533. var p = points[(i + 1) % len];
  13534. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13535. }
  13536. }
  13537. else {
  13538. ctx.moveTo(points[0][0], points[0][1]);
  13539. for (var i = 1, l = points.length; i < l; i++) {
  13540. ctx.lineTo(points[i][0], points[i][1]);
  13541. }
  13542. }
  13543. closePath && ctx.closePath();
  13544. }
  13545. }
  13546. var PolygonShape = (function () {
  13547. function PolygonShape() {
  13548. this.points = null;
  13549. this.smooth = 0;
  13550. this.smoothConstraint = null;
  13551. }
  13552. return PolygonShape;
  13553. }());
  13554. var Polygon = (function (_super) {
  13555. __extends(Polygon, _super);
  13556. function Polygon(opts) {
  13557. return _super.call(this, opts) || this;
  13558. }
  13559. Polygon.prototype.getDefaultShape = function () {
  13560. return new PolygonShape();
  13561. };
  13562. Polygon.prototype.buildPath = function (ctx, shape) {
  13563. buildPath$2(ctx, shape, true);
  13564. };
  13565. return Polygon;
  13566. }(Path));
  13567. Polygon.prototype.type = 'polygon';
  13568. var PolylineShape = (function () {
  13569. function PolylineShape() {
  13570. this.points = null;
  13571. this.percent = 1;
  13572. this.smooth = 0;
  13573. this.smoothConstraint = null;
  13574. }
  13575. return PolylineShape;
  13576. }());
  13577. var Polyline = (function (_super) {
  13578. __extends(Polyline, _super);
  13579. function Polyline(opts) {
  13580. return _super.call(this, opts) || this;
  13581. }
  13582. Polyline.prototype.getDefaultStyle = function () {
  13583. return {
  13584. stroke: '#000',
  13585. fill: null
  13586. };
  13587. };
  13588. Polyline.prototype.getDefaultShape = function () {
  13589. return new PolylineShape();
  13590. };
  13591. Polyline.prototype.buildPath = function (ctx, shape) {
  13592. buildPath$2(ctx, shape, false);
  13593. };
  13594. return Polyline;
  13595. }(Path));
  13596. Polyline.prototype.type = 'polyline';
  13597. var subPixelOptimizeOutputShape$1 = {};
  13598. var LineShape = (function () {
  13599. function LineShape() {
  13600. this.x1 = 0;
  13601. this.y1 = 0;
  13602. this.x2 = 0;
  13603. this.y2 = 0;
  13604. this.percent = 1;
  13605. }
  13606. return LineShape;
  13607. }());
  13608. var Line = (function (_super) {
  13609. __extends(Line, _super);
  13610. function Line(opts) {
  13611. return _super.call(this, opts) || this;
  13612. }
  13613. Line.prototype.getDefaultStyle = function () {
  13614. return {
  13615. stroke: '#000',
  13616. fill: null
  13617. };
  13618. };
  13619. Line.prototype.getDefaultShape = function () {
  13620. return new LineShape();
  13621. };
  13622. Line.prototype.buildPath = function (ctx, shape) {
  13623. var x1;
  13624. var y1;
  13625. var x2;
  13626. var y2;
  13627. if (this.subPixelOptimize) {
  13628. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13629. x1 = optimizedShape.x1;
  13630. y1 = optimizedShape.y1;
  13631. x2 = optimizedShape.x2;
  13632. y2 = optimizedShape.y2;
  13633. }
  13634. else {
  13635. x1 = shape.x1;
  13636. y1 = shape.y1;
  13637. x2 = shape.x2;
  13638. y2 = shape.y2;
  13639. }
  13640. var percent = shape.percent;
  13641. if (percent === 0) {
  13642. return;
  13643. }
  13644. ctx.moveTo(x1, y1);
  13645. if (percent < 1) {
  13646. x2 = x1 * (1 - percent) + x2 * percent;
  13647. y2 = y1 * (1 - percent) + y2 * percent;
  13648. }
  13649. ctx.lineTo(x2, y2);
  13650. };
  13651. Line.prototype.pointAt = function (p) {
  13652. var shape = this.shape;
  13653. return [
  13654. shape.x1 * (1 - p) + shape.x2 * p,
  13655. shape.y1 * (1 - p) + shape.y2 * p
  13656. ];
  13657. };
  13658. return Line;
  13659. }(Path));
  13660. Line.prototype.type = 'line';
  13661. var out = [];
  13662. var BezierCurveShape = (function () {
  13663. function BezierCurveShape() {
  13664. this.x1 = 0;
  13665. this.y1 = 0;
  13666. this.x2 = 0;
  13667. this.y2 = 0;
  13668. this.cpx1 = 0;
  13669. this.cpy1 = 0;
  13670. this.percent = 1;
  13671. }
  13672. return BezierCurveShape;
  13673. }());
  13674. function someVectorAt(shape, t, isTangent) {
  13675. var cpx2 = shape.cpx2;
  13676. var cpy2 = shape.cpy2;
  13677. if (cpx2 != null || cpy2 != null) {
  13678. return [
  13679. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13680. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13681. ];
  13682. }
  13683. else {
  13684. return [
  13685. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13686. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13687. ];
  13688. }
  13689. }
  13690. var BezierCurve = (function (_super) {
  13691. __extends(BezierCurve, _super);
  13692. function BezierCurve(opts) {
  13693. return _super.call(this, opts) || this;
  13694. }
  13695. BezierCurve.prototype.getDefaultStyle = function () {
  13696. return {
  13697. stroke: '#000',
  13698. fill: null
  13699. };
  13700. };
  13701. BezierCurve.prototype.getDefaultShape = function () {
  13702. return new BezierCurveShape();
  13703. };
  13704. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13705. var x1 = shape.x1;
  13706. var y1 = shape.y1;
  13707. var x2 = shape.x2;
  13708. var y2 = shape.y2;
  13709. var cpx1 = shape.cpx1;
  13710. var cpy1 = shape.cpy1;
  13711. var cpx2 = shape.cpx2;
  13712. var cpy2 = shape.cpy2;
  13713. var percent = shape.percent;
  13714. if (percent === 0) {
  13715. return;
  13716. }
  13717. ctx.moveTo(x1, y1);
  13718. if (cpx2 == null || cpy2 == null) {
  13719. if (percent < 1) {
  13720. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13721. cpx1 = out[1];
  13722. x2 = out[2];
  13723. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13724. cpy1 = out[1];
  13725. y2 = out[2];
  13726. }
  13727. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13728. }
  13729. else {
  13730. if (percent < 1) {
  13731. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13732. cpx1 = out[1];
  13733. cpx2 = out[2];
  13734. x2 = out[3];
  13735. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13736. cpy1 = out[1];
  13737. cpy2 = out[2];
  13738. y2 = out[3];
  13739. }
  13740. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13741. }
  13742. };
  13743. BezierCurve.prototype.pointAt = function (t) {
  13744. return someVectorAt(this.shape, t, false);
  13745. };
  13746. BezierCurve.prototype.tangentAt = function (t) {
  13747. var p = someVectorAt(this.shape, t, true);
  13748. return normalize(p, p);
  13749. };
  13750. return BezierCurve;
  13751. }(Path));
  13752. BezierCurve.prototype.type = 'bezier-curve';
  13753. var ArcShape = (function () {
  13754. function ArcShape() {
  13755. this.cx = 0;
  13756. this.cy = 0;
  13757. this.r = 0;
  13758. this.startAngle = 0;
  13759. this.endAngle = Math.PI * 2;
  13760. this.clockwise = true;
  13761. }
  13762. return ArcShape;
  13763. }());
  13764. var Arc = (function (_super) {
  13765. __extends(Arc, _super);
  13766. function Arc(opts) {
  13767. return _super.call(this, opts) || this;
  13768. }
  13769. Arc.prototype.getDefaultStyle = function () {
  13770. return {
  13771. stroke: '#000',
  13772. fill: null
  13773. };
  13774. };
  13775. Arc.prototype.getDefaultShape = function () {
  13776. return new ArcShape();
  13777. };
  13778. Arc.prototype.buildPath = function (ctx, shape) {
  13779. var x = shape.cx;
  13780. var y = shape.cy;
  13781. var r = Math.max(shape.r, 0);
  13782. var startAngle = shape.startAngle;
  13783. var endAngle = shape.endAngle;
  13784. var clockwise = shape.clockwise;
  13785. var unitX = Math.cos(startAngle);
  13786. var unitY = Math.sin(startAngle);
  13787. ctx.moveTo(unitX * r + x, unitY * r + y);
  13788. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13789. };
  13790. return Arc;
  13791. }(Path));
  13792. Arc.prototype.type = 'arc';
  13793. var CompoundPath = (function (_super) {
  13794. __extends(CompoundPath, _super);
  13795. function CompoundPath() {
  13796. var _this = _super !== null && _super.apply(this, arguments) || this;
  13797. _this.type = 'compound';
  13798. return _this;
  13799. }
  13800. CompoundPath.prototype._updatePathDirty = function () {
  13801. var paths = this.shape.paths;
  13802. var dirtyPath = this.shapeChanged();
  13803. for (var i = 0; i < paths.length; i++) {
  13804. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13805. }
  13806. if (dirtyPath) {
  13807. this.dirtyShape();
  13808. }
  13809. };
  13810. CompoundPath.prototype.beforeBrush = function () {
  13811. this._updatePathDirty();
  13812. var paths = this.shape.paths || [];
  13813. var scale = this.getGlobalScale();
  13814. for (var i = 0; i < paths.length; i++) {
  13815. if (!paths[i].path) {
  13816. paths[i].createPathProxy();
  13817. }
  13818. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13819. }
  13820. };
  13821. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13822. var paths = shape.paths || [];
  13823. for (var i = 0; i < paths.length; i++) {
  13824. paths[i].buildPath(ctx, paths[i].shape, true);
  13825. }
  13826. };
  13827. CompoundPath.prototype.afterBrush = function () {
  13828. var paths = this.shape.paths || [];
  13829. for (var i = 0; i < paths.length; i++) {
  13830. paths[i].pathUpdated();
  13831. }
  13832. };
  13833. CompoundPath.prototype.getBoundingRect = function () {
  13834. this._updatePathDirty.call(this);
  13835. return Path.prototype.getBoundingRect.call(this);
  13836. };
  13837. return CompoundPath;
  13838. }(Path));
  13839. var Gradient = (function () {
  13840. function Gradient(colorStops) {
  13841. this.colorStops = colorStops || [];
  13842. }
  13843. Gradient.prototype.addColorStop = function (offset, color) {
  13844. this.colorStops.push({
  13845. offset: offset,
  13846. color: color
  13847. });
  13848. };
  13849. return Gradient;
  13850. }());
  13851. var LinearGradient = (function (_super) {
  13852. __extends(LinearGradient, _super);
  13853. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13854. var _this = _super.call(this, colorStops) || this;
  13855. _this.x = x == null ? 0 : x;
  13856. _this.y = y == null ? 0 : y;
  13857. _this.x2 = x2 == null ? 1 : x2;
  13858. _this.y2 = y2 == null ? 0 : y2;
  13859. _this.type = 'linear';
  13860. _this.global = globalCoord || false;
  13861. return _this;
  13862. }
  13863. return LinearGradient;
  13864. }(Gradient));
  13865. var RadialGradient = (function (_super) {
  13866. __extends(RadialGradient, _super);
  13867. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13868. var _this = _super.call(this, colorStops) || this;
  13869. _this.x = x == null ? 0.5 : x;
  13870. _this.y = y == null ? 0.5 : y;
  13871. _this.r = r == null ? 0.5 : r;
  13872. _this.type = 'radial';
  13873. _this.global = globalCoord || false;
  13874. return _this;
  13875. }
  13876. return RadialGradient;
  13877. }(Gradient));
  13878. var extent = [0, 0];
  13879. var extent2 = [0, 0];
  13880. var minTv$1 = new Point();
  13881. var maxTv$1 = new Point();
  13882. var OrientedBoundingRect = (function () {
  13883. function OrientedBoundingRect(rect, transform) {
  13884. this._corners = [];
  13885. this._axes = [];
  13886. this._origin = [0, 0];
  13887. for (var i = 0; i < 4; i++) {
  13888. this._corners[i] = new Point();
  13889. }
  13890. for (var i = 0; i < 2; i++) {
  13891. this._axes[i] = new Point();
  13892. }
  13893. if (rect) {
  13894. this.fromBoundingRect(rect, transform);
  13895. }
  13896. }
  13897. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13898. var corners = this._corners;
  13899. var axes = this._axes;
  13900. var x = rect.x;
  13901. var y = rect.y;
  13902. var x2 = x + rect.width;
  13903. var y2 = y + rect.height;
  13904. corners[0].set(x, y);
  13905. corners[1].set(x2, y);
  13906. corners[2].set(x2, y2);
  13907. corners[3].set(x, y2);
  13908. if (transform) {
  13909. for (var i = 0; i < 4; i++) {
  13910. corners[i].transform(transform);
  13911. }
  13912. }
  13913. Point.sub(axes[0], corners[1], corners[0]);
  13914. Point.sub(axes[1], corners[3], corners[0]);
  13915. axes[0].normalize();
  13916. axes[1].normalize();
  13917. for (var i = 0; i < 2; i++) {
  13918. this._origin[i] = axes[i].dot(corners[0]);
  13919. }
  13920. };
  13921. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13922. var overlapped = true;
  13923. var noMtv = !mtv;
  13924. minTv$1.set(Infinity, Infinity);
  13925. maxTv$1.set(0, 0);
  13926. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13927. overlapped = false;
  13928. if (noMtv) {
  13929. return overlapped;
  13930. }
  13931. }
  13932. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13933. overlapped = false;
  13934. if (noMtv) {
  13935. return overlapped;
  13936. }
  13937. }
  13938. if (!noMtv) {
  13939. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13940. }
  13941. return overlapped;
  13942. };
  13943. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13944. var overlapped = true;
  13945. for (var i = 0; i < 2; i++) {
  13946. var axis = this._axes[i];
  13947. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13948. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13949. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13950. overlapped = false;
  13951. if (noMtv) {
  13952. return overlapped;
  13953. }
  13954. var dist0 = Math.abs(extent2[0] - extent[1]);
  13955. var dist1 = Math.abs(extent[0] - extent2[1]);
  13956. if (Math.min(dist0, dist1) > maxTv.len()) {
  13957. if (dist0 < dist1) {
  13958. Point.scale(maxTv, axis, -dist0 * inverse);
  13959. }
  13960. else {
  13961. Point.scale(maxTv, axis, dist1 * inverse);
  13962. }
  13963. }
  13964. }
  13965. else if (minTv) {
  13966. var dist0 = Math.abs(extent2[0] - extent[1]);
  13967. var dist1 = Math.abs(extent[0] - extent2[1]);
  13968. if (Math.min(dist0, dist1) < minTv.len()) {
  13969. if (dist0 < dist1) {
  13970. Point.scale(minTv, axis, dist0 * inverse);
  13971. }
  13972. else {
  13973. Point.scale(minTv, axis, -dist1 * inverse);
  13974. }
  13975. }
  13976. }
  13977. }
  13978. return overlapped;
  13979. };
  13980. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13981. var axis = this._axes[dim];
  13982. var origin = this._origin;
  13983. var proj = corners[0].dot(axis) + origin[dim];
  13984. var min = proj;
  13985. var max = proj;
  13986. for (var i = 1; i < corners.length; i++) {
  13987. var proj_1 = corners[i].dot(axis) + origin[dim];
  13988. min = Math.min(proj_1, min);
  13989. max = Math.max(proj_1, max);
  13990. }
  13991. out[0] = min;
  13992. out[1] = max;
  13993. };
  13994. return OrientedBoundingRect;
  13995. }());
  13996. var m = [];
  13997. var IncrementalDisplayable = (function (_super) {
  13998. __extends(IncrementalDisplayable, _super);
  13999. function IncrementalDisplayable() {
  14000. var _this = _super !== null && _super.apply(this, arguments) || this;
  14001. _this.notClear = true;
  14002. _this.incremental = true;
  14003. _this._displayables = [];
  14004. _this._temporaryDisplayables = [];
  14005. _this._cursor = 0;
  14006. return _this;
  14007. }
  14008. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  14009. cb.call(context, this);
  14010. };
  14011. IncrementalDisplayable.prototype.useStyle = function () {
  14012. this.style = {};
  14013. };
  14014. IncrementalDisplayable.prototype.getCursor = function () {
  14015. return this._cursor;
  14016. };
  14017. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  14018. this._cursor = this._displayables.length;
  14019. };
  14020. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  14021. this._displayables = [];
  14022. this._temporaryDisplayables = [];
  14023. this._cursor = 0;
  14024. this.markRedraw();
  14025. this.notClear = false;
  14026. };
  14027. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  14028. this._temporaryDisplayables = [];
  14029. };
  14030. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  14031. if (notPersistent) {
  14032. this._temporaryDisplayables.push(displayable);
  14033. }
  14034. else {
  14035. this._displayables.push(displayable);
  14036. }
  14037. this.markRedraw();
  14038. };
  14039. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  14040. notPersistent = notPersistent || false;
  14041. for (var i = 0; i < displayables.length; i++) {
  14042. this.addDisplayable(displayables[i], notPersistent);
  14043. }
  14044. };
  14045. IncrementalDisplayable.prototype.getDisplayables = function () {
  14046. return this._displayables;
  14047. };
  14048. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  14049. return this._temporaryDisplayables;
  14050. };
  14051. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  14052. for (var i = this._cursor; i < this._displayables.length; i++) {
  14053. cb && cb(this._displayables[i]);
  14054. }
  14055. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14056. cb && cb(this._temporaryDisplayables[i]);
  14057. }
  14058. };
  14059. IncrementalDisplayable.prototype.update = function () {
  14060. this.updateTransform();
  14061. for (var i = this._cursor; i < this._displayables.length; i++) {
  14062. var displayable = this._displayables[i];
  14063. displayable.parent = this;
  14064. displayable.update();
  14065. displayable.parent = null;
  14066. }
  14067. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14068. var displayable = this._temporaryDisplayables[i];
  14069. displayable.parent = this;
  14070. displayable.update();
  14071. displayable.parent = null;
  14072. }
  14073. };
  14074. IncrementalDisplayable.prototype.getBoundingRect = function () {
  14075. if (!this._rect) {
  14076. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14077. for (var i = 0; i < this._displayables.length; i++) {
  14078. var displayable = this._displayables[i];
  14079. var childRect = displayable.getBoundingRect().clone();
  14080. if (displayable.needLocalTransform()) {
  14081. childRect.applyTransform(displayable.getLocalTransform(m));
  14082. }
  14083. rect.union(childRect);
  14084. }
  14085. this._rect = rect;
  14086. }
  14087. return this._rect;
  14088. };
  14089. IncrementalDisplayable.prototype.contain = function (x, y) {
  14090. var localPos = this.transformCoordToLocal(x, y);
  14091. var rect = this.getBoundingRect();
  14092. if (rect.contain(localPos[0], localPos[1])) {
  14093. for (var i = 0; i < this._displayables.length; i++) {
  14094. var displayable = this._displayables[i];
  14095. if (displayable.contain(x, y)) {
  14096. return true;
  14097. }
  14098. }
  14099. }
  14100. return false;
  14101. };
  14102. return IncrementalDisplayable;
  14103. }(Displayable));
  14104. var transitionStore = makeInner();
  14105. /**
  14106. * Return null if animation is disabled.
  14107. */
  14108. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  14109. extraOpts, // TODO It's only for pictorial bar now.
  14110. extraDelayParams) {
  14111. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14112. // If animation is enabled. Will use this animation config in payload.
  14113. // If animation is disabled. Just ignore it.
  14114. if (animatableModel && animatableModel.ecModel) {
  14115. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14116. animationPayload = updatePayload && updatePayload.animation;
  14117. }
  14118. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14119. var isUpdate = animationType === 'update';
  14120. if (animationEnabled) {
  14121. var duration = void 0;
  14122. var easing = void 0;
  14123. var delay = void 0;
  14124. if (extraOpts) {
  14125. duration = retrieve2(extraOpts.duration, 200);
  14126. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14127. delay = 0;
  14128. } else {
  14129. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14130. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14131. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14132. } // animation from payload has highest priority.
  14133. if (animationPayload) {
  14134. animationPayload.duration != null && (duration = animationPayload.duration);
  14135. animationPayload.easing != null && (easing = animationPayload.easing);
  14136. animationPayload.delay != null && (delay = animationPayload.delay);
  14137. }
  14138. if (isFunction(delay)) {
  14139. delay = delay(dataIndex, extraDelayParams);
  14140. }
  14141. if (isFunction(duration)) {
  14142. duration = duration(dataIndex);
  14143. }
  14144. var config = {
  14145. duration: duration || 0,
  14146. delay: delay,
  14147. easing: easing
  14148. };
  14149. return config;
  14150. } else {
  14151. return null;
  14152. }
  14153. }
  14154. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14155. var isFrom = false;
  14156. var removeOpt;
  14157. if (isFunction(dataIndex)) {
  14158. during = cb;
  14159. cb = dataIndex;
  14160. dataIndex = null;
  14161. } else if (isObject(dataIndex)) {
  14162. cb = dataIndex.cb;
  14163. during = dataIndex.during;
  14164. isFrom = dataIndex.isFrom;
  14165. removeOpt = dataIndex.removeOpt;
  14166. dataIndex = dataIndex.dataIndex;
  14167. }
  14168. var isRemove = animationType === 'leave';
  14169. if (!isRemove) {
  14170. // Must stop the remove animation.
  14171. el.stopAnimation('leave');
  14172. }
  14173. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14174. if (animationConfig && animationConfig.duration > 0) {
  14175. var duration = animationConfig.duration;
  14176. var animationDelay = animationConfig.delay;
  14177. var animationEasing = animationConfig.easing;
  14178. var animateConfig = {
  14179. duration: duration,
  14180. delay: animationDelay || 0,
  14181. easing: animationEasing,
  14182. done: cb,
  14183. force: !!cb || !!during,
  14184. // Set to final state in update/init animation.
  14185. // So the post processing based on the path shape can be done correctly.
  14186. setToFinal: !isRemove,
  14187. scope: animationType,
  14188. during: during
  14189. };
  14190. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14191. } else {
  14192. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  14193. !isFrom && el.attr(props); // Call during at least once.
  14194. during && during(1);
  14195. cb && cb();
  14196. }
  14197. }
  14198. /**
  14199. * Update graphic element properties with or without animation according to the
  14200. * configuration in series.
  14201. *
  14202. * Caution: this method will stop previous animation.
  14203. * So do not use this method to one element twice before
  14204. * animation starts, unless you know what you are doing.
  14205. * @example
  14206. * graphic.updateProps(el, {
  14207. * position: [100, 100]
  14208. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14209. * // Or
  14210. * graphic.updateProps(el, {
  14211. * position: [100, 100]
  14212. * }, seriesModel, function () { console.log('Animation done!'); });
  14213. */
  14214. function updateProps(el, props, // TODO: TYPE AnimatableModel
  14215. animatableModel, dataIndex, cb, during) {
  14216. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14217. }
  14218. /**
  14219. * Init graphic element properties with or without animation according to the
  14220. * configuration in series.
  14221. *
  14222. * Caution: this method will stop previous animation.
  14223. * So do not use this method to one element twice before
  14224. * animation starts, unless you know what you are doing.
  14225. */
  14226. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14227. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14228. }
  14229. /**
  14230. * If element is removed.
  14231. * It can determine if element is having remove animation.
  14232. */
  14233. function isElementRemoved(el) {
  14234. if (!el.__zr) {
  14235. return true;
  14236. }
  14237. for (var i = 0; i < el.animators.length; i++) {
  14238. var animator = el.animators[i];
  14239. if (animator.scope === 'leave') {
  14240. return true;
  14241. }
  14242. }
  14243. return false;
  14244. }
  14245. /**
  14246. * Remove graphic element
  14247. */
  14248. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14249. // Don't do remove animation twice.
  14250. if (isElementRemoved(el)) {
  14251. return;
  14252. }
  14253. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14254. }
  14255. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14256. el.removeTextContent();
  14257. el.removeTextGuideLine();
  14258. removeElement(el, {
  14259. style: {
  14260. opacity: 0
  14261. }
  14262. }, animatableModel, dataIndex, done);
  14263. }
  14264. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14265. function doRemove() {
  14266. el.parent && el.parent.remove(el);
  14267. } // Hide label and labelLine first
  14268. // TODO Also use fade out animation?
  14269. if (!el.isGroup) {
  14270. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14271. } else {
  14272. el.traverse(function (disp) {
  14273. if (!disp.isGroup) {
  14274. // Can invoke doRemove multiple times.
  14275. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14276. }
  14277. });
  14278. }
  14279. }
  14280. /**
  14281. * Save old style for style transition in universalTransition module.
  14282. * It's used when element will be reused in each render.
  14283. * For chart like map, heatmap, which will always create new element.
  14284. * We don't need to save this because universalTransition can get old style from the old element
  14285. */
  14286. function saveOldStyle(el) {
  14287. transitionStore(el).oldStyle = el.style;
  14288. }
  14289. function getOldStyle(el) {
  14290. return transitionStore(el).oldStyle;
  14291. }
  14292. var mathMax$4 = Math.max;
  14293. var mathMin$4 = Math.min;
  14294. var _customShapeMap = {};
  14295. /**
  14296. * Extend shape with parameters
  14297. */
  14298. function extendShape(opts) {
  14299. return Path.extend(opts);
  14300. }
  14301. var extendPathFromString = extendFromString;
  14302. /**
  14303. * Extend path
  14304. */
  14305. function extendPath(pathData, opts) {
  14306. return extendPathFromString(pathData, opts);
  14307. }
  14308. /**
  14309. * Register a user defined shape.
  14310. * The shape class can be fetched by `getShapeClass`
  14311. * This method will overwrite the registered shapes, including
  14312. * the registered built-in shapes, if using the same `name`.
  14313. * The shape can be used in `custom series` and
  14314. * `graphic component` by declaring `{type: name}`.
  14315. *
  14316. * @param name
  14317. * @param ShapeClass Can be generated by `extendShape`.
  14318. */
  14319. function registerShape(name, ShapeClass) {
  14320. _customShapeMap[name] = ShapeClass;
  14321. }
  14322. /**
  14323. * Find shape class registered by `registerShape`. Usually used in
  14324. * fetching user defined shape.
  14325. *
  14326. * [Caution]:
  14327. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14328. * to use user registered shapes.
  14329. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14330. * `registerShape` by default. That enables users to get both built-in
  14331. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14332. * the built-in shapes by using names like 'circle', 'rect' via calling
  14333. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14334. * in case that it is overwritten by users, except that some features, like
  14335. * `custom series`, `graphic component`, do it deliberately.
  14336. *
  14337. * (2) In the features like `custom series`, `graphic component`, the user input
  14338. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14339. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14340. * are reserved names, that is, if some user registers a shape named `'image'`,
  14341. * the shape will not be used. If we intending to add some more reserved names
  14342. * in feature, that might bring break changes (disable some existing user shape
  14343. * names). But that case probably rarely happens. So we don't make more mechanism
  14344. * to resolve this issue here.
  14345. *
  14346. * @param name
  14347. * @return The shape class. If not found, return nothing.
  14348. */
  14349. function getShapeClass(name) {
  14350. if (_customShapeMap.hasOwnProperty(name)) {
  14351. return _customShapeMap[name];
  14352. }
  14353. }
  14354. /**
  14355. * Create a path element from path data string
  14356. * @param pathData
  14357. * @param opts
  14358. * @param rect
  14359. * @param layout 'center' or 'cover' default to be cover
  14360. */
  14361. function makePath(pathData, opts, rect, layout) {
  14362. var path = createFromString(pathData, opts);
  14363. if (rect) {
  14364. if (layout === 'center') {
  14365. rect = centerGraphic(rect, path.getBoundingRect());
  14366. }
  14367. resizePath(path, rect);
  14368. }
  14369. return path;
  14370. }
  14371. /**
  14372. * Create a image element from image url
  14373. * @param imageUrl image url
  14374. * @param opts options
  14375. * @param rect constrain rect
  14376. * @param layout 'center' or 'cover'. Default to be 'cover'
  14377. */
  14378. function makeImage(imageUrl, rect, layout) {
  14379. var zrImg = new ZRImage({
  14380. style: {
  14381. image: imageUrl,
  14382. x: rect.x,
  14383. y: rect.y,
  14384. width: rect.width,
  14385. height: rect.height
  14386. },
  14387. onload: function (img) {
  14388. if (layout === 'center') {
  14389. var boundingRect = {
  14390. width: img.width,
  14391. height: img.height
  14392. };
  14393. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14394. }
  14395. }
  14396. });
  14397. return zrImg;
  14398. }
  14399. /**
  14400. * Get position of centered element in bounding box.
  14401. *
  14402. * @param rect element local bounding box
  14403. * @param boundingRect constraint bounding box
  14404. * @return element position containing x, y, width, and height
  14405. */
  14406. function centerGraphic(rect, boundingRect) {
  14407. // Set rect to center, keep width / height ratio.
  14408. var aspect = boundingRect.width / boundingRect.height;
  14409. var width = rect.height * aspect;
  14410. var height;
  14411. if (width <= rect.width) {
  14412. height = rect.height;
  14413. } else {
  14414. width = rect.width;
  14415. height = width / aspect;
  14416. }
  14417. var cx = rect.x + rect.width / 2;
  14418. var cy = rect.y + rect.height / 2;
  14419. return {
  14420. x: cx - width / 2,
  14421. y: cy - height / 2,
  14422. width: width,
  14423. height: height
  14424. };
  14425. }
  14426. var mergePath$1 = mergePath;
  14427. /**
  14428. * Resize a path to fit the rect
  14429. * @param path
  14430. * @param rect
  14431. */
  14432. function resizePath(path, rect) {
  14433. if (!path.applyTransform) {
  14434. return;
  14435. }
  14436. var pathRect = path.getBoundingRect();
  14437. var m = pathRect.calculateTransform(rect);
  14438. path.applyTransform(m);
  14439. }
  14440. /**
  14441. * Sub pixel optimize line for canvas
  14442. */
  14443. function subPixelOptimizeLine$1(shape, lineWidth) {
  14444. subPixelOptimizeLine(shape, shape, {
  14445. lineWidth: lineWidth
  14446. });
  14447. return shape;
  14448. }
  14449. /**
  14450. * Sub pixel optimize rect for canvas
  14451. */
  14452. function subPixelOptimizeRect$1(param) {
  14453. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14454. return param;
  14455. }
  14456. /**
  14457. * Sub pixel optimize for canvas
  14458. *
  14459. * @param position Coordinate, such as x, y
  14460. * @param lineWidth Should be nonnegative integer.
  14461. * @param positiveOrNegative Default false (negative).
  14462. * @return Optimized position.
  14463. */
  14464. var subPixelOptimize$1 = subPixelOptimize;
  14465. /**
  14466. * Get transform matrix of target (param target),
  14467. * in coordinate of its ancestor (param ancestor)
  14468. *
  14469. * @param target
  14470. * @param [ancestor]
  14471. */
  14472. function getTransform(target, ancestor) {
  14473. var mat = identity([]);
  14474. while (target && target !== ancestor) {
  14475. mul$1(mat, target.getLocalTransform(), mat);
  14476. target = target.parent;
  14477. }
  14478. return mat;
  14479. }
  14480. /**
  14481. * Apply transform to an vertex.
  14482. * @param target [x, y]
  14483. * @param transform Can be:
  14484. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14485. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14486. * @param invert Whether use invert matrix.
  14487. * @return [x, y]
  14488. */
  14489. function applyTransform$1(target, transform, invert$1) {
  14490. if (transform && !isArrayLike(transform)) {
  14491. transform = Transformable.getLocalTransform(transform);
  14492. }
  14493. if (invert$1) {
  14494. transform = invert([], transform);
  14495. }
  14496. return applyTransform([], target, transform);
  14497. }
  14498. /**
  14499. * @param direction 'left' 'right' 'top' 'bottom'
  14500. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14501. * @param invert Whether use invert matrix.
  14502. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14503. */
  14504. function transformDirection(direction, transform, invert) {
  14505. // Pick a base, ensure that transform result will not be (0, 0).
  14506. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14507. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14508. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14509. vertex = applyTransform$1(vertex, transform, invert);
  14510. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14511. }
  14512. function isNotGroup(el) {
  14513. return !el.isGroup;
  14514. }
  14515. function isPath(el) {
  14516. return el.shape != null;
  14517. }
  14518. /**
  14519. * Apply group transition animation from g1 to g2.
  14520. * If no animatableModel, no animation.
  14521. */
  14522. function groupTransition(g1, g2, animatableModel) {
  14523. if (!g1 || !g2) {
  14524. return;
  14525. }
  14526. function getElMap(g) {
  14527. var elMap = {};
  14528. g.traverse(function (el) {
  14529. if (isNotGroup(el) && el.anid) {
  14530. elMap[el.anid] = el;
  14531. }
  14532. });
  14533. return elMap;
  14534. }
  14535. function getAnimatableProps(el) {
  14536. var obj = {
  14537. x: el.x,
  14538. y: el.y,
  14539. rotation: el.rotation
  14540. };
  14541. if (isPath(el)) {
  14542. obj.shape = extend({}, el.shape);
  14543. }
  14544. return obj;
  14545. }
  14546. var elMap1 = getElMap(g1);
  14547. g2.traverse(function (el) {
  14548. if (isNotGroup(el) && el.anid) {
  14549. var oldEl = elMap1[el.anid];
  14550. if (oldEl) {
  14551. var newProp = getAnimatableProps(el);
  14552. el.attr(getAnimatableProps(oldEl));
  14553. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14554. }
  14555. }
  14556. });
  14557. }
  14558. function clipPointsByRect(points, rect) {
  14559. // FIXME: This way might be incorrect when graphic clipped by a corner
  14560. // and when element has a border.
  14561. return map(points, function (point) {
  14562. var x = point[0];
  14563. x = mathMax$4(x, rect.x);
  14564. x = mathMin$4(x, rect.x + rect.width);
  14565. var y = point[1];
  14566. y = mathMax$4(y, rect.y);
  14567. y = mathMin$4(y, rect.y + rect.height);
  14568. return [x, y];
  14569. });
  14570. }
  14571. /**
  14572. * Return a new clipped rect. If rect size are negative, return undefined.
  14573. */
  14574. function clipRectByRect(targetRect, rect) {
  14575. var x = mathMax$4(targetRect.x, rect.x);
  14576. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14577. var y = mathMax$4(targetRect.y, rect.y);
  14578. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14579. // should be painted. So return undefined.
  14580. if (x2 >= x && y2 >= y) {
  14581. return {
  14582. x: x,
  14583. y: y,
  14584. width: x2 - x,
  14585. height: y2 - y
  14586. };
  14587. }
  14588. }
  14589. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14590. opt, rect) {
  14591. var innerOpts = extend({
  14592. rectHover: true
  14593. }, opt);
  14594. var style = innerOpts.style = {
  14595. strokeNoScale: true
  14596. };
  14597. rect = rect || {
  14598. x: -1,
  14599. y: -1,
  14600. width: 2,
  14601. height: 2
  14602. };
  14603. if (iconStr) {
  14604. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14605. }
  14606. }
  14607. /**
  14608. * Return `true` if the given line (line `a`) and the given polygon
  14609. * are intersect.
  14610. * Note that we do not count colinear as intersect here because no
  14611. * requirement for that. We could do that if required in future.
  14612. */
  14613. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14614. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14615. var p = points[i];
  14616. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14617. return true;
  14618. }
  14619. p2 = p;
  14620. }
  14621. }
  14622. /**
  14623. * Return `true` if the given two lines (line `a` and line `b`)
  14624. * are intersect.
  14625. * Note that we do not count colinear as intersect here because no
  14626. * requirement for that. We could do that if required in future.
  14627. */
  14628. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14629. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14630. var mx = a2x - a1x;
  14631. var my = a2y - a1y;
  14632. var nx = b2x - b1x;
  14633. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14634. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14635. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14636. if (nearZero(nmCrossProduct)) {
  14637. return false;
  14638. } // `vec_m` and `vec_n` are intersect iff
  14639. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14640. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14641. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14642. var b1a1x = a1x - b1x;
  14643. var b1a1y = a1y - b1y;
  14644. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14645. if (q < 0 || q > 1) {
  14646. return false;
  14647. }
  14648. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14649. if (p < 0 || p > 1) {
  14650. return false;
  14651. }
  14652. return true;
  14653. }
  14654. /**
  14655. * Cross product of 2-dimension vector.
  14656. */
  14657. function crossProduct2d(x1, y1, x2, y2) {
  14658. return x1 * y2 - x2 * y1;
  14659. }
  14660. function nearZero(val) {
  14661. return val <= 1e-6 && val >= -1e-6;
  14662. }
  14663. function setTooltipConfig(opt) {
  14664. var itemTooltipOption = opt.itemTooltipOption;
  14665. var componentModel = opt.componentModel;
  14666. var itemName = opt.itemName;
  14667. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14668. formatter: itemTooltipOption
  14669. } : itemTooltipOption;
  14670. var mainType = componentModel.mainType;
  14671. var componentIndex = componentModel.componentIndex;
  14672. var formatterParams = {
  14673. componentType: mainType,
  14674. name: itemName,
  14675. $vars: ['name']
  14676. };
  14677. formatterParams[mainType + 'Index'] = componentIndex;
  14678. var formatterParamsExtra = opt.formatterParamsExtra;
  14679. if (formatterParamsExtra) {
  14680. each(keys(formatterParamsExtra), function (key) {
  14681. if (!hasOwn(formatterParams, key)) {
  14682. formatterParams[key] = formatterParamsExtra[key];
  14683. formatterParams.$vars.push(key);
  14684. }
  14685. });
  14686. }
  14687. var ecData = getECData(opt.el);
  14688. ecData.componentMainType = mainType;
  14689. ecData.componentIndex = componentIndex;
  14690. ecData.tooltipConfig = {
  14691. name: itemName,
  14692. option: defaults({
  14693. content: itemName,
  14694. formatterParams: formatterParams
  14695. }, itemTooltipOptionObj)
  14696. };
  14697. }
  14698. function traverseElement(el, cb) {
  14699. var stopped; // TODO
  14700. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14701. if (el.isGroup) {
  14702. stopped = cb(el);
  14703. }
  14704. if (!stopped) {
  14705. el.traverse(cb);
  14706. }
  14707. }
  14708. function traverseElements(els, cb) {
  14709. if (els) {
  14710. if (isArray(els)) {
  14711. for (var i = 0; i < els.length; i++) {
  14712. traverseElement(els[i], cb);
  14713. }
  14714. } else {
  14715. traverseElement(els, cb);
  14716. }
  14717. }
  14718. } // Register built-in shapes. These shapes might be overwritten
  14719. // by users, although we do not recommend that.
  14720. registerShape('circle', Circle);
  14721. registerShape('ellipse', Ellipse);
  14722. registerShape('sector', Sector);
  14723. registerShape('ring', Ring);
  14724. registerShape('polygon', Polygon);
  14725. registerShape('polyline', Polyline);
  14726. registerShape('rect', Rect);
  14727. registerShape('line', Line);
  14728. registerShape('bezierCurve', BezierCurve);
  14729. registerShape('arc', Arc);
  14730. var graphic = /*#__PURE__*/Object.freeze({
  14731. __proto__: null,
  14732. updateProps: updateProps,
  14733. initProps: initProps,
  14734. removeElement: removeElement,
  14735. removeElementWithFadeOut: removeElementWithFadeOut,
  14736. isElementRemoved: isElementRemoved,
  14737. extendShape: extendShape,
  14738. extendPath: extendPath,
  14739. registerShape: registerShape,
  14740. getShapeClass: getShapeClass,
  14741. makePath: makePath,
  14742. makeImage: makeImage,
  14743. mergePath: mergePath$1,
  14744. resizePath: resizePath,
  14745. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14746. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14747. subPixelOptimize: subPixelOptimize$1,
  14748. getTransform: getTransform,
  14749. applyTransform: applyTransform$1,
  14750. transformDirection: transformDirection,
  14751. groupTransition: groupTransition,
  14752. clipPointsByRect: clipPointsByRect,
  14753. clipRectByRect: clipRectByRect,
  14754. createIcon: createIcon,
  14755. linePolygonIntersect: linePolygonIntersect,
  14756. lineLineIntersect: lineLineIntersect,
  14757. setTooltipConfig: setTooltipConfig,
  14758. traverseElements: traverseElements,
  14759. Group: Group,
  14760. Image: ZRImage,
  14761. Text: ZRText,
  14762. Circle: Circle,
  14763. Ellipse: Ellipse,
  14764. Sector: Sector,
  14765. Ring: Ring,
  14766. Polygon: Polygon,
  14767. Polyline: Polyline,
  14768. Rect: Rect,
  14769. Line: Line,
  14770. BezierCurve: BezierCurve,
  14771. Arc: Arc,
  14772. IncrementalDisplayable: IncrementalDisplayable,
  14773. CompoundPath: CompoundPath,
  14774. LinearGradient: LinearGradient,
  14775. RadialGradient: RadialGradient,
  14776. BoundingRect: BoundingRect,
  14777. OrientedBoundingRect: OrientedBoundingRect,
  14778. Point: Point,
  14779. Path: Path
  14780. });
  14781. var EMPTY_OBJ = {};
  14782. function setLabelText(label, labelTexts) {
  14783. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14784. var stateName = SPECIAL_STATES[i];
  14785. var text = labelTexts[stateName];
  14786. var state = label.ensureState(stateName);
  14787. state.style = state.style || {};
  14788. state.style.text = text;
  14789. }
  14790. var oldStates = label.currentStates.slice();
  14791. label.clearStates(true);
  14792. label.setStyle({
  14793. text: labelTexts.normal
  14794. });
  14795. label.useStates(oldStates, true);
  14796. }
  14797. function getLabelText(opt, stateModels, interpolatedValue) {
  14798. var labelFetcher = opt.labelFetcher;
  14799. var labelDataIndex = opt.labelDataIndex;
  14800. var labelDimIndex = opt.labelDimIndex;
  14801. var normalModel = stateModels.normal;
  14802. var baseText;
  14803. if (labelFetcher) {
  14804. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14805. interpolatedValue: interpolatedValue
  14806. } : null);
  14807. }
  14808. if (baseText == null) {
  14809. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14810. }
  14811. var statesText = {
  14812. normal: baseText
  14813. };
  14814. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14815. var stateName = SPECIAL_STATES[i];
  14816. var stateModel = stateModels[stateName];
  14817. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14818. }
  14819. return statesText;
  14820. }
  14821. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14822. ) {
  14823. opt = opt || EMPTY_OBJ;
  14824. var isSetOnText = targetEl instanceof ZRText;
  14825. var needsCreateText = false;
  14826. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14827. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14828. if (stateModel && stateModel.getShallow('show')) {
  14829. needsCreateText = true;
  14830. break;
  14831. }
  14832. }
  14833. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14834. if (needsCreateText) {
  14835. if (!isSetOnText) {
  14836. // Reuse the previous
  14837. if (!textContent) {
  14838. textContent = new ZRText();
  14839. targetEl.setTextContent(textContent);
  14840. } // Use same state proxy
  14841. if (targetEl.stateProxy) {
  14842. textContent.stateProxy = targetEl.stateProxy;
  14843. }
  14844. }
  14845. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14846. var normalModel = labelStatesModels.normal;
  14847. var showNormal = !!normalModel.getShallow('show');
  14848. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14849. normalStyle.text = labelStatesTexts.normal;
  14850. if (!isSetOnText) {
  14851. // Always create new
  14852. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14853. }
  14854. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14855. var stateName = SPECIAL_STATES[i];
  14856. var stateModel = labelStatesModels[stateName];
  14857. if (stateModel) {
  14858. var stateObj = textContent.ensureState(stateName);
  14859. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14860. if (stateShow !== showNormal) {
  14861. stateObj.ignore = !stateShow;
  14862. }
  14863. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14864. stateObj.style.text = labelStatesTexts[stateName];
  14865. if (!isSetOnText) {
  14866. var targetElEmphasisState = targetEl.ensureState(stateName);
  14867. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14868. }
  14869. }
  14870. } // PENDING: if there is many requirements that emphasis position
  14871. // need to be different from normal position, we might consider
  14872. // auto silent is those cases.
  14873. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14874. if (textContent.style.x != null) {
  14875. normalStyle.x = textContent.style.x;
  14876. }
  14877. if (textContent.style.y != null) {
  14878. normalStyle.y = textContent.style.y;
  14879. }
  14880. textContent.ignore = !showNormal; // Always create new style.
  14881. textContent.useStyle(normalStyle);
  14882. textContent.dirty();
  14883. if (opt.enableTextSetter) {
  14884. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14885. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14886. setLabelText(textContent, labelStatesTexts);
  14887. };
  14888. }
  14889. } else if (textContent) {
  14890. // Not display rich text.
  14891. textContent.ignore = true;
  14892. }
  14893. targetEl.dirty();
  14894. }
  14895. function getLabelStatesModels(itemModel, labelName) {
  14896. labelName = labelName || 'label';
  14897. var statesModels = {
  14898. normal: itemModel.getModel(labelName)
  14899. };
  14900. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14901. var stateName = SPECIAL_STATES[i];
  14902. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14903. }
  14904. return statesModels;
  14905. }
  14906. /**
  14907. * Set basic textStyle properties.
  14908. */
  14909. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14910. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14911. ) {
  14912. var textStyle = {};
  14913. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14914. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14915. return textStyle;
  14916. }
  14917. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14918. opt = opt || {};
  14919. var textConfig = {};
  14920. var labelPosition;
  14921. var labelRotate = textStyleModel.getShallow('rotate');
  14922. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14923. var labelOffset = textStyleModel.getShallow('offset');
  14924. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14925. // in bar series, and magric type should be considered.
  14926. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14927. if (labelPosition != null) {
  14928. textConfig.position = labelPosition;
  14929. }
  14930. if (labelOffset != null) {
  14931. textConfig.offset = labelOffset;
  14932. }
  14933. if (labelRotate != null) {
  14934. labelRotate *= Math.PI / 180;
  14935. textConfig.rotation = labelRotate;
  14936. }
  14937. if (labelDistance != null) {
  14938. textConfig.distance = labelDistance;
  14939. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14940. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14941. return textConfig;
  14942. }
  14943. /**
  14944. * The uniform entry of set text style, that is, retrieve style definitions
  14945. * from `model` and set to `textStyle` object.
  14946. *
  14947. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14948. * properties will be set. (Consider the states of normal and emphasis and
  14949. * default value can be adopted, merge would make the logic too complicated
  14950. * to manage.)
  14951. */
  14952. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14953. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14954. opt = opt || EMPTY_OBJ;
  14955. var ecModel = textStyleModel.ecModel;
  14956. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14957. // {
  14958. // data: [{
  14959. // value: 12,
  14960. // label: {
  14961. // rich: {
  14962. // // no 'a' here but using parent 'a'.
  14963. // }
  14964. // }
  14965. // }],
  14966. // rich: {
  14967. // a: { ... }
  14968. // }
  14969. // }
  14970. var richItemNames = getRichItemNames(textStyleModel);
  14971. var richResult;
  14972. if (richItemNames) {
  14973. richResult = {};
  14974. for (var name_1 in richItemNames) {
  14975. if (richItemNames.hasOwnProperty(name_1)) {
  14976. // Cascade is supported in rich.
  14977. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14978. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14979. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14980. // That might confuses users. So probably we should put `textStyleModel` as the
  14981. // root ancestor of the `richTextStyle`. But that would be a break change.
  14982. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14983. }
  14984. }
  14985. }
  14986. if (richResult) {
  14987. textStyle.rich = richResult;
  14988. }
  14989. var overflow = textStyleModel.get('overflow');
  14990. if (overflow) {
  14991. textStyle.overflow = overflow;
  14992. }
  14993. var margin = textStyleModel.get('minMargin');
  14994. if (margin != null) {
  14995. textStyle.margin = margin;
  14996. }
  14997. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14998. } // Consider case:
  14999. // {
  15000. // data: [{
  15001. // value: 12,
  15002. // label: {
  15003. // rich: {
  15004. // // no 'a' here but using parent 'a'.
  15005. // }
  15006. // }
  15007. // }],
  15008. // rich: {
  15009. // a: { ... }
  15010. // }
  15011. // }
  15012. // TODO TextStyleModel
  15013. function getRichItemNames(textStyleModel) {
  15014. // Use object to remove duplicated names.
  15015. var richItemNameMap;
  15016. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15017. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15018. if (rich) {
  15019. richItemNameMap = richItemNameMap || {};
  15020. var richKeys = keys(rich);
  15021. for (var i = 0; i < richKeys.length; i++) {
  15022. var richKey = richKeys[i];
  15023. richItemNameMap[richKey] = 1;
  15024. }
  15025. }
  15026. textStyleModel = textStyleModel.parentModel;
  15027. }
  15028. return richItemNameMap;
  15029. }
  15030. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  15031. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  15032. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  15033. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  15034. // In merge mode, default value should not be given.
  15035. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  15036. var inheritColor = opt && opt.inheritColor;
  15037. var fillColor = textStyleModel.getShallow('color');
  15038. var strokeColor = textStyleModel.getShallow('textBorderColor');
  15039. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  15040. if (fillColor === 'inherit' || fillColor === 'auto') {
  15041. if ("development" !== 'production') {
  15042. if (fillColor === 'auto') {
  15043. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15044. }
  15045. }
  15046. if (inheritColor) {
  15047. fillColor = inheritColor;
  15048. } else {
  15049. fillColor = null;
  15050. }
  15051. }
  15052. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  15053. if ("development" !== 'production') {
  15054. if (strokeColor === 'auto') {
  15055. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15056. }
  15057. }
  15058. if (inheritColor) {
  15059. strokeColor = inheritColor;
  15060. } else {
  15061. strokeColor = null;
  15062. }
  15063. }
  15064. if (!isAttached) {
  15065. // Only use default global textStyle.color if text is individual.
  15066. // Otherwise it will use the strategy of attached text color because text may be on a path.
  15067. fillColor = fillColor || globalTextStyle.color;
  15068. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  15069. }
  15070. if (fillColor != null) {
  15071. textStyle.fill = fillColor;
  15072. }
  15073. if (strokeColor != null) {
  15074. textStyle.stroke = strokeColor;
  15075. }
  15076. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  15077. if (textBorderWidth != null) {
  15078. textStyle.lineWidth = textBorderWidth;
  15079. }
  15080. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  15081. if (textBorderType != null) {
  15082. textStyle.lineDash = textBorderType;
  15083. }
  15084. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  15085. if (textBorderDashOffset != null) {
  15086. textStyle.lineDashOffset = textBorderDashOffset;
  15087. }
  15088. if (!isNotNormal && opacity == null && !inRich) {
  15089. opacity = opt && opt.defaultOpacity;
  15090. }
  15091. if (opacity != null) {
  15092. textStyle.opacity = opacity;
  15093. } // TODO
  15094. if (!isNotNormal && !isAttached) {
  15095. // Set default finally.
  15096. if (textStyle.fill == null && opt.inheritColor) {
  15097. textStyle.fill = opt.inheritColor;
  15098. }
  15099. } // Do not use `getFont` here, because merge should be supported, where
  15100. // part of these properties may be changed in emphasis style, and the
  15101. // others should remain their original value got from normal style.
  15102. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  15103. var key = TEXT_PROPS_WITH_GLOBAL[i];
  15104. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  15105. if (val != null) {
  15106. textStyle[key] = val;
  15107. }
  15108. }
  15109. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  15110. var key = TEXT_PROPS_SELF[i];
  15111. var val = textStyleModel.getShallow(key);
  15112. if (val != null) {
  15113. textStyle[key] = val;
  15114. }
  15115. }
  15116. if (textStyle.verticalAlign == null) {
  15117. var baseline = textStyleModel.getShallow('baseline');
  15118. if (baseline != null) {
  15119. textStyle.verticalAlign = baseline;
  15120. }
  15121. }
  15122. if (!isBlock || !opt.disableBox) {
  15123. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15124. var key = TEXT_PROPS_BOX[i];
  15125. var val = textStyleModel.getShallow(key);
  15126. if (val != null) {
  15127. textStyle[key] = val;
  15128. }
  15129. }
  15130. var borderType = textStyleModel.getShallow('borderType');
  15131. if (borderType != null) {
  15132. textStyle.borderDash = borderType;
  15133. }
  15134. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15135. if ("development" !== 'production') {
  15136. if (textStyle.backgroundColor === 'auto') {
  15137. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15138. }
  15139. }
  15140. textStyle.backgroundColor = inheritColor;
  15141. }
  15142. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15143. if ("development" !== 'production') {
  15144. if (textStyle.borderColor === 'auto') {
  15145. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15146. }
  15147. }
  15148. textStyle.borderColor = inheritColor;
  15149. }
  15150. }
  15151. }
  15152. function getFont(opt, ecModel) {
  15153. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15154. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  15155. 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(' '));
  15156. }
  15157. var labelInner = makeInner();
  15158. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15159. if (!label) {
  15160. return;
  15161. }
  15162. var obj = labelInner(label);
  15163. obj.prevValue = obj.value;
  15164. obj.value = value;
  15165. var normalLabelModel = labelStatesModels.normal;
  15166. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15167. if (obj.valueAnimation) {
  15168. obj.precision = normalLabelModel.get('precision');
  15169. obj.defaultInterpolatedText = getDefaultText;
  15170. obj.statesModels = labelStatesModels;
  15171. }
  15172. }
  15173. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  15174. var labelInnerStore = labelInner(textEl);
  15175. if (!labelInnerStore.valueAnimation || labelInnerStore.prevValue === labelInnerStore.value) {
  15176. // Value not changed, no new label animation
  15177. return;
  15178. }
  15179. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  15180. // Otherwise it will jump to the `obj.value` when this new animation started.
  15181. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  15182. var targetValue = labelInnerStore.value;
  15183. function during(percent) {
  15184. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  15185. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  15186. var labelText = getLabelText({
  15187. labelDataIndex: dataIndex,
  15188. labelFetcher: labelFetcher,
  15189. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  15190. }, labelInnerStore.statesModels, interpolated);
  15191. setLabelText(textEl, labelText);
  15192. }
  15193. textEl.percent = 0;
  15194. (labelInnerStore.prevValue == null ? initProps : updateProps)(textEl, {
  15195. // percent is used to prevent animation from being aborted #15916
  15196. percent: 1
  15197. }, animatableModel, dataIndex, null, during);
  15198. }
  15199. var PATH_COLOR = ['textStyle', 'color'];
  15200. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow']; // TODO Performance improvement?
  15201. var tmpText = new ZRText();
  15202. var TextStyleMixin =
  15203. /** @class */
  15204. function () {
  15205. function TextStyleMixin() {}
  15206. /**
  15207. * Get color property or get color from option.textStyle.color
  15208. */
  15209. // TODO Callback
  15210. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15211. var ecModel = this.ecModel;
  15212. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15213. };
  15214. /**
  15215. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15216. * @return {string}
  15217. */
  15218. TextStyleMixin.prototype.getFont = function () {
  15219. return getFont({
  15220. fontStyle: this.getShallow('fontStyle'),
  15221. fontWeight: this.getShallow('fontWeight'),
  15222. fontSize: this.getShallow('fontSize'),
  15223. fontFamily: this.getShallow('fontFamily')
  15224. }, this.ecModel);
  15225. };
  15226. TextStyleMixin.prototype.getTextRect = function (text) {
  15227. var style = {
  15228. text: text,
  15229. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15230. };
  15231. for (var i = 0; i < textStyleParams.length; i++) {
  15232. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15233. }
  15234. tmpText.useStyle(style);
  15235. tmpText.update();
  15236. return tmpText.getBoundingRect();
  15237. };
  15238. return TextStyleMixin;
  15239. }();
  15240. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15241. // So do not transfer decal directly.
  15242. ];
  15243. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15244. var LineStyleMixin =
  15245. /** @class */
  15246. function () {
  15247. function LineStyleMixin() {}
  15248. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15249. return getLineStyle(this, excludes);
  15250. };
  15251. return LineStyleMixin;
  15252. }();
  15253. var ITEM_STYLE_KEY_MAP = [['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'borderType'], ['lineDashOffset', 'borderDashOffset'], ['lineCap', 'borderCap'], ['lineJoin', 'borderJoin'], ['miterLimit', 'borderMiterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15254. // So do not transfer decal directly.
  15255. ];
  15256. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15257. var ItemStyleMixin =
  15258. /** @class */
  15259. function () {
  15260. function ItemStyleMixin() {}
  15261. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15262. return getItemStyle(this, excludes, includes);
  15263. };
  15264. return ItemStyleMixin;
  15265. }();
  15266. var Model =
  15267. /** @class */
  15268. function () {
  15269. function Model(option, parentModel, ecModel) {
  15270. this.parentModel = parentModel;
  15271. this.ecModel = ecModel;
  15272. this.option = option; // Simple optimization
  15273. // if (this.init) {
  15274. // if (arguments.length <= 4) {
  15275. // this.init(option, parentModel, ecModel, extraOpt);
  15276. // }
  15277. // else {
  15278. // this.init.apply(this, arguments);
  15279. // }
  15280. // }
  15281. }
  15282. Model.prototype.init = function (option, parentModel, ecModel) {
  15283. var rest = [];
  15284. for (var _i = 3; _i < arguments.length; _i++) {
  15285. rest[_i - 3] = arguments[_i];
  15286. }
  15287. };
  15288. /**
  15289. * Merge the input option to me.
  15290. */
  15291. Model.prototype.mergeOption = function (option, ecModel) {
  15292. merge(this.option, option, true);
  15293. }; // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15294. // TODO: TYPE strict key check?
  15295. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15296. Model.prototype.get = function (path, ignoreParent) {
  15297. if (path == null) {
  15298. return this.option;
  15299. }
  15300. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15301. };
  15302. Model.prototype.getShallow = function (key, ignoreParent) {
  15303. var option = this.option;
  15304. var val = option == null ? option : option[key];
  15305. if (val == null && !ignoreParent) {
  15306. var parentModel = this.parentModel;
  15307. if (parentModel) {
  15308. // FIXME:TS do not know how to make it works
  15309. val = parentModel.getShallow(key);
  15310. }
  15311. }
  15312. return val;
  15313. }; // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15314. // getModel(path: string | string[], parentModel?: Model): Model;
  15315. // TODO 'a.b.c' is deprecated
  15316. Model.prototype.getModel = function (path, parentModel) {
  15317. var hasPath = path != null;
  15318. var pathFinal = hasPath ? this.parsePath(path) : null;
  15319. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15320. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15321. return new Model(obj, parentModel, this.ecModel);
  15322. };
  15323. /**
  15324. * If model has option
  15325. */
  15326. Model.prototype.isEmpty = function () {
  15327. return this.option == null;
  15328. };
  15329. Model.prototype.restoreData = function () {}; // Pending
  15330. Model.prototype.clone = function () {
  15331. var Ctor = this.constructor;
  15332. return new Ctor(clone(this.option));
  15333. }; // setReadOnly(properties): void {
  15334. // clazzUtil.setReadOnly(this, properties);
  15335. // }
  15336. // If path is null/undefined, return null/undefined.
  15337. Model.prototype.parsePath = function (path) {
  15338. if (typeof path === 'string') {
  15339. return path.split('.');
  15340. }
  15341. return path;
  15342. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  15343. // Default to be a identity resolver.
  15344. // Can be modified to a different resolver.
  15345. Model.prototype.resolveParentPath = function (path) {
  15346. return path;
  15347. }; // FIXME:TS check whether put this method here
  15348. Model.prototype.isAnimationEnabled = function () {
  15349. if (!env.node && this.option) {
  15350. if (this.option.animation != null) {
  15351. return !!this.option.animation;
  15352. } else if (this.parentModel) {
  15353. return this.parentModel.isAnimationEnabled();
  15354. }
  15355. }
  15356. };
  15357. Model.prototype._doGet = function (pathArr, parentModel) {
  15358. var obj = this.option;
  15359. if (!pathArr) {
  15360. return obj;
  15361. }
  15362. for (var i = 0; i < pathArr.length; i++) {
  15363. // Ignore empty
  15364. if (!pathArr[i]) {
  15365. continue;
  15366. } // obj could be number/string/... (like 0)
  15367. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15368. if (obj == null) {
  15369. break;
  15370. }
  15371. }
  15372. if (obj == null && parentModel) {
  15373. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15374. }
  15375. return obj;
  15376. };
  15377. return Model;
  15378. }();
  15379. enableClassExtend(Model);
  15380. enableClassCheck(Model);
  15381. mixin(Model, LineStyleMixin);
  15382. mixin(Model, ItemStyleMixin);
  15383. mixin(Model, AreaStyleMixin);
  15384. mixin(Model, TextStyleMixin);
  15385. var base = Math.round(Math.random() * 10);
  15386. /**
  15387. * @public
  15388. * @param {string} type
  15389. * @return {string}
  15390. */
  15391. function getUID(type) {
  15392. // Considering the case of crossing js context,
  15393. // use Math.random to make id as unique as possible.
  15394. return [type || '', base++].join('_');
  15395. }
  15396. /**
  15397. * Implements `SubTypeDefaulterManager` for `target`.
  15398. */
  15399. function enableSubTypeDefaulter(target) {
  15400. var subTypeDefaulters = {};
  15401. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15402. var componentTypeInfo = parseClassType(componentType);
  15403. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15404. };
  15405. target.determineSubType = function (componentType, option) {
  15406. var type = option.type;
  15407. if (!type) {
  15408. var componentTypeMain = parseClassType(componentType).main;
  15409. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15410. type = subTypeDefaulters[componentTypeMain](option);
  15411. }
  15412. }
  15413. return type;
  15414. };
  15415. }
  15416. /**
  15417. * Implements `TopologicalTravelable<any>` for `entity`.
  15418. *
  15419. * Topological travel on Activity Network (Activity On Vertices).
  15420. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15421. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15422. * If there is circular dependencey, Error will be thrown.
  15423. */
  15424. function enableTopologicalTravel(entity, dependencyGetter) {
  15425. /**
  15426. * @param targetNameList Target Component type list.
  15427. * Can be ['aa', 'bb', 'aa.xx']
  15428. * @param fullNameList By which we can build dependency graph.
  15429. * @param callback Params: componentType, dependencies.
  15430. * @param context Scope of callback.
  15431. */
  15432. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15433. if (!targetNameList.length) {
  15434. return;
  15435. }
  15436. var result = makeDepndencyGraph(fullNameList);
  15437. var graph = result.graph;
  15438. var noEntryList = result.noEntryList;
  15439. var targetNameSet = {};
  15440. each(targetNameList, function (name) {
  15441. targetNameSet[name] = true;
  15442. });
  15443. while (noEntryList.length) {
  15444. var currComponentType = noEntryList.pop();
  15445. var currVertex = graph[currComponentType];
  15446. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15447. if (isInTargetNameSet) {
  15448. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15449. delete targetNameSet[currComponentType];
  15450. }
  15451. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15452. }
  15453. each(targetNameSet, function () {
  15454. var errMsg = '';
  15455. if ("development" !== 'production') {
  15456. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15457. }
  15458. throw new Error(errMsg);
  15459. });
  15460. function removeEdge(succComponentType) {
  15461. graph[succComponentType].entryCount--;
  15462. if (graph[succComponentType].entryCount === 0) {
  15463. noEntryList.push(succComponentType);
  15464. }
  15465. } // Consider this case: legend depends on series, and we call
  15466. // chart.setOption({series: [...]}), where only series is in option.
  15467. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15468. // not be called, but only sereis.mergeOption is called. Thus legend
  15469. // have no chance to update its local record about series (like which
  15470. // name of series is available in legend).
  15471. function removeEdgeAndAdd(succComponentType) {
  15472. targetNameSet[succComponentType] = true;
  15473. removeEdge(succComponentType);
  15474. }
  15475. };
  15476. function makeDepndencyGraph(fullNameList) {
  15477. var graph = {};
  15478. var noEntryList = [];
  15479. each(fullNameList, function (name) {
  15480. var thisItem = createDependencyGraphItem(graph, name);
  15481. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15482. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15483. thisItem.entryCount = availableDeps.length;
  15484. if (thisItem.entryCount === 0) {
  15485. noEntryList.push(name);
  15486. }
  15487. each(availableDeps, function (dependentName) {
  15488. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15489. thisItem.predecessor.push(dependentName);
  15490. }
  15491. var thatItem = createDependencyGraphItem(graph, dependentName);
  15492. if (indexOf(thatItem.successor, dependentName) < 0) {
  15493. thatItem.successor.push(name);
  15494. }
  15495. });
  15496. });
  15497. return {
  15498. graph: graph,
  15499. noEntryList: noEntryList
  15500. };
  15501. }
  15502. function createDependencyGraphItem(graph, name) {
  15503. if (!graph[name]) {
  15504. graph[name] = {
  15505. predecessor: [],
  15506. successor: []
  15507. };
  15508. }
  15509. return graph[name];
  15510. }
  15511. function getAvailableDependencies(originalDeps, fullNameList) {
  15512. var availableDeps = [];
  15513. each(originalDeps, function (dep) {
  15514. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15515. });
  15516. return availableDeps;
  15517. }
  15518. }
  15519. function inheritDefaultOption(superOption, subOption) {
  15520. // See also `model/Component.ts#getDefaultOption`
  15521. return merge(merge({}, superOption, true), subOption, true);
  15522. }
  15523. /*
  15524. * Licensed to the Apache Software Foundation (ASF) under one
  15525. * or more contributor license agreements. See the NOTICE file
  15526. * distributed with this work for additional information
  15527. * regarding copyright ownership. The ASF licenses this file
  15528. * to you under the Apache License, Version 2.0 (the
  15529. * "License"); you may not use this file except in compliance
  15530. * with the License. You may obtain a copy of the License at
  15531. *
  15532. * http://www.apache.org/licenses/LICENSE-2.0
  15533. *
  15534. * Unless required by applicable law or agreed to in writing,
  15535. * software distributed under the License is distributed on an
  15536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15537. * KIND, either express or implied. See the License for the
  15538. * specific language governing permissions and limitations
  15539. * under the License.
  15540. */
  15541. /**
  15542. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15543. */
  15544. /*
  15545. * Licensed to the Apache Software Foundation (ASF) under one
  15546. * or more contributor license agreements. See the NOTICE file
  15547. * distributed with this work for additional information
  15548. * regarding copyright ownership. The ASF licenses this file
  15549. * to you under the Apache License, Version 2.0 (the
  15550. * "License"); you may not use this file except in compliance
  15551. * with the License. You may obtain a copy of the License at
  15552. *
  15553. * http://www.apache.org/licenses/LICENSE-2.0
  15554. *
  15555. * Unless required by applicable law or agreed to in writing,
  15556. * software distributed under the License is distributed on an
  15557. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15558. * KIND, either express or implied. See the License for the
  15559. * specific language governing permissions and limitations
  15560. * under the License.
  15561. */
  15562. /**
  15563. * Language: English.
  15564. */
  15565. var langEN = {
  15566. time: {
  15567. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15568. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15569. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15570. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15571. },
  15572. legend: {
  15573. selector: {
  15574. all: 'All',
  15575. inverse: 'Inv'
  15576. }
  15577. },
  15578. toolbox: {
  15579. brush: {
  15580. title: {
  15581. rect: 'Box Select',
  15582. polygon: 'Lasso Select',
  15583. lineX: 'Horizontally Select',
  15584. lineY: 'Vertically Select',
  15585. keep: 'Keep Selections',
  15586. clear: 'Clear Selections'
  15587. }
  15588. },
  15589. dataView: {
  15590. title: 'Data View',
  15591. lang: ['Data View', 'Close', 'Refresh']
  15592. },
  15593. dataZoom: {
  15594. title: {
  15595. zoom: 'Zoom',
  15596. back: 'Zoom Reset'
  15597. }
  15598. },
  15599. magicType: {
  15600. title: {
  15601. line: 'Switch to Line Chart',
  15602. bar: 'Switch to Bar Chart',
  15603. stack: 'Stack',
  15604. tiled: 'Tile'
  15605. }
  15606. },
  15607. restore: {
  15608. title: 'Restore'
  15609. },
  15610. saveAsImage: {
  15611. title: 'Save as Image',
  15612. lang: ['Right Click to Save Image']
  15613. }
  15614. },
  15615. series: {
  15616. typeNames: {
  15617. pie: 'Pie chart',
  15618. bar: 'Bar chart',
  15619. line: 'Line chart',
  15620. scatter: 'Scatter plot',
  15621. effectScatter: 'Ripple scatter plot',
  15622. radar: 'Radar chart',
  15623. tree: 'Tree',
  15624. treemap: 'Treemap',
  15625. boxplot: 'Boxplot',
  15626. candlestick: 'Candlestick',
  15627. k: 'K line chart',
  15628. heatmap: 'Heat map',
  15629. map: 'Map',
  15630. parallel: 'Parallel coordinate map',
  15631. lines: 'Line graph',
  15632. graph: 'Relationship graph',
  15633. sankey: 'Sankey diagram',
  15634. funnel: 'Funnel chart',
  15635. gauge: 'Gauge',
  15636. pictorialBar: 'Pictorial bar',
  15637. themeRiver: 'Theme River Map',
  15638. sunburst: 'Sunburst'
  15639. }
  15640. },
  15641. aria: {
  15642. general: {
  15643. withTitle: 'This is a chart about "{title}"',
  15644. withoutTitle: 'This is a chart'
  15645. },
  15646. series: {
  15647. single: {
  15648. prefix: '',
  15649. withName: ' with type {seriesType} named {seriesName}.',
  15650. withoutName: ' with type {seriesType}.'
  15651. },
  15652. multiple: {
  15653. prefix: '. It consists of {seriesCount} series count.',
  15654. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15655. withoutName: ' The {seriesId} series is a {seriesType}.',
  15656. separator: {
  15657. middle: '',
  15658. end: ''
  15659. }
  15660. }
  15661. },
  15662. data: {
  15663. allData: 'The data is as follows: ',
  15664. partialData: 'The first {displayCnt} items are: ',
  15665. withName: 'the data for {name} is {value}',
  15666. withoutName: '{value}',
  15667. separator: {
  15668. middle: ', ',
  15669. end: '. '
  15670. }
  15671. }
  15672. }
  15673. };
  15674. /*
  15675. * Licensed to the Apache Software Foundation (ASF) under one
  15676. * or more contributor license agreements. See the NOTICE file
  15677. * distributed with this work for additional information
  15678. * regarding copyright ownership. The ASF licenses this file
  15679. * to you under the Apache License, Version 2.0 (the
  15680. * "License"); you may not use this file except in compliance
  15681. * with the License. You may obtain a copy of the License at
  15682. *
  15683. * http://www.apache.org/licenses/LICENSE-2.0
  15684. *
  15685. * Unless required by applicable law or agreed to in writing,
  15686. * software distributed under the License is distributed on an
  15687. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15688. * KIND, either express or implied. See the License for the
  15689. * specific language governing permissions and limitations
  15690. * under the License.
  15691. */
  15692. /**
  15693. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15694. */
  15695. /*
  15696. * Licensed to the Apache Software Foundation (ASF) under one
  15697. * or more contributor license agreements. See the NOTICE file
  15698. * distributed with this work for additional information
  15699. * regarding copyright ownership. The ASF licenses this file
  15700. * to you under the Apache License, Version 2.0 (the
  15701. * "License"); you may not use this file except in compliance
  15702. * with the License. You may obtain a copy of the License at
  15703. *
  15704. * http://www.apache.org/licenses/LICENSE-2.0
  15705. *
  15706. * Unless required by applicable law or agreed to in writing,
  15707. * software distributed under the License is distributed on an
  15708. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15709. * KIND, either express or implied. See the License for the
  15710. * specific language governing permissions and limitations
  15711. * under the License.
  15712. */
  15713. var langZH = {
  15714. time: {
  15715. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15716. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15717. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15718. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15719. },
  15720. legend: {
  15721. selector: {
  15722. all: '全选',
  15723. inverse: '反选'
  15724. }
  15725. },
  15726. toolbox: {
  15727. brush: {
  15728. title: {
  15729. rect: '矩形选择',
  15730. polygon: '圈选',
  15731. lineX: '横向选择',
  15732. lineY: '纵向选择',
  15733. keep: '保持选择',
  15734. clear: '清除选择'
  15735. }
  15736. },
  15737. dataView: {
  15738. title: '数据视图',
  15739. lang: ['数据视图', '关闭', '刷新']
  15740. },
  15741. dataZoom: {
  15742. title: {
  15743. zoom: '区域缩放',
  15744. back: '区域缩放还原'
  15745. }
  15746. },
  15747. magicType: {
  15748. title: {
  15749. line: '切换为折线图',
  15750. bar: '切换为柱状图',
  15751. stack: '切换为堆叠',
  15752. tiled: '切换为平铺'
  15753. }
  15754. },
  15755. restore: {
  15756. title: '还原'
  15757. },
  15758. saveAsImage: {
  15759. title: '保存为图片',
  15760. lang: ['右键另存为图片']
  15761. }
  15762. },
  15763. series: {
  15764. typeNames: {
  15765. pie: '饼图',
  15766. bar: '柱状图',
  15767. line: '折线图',
  15768. scatter: '散点图',
  15769. effectScatter: '涟漪散点图',
  15770. radar: '雷达图',
  15771. tree: '树图',
  15772. treemap: '矩形树图',
  15773. boxplot: '箱型图',
  15774. candlestick: 'K线图',
  15775. k: 'K线图',
  15776. heatmap: '热力图',
  15777. map: '地图',
  15778. parallel: '平行坐标图',
  15779. lines: '线图',
  15780. graph: '关系图',
  15781. sankey: '桑基图',
  15782. funnel: '漏斗图',
  15783. gauge: '仪表盘图',
  15784. pictorialBar: '象形柱图',
  15785. themeRiver: '主题河流图',
  15786. sunburst: '旭日图'
  15787. }
  15788. },
  15789. aria: {
  15790. general: {
  15791. withTitle: '这是一个关于“{title}”的图表。',
  15792. withoutTitle: '这是一个图表,'
  15793. },
  15794. series: {
  15795. single: {
  15796. prefix: '',
  15797. withName: '图表类型是{seriesType},表示{seriesName}。',
  15798. withoutName: '图表类型是{seriesType}。'
  15799. },
  15800. multiple: {
  15801. prefix: '它由{seriesCount}个图表系列组成。',
  15802. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15803. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15804. separator: {
  15805. middle: ';',
  15806. end: '。'
  15807. }
  15808. }
  15809. },
  15810. data: {
  15811. allData: '其数据是——',
  15812. partialData: '其中,前{displayCnt}项是——',
  15813. withName: '{name}的数据是{value}',
  15814. withoutName: '{value}',
  15815. separator: {
  15816. middle: ',',
  15817. end: ''
  15818. }
  15819. }
  15820. }
  15821. };
  15822. var LOCALE_ZH = 'ZH';
  15823. var LOCALE_EN = 'EN';
  15824. var DEFAULT_LOCALE = LOCALE_EN;
  15825. var localeStorage = {};
  15826. var localeModels = {};
  15827. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15828. var langStr = (
  15829. /* eslint-disable-next-line */
  15830. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15831. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15832. }();
  15833. function registerLocale(locale, localeObj) {
  15834. locale = locale.toUpperCase();
  15835. localeModels[locale] = new Model(localeObj);
  15836. localeStorage[locale] = localeObj;
  15837. } // export function getLocale(locale: string) {
  15838. // return localeStorage[locale];
  15839. // }
  15840. function createLocaleObject(locale) {
  15841. if (isString(locale)) {
  15842. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15843. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15844. return clone(localeObj);
  15845. } else {
  15846. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15847. }
  15848. } else {
  15849. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15850. }
  15851. }
  15852. function getLocaleModel(lang) {
  15853. return localeModels[lang];
  15854. }
  15855. function getDefaultLocaleModel() {
  15856. return localeModels[DEFAULT_LOCALE];
  15857. } // Default locale
  15858. registerLocale(LOCALE_EN, langEN);
  15859. registerLocale(LOCALE_ZH, langZH);
  15860. var ONE_SECOND = 1000;
  15861. var ONE_MINUTE = ONE_SECOND * 60;
  15862. var ONE_HOUR = ONE_MINUTE * 60;
  15863. var ONE_DAY = ONE_HOUR * 24;
  15864. var ONE_YEAR = ONE_DAY * 365;
  15865. var defaultLeveledFormatter = {
  15866. year: '{yyyy}',
  15867. month: '{MMM}',
  15868. day: '{d}',
  15869. hour: '{HH}:{mm}',
  15870. minute: '{HH}:{mm}',
  15871. second: '{HH}:{mm}:{ss}',
  15872. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15873. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15874. };
  15875. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15876. var fullLeveledFormatter = {
  15877. year: '{yyyy}',
  15878. month: '{yyyy}-{MM}',
  15879. day: fullDayFormatter,
  15880. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15881. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15882. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15883. millisecond: defaultLeveledFormatter.none
  15884. };
  15885. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15886. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15887. function pad(str, len) {
  15888. str += '';
  15889. return '0000'.substr(0, len - str.length) + str;
  15890. }
  15891. function getPrimaryTimeUnit(timeUnit) {
  15892. switch (timeUnit) {
  15893. case 'half-year':
  15894. case 'quarter':
  15895. return 'month';
  15896. case 'week':
  15897. case 'half-week':
  15898. return 'day';
  15899. case 'half-day':
  15900. case 'quarter-day':
  15901. return 'hour';
  15902. default:
  15903. // year, minutes, second, milliseconds
  15904. return timeUnit;
  15905. }
  15906. }
  15907. function isPrimaryTimeUnit(timeUnit) {
  15908. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15909. }
  15910. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15911. switch (timeUnit) {
  15912. case 'year':
  15913. case 'month':
  15914. return 'day';
  15915. case 'millisecond':
  15916. return 'millisecond';
  15917. default:
  15918. // Also for day, hour, minute, second
  15919. return 'second';
  15920. }
  15921. }
  15922. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15923. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15924. time, template, isUTC, lang) {
  15925. var date = parseDate(time);
  15926. var y = date[fullYearGetterName(isUTC)]();
  15927. var M = date[monthGetterName(isUTC)]() + 1;
  15928. var q = Math.floor((M - 1) / 3) + 1;
  15929. var d = date[dateGetterName(isUTC)]();
  15930. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15931. var H = date[hoursGetterName(isUTC)]();
  15932. var h = (H - 1) % 12 + 1;
  15933. var m = date[minutesGetterName(isUTC)]();
  15934. var s = date[secondsGetterName(isUTC)]();
  15935. var S = date[millisecondsGetterName(isUTC)]();
  15936. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15937. var timeModel = localeModel.getModel('time');
  15938. var month = timeModel.get('month');
  15939. var monthAbbr = timeModel.get('monthAbbr');
  15940. var dayOfWeek = timeModel.get('dayOfWeek');
  15941. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15942. return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, y % 100 + '').replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15943. }
  15944. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15945. var template = null;
  15946. if (isString(formatter)) {
  15947. // Single formatter for all units at all levels
  15948. template = formatter;
  15949. } else if (isFunction(formatter)) {
  15950. // Callback formatter
  15951. template = formatter(tick.value, idx, {
  15952. level: tick.level
  15953. });
  15954. } else {
  15955. var defaults$1 = extend({}, defaultLeveledFormatter);
  15956. if (tick.level > 0) {
  15957. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15958. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15959. }
  15960. }
  15961. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15962. : defaults(formatter, defaults$1) : defaults$1;
  15963. var unit = getUnitFromValue(tick.value, isUTC);
  15964. if (mergedFormatter[unit]) {
  15965. template = mergedFormatter[unit];
  15966. } else if (mergedFormatter.inherit) {
  15967. // Unit formatter is not defined and should inherit from bigger units
  15968. var targetId = timeUnits.indexOf(unit);
  15969. for (var i = targetId - 1; i >= 0; --i) {
  15970. if (mergedFormatter[unit]) {
  15971. template = mergedFormatter[unit];
  15972. break;
  15973. }
  15974. }
  15975. template = template || defaults$1.none;
  15976. }
  15977. if (isArray(template)) {
  15978. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15979. levelId = Math.min(levelId, template.length - 1);
  15980. template = template[levelId];
  15981. }
  15982. }
  15983. return format(new Date(tick.value), template, isUTC, lang);
  15984. }
  15985. function getUnitFromValue(value, isUTC) {
  15986. var date = parseDate(value);
  15987. var M = date[monthGetterName(isUTC)]() + 1;
  15988. var d = date[dateGetterName(isUTC)]();
  15989. var h = date[hoursGetterName(isUTC)]();
  15990. var m = date[minutesGetterName(isUTC)]();
  15991. var s = date[secondsGetterName(isUTC)]();
  15992. var S = date[millisecondsGetterName(isUTC)]();
  15993. var isSecond = S === 0;
  15994. var isMinute = isSecond && s === 0;
  15995. var isHour = isMinute && m === 0;
  15996. var isDay = isHour && h === 0;
  15997. var isMonth = isDay && d === 1;
  15998. var isYear = isMonth && M === 1;
  15999. if (isYear) {
  16000. return 'year';
  16001. } else if (isMonth) {
  16002. return 'month';
  16003. } else if (isDay) {
  16004. return 'day';
  16005. } else if (isHour) {
  16006. return 'hour';
  16007. } else if (isMinute) {
  16008. return 'minute';
  16009. } else if (isSecond) {
  16010. return 'second';
  16011. } else {
  16012. return 'millisecond';
  16013. }
  16014. }
  16015. function getUnitValue(value, unit, isUTC) {
  16016. var date = isNumber(value) ? parseDate(value) : value;
  16017. unit = unit || getUnitFromValue(value, isUTC);
  16018. switch (unit) {
  16019. case 'year':
  16020. return date[fullYearGetterName(isUTC)]();
  16021. case 'half-year':
  16022. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  16023. case 'quarter':
  16024. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  16025. case 'month':
  16026. return date[monthGetterName(isUTC)]();
  16027. case 'day':
  16028. return date[dateGetterName(isUTC)]();
  16029. case 'half-day':
  16030. return date[hoursGetterName(isUTC)]() / 24;
  16031. case 'hour':
  16032. return date[hoursGetterName(isUTC)]();
  16033. case 'minute':
  16034. return date[minutesGetterName(isUTC)]();
  16035. case 'second':
  16036. return date[secondsGetterName(isUTC)]();
  16037. case 'millisecond':
  16038. return date[millisecondsGetterName(isUTC)]();
  16039. }
  16040. }
  16041. function fullYearGetterName(isUTC) {
  16042. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  16043. }
  16044. function monthGetterName(isUTC) {
  16045. return isUTC ? 'getUTCMonth' : 'getMonth';
  16046. }
  16047. function dateGetterName(isUTC) {
  16048. return isUTC ? 'getUTCDate' : 'getDate';
  16049. }
  16050. function hoursGetterName(isUTC) {
  16051. return isUTC ? 'getUTCHours' : 'getHours';
  16052. }
  16053. function minutesGetterName(isUTC) {
  16054. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  16055. }
  16056. function secondsGetterName(isUTC) {
  16057. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  16058. }
  16059. function millisecondsGetterName(isUTC) {
  16060. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  16061. }
  16062. function fullYearSetterName(isUTC) {
  16063. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  16064. }
  16065. function monthSetterName(isUTC) {
  16066. return isUTC ? 'setUTCMonth' : 'setMonth';
  16067. }
  16068. function dateSetterName(isUTC) {
  16069. return isUTC ? 'setUTCDate' : 'setDate';
  16070. }
  16071. function hoursSetterName(isUTC) {
  16072. return isUTC ? 'setUTCHours' : 'setHours';
  16073. }
  16074. function minutesSetterName(isUTC) {
  16075. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  16076. }
  16077. function secondsSetterName(isUTC) {
  16078. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  16079. }
  16080. function millisecondsSetterName(isUTC) {
  16081. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  16082. }
  16083. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  16084. var textEl = new ZRText({
  16085. style: {
  16086. text: text,
  16087. font: font,
  16088. align: align,
  16089. verticalAlign: verticalAlign,
  16090. padding: padding,
  16091. rich: rich,
  16092. overflow: truncate ? 'truncate' : null,
  16093. lineHeight: lineHeight
  16094. }
  16095. });
  16096. return textEl.getBoundingRect();
  16097. }
  16098. /**
  16099. * Add a comma each three digit.
  16100. */
  16101. function addCommas(x) {
  16102. if (!isNumeric(x)) {
  16103. return isString(x) ? x : '-';
  16104. }
  16105. var parts = (x + '').split('.');
  16106. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  16107. }
  16108. function toCamelCase(str, upperCaseFirst) {
  16109. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16110. return group1.toUpperCase();
  16111. });
  16112. if (upperCaseFirst && str) {
  16113. str = str.charAt(0).toUpperCase() + str.slice(1);
  16114. }
  16115. return str;
  16116. }
  16117. var normalizeCssArray$1 = normalizeCssArray;
  16118. /**
  16119. * Make value user readable for tooltip and label.
  16120. * "User readable":
  16121. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  16122. * Avoid to display an empty string, which users can not recognize there is
  16123. * a value and it might look like a bug.
  16124. */
  16125. function makeValueReadable(value, valueType, useUTC) {
  16126. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  16127. function stringToUserReadable(str) {
  16128. return str && trim(str) ? str : '-';
  16129. }
  16130. function isNumberUserReadable(num) {
  16131. return !!(num != null && !isNaN(num) && isFinite(num));
  16132. }
  16133. var isTypeTime = valueType === 'time';
  16134. var isValueDate = value instanceof Date;
  16135. if (isTypeTime || isValueDate) {
  16136. var date = isTypeTime ? parseDate(value) : value;
  16137. if (!isNaN(+date)) {
  16138. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  16139. } else if (isValueDate) {
  16140. return '-';
  16141. } // In other cases, continue to try to display the value in the following code.
  16142. }
  16143. if (valueType === 'ordinal') {
  16144. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  16145. } // By default.
  16146. var numericResult = numericToNumber(value);
  16147. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16148. }
  16149. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16150. var wrapVar = function (varName, seriesIdx) {
  16151. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16152. };
  16153. /**
  16154. * Template formatter
  16155. * @param {Array.<Object>|Object} paramsList
  16156. */
  16157. function formatTpl(tpl, paramsList, encode) {
  16158. if (!isArray(paramsList)) {
  16159. paramsList = [paramsList];
  16160. }
  16161. var seriesLen = paramsList.length;
  16162. if (!seriesLen) {
  16163. return '';
  16164. }
  16165. var $vars = paramsList[0].$vars || [];
  16166. for (var i = 0; i < $vars.length; i++) {
  16167. var alias = TPL_VAR_ALIAS[i];
  16168. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16169. }
  16170. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16171. for (var k = 0; k < $vars.length; k++) {
  16172. var val = paramsList[seriesIdx][$vars[k]];
  16173. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16174. }
  16175. }
  16176. return tpl;
  16177. }
  16178. /**
  16179. * simple Template formatter
  16180. */
  16181. function formatTplSimple(tpl, param, encode) {
  16182. each(param, function (value, key) {
  16183. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  16184. });
  16185. return tpl;
  16186. }
  16187. function getTooltipMarker(inOpt, extraCssText) {
  16188. var opt = isString(inOpt) ? {
  16189. color: inOpt,
  16190. extraCssText: extraCssText
  16191. } : inOpt || {};
  16192. var color = opt.color;
  16193. var type = opt.type;
  16194. extraCssText = opt.extraCssText;
  16195. var renderMode = opt.renderMode || 'html';
  16196. if (!color) {
  16197. return '';
  16198. }
  16199. if (renderMode === 'html') {
  16200. return type === 'subItem' ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;' + 'border-radius:4px;width:4px;height:4px;background-color:' // Only support string
  16201. + 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>';
  16202. } else {
  16203. // Should better not to auto generate style name by auto-increment number here.
  16204. // Because this util is usually called in tooltip formatter, which is probably
  16205. // called repeatedly when mouse move and the auto-increment number increases fast.
  16206. // Users can make their own style name by theirselves, make it unique and readable.
  16207. var markerId = opt.markerId || 'markerX';
  16208. return {
  16209. renderMode: renderMode,
  16210. content: '{' + markerId + '|} ',
  16211. style: type === 'subItem' ? {
  16212. width: 4,
  16213. height: 4,
  16214. borderRadius: 2,
  16215. backgroundColor: color
  16216. } : {
  16217. width: 10,
  16218. height: 10,
  16219. borderRadius: 5,
  16220. backgroundColor: color
  16221. }
  16222. };
  16223. }
  16224. }
  16225. /**
  16226. * @deprecated Use `time/format` instead.
  16227. * ISO Date format
  16228. * @param {string} tpl
  16229. * @param {number} value
  16230. * @param {boolean} [isUTC=false] Default in local time.
  16231. * see `module:echarts/scale/Time`
  16232. * and `module:echarts/util/number#parseDate`.
  16233. * @inner
  16234. */
  16235. function formatTime(tpl, value, isUTC) {
  16236. if ("development" !== 'production') {
  16237. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16238. }
  16239. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16240. tpl = 'MM-dd\nyyyy';
  16241. }
  16242. var date = parseDate(value);
  16243. var getUTC = isUTC ? 'getUTC' : 'get';
  16244. var y = date[getUTC + 'FullYear']();
  16245. var M = date[getUTC + 'Month']() + 1;
  16246. var d = date[getUTC + 'Date']();
  16247. var h = date[getUTC + 'Hours']();
  16248. var m = date[getUTC + 'Minutes']();
  16249. var s = date[getUTC + 'Seconds']();
  16250. var S = date[getUTC + 'Milliseconds']();
  16251. 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));
  16252. return tpl;
  16253. }
  16254. /**
  16255. * Capital first
  16256. * @param {string} str
  16257. * @return {string}
  16258. */
  16259. function capitalFirst(str) {
  16260. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16261. }
  16262. /**
  16263. * @return Never be null/undefined.
  16264. */
  16265. function convertToColorString(color, defaultColor) {
  16266. defaultColor = defaultColor || 'transparent';
  16267. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16268. }
  16269. /**
  16270. * open new tab
  16271. * @param link url
  16272. * @param target blank or self
  16273. */
  16274. function windowOpen(link, target) {
  16275. /* global window */
  16276. if (target === '_blank' || target === 'blank') {
  16277. var blank = window.open();
  16278. blank.opener = null;
  16279. blank.location.href = link;
  16280. } else {
  16281. window.open(link, target);
  16282. }
  16283. }
  16284. var each$1 = each;
  16285. /**
  16286. * @public
  16287. */
  16288. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16289. /**
  16290. * @public
  16291. */
  16292. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16293. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16294. var x = 0;
  16295. var y = 0;
  16296. if (maxWidth == null) {
  16297. maxWidth = Infinity;
  16298. }
  16299. if (maxHeight == null) {
  16300. maxHeight = Infinity;
  16301. }
  16302. var currentLineMaxSize = 0;
  16303. group.eachChild(function (child, idx) {
  16304. var rect = child.getBoundingRect();
  16305. var nextChild = group.childAt(idx + 1);
  16306. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16307. var nextX;
  16308. var nextY;
  16309. if (orient === 'horizontal') {
  16310. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16311. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16312. // FIXME compare before adding gap?
  16313. if (nextX > maxWidth || child.newline) {
  16314. x = 0;
  16315. nextX = moveX;
  16316. y += currentLineMaxSize + gap;
  16317. currentLineMaxSize = rect.height;
  16318. } else {
  16319. // FIXME: consider rect.y is not `0`?
  16320. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16321. }
  16322. } else {
  16323. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16324. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16325. if (nextY > maxHeight || child.newline) {
  16326. x += currentLineMaxSize + gap;
  16327. y = 0;
  16328. nextY = moveY;
  16329. currentLineMaxSize = rect.width;
  16330. } else {
  16331. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16332. }
  16333. }
  16334. if (child.newline) {
  16335. return;
  16336. }
  16337. child.x = x;
  16338. child.y = y;
  16339. child.markRedraw();
  16340. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16341. });
  16342. }
  16343. /**
  16344. * VBox or HBox layouting
  16345. * @param {string} orient
  16346. * @param {module:zrender/graphic/Group} group
  16347. * @param {number} gap
  16348. * @param {number} [width=Infinity]
  16349. * @param {number} [height=Infinity]
  16350. */
  16351. var box = boxLayout;
  16352. /**
  16353. * VBox layouting
  16354. * @param {module:zrender/graphic/Group} group
  16355. * @param {number} gap
  16356. * @param {number} [width=Infinity]
  16357. * @param {number} [height=Infinity]
  16358. */
  16359. var vbox = curry(boxLayout, 'vertical');
  16360. /**
  16361. * HBox layouting
  16362. * @param {module:zrender/graphic/Group} group
  16363. * @param {number} gap
  16364. * @param {number} [width=Infinity]
  16365. * @param {number} [height=Infinity]
  16366. */
  16367. var hbox = curry(boxLayout, 'horizontal');
  16368. /**
  16369. * If x or x2 is not specified or 'center' 'left' 'right',
  16370. * the width would be as long as possible.
  16371. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16372. * the height would be as long as possible.
  16373. */
  16374. function getAvailableSize(positionInfo, containerRect, margin) {
  16375. var containerWidth = containerRect.width;
  16376. var containerHeight = containerRect.height;
  16377. var x = parsePercent$1(positionInfo.left, containerWidth);
  16378. var y = parsePercent$1(positionInfo.top, containerHeight);
  16379. var x2 = parsePercent$1(positionInfo.right, containerWidth);
  16380. var y2 = parsePercent$1(positionInfo.bottom, containerHeight);
  16381. (isNaN(x) || isNaN(parseFloat(positionInfo.left))) && (x = 0);
  16382. (isNaN(x2) || isNaN(parseFloat(positionInfo.right))) && (x2 = containerWidth);
  16383. (isNaN(y) || isNaN(parseFloat(positionInfo.top))) && (y = 0);
  16384. (isNaN(y2) || isNaN(parseFloat(positionInfo.bottom))) && (y2 = containerHeight);
  16385. margin = normalizeCssArray$1(margin || 0);
  16386. return {
  16387. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16388. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16389. };
  16390. }
  16391. /**
  16392. * Parse position info.
  16393. */
  16394. function getLayoutRect(positionInfo, containerRect, margin) {
  16395. margin = normalizeCssArray$1(margin || 0);
  16396. var containerWidth = containerRect.width;
  16397. var containerHeight = containerRect.height;
  16398. var left = parsePercent$1(positionInfo.left, containerWidth);
  16399. var top = parsePercent$1(positionInfo.top, containerHeight);
  16400. var right = parsePercent$1(positionInfo.right, containerWidth);
  16401. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16402. var width = parsePercent$1(positionInfo.width, containerWidth);
  16403. var height = parsePercent$1(positionInfo.height, containerHeight);
  16404. var verticalMargin = margin[2] + margin[0];
  16405. var horizontalMargin = margin[1] + margin[3];
  16406. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16407. if (isNaN(width)) {
  16408. width = containerWidth - right - horizontalMargin - left;
  16409. }
  16410. if (isNaN(height)) {
  16411. height = containerHeight - bottom - verticalMargin - top;
  16412. }
  16413. if (aspect != null) {
  16414. // If width and height are not given
  16415. // 1. Graph should not exceeds the container
  16416. // 2. Aspect must be keeped
  16417. // 3. Graph should take the space as more as possible
  16418. // FIXME
  16419. // Margin is not considered, because there is no case that both
  16420. // using margin and aspect so far.
  16421. if (isNaN(width) && isNaN(height)) {
  16422. if (aspect > containerWidth / containerHeight) {
  16423. width = containerWidth * 0.8;
  16424. } else {
  16425. height = containerHeight * 0.8;
  16426. }
  16427. } // Calculate width or height with given aspect
  16428. if (isNaN(width)) {
  16429. width = aspect * height;
  16430. }
  16431. if (isNaN(height)) {
  16432. height = width / aspect;
  16433. }
  16434. } // If left is not specified, calculate left from right and width
  16435. if (isNaN(left)) {
  16436. left = containerWidth - right - width - horizontalMargin;
  16437. }
  16438. if (isNaN(top)) {
  16439. top = containerHeight - bottom - height - verticalMargin;
  16440. } // Align left and top
  16441. switch (positionInfo.left || positionInfo.right) {
  16442. case 'center':
  16443. left = containerWidth / 2 - width / 2 - margin[3];
  16444. break;
  16445. case 'right':
  16446. left = containerWidth - width - horizontalMargin;
  16447. break;
  16448. }
  16449. switch (positionInfo.top || positionInfo.bottom) {
  16450. case 'middle':
  16451. case 'center':
  16452. top = containerHeight / 2 - height / 2 - margin[0];
  16453. break;
  16454. case 'bottom':
  16455. top = containerHeight - height - verticalMargin;
  16456. break;
  16457. } // If something is wrong and left, top, width, height are calculated as NaN
  16458. left = left || 0;
  16459. top = top || 0;
  16460. if (isNaN(width)) {
  16461. // Width may be NaN if only one value is given except width
  16462. width = containerWidth - horizontalMargin - left - (right || 0);
  16463. }
  16464. if (isNaN(height)) {
  16465. // Height may be NaN if only one value is given except height
  16466. height = containerHeight - verticalMargin - top - (bottom || 0);
  16467. }
  16468. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16469. rect.margin = margin;
  16470. return rect;
  16471. }
  16472. /**
  16473. * Position a zr element in viewport
  16474. * Group position is specified by either
  16475. * {left, top}, {right, bottom}
  16476. * If all properties exists, right and bottom will be igonred.
  16477. *
  16478. * Logic:
  16479. * 1. Scale (against origin point in parent coord)
  16480. * 2. Rotate (against origin point in parent coord)
  16481. * 3. Translate (with el.position by this method)
  16482. * So this method only fixes the last step 'Translate', which does not affect
  16483. * scaling and rotating.
  16484. *
  16485. * If be called repeatedly with the same input el, the same result will be gotten.
  16486. *
  16487. * Return true if the layout happened.
  16488. *
  16489. * @param el Should have `getBoundingRect` method.
  16490. * @param positionInfo
  16491. * @param positionInfo.left
  16492. * @param positionInfo.top
  16493. * @param positionInfo.right
  16494. * @param positionInfo.bottom
  16495. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16496. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16497. * @param containerRect
  16498. * @param margin
  16499. * @param opt
  16500. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16501. * @param opt.boundingMode
  16502. * Specify how to calculate boundingRect when locating.
  16503. * 'all': Position the boundingRect that is transformed and uioned
  16504. * both itself and its descendants.
  16505. * This mode simplies confine the elements in the bounding
  16506. * of their container (e.g., using 'right: 0').
  16507. * 'raw': Position the boundingRect that is not transformed and only itself.
  16508. * This mode is useful when you want a element can overflow its
  16509. * container. (Consider a rotated circle needs to be located in a corner.)
  16510. * In this mode positionInfo.width/height can only be number.
  16511. */
  16512. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16513. var h = !opt || !opt.hv || opt.hv[0];
  16514. var v = !opt || !opt.hv || opt.hv[1];
  16515. var boundingMode = opt && opt.boundingMode || 'all';
  16516. out = out || el;
  16517. out.x = el.x;
  16518. out.y = el.y;
  16519. if (!h && !v) {
  16520. return false;
  16521. }
  16522. var rect;
  16523. if (boundingMode === 'raw') {
  16524. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16525. } else {
  16526. rect = el.getBoundingRect();
  16527. if (el.needLocalTransform()) {
  16528. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16529. // which should not be modified.
  16530. rect = rect.clone();
  16531. rect.applyTransform(transform);
  16532. }
  16533. } // The real width and height can not be specified but calculated by the given el.
  16534. var layoutRect = getLayoutRect(defaults({
  16535. width: rect.width,
  16536. height: rect.height
  16537. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16538. // (see zrender/core/Transformable#getLocalTransform),
  16539. // we can just only modify el.position to get final result.
  16540. var dx = h ? layoutRect.x - rect.x : 0;
  16541. var dy = v ? layoutRect.y - rect.y : 0;
  16542. if (boundingMode === 'raw') {
  16543. out.x = dx;
  16544. out.y = dy;
  16545. } else {
  16546. out.x += dx;
  16547. out.y += dy;
  16548. }
  16549. if (out === el) {
  16550. el.markRedraw();
  16551. }
  16552. return true;
  16553. }
  16554. /**
  16555. * @param option Contains some of the properties in HV_NAMES.
  16556. * @param hvIdx 0: horizontal; 1: vertical.
  16557. */
  16558. function sizeCalculable(option, hvIdx) {
  16559. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  16560. }
  16561. function fetchLayoutMode(ins) {
  16562. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16563. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16564. type: layoutMode
  16565. } : null;
  16566. }
  16567. /**
  16568. * Consider Case:
  16569. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16570. * through setOption or media query, using normal zrUtil.merge will cause
  16571. * {right: 0} does not take effect.
  16572. *
  16573. * @example
  16574. * ComponentModel.extend({
  16575. * init: function () {
  16576. * ...
  16577. * let inputPositionParams = layout.getLayoutParams(option);
  16578. * this.mergeOption(inputPositionParams);
  16579. * },
  16580. * mergeOption: function (newOption) {
  16581. * newOption && zrUtil.merge(thisOption, newOption, true);
  16582. * layout.mergeLayoutParam(thisOption, newOption);
  16583. * }
  16584. * });
  16585. *
  16586. * @param targetOption
  16587. * @param newOption
  16588. * @param opt
  16589. */
  16590. function mergeLayoutParam(targetOption, newOption, opt) {
  16591. var ignoreSize = opt && opt.ignoreSize;
  16592. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16593. var hResult = merge(HV_NAMES[0], 0);
  16594. var vResult = merge(HV_NAMES[1], 1);
  16595. copy(HV_NAMES[0], targetOption, hResult);
  16596. copy(HV_NAMES[1], targetOption, vResult);
  16597. function merge(names, hvIdx) {
  16598. var newParams = {};
  16599. var newValueCount = 0;
  16600. var merged = {};
  16601. var mergedValueCount = 0;
  16602. var enoughParamNumber = 2;
  16603. each$1(names, function (name) {
  16604. merged[name] = targetOption[name];
  16605. });
  16606. each$1(names, function (name) {
  16607. // Consider case: newOption.width is null, which is
  16608. // set by user for removing width setting.
  16609. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16610. hasValue(newParams, name) && newValueCount++;
  16611. hasValue(merged, name) && mergedValueCount++;
  16612. });
  16613. if (ignoreSize[hvIdx]) {
  16614. // Only one of left/right is premitted to exist.
  16615. if (hasValue(newOption, names[1])) {
  16616. merged[names[2]] = null;
  16617. } else if (hasValue(newOption, names[2])) {
  16618. merged[names[1]] = null;
  16619. }
  16620. return merged;
  16621. } // Case: newOption: {width: ..., right: ...},
  16622. // or targetOption: {right: ...} and newOption: {width: ...},
  16623. // There is no conflict when merged only has params count
  16624. // little than enoughParamNumber.
  16625. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16626. return merged;
  16627. } // Case: newOption: {width: ..., right: ...},
  16628. // Than we can make sure user only want those two, and ignore
  16629. // all origin params in targetOption.
  16630. else if (newValueCount >= enoughParamNumber) {
  16631. return newParams;
  16632. } else {
  16633. // Chose another param from targetOption by priority.
  16634. for (var i = 0; i < names.length; i++) {
  16635. var name_1 = names[i];
  16636. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16637. newParams[name_1] = targetOption[name_1];
  16638. break;
  16639. }
  16640. }
  16641. return newParams;
  16642. }
  16643. }
  16644. function hasProp(obj, name) {
  16645. return obj.hasOwnProperty(name);
  16646. }
  16647. function hasValue(obj, name) {
  16648. return obj[name] != null && obj[name] !== 'auto';
  16649. }
  16650. function copy(names, target, source) {
  16651. each$1(names, function (name) {
  16652. target[name] = source[name];
  16653. });
  16654. }
  16655. }
  16656. /**
  16657. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16658. */
  16659. function getLayoutParams(source) {
  16660. return copyLayoutParams({}, source);
  16661. }
  16662. /**
  16663. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16664. * @param {Object} source
  16665. * @return {Object} Result contains those props.
  16666. */
  16667. function copyLayoutParams(target, source) {
  16668. source && target && each$1(LOCATION_PARAMS, function (name) {
  16669. source.hasOwnProperty(name) && (target[name] = source[name]);
  16670. });
  16671. return target;
  16672. }
  16673. var inner = makeInner();
  16674. var ComponentModel =
  16675. /** @class */
  16676. function (_super) {
  16677. __extends(ComponentModel, _super);
  16678. function ComponentModel(option, parentModel, ecModel) {
  16679. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16680. _this.uid = getUID('ec_cpt_model');
  16681. return _this;
  16682. }
  16683. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16684. this.mergeDefaultAndTheme(option, ecModel);
  16685. };
  16686. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16687. var layoutMode = fetchLayoutMode(this);
  16688. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16689. var themeModel = ecModel.getTheme();
  16690. merge(option, themeModel.get(this.mainType));
  16691. merge(option, this.getDefaultOption());
  16692. if (layoutMode) {
  16693. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16694. }
  16695. };
  16696. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16697. merge(this.option, option, true);
  16698. var layoutMode = fetchLayoutMode(this);
  16699. if (layoutMode) {
  16700. mergeLayoutParam(this.option, option, layoutMode);
  16701. }
  16702. };
  16703. /**
  16704. * Called immediately after `init` or `mergeOption` of this instance called.
  16705. */
  16706. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16707. /**
  16708. * [How to declare defaultOption]:
  16709. *
  16710. * (A) If using class declaration in typescript (since echarts 5):
  16711. * ```ts
  16712. * import {ComponentOption} from '../model/option.js';
  16713. * export interface XxxOption extends ComponentOption {
  16714. * aaa: number
  16715. * }
  16716. * export class XxxModel extends Component {
  16717. * static type = 'xxx';
  16718. * static defaultOption: XxxOption = {
  16719. * aaa: 123
  16720. * }
  16721. * }
  16722. * Component.registerClass(XxxModel);
  16723. * ```
  16724. * ```ts
  16725. * import {inheritDefaultOption} from '../util/component.js';
  16726. * import {XxxModel, XxxOption} from './XxxModel.js';
  16727. * export interface XxxSubOption extends XxxOption {
  16728. * bbb: number
  16729. * }
  16730. * class XxxSubModel extends XxxModel {
  16731. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16732. * bbb: 456
  16733. * })
  16734. * fn() {
  16735. * let opt = this.getDefaultOption();
  16736. * // opt is {aaa: 123, bbb: 456}
  16737. * }
  16738. * }
  16739. * ```
  16740. *
  16741. * (B) If using class extend (previous approach in echarts 3 & 4):
  16742. * ```js
  16743. * let XxxComponent = Component.extend({
  16744. * defaultOption: {
  16745. * xx: 123
  16746. * }
  16747. * })
  16748. * ```
  16749. * ```js
  16750. * let XxxSubComponent = XxxComponent.extend({
  16751. * defaultOption: {
  16752. * yy: 456
  16753. * },
  16754. * fn: function () {
  16755. * let opt = this.getDefaultOption();
  16756. * // opt is {xx: 123, yy: 456}
  16757. * }
  16758. * })
  16759. * ```
  16760. */
  16761. ComponentModel.prototype.getDefaultOption = function () {
  16762. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16763. // in legacy env and auto merge defaultOption. So if using class
  16764. // declaration, defaultOption should be merged manually.
  16765. if (!isExtendedClass(ctor)) {
  16766. // When using ts class, defaultOption must be declared as static.
  16767. return ctor.defaultOption;
  16768. } // FIXME: remove this approach?
  16769. var fields = inner(this);
  16770. if (!fields.defaultOption) {
  16771. var optList = [];
  16772. var clz = ctor;
  16773. while (clz) {
  16774. var opt = clz.prototype.defaultOption;
  16775. opt && optList.push(opt);
  16776. clz = clz.superClass;
  16777. }
  16778. var defaultOption = {};
  16779. for (var i = optList.length - 1; i >= 0; i--) {
  16780. defaultOption = merge(defaultOption, optList[i], true);
  16781. }
  16782. fields.defaultOption = defaultOption;
  16783. }
  16784. return fields.defaultOption;
  16785. };
  16786. /**
  16787. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16788. * The same behavior as `modelUtil.parseFinder`.
  16789. *
  16790. * @param useDefault In many cases like series refer axis and axis refer grid,
  16791. * If axis index / axis id not specified, use the first target as default.
  16792. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16793. */
  16794. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16795. var indexKey = mainType + 'Index';
  16796. var idKey = mainType + 'Id';
  16797. return queryReferringComponents(this.ecModel, mainType, {
  16798. index: this.get(indexKey, true),
  16799. id: this.get(idKey, true)
  16800. }, opt);
  16801. };
  16802. ComponentModel.prototype.getBoxLayoutParams = function () {
  16803. // Consider itself having box layout configs.
  16804. var boxLayoutModel = this;
  16805. return {
  16806. left: boxLayoutModel.get('left'),
  16807. top: boxLayoutModel.get('top'),
  16808. right: boxLayoutModel.get('right'),
  16809. bottom: boxLayoutModel.get('bottom'),
  16810. width: boxLayoutModel.get('width'),
  16811. height: boxLayoutModel.get('height')
  16812. };
  16813. };
  16814. /**
  16815. * Get key for zlevel.
  16816. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16817. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16818. */
  16819. ComponentModel.prototype.getZLevelKey = function () {
  16820. return '';
  16821. };
  16822. ComponentModel.prototype.setZLevel = function (zlevel) {
  16823. this.option.zlevel = zlevel;
  16824. };
  16825. ComponentModel.protoInitialize = function () {
  16826. var proto = ComponentModel.prototype;
  16827. proto.type = 'component';
  16828. proto.id = '';
  16829. proto.name = '';
  16830. proto.mainType = '';
  16831. proto.subType = '';
  16832. proto.componentIndex = 0;
  16833. }();
  16834. return ComponentModel;
  16835. }(Model);
  16836. mountExtend(ComponentModel, Model);
  16837. enableClassManagement(ComponentModel);
  16838. enableSubTypeDefaulter(ComponentModel);
  16839. enableTopologicalTravel(ComponentModel, getDependencies);
  16840. function getDependencies(componentType) {
  16841. var deps = [];
  16842. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16843. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16844. }); // Ensure main type.
  16845. deps = map(deps, function (type) {
  16846. return parseClassType(type).main;
  16847. }); // Hack dataset for convenience.
  16848. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16849. deps.unshift('dataset');
  16850. }
  16851. return deps;
  16852. }
  16853. /*
  16854. * Licensed to the Apache Software Foundation (ASF) under one
  16855. * or more contributor license agreements. See the NOTICE file
  16856. * distributed with this work for additional information
  16857. * regarding copyright ownership. The ASF licenses this file
  16858. * to you under the Apache License, Version 2.0 (the
  16859. * "License"); you may not use this file except in compliance
  16860. * with the License. You may obtain a copy of the License at
  16861. *
  16862. * http://www.apache.org/licenses/LICENSE-2.0
  16863. *
  16864. * Unless required by applicable law or agreed to in writing,
  16865. * software distributed under the License is distributed on an
  16866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16867. * KIND, either express or implied. See the License for the
  16868. * specific language governing permissions and limitations
  16869. * under the License.
  16870. */
  16871. /**
  16872. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16873. */
  16874. /*
  16875. * Licensed to the Apache Software Foundation (ASF) under one
  16876. * or more contributor license agreements. See the NOTICE file
  16877. * distributed with this work for additional information
  16878. * regarding copyright ownership. The ASF licenses this file
  16879. * to you under the Apache License, Version 2.0 (the
  16880. * "License"); you may not use this file except in compliance
  16881. * with the License. You may obtain a copy of the License at
  16882. *
  16883. * http://www.apache.org/licenses/LICENSE-2.0
  16884. *
  16885. * Unless required by applicable law or agreed to in writing,
  16886. * software distributed under the License is distributed on an
  16887. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16888. * KIND, either express or implied. See the License for the
  16889. * specific language governing permissions and limitations
  16890. * under the License.
  16891. */
  16892. var platform = ''; // Navigator not exists in node
  16893. if (typeof navigator !== 'undefined') {
  16894. /* global navigator */
  16895. platform = navigator.platform || '';
  16896. }
  16897. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16898. var globalDefault = {
  16899. darkMode: 'auto',
  16900. // backgroundColor: 'rgba(0,0,0,0)',
  16901. colorBy: 'series',
  16902. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16903. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16904. aria: {
  16905. decal: {
  16906. decals: [{
  16907. color: decalColor,
  16908. dashArrayX: [1, 0],
  16909. dashArrayY: [2, 5],
  16910. symbolSize: 1,
  16911. rotation: Math.PI / 6
  16912. }, {
  16913. color: decalColor,
  16914. symbol: 'circle',
  16915. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16916. dashArrayY: [6, 0],
  16917. symbolSize: 0.8
  16918. }, {
  16919. color: decalColor,
  16920. dashArrayX: [1, 0],
  16921. dashArrayY: [4, 3],
  16922. rotation: -Math.PI / 4
  16923. }, {
  16924. color: decalColor,
  16925. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16926. dashArrayY: [6, 0]
  16927. }, {
  16928. color: decalColor,
  16929. dashArrayX: [[1, 0], [1, 6]],
  16930. dashArrayY: [1, 0, 6, 0],
  16931. rotation: Math.PI / 4
  16932. }, {
  16933. color: decalColor,
  16934. symbol: 'triangle',
  16935. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16936. dashArrayY: [7, 2],
  16937. symbolSize: 0.75
  16938. }]
  16939. }
  16940. },
  16941. // If xAxis and yAxis declared, grid is created by default.
  16942. // grid: {},
  16943. textStyle: {
  16944. // color: '#000',
  16945. // decoration: 'none',
  16946. // PENDING
  16947. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16948. // fontFamily: 'Arial, Verdana, sans-serif',
  16949. fontSize: 12,
  16950. fontStyle: 'normal',
  16951. fontWeight: 'normal'
  16952. },
  16953. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16954. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16955. // Default is source-over
  16956. blendMode: null,
  16957. stateAnimation: {
  16958. duration: 300,
  16959. easing: 'cubicOut'
  16960. },
  16961. animation: 'auto',
  16962. animationDuration: 1000,
  16963. animationDurationUpdate: 500,
  16964. animationEasing: 'cubicInOut',
  16965. animationEasingUpdate: 'cubicInOut',
  16966. animationThreshold: 2000,
  16967. // Configuration for progressive/incremental rendering
  16968. progressiveThreshold: 3000,
  16969. progressive: 400,
  16970. // Threshold of if use single hover layer to optimize.
  16971. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16972. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16973. // which is unexpected.
  16974. // see example <echarts/test/heatmap-large.html>.
  16975. hoverLayerThreshold: 3000,
  16976. // See: module:echarts/scale/Time
  16977. useUTC: false
  16978. };
  16979. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16980. var SOURCE_FORMAT_ORIGINAL = 'original';
  16981. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16982. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16983. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16984. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16985. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16986. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16987. var SERIES_LAYOUT_BY_ROW = 'row';
  16988. var BE_ORDINAL = {
  16989. Must: 1,
  16990. Might: 2,
  16991. Not: 3 // Other cases
  16992. };
  16993. var innerGlobalModel = makeInner();
  16994. /**
  16995. * MUST be called before mergeOption of all series.
  16996. */
  16997. function resetSourceDefaulter(ecModel) {
  16998. // `datasetMap` is used to make default encode.
  16999. innerGlobalModel(ecModel).datasetMap = createHashMap();
  17000. }
  17001. /**
  17002. * [The strategy of the arrengment of data dimensions for dataset]:
  17003. * "value way": all axes are non-category axes. So series one by one take
  17004. * several (the number is coordSysDims.length) dimensions from dataset.
  17005. * The result of data arrengment of data dimensions like:
  17006. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17007. * "category way": at least one axis is category axis. So the the first data
  17008. * dimension is always mapped to the first category axis and shared by
  17009. * all of the series. The other data dimensions are taken by series like
  17010. * "value way" does.
  17011. * The result of data arrengment of data dimensions like:
  17012. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17013. *
  17014. * @return encode Never be `null/undefined`.
  17015. */
  17016. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17017. var encode = {};
  17018. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17019. if (!datasetModel || !coordDimensions) {
  17020. return encode;
  17021. }
  17022. var encodeItemName = [];
  17023. var encodeSeriesName = [];
  17024. var ecModel = seriesModel.ecModel;
  17025. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  17026. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17027. var baseCategoryDimIndex;
  17028. var categoryWayValueDimStart;
  17029. coordDimensions = coordDimensions.slice();
  17030. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  17031. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  17032. name: coordDimInfoLoose
  17033. };
  17034. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17035. baseCategoryDimIndex = coordDimIdx;
  17036. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  17037. }
  17038. encode[coordDimInfo.name] = [];
  17039. });
  17040. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17041. categoryWayDim: categoryWayValueDimStart,
  17042. valueWayDim: 0
  17043. }); // TODO
  17044. // Auto detect first time axis and do arrangement.
  17045. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17046. var coordDimName = coordDimInfo.name;
  17047. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  17048. if (baseCategoryDimIndex == null) {
  17049. var start = datasetRecord.valueWayDim;
  17050. pushDim(encode[coordDimName], start, count);
  17051. pushDim(encodeSeriesName, start, count);
  17052. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  17053. // especially when encode x y specified.
  17054. // consider: when multiple series share one dimension
  17055. // category axis, series name should better use
  17056. // the other dimension name. On the other hand, use
  17057. // both dimensions name.
  17058. } // In category way, the first category axis.
  17059. else if (baseCategoryDimIndex === coordDimIdx) {
  17060. pushDim(encode[coordDimName], 0, count);
  17061. pushDim(encodeItemName, 0, count);
  17062. } // In category way, the other axis.
  17063. else {
  17064. var start = datasetRecord.categoryWayDim;
  17065. pushDim(encode[coordDimName], start, count);
  17066. pushDim(encodeSeriesName, start, count);
  17067. datasetRecord.categoryWayDim += count;
  17068. }
  17069. });
  17070. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17071. for (var i = 0; i < idxCount; i++) {
  17072. dimIdxArr.push(idxFrom + i);
  17073. }
  17074. }
  17075. function getDataDimCountOnCoordDim(coordDimInfo) {
  17076. var dimsDef = coordDimInfo.dimsDef;
  17077. return dimsDef ? dimsDef.length : 1;
  17078. }
  17079. encodeItemName.length && (encode.itemName = encodeItemName);
  17080. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17081. return encode;
  17082. }
  17083. /**
  17084. * Work for data like [{name: ..., value: ...}, ...].
  17085. *
  17086. * @return encode Never be `null/undefined`.
  17087. */
  17088. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17089. var encode = {};
  17090. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17091. if (!datasetModel) {
  17092. return encode;
  17093. }
  17094. var sourceFormat = source.sourceFormat;
  17095. var dimensionsDefine = source.dimensionsDefine;
  17096. var potentialNameDimIndex;
  17097. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17098. each(dimensionsDefine, function (dim, idx) {
  17099. if ((isObject(dim) ? dim.name : dim) === 'name') {
  17100. potentialNameDimIndex = idx;
  17101. }
  17102. });
  17103. }
  17104. var idxResult = function () {
  17105. var idxRes0 = {};
  17106. var idxRes1 = {};
  17107. var guessRecords = []; // 5 is an experience value.
  17108. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17109. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17110. guessRecords.push(guessResult);
  17111. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17112. // and then find a name dim with the priority:
  17113. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17114. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17115. idxRes0.v = i;
  17116. }
  17117. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17118. idxRes0.n = i;
  17119. }
  17120. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17121. return idxRes0;
  17122. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17123. // find the first BE_ORDINAL.Might as the value dim,
  17124. // and then find a name dim with the priority:
  17125. // "other dim" > "the value dim itself".
  17126. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17127. // treated as number.
  17128. if (!isPureNumber) {
  17129. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17130. idxRes1.v = i;
  17131. }
  17132. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17133. idxRes1.n = i;
  17134. }
  17135. }
  17136. }
  17137. function fulfilled(idxResult) {
  17138. return idxResult.v != null && idxResult.n != null;
  17139. }
  17140. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17141. }();
  17142. if (idxResult) {
  17143. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  17144. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label uses itemName in charts.
  17145. // So we don't set encodeLabel here.
  17146. encode.itemName = [nameDimIndex];
  17147. encode.seriesName = [nameDimIndex];
  17148. }
  17149. return encode;
  17150. }
  17151. /**
  17152. * @return If return null/undefined, indicate that should not use datasetModel.
  17153. */
  17154. function querySeriesUpstreamDatasetModel(seriesModel) {
  17155. // Caution: consider the scenario:
  17156. // A dataset is declared and a series is not expected to use the dataset,
  17157. // and at the beginning `setOption({series: { noData })` (just prepare other
  17158. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17159. // the user should set an empty array to avoid that dataset is used by default.
  17160. var thisData = seriesModel.get('data', true);
  17161. if (!thisData) {
  17162. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  17163. index: seriesModel.get('datasetIndex', true),
  17164. id: seriesModel.get('datasetId', true)
  17165. }, SINGLE_REFERRING).models[0];
  17166. }
  17167. }
  17168. /**
  17169. * @return Always return an array event empty.
  17170. */
  17171. function queryDatasetUpstreamDatasetModels(datasetModel) {
  17172. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  17173. // Otherwise, no reference.
  17174. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  17175. return [];
  17176. }
  17177. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  17178. index: datasetModel.get('fromDatasetIndex', true),
  17179. id: datasetModel.get('fromDatasetId', true)
  17180. }, SINGLE_REFERRING).models;
  17181. }
  17182. /**
  17183. * The rule should not be complex, otherwise user might not
  17184. * be able to known where the data is wrong.
  17185. * The code is ugly, but how to make it neat?
  17186. */
  17187. function guessOrdinal(source, dimIndex) {
  17188. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17189. } // dimIndex may be overflow source data.
  17190. // return {BE_ORDINAL}
  17191. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17192. var result; // Experience value.
  17193. var maxLoop = 5;
  17194. if (isTypedArray(data)) {
  17195. return BE_ORDINAL.Not;
  17196. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17197. // always exists in source.
  17198. var dimName;
  17199. var dimType;
  17200. if (dimensionsDefine) {
  17201. var dimDefItem = dimensionsDefine[dimIndex];
  17202. if (isObject(dimDefItem)) {
  17203. dimName = dimDefItem.name;
  17204. dimType = dimDefItem.type;
  17205. } else if (isString(dimDefItem)) {
  17206. dimName = dimDefItem;
  17207. }
  17208. }
  17209. if (dimType != null) {
  17210. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17211. }
  17212. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17213. var dataArrayRows = data;
  17214. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17215. var sample = dataArrayRows[dimIndex];
  17216. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17217. if ((result = detectValue(sample[startIndex + i])) != null) {
  17218. return result;
  17219. }
  17220. }
  17221. } else {
  17222. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  17223. var row = dataArrayRows[startIndex + i];
  17224. if (row && (result = detectValue(row[dimIndex])) != null) {
  17225. return result;
  17226. }
  17227. }
  17228. }
  17229. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17230. var dataObjectRows = data;
  17231. if (!dimName) {
  17232. return BE_ORDINAL.Not;
  17233. }
  17234. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  17235. var item = dataObjectRows[i];
  17236. if (item && (result = detectValue(item[dimName])) != null) {
  17237. return result;
  17238. }
  17239. }
  17240. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17241. var dataKeyedColumns = data;
  17242. if (!dimName) {
  17243. return BE_ORDINAL.Not;
  17244. }
  17245. var sample = dataKeyedColumns[dimName];
  17246. if (!sample || isTypedArray(sample)) {
  17247. return BE_ORDINAL.Not;
  17248. }
  17249. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17250. if ((result = detectValue(sample[i])) != null) {
  17251. return result;
  17252. }
  17253. }
  17254. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17255. var dataOriginal = data;
  17256. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17257. var item = dataOriginal[i];
  17258. var val = getDataItemValue(item);
  17259. if (!isArray(val)) {
  17260. return BE_ORDINAL.Not;
  17261. }
  17262. if ((result = detectValue(val[dimIndex])) != null) {
  17263. return result;
  17264. }
  17265. }
  17266. }
  17267. function detectValue(val) {
  17268. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17269. // `isFinit('')` get `true`.
  17270. if (val != null && isFinite(val) && val !== '') {
  17271. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17272. } else if (beStr && val !== '-') {
  17273. return BE_ORDINAL.Must;
  17274. }
  17275. }
  17276. return BE_ORDINAL.Not;
  17277. }
  17278. var internalOptionCreatorMap = createHashMap();
  17279. function registerInternalOptionCreator(mainType, creator) {
  17280. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17281. internalOptionCreatorMap.set(mainType, creator);
  17282. }
  17283. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17284. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17285. if (!internalOptionCreator) {
  17286. return newCmptOptionList;
  17287. }
  17288. var internalOptions = internalOptionCreator(ecModel);
  17289. if (!internalOptions) {
  17290. return newCmptOptionList;
  17291. }
  17292. if ("development" !== 'production') {
  17293. for (var i = 0; i < internalOptions.length; i++) {
  17294. assert(isComponentIdInternal(internalOptions[i]));
  17295. }
  17296. }
  17297. return newCmptOptionList.concat(internalOptions);
  17298. }
  17299. var innerColor = makeInner();
  17300. var innerDecal = makeInner();
  17301. var PaletteMixin =
  17302. /** @class */
  17303. function () {
  17304. function PaletteMixin() {}
  17305. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17306. var defaultPalette = normalizeToArray(this.get('color', true));
  17307. var layeredPalette = this.get('colorLayer', true);
  17308. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17309. };
  17310. PaletteMixin.prototype.clearColorPalette = function () {
  17311. clearPalette(this, innerColor);
  17312. };
  17313. return PaletteMixin;
  17314. }();
  17315. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17316. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17317. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17318. }
  17319. function getNearestPalette(palettes, requestColorNum) {
  17320. var paletteNum = palettes.length; // TODO palettes must be in order
  17321. for (var i = 0; i < paletteNum; i++) {
  17322. if (palettes[i].length > requestColorNum) {
  17323. return palettes[i];
  17324. }
  17325. }
  17326. return palettes[paletteNum - 1];
  17327. }
  17328. /**
  17329. * @param name MUST NOT be null/undefined. Otherwise call this function
  17330. * twise with the same parameters will get different result.
  17331. * @param scope default this.
  17332. * @return Can be null/undefined
  17333. */
  17334. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17335. scope = scope || that;
  17336. var scopeFields = inner(scope);
  17337. var paletteIdx = scopeFields.paletteIdx || 0;
  17338. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17339. if (paletteNameMap.hasOwnProperty(name)) {
  17340. return paletteNameMap[name];
  17341. }
  17342. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  17343. palette = palette || defaultPalette;
  17344. if (!palette || !palette.length) {
  17345. return;
  17346. }
  17347. var pickedPaletteItem = palette[paletteIdx];
  17348. if (name) {
  17349. paletteNameMap[name] = pickedPaletteItem;
  17350. }
  17351. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17352. return pickedPaletteItem;
  17353. }
  17354. function clearPalette(that, inner) {
  17355. inner(that).paletteIdx = 0;
  17356. inner(that).paletteNameMap = {};
  17357. }
  17358. // Internal method names:
  17359. // -----------------------
  17360. var reCreateSeriesIndices;
  17361. var assertSeriesInitialized;
  17362. var initBase;
  17363. var OPTION_INNER_KEY = '\0_ec_inner';
  17364. var OPTION_INNER_VALUE = 1;
  17365. var BUITIN_COMPONENTS_MAP = {
  17366. grid: 'GridComponent',
  17367. polar: 'PolarComponent',
  17368. geo: 'GeoComponent',
  17369. singleAxis: 'SingleAxisComponent',
  17370. parallel: 'ParallelComponent',
  17371. calendar: 'CalendarComponent',
  17372. graphic: 'GraphicComponent',
  17373. toolbox: 'ToolboxComponent',
  17374. tooltip: 'TooltipComponent',
  17375. axisPointer: 'AxisPointerComponent',
  17376. brush: 'BrushComponent',
  17377. title: 'TitleComponent',
  17378. timeline: 'TimelineComponent',
  17379. markPoint: 'MarkPointComponent',
  17380. markLine: 'MarkLineComponent',
  17381. markArea: 'MarkAreaComponent',
  17382. legend: 'LegendComponent',
  17383. dataZoom: 'DataZoomComponent',
  17384. visualMap: 'VisualMapComponent',
  17385. // aria: 'AriaComponent',
  17386. // dataset: 'DatasetComponent',
  17387. // Dependencies
  17388. xAxis: 'GridComponent',
  17389. yAxis: 'GridComponent',
  17390. angleAxis: 'PolarComponent',
  17391. radiusAxis: 'PolarComponent'
  17392. };
  17393. var BUILTIN_CHARTS_MAP = {
  17394. line: 'LineChart',
  17395. bar: 'BarChart',
  17396. pie: 'PieChart',
  17397. scatter: 'ScatterChart',
  17398. radar: 'RadarChart',
  17399. map: 'MapChart',
  17400. tree: 'TreeChart',
  17401. treemap: 'TreemapChart',
  17402. graph: 'GraphChart',
  17403. gauge: 'GaugeChart',
  17404. funnel: 'FunnelChart',
  17405. parallel: 'ParallelChart',
  17406. sankey: 'SankeyChart',
  17407. boxplot: 'BoxplotChart',
  17408. candlestick: 'CandlestickChart',
  17409. effectScatter: 'EffectScatterChart',
  17410. lines: 'LinesChart',
  17411. heatmap: 'HeatmapChart',
  17412. pictorialBar: 'PictorialBarChart',
  17413. themeRiver: 'ThemeRiverChart',
  17414. sunburst: 'SunburstChart',
  17415. custom: 'CustomChart'
  17416. };
  17417. var componetsMissingLogPrinted = {};
  17418. function checkMissingComponents(option) {
  17419. each(option, function (componentOption, mainType) {
  17420. if (!ComponentModel.hasClass(mainType)) {
  17421. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17422. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17423. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17424. componetsMissingLogPrinted[componentImportName] = true;
  17425. }
  17426. }
  17427. });
  17428. }
  17429. var GlobalModel =
  17430. /** @class */
  17431. function (_super) {
  17432. __extends(GlobalModel, _super);
  17433. function GlobalModel() {
  17434. return _super !== null && _super.apply(this, arguments) || this;
  17435. }
  17436. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17437. theme = theme || {};
  17438. this.option = null; // Mark as not initialized.
  17439. this._theme = new Model(theme);
  17440. this._locale = new Model(locale);
  17441. this._optionManager = optionManager;
  17442. };
  17443. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17444. if ("development" !== 'production') {
  17445. assert(option != null, 'option is null/undefined');
  17446. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17447. }
  17448. var innerOpt = normalizeSetOptionInput(opts);
  17449. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17450. this._resetOption(null, innerOpt);
  17451. };
  17452. /**
  17453. * @param type null/undefined: reset all.
  17454. * 'recreate': force recreate all.
  17455. * 'timeline': only reset timeline option
  17456. * 'media': only reset media query option
  17457. * @return Whether option changed.
  17458. */
  17459. GlobalModel.prototype.resetOption = function (type, opt) {
  17460. return this._resetOption(type, normalizeSetOptionInput(opt));
  17461. };
  17462. GlobalModel.prototype._resetOption = function (type, opt) {
  17463. var optionChanged = false;
  17464. var optionManager = this._optionManager;
  17465. if (!type || type === 'recreate') {
  17466. var baseOption = optionManager.mountOption(type === 'recreate');
  17467. if ("development" !== 'production') {
  17468. checkMissingComponents(baseOption);
  17469. }
  17470. if (!this.option || type === 'recreate') {
  17471. initBase(this, baseOption);
  17472. } else {
  17473. this.restoreData();
  17474. this._mergeOption(baseOption, opt);
  17475. }
  17476. optionChanged = true;
  17477. }
  17478. if (type === 'timeline' || type === 'media') {
  17479. this.restoreData();
  17480. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17481. // it should better not have the same props with `MediaUnit['option']`.
  17482. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17483. // rather than original "baseOption". If they both override a prop, the result might be
  17484. // unexpected when media state changed after `setOption` called.
  17485. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17486. // (`{baseOption, media}`) in `setOption`.
  17487. // For `timeline`, the case is the same.
  17488. if (!type || type === 'recreate' || type === 'timeline') {
  17489. var timelineOption = optionManager.getTimelineOption(this);
  17490. if (timelineOption) {
  17491. optionChanged = true;
  17492. this._mergeOption(timelineOption, opt);
  17493. }
  17494. }
  17495. if (!type || type === 'recreate' || type === 'media') {
  17496. var mediaOptions = optionManager.getMediaOption(this);
  17497. if (mediaOptions.length) {
  17498. each(mediaOptions, function (mediaOption) {
  17499. optionChanged = true;
  17500. this._mergeOption(mediaOption, opt);
  17501. }, this);
  17502. }
  17503. }
  17504. return optionChanged;
  17505. };
  17506. GlobalModel.prototype.mergeOption = function (option) {
  17507. this._mergeOption(option, null);
  17508. };
  17509. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17510. var option = this.option;
  17511. var componentsMap = this._componentsMap;
  17512. var componentsCount = this._componentsCount;
  17513. var newCmptTypes = [];
  17514. var newCmptTypeMap = createHashMap();
  17515. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17516. resetSourceDefaulter(this); // If no component class, merge directly.
  17517. // For example: color, animaiton options, etc.
  17518. each(newOption, function (componentOption, mainType) {
  17519. if (componentOption == null) {
  17520. return;
  17521. }
  17522. if (!ComponentModel.hasClass(mainType)) {
  17523. // globalSettingTask.dirty();
  17524. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17525. } else if (mainType) {
  17526. newCmptTypes.push(mainType);
  17527. newCmptTypeMap.set(mainType, true);
  17528. }
  17529. });
  17530. if (replaceMergeMainTypeMap) {
  17531. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17532. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17533. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17534. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17535. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17536. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17537. newCmptTypes.push(mainTypeInReplaceMerge);
  17538. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17539. }
  17540. });
  17541. }
  17542. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17543. function visitComponent(mainType) {
  17544. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17545. var oldCmptList = componentsMap.get(mainType);
  17546. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  17547. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17548. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  17549. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  17550. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17551. // components, which is probably incorrect logic.
  17552. option[mainType] = null;
  17553. componentsMap.set(mainType, null);
  17554. componentsCount.set(mainType, 0);
  17555. var optionsByMainType = [];
  17556. var cmptsByMainType = [];
  17557. var cmptsCountByMainType = 0;
  17558. var tooltipExists;
  17559. var tooltipWarningLogged;
  17560. each(mappingResult, function (resultItem, index) {
  17561. var componentModel = resultItem.existing;
  17562. var newCmptOption = resultItem.newOption;
  17563. if (!newCmptOption) {
  17564. if (componentModel) {
  17565. // Consider where is no new option and should be merged using {},
  17566. // see removeEdgeAndAdd in topologicalTravel and
  17567. // ComponentModel.getAllClassMainTypes.
  17568. componentModel.mergeOption({}, this);
  17569. componentModel.optionUpdated({}, false);
  17570. } // If no both `resultItem.exist` and `resultItem.option`,
  17571. // either it is in `replaceMerge` and not matched by any id,
  17572. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17573. } else {
  17574. var isSeriesType = mainType === 'series';
  17575. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17576. );
  17577. if (!ComponentModelClass) {
  17578. if ("development" !== 'production') {
  17579. var subType = resultItem.keyInfo.subType;
  17580. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17581. if (!componetsMissingLogPrinted[subType]) {
  17582. componetsMissingLogPrinted[subType] = true;
  17583. if (seriesImportName) {
  17584. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17585. } else {
  17586. error("Unknown series " + subType);
  17587. }
  17588. }
  17589. }
  17590. return;
  17591. } // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17592. if (mainType === 'tooltip') {
  17593. if (tooltipExists) {
  17594. if ("development" !== 'production') {
  17595. if (!tooltipWarningLogged) {
  17596. warn('Currently only one tooltip component is allowed.');
  17597. tooltipWarningLogged = true;
  17598. }
  17599. }
  17600. return;
  17601. }
  17602. tooltipExists = true;
  17603. }
  17604. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17605. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17606. componentModel.mergeOption(newCmptOption, this);
  17607. componentModel.optionUpdated(newCmptOption, false);
  17608. } else {
  17609. // PENDING Global as parent ?
  17610. var extraOpt = extend({
  17611. componentIndex: index
  17612. }, resultItem.keyInfo);
  17613. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  17614. extend(componentModel, extraOpt);
  17615. if (resultItem.brandNew) {
  17616. componentModel.__requireNewView = true;
  17617. }
  17618. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  17619. // newCmptOption has been used as componentModel.option
  17620. // and may be merged with theme and default, so pass null
  17621. // to avoid confusion.
  17622. componentModel.optionUpdated(null, true);
  17623. }
  17624. }
  17625. if (componentModel) {
  17626. optionsByMainType.push(componentModel.option);
  17627. cmptsByMainType.push(componentModel);
  17628. cmptsCountByMainType++;
  17629. } else {
  17630. // Always do assign to avoid elided item in array.
  17631. optionsByMainType.push(void 0);
  17632. cmptsByMainType.push(void 0);
  17633. }
  17634. }, this);
  17635. option[mainType] = optionsByMainType;
  17636. componentsMap.set(mainType, cmptsByMainType);
  17637. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  17638. if (mainType === 'series') {
  17639. reCreateSeriesIndices(this);
  17640. }
  17641. } // If no series declared, ensure `_seriesIndices` initialized.
  17642. if (!this._seriesIndices) {
  17643. reCreateSeriesIndices(this);
  17644. }
  17645. };
  17646. /**
  17647. * Get option for output (cloned option and inner info removed)
  17648. */
  17649. GlobalModel.prototype.getOption = function () {
  17650. var option = clone(this.option);
  17651. each(option, function (optInMainType, mainType) {
  17652. if (ComponentModel.hasClass(mainType)) {
  17653. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  17654. // Inner cmpts might not be at last since ec5.0, but still
  17655. // compatible for users: if inner cmpt at last, splice the returned array.
  17656. var realLen = opts.length;
  17657. var metNonInner = false;
  17658. for (var i = realLen - 1; i >= 0; i--) {
  17659. // Remove options with inner id.
  17660. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17661. metNonInner = true;
  17662. } else {
  17663. opts[i] = null;
  17664. !metNonInner && realLen--;
  17665. }
  17666. }
  17667. opts.length = realLen;
  17668. option[mainType] = opts;
  17669. }
  17670. });
  17671. delete option[OPTION_INNER_KEY];
  17672. return option;
  17673. };
  17674. GlobalModel.prototype.getTheme = function () {
  17675. return this._theme;
  17676. };
  17677. GlobalModel.prototype.getLocaleModel = function () {
  17678. return this._locale;
  17679. };
  17680. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17681. this._payload = payload;
  17682. };
  17683. GlobalModel.prototype.getUpdatePayload = function () {
  17684. return this._payload;
  17685. };
  17686. /**
  17687. * @param idx If not specified, return the first one.
  17688. */
  17689. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17690. var list = this._componentsMap.get(mainType);
  17691. if (list) {
  17692. var cmpt = list[idx || 0];
  17693. if (cmpt) {
  17694. return cmpt;
  17695. } else if (idx == null) {
  17696. for (var i = 0; i < list.length; i++) {
  17697. if (list[i]) {
  17698. return list[i];
  17699. }
  17700. }
  17701. }
  17702. }
  17703. };
  17704. /**
  17705. * @return Never be null/undefined.
  17706. */
  17707. GlobalModel.prototype.queryComponents = function (condition) {
  17708. var mainType = condition.mainType;
  17709. if (!mainType) {
  17710. return [];
  17711. }
  17712. var index = condition.index;
  17713. var id = condition.id;
  17714. var name = condition.name;
  17715. var cmpts = this._componentsMap.get(mainType);
  17716. if (!cmpts || !cmpts.length) {
  17717. return [];
  17718. }
  17719. var result;
  17720. if (index != null) {
  17721. result = [];
  17722. each(normalizeToArray(index), function (idx) {
  17723. cmpts[idx] && result.push(cmpts[idx]);
  17724. });
  17725. } else if (id != null) {
  17726. result = queryByIdOrName('id', id, cmpts);
  17727. } else if (name != null) {
  17728. result = queryByIdOrName('name', name, cmpts);
  17729. } else {
  17730. // Return all non-empty components in that mainType
  17731. result = filter(cmpts, function (cmpt) {
  17732. return !!cmpt;
  17733. });
  17734. }
  17735. return filterBySubType(result, condition);
  17736. };
  17737. /**
  17738. * The interface is different from queryComponents,
  17739. * which is convenient for inner usage.
  17740. *
  17741. * @usage
  17742. * let result = findComponents(
  17743. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17744. * );
  17745. * let result = findComponents(
  17746. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17747. * );
  17748. * let result = findComponents(
  17749. * {mainType: 'series',
  17750. * filter: function (model, index) {...}}
  17751. * );
  17752. * // result like [component0, componnet1, ...]
  17753. */
  17754. GlobalModel.prototype.findComponents = function (condition) {
  17755. var query = condition.query;
  17756. var mainType = condition.mainType;
  17757. var queryCond = getQueryCond(query);
  17758. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17759. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17760. return !!cmpt;
  17761. });
  17762. return doFilter(filterBySubType(result, condition));
  17763. function getQueryCond(q) {
  17764. var indexAttr = mainType + 'Index';
  17765. var idAttr = mainType + 'Id';
  17766. var nameAttr = mainType + 'Name';
  17767. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17768. mainType: mainType,
  17769. // subType will be filtered finally.
  17770. index: q[indexAttr],
  17771. id: q[idAttr],
  17772. name: q[nameAttr]
  17773. } : null;
  17774. }
  17775. function doFilter(res) {
  17776. return condition.filter ? filter(res, condition.filter) : res;
  17777. }
  17778. };
  17779. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17780. var componentsMap = this._componentsMap;
  17781. if (isFunction(mainType)) {
  17782. var ctxForAll_1 = cb;
  17783. var cbForAll_1 = mainType;
  17784. componentsMap.each(function (cmpts, componentType) {
  17785. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17786. var cmpt = cmpts[i];
  17787. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17788. }
  17789. });
  17790. } else {
  17791. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17792. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17793. var cmpt = cmpts[i];
  17794. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17795. }
  17796. }
  17797. };
  17798. /**
  17799. * Get series list before filtered by name.
  17800. */
  17801. GlobalModel.prototype.getSeriesByName = function (name) {
  17802. var nameStr = convertOptionIdName(name, null);
  17803. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17804. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17805. });
  17806. };
  17807. /**
  17808. * Get series list before filtered by index.
  17809. */
  17810. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17811. return this._componentsMap.get('series')[seriesIndex];
  17812. };
  17813. /**
  17814. * Get series list before filtered by type.
  17815. * FIXME: rename to getRawSeriesByType?
  17816. */
  17817. GlobalModel.prototype.getSeriesByType = function (subType) {
  17818. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17819. return !!oneSeries && oneSeries.subType === subType;
  17820. });
  17821. };
  17822. /**
  17823. * Get all series before filtered.
  17824. */
  17825. GlobalModel.prototype.getSeries = function () {
  17826. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17827. return !!oneSeries;
  17828. });
  17829. };
  17830. /**
  17831. * Count series before filtered.
  17832. */
  17833. GlobalModel.prototype.getSeriesCount = function () {
  17834. return this._componentsCount.get('series');
  17835. };
  17836. /**
  17837. * After filtering, series may be different
  17838. * from raw series.
  17839. */
  17840. GlobalModel.prototype.eachSeries = function (cb, context) {
  17841. assertSeriesInitialized(this);
  17842. each(this._seriesIndices, function (rawSeriesIndex) {
  17843. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17844. cb.call(context, series, rawSeriesIndex);
  17845. }, this);
  17846. };
  17847. /**
  17848. * Iterate raw series before filtered.
  17849. *
  17850. * @param {Function} cb
  17851. * @param {*} context
  17852. */
  17853. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17854. each(this._componentsMap.get('series'), function (series) {
  17855. series && cb.call(context, series, series.componentIndex);
  17856. });
  17857. };
  17858. /**
  17859. * After filtering, series may be different.
  17860. * from raw series.
  17861. */
  17862. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17863. assertSeriesInitialized(this);
  17864. each(this._seriesIndices, function (rawSeriesIndex) {
  17865. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17866. if (series.subType === subType) {
  17867. cb.call(context, series, rawSeriesIndex);
  17868. }
  17869. }, this);
  17870. };
  17871. /**
  17872. * Iterate raw series before filtered of given type.
  17873. */
  17874. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17875. return each(this.getSeriesByType(subType), cb, context);
  17876. };
  17877. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17878. assertSeriesInitialized(this);
  17879. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17880. };
  17881. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17882. return (this._seriesIndices || []).slice();
  17883. };
  17884. GlobalModel.prototype.filterSeries = function (cb, context) {
  17885. assertSeriesInitialized(this);
  17886. var newSeriesIndices = [];
  17887. each(this._seriesIndices, function (seriesRawIdx) {
  17888. var series = this._componentsMap.get('series')[seriesRawIdx];
  17889. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17890. }, this);
  17891. this._seriesIndices = newSeriesIndices;
  17892. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17893. };
  17894. GlobalModel.prototype.restoreData = function (payload) {
  17895. reCreateSeriesIndices(this);
  17896. var componentsMap = this._componentsMap;
  17897. var componentTypes = [];
  17898. componentsMap.each(function (components, componentType) {
  17899. if (ComponentModel.hasClass(componentType)) {
  17900. componentTypes.push(componentType);
  17901. }
  17902. });
  17903. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17904. each(componentsMap.get(componentType), function (component) {
  17905. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17906. component.restoreData();
  17907. }
  17908. });
  17909. });
  17910. };
  17911. GlobalModel.internalField = function () {
  17912. reCreateSeriesIndices = function (ecModel) {
  17913. var seriesIndices = ecModel._seriesIndices = [];
  17914. each(ecModel._componentsMap.get('series'), function (series) {
  17915. // series may have been removed by `replaceMerge`.
  17916. series && seriesIndices.push(series.componentIndex);
  17917. });
  17918. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17919. };
  17920. assertSeriesInitialized = function (ecModel) {
  17921. // Components that use _seriesIndices should depends on series component,
  17922. // which make sure that their initialization is after series.
  17923. if ("development" !== 'production') {
  17924. if (!ecModel._seriesIndices) {
  17925. throw new Error('Option should contains series.');
  17926. }
  17927. }
  17928. };
  17929. initBase = function (ecModel, baseOption) {
  17930. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  17931. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  17932. ecModel.option = {};
  17933. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17934. // before series initialized.
  17935. ecModel._componentsMap = createHashMap({
  17936. series: []
  17937. });
  17938. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17939. // performed before theme and globalDefault merge.
  17940. var airaOption = baseOption.aria;
  17941. if (isObject(airaOption) && airaOption.enabled == null) {
  17942. airaOption.enabled = true;
  17943. }
  17944. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17945. merge(baseOption, globalDefault, false);
  17946. ecModel._mergeOption(baseOption, null);
  17947. };
  17948. }();
  17949. return GlobalModel;
  17950. }(Model);
  17951. function isNotTargetSeries(seriesModel, payload) {
  17952. if (payload) {
  17953. var index = payload.seriesIndex;
  17954. var id = payload.seriesId;
  17955. var name_1 = payload.seriesName;
  17956. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17957. }
  17958. }
  17959. function mergeTheme(option, theme) {
  17960. // PENDING
  17961. // NOT use `colorLayer` in theme if option has `color`
  17962. var notMergeColorLayer = option.color && !option.colorLayer;
  17963. each(theme, function (themeItem, name) {
  17964. if (name === 'colorLayer' && notMergeColorLayer) {
  17965. return;
  17966. } // If it is component model mainType, the model handles that merge later.
  17967. // otherwise, merge them here.
  17968. if (!ComponentModel.hasClass(name)) {
  17969. if (typeof themeItem === 'object') {
  17970. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17971. } else {
  17972. if (option[name] == null) {
  17973. option[name] = themeItem;
  17974. }
  17975. }
  17976. }
  17977. });
  17978. }
  17979. function queryByIdOrName(attr, idOrName, cmpts) {
  17980. // Here is a break from echarts4: string and number are
  17981. // treated as equal.
  17982. if (isArray(idOrName)) {
  17983. var keyMap_1 = createHashMap();
  17984. each(idOrName, function (idOrNameItem) {
  17985. if (idOrNameItem != null) {
  17986. var idName = convertOptionIdName(idOrNameItem, null);
  17987. idName != null && keyMap_1.set(idOrNameItem, true);
  17988. }
  17989. });
  17990. return filter(cmpts, function (cmpt) {
  17991. return cmpt && keyMap_1.get(cmpt[attr]);
  17992. });
  17993. } else {
  17994. var idName_1 = convertOptionIdName(idOrName, null);
  17995. return filter(cmpts, function (cmpt) {
  17996. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17997. });
  17998. }
  17999. }
  18000. function filterBySubType(components, condition) {
  18001. // Using hasOwnProperty for restrict. Consider
  18002. // subType is undefined in user payload.
  18003. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  18004. return cmpt && cmpt.subType === condition.subType;
  18005. }) : components;
  18006. }
  18007. function normalizeSetOptionInput(opts) {
  18008. var replaceMergeMainTypeMap = createHashMap();
  18009. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  18010. if ("development" !== 'production') {
  18011. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  18012. }
  18013. replaceMergeMainTypeMap.set(mainType, true);
  18014. });
  18015. return {
  18016. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  18017. };
  18018. }
  18019. mixin(GlobalModel, PaletteMixin);
  18020. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  18021. 'getOption', // 'getViewOfComponentModel',
  18022. // 'getViewOfSeriesModel',
  18023. 'getId', 'updateLabelLayout'];
  18024. var ExtensionAPI =
  18025. /** @class */
  18026. function () {
  18027. function ExtensionAPI(ecInstance) {
  18028. each(availableMethods, function (methodName) {
  18029. this[methodName] = bind(ecInstance[methodName], ecInstance);
  18030. }, this);
  18031. }
  18032. return ExtensionAPI;
  18033. }();
  18034. var coordinateSystemCreators = {};
  18035. var CoordinateSystemManager =
  18036. /** @class */
  18037. function () {
  18038. function CoordinateSystemManager() {
  18039. this._coordinateSystems = [];
  18040. }
  18041. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  18042. var coordinateSystems = [];
  18043. each(coordinateSystemCreators, function (creator, type) {
  18044. var list = creator.create(ecModel, api);
  18045. coordinateSystems = coordinateSystems.concat(list || []);
  18046. });
  18047. this._coordinateSystems = coordinateSystems;
  18048. };
  18049. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  18050. each(this._coordinateSystems, function (coordSys) {
  18051. coordSys.update && coordSys.update(ecModel, api);
  18052. });
  18053. };
  18054. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  18055. return this._coordinateSystems.slice();
  18056. };
  18057. CoordinateSystemManager.register = function (type, creator) {
  18058. coordinateSystemCreators[type] = creator;
  18059. };
  18060. CoordinateSystemManager.get = function (type) {
  18061. return coordinateSystemCreators[type];
  18062. };
  18063. return CoordinateSystemManager;
  18064. }();
  18065. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  18066. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  18067. /**
  18068. * TERM EXPLANATIONS:
  18069. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  18070. */
  18071. var OptionManager =
  18072. /** @class */
  18073. function () {
  18074. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18075. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18076. // rawOption cloned and backuped when timeline changed, which does no
  18077. // good to performance. What's more, that both timeline and setOption
  18078. // method supply 'notMerge' brings complex and some problems.
  18079. // Consider this case:
  18080. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18081. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18082. function OptionManager(api) {
  18083. this._timelineOptions = [];
  18084. this._mediaList = [];
  18085. /**
  18086. * -1, means default.
  18087. * empty means no media.
  18088. */
  18089. this._currentMediaIndices = [];
  18090. this._api = api;
  18091. }
  18092. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  18093. if (rawOption) {
  18094. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18095. each(normalizeToArray(rawOption.series), function (series) {
  18096. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18097. });
  18098. each(normalizeToArray(rawOption.dataset), function (dataset) {
  18099. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  18100. });
  18101. } // Caution: some series modify option data, if do not clone,
  18102. // it should ensure that the repeat modify correctly
  18103. // (create a new object when modify itself).
  18104. rawOption = clone(rawOption); // FIXME
  18105. // If some property is set in timeline options or media option but
  18106. // not set in baseOption, a warning should be given.
  18107. var optionBackup = this._optionBackup;
  18108. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  18109. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  18110. if (optionBackup) {
  18111. // FIXME
  18112. // the restore merge solution is essentially incorrect.
  18113. // the mapping can not be 100% consistent with ecModel, which probably brings
  18114. // potential bug!
  18115. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  18116. // let fakeCmptsMap = this._fakeCmptsMap;
  18117. // if (!fakeCmptsMap) {
  18118. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  18119. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  18120. // }
  18121. // mergeToBackupOption(
  18122. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  18123. // );
  18124. // For simplicity, timeline options and media options do not support merge,
  18125. // that is, if you `setOption` twice and both has timeline options, the latter
  18126. // timeline options will not be merged to the former, but just substitute them.
  18127. if (newParsedOption.timelineOptions.length) {
  18128. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  18129. }
  18130. if (newParsedOption.mediaList.length) {
  18131. optionBackup.mediaList = newParsedOption.mediaList;
  18132. }
  18133. if (newParsedOption.mediaDefault) {
  18134. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  18135. }
  18136. } else {
  18137. this._optionBackup = newParsedOption;
  18138. }
  18139. };
  18140. OptionManager.prototype.mountOption = function (isRecreate) {
  18141. var optionBackup = this._optionBackup;
  18142. this._timelineOptions = optionBackup.timelineOptions;
  18143. this._mediaList = optionBackup.mediaList;
  18144. this._mediaDefault = optionBackup.mediaDefault;
  18145. this._currentMediaIndices = [];
  18146. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  18147. // called, and is merged into every new option by inner method `mergeToBackupOption`
  18148. // each time `setOption` called, can be only used in `isRecreate`, because
  18149. // its reliability is under suspicion. In other cases option merge is
  18150. // performed by `model.mergeOption`.
  18151. ? optionBackup.baseOption : this._newBaseOption);
  18152. };
  18153. OptionManager.prototype.getTimelineOption = function (ecModel) {
  18154. var option;
  18155. var timelineOptions = this._timelineOptions;
  18156. if (timelineOptions.length) {
  18157. // getTimelineOption can only be called after ecModel inited,
  18158. // so we can get currentIndex from timelineModel.
  18159. var timelineModel = ecModel.getComponent('timeline');
  18160. if (timelineModel) {
  18161. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  18162. timelineOptions[timelineModel.getCurrentIndex()]);
  18163. }
  18164. }
  18165. return option;
  18166. };
  18167. OptionManager.prototype.getMediaOption = function (ecModel) {
  18168. var ecWidth = this._api.getWidth();
  18169. var ecHeight = this._api.getHeight();
  18170. var mediaList = this._mediaList;
  18171. var mediaDefault = this._mediaDefault;
  18172. var indices = [];
  18173. var result = []; // No media defined.
  18174. if (!mediaList.length && !mediaDefault) {
  18175. return result;
  18176. } // Multi media may be applied, the latter defined media has higher priority.
  18177. for (var i = 0, len = mediaList.length; i < len; i++) {
  18178. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18179. indices.push(i);
  18180. }
  18181. } // FIXME
  18182. // Whether mediaDefault should force users to provide? Otherwise
  18183. // the change by media query can not be recorvered.
  18184. if (!indices.length && mediaDefault) {
  18185. indices = [-1];
  18186. }
  18187. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18188. result = map(indices, function (index) {
  18189. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  18190. });
  18191. } // Otherwise return nothing.
  18192. this._currentMediaIndices = indices;
  18193. return result;
  18194. };
  18195. return OptionManager;
  18196. }();
  18197. /**
  18198. * [RAW_OPTION_PATTERNS]
  18199. * (Note: "series: []" represents all other props in `ECUnitOption`)
  18200. *
  18201. * (1) No prop "baseOption" declared:
  18202. * Root option is used as "baseOption" (except prop "options" and "media").
  18203. * ```js
  18204. * option = {
  18205. * series: [],
  18206. * timeline: {},
  18207. * options: [],
  18208. * };
  18209. * option = {
  18210. * series: [],
  18211. * media: {},
  18212. * };
  18213. * option = {
  18214. * series: [],
  18215. * timeline: {},
  18216. * options: [],
  18217. * media: {},
  18218. * }
  18219. * ```
  18220. *
  18221. * (2) Prop "baseOption" declared:
  18222. * If "baseOption" declared, `ECUnitOption` props can only be declared
  18223. * inside "baseOption" except prop "timeline" (compat ec2).
  18224. * ```js
  18225. * option = {
  18226. * baseOption: {
  18227. * timeline: {},
  18228. * series: [],
  18229. * },
  18230. * options: []
  18231. * };
  18232. * option = {
  18233. * baseOption: {
  18234. * series: [],
  18235. * },
  18236. * media: []
  18237. * };
  18238. * option = {
  18239. * baseOption: {
  18240. * timeline: {},
  18241. * series: [],
  18242. * },
  18243. * options: []
  18244. * media: []
  18245. * };
  18246. * option = {
  18247. * // ec3 compat ec2: allow (only) `timeline` declared
  18248. * // outside baseOption. Keep this setting for compat.
  18249. * timeline: {},
  18250. * baseOption: {
  18251. * series: [],
  18252. * },
  18253. * options: [],
  18254. * media: []
  18255. * };
  18256. * ```
  18257. */
  18258. function parseRawOption( // `rawOption` May be modified
  18259. rawOption, optionPreprocessorFuncs, isNew) {
  18260. var mediaList = [];
  18261. var mediaDefault;
  18262. var baseOption;
  18263. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  18264. var timelineOnRoot = rawOption.timeline;
  18265. var timelineOptionsOnRoot = rawOption.options;
  18266. var mediaOnRoot = rawOption.media;
  18267. var hasMedia = !!rawOption.media;
  18268. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18269. if (declaredBaseOption) {
  18270. baseOption = declaredBaseOption; // For merge option.
  18271. if (!baseOption.timeline) {
  18272. baseOption.timeline = timelineOnRoot;
  18273. }
  18274. } // For convenience, enable to use the root option as the `baseOption`:
  18275. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18276. else {
  18277. if (hasTimeline || hasMedia) {
  18278. rawOption.options = rawOption.media = null;
  18279. }
  18280. baseOption = rawOption;
  18281. }
  18282. if (hasMedia) {
  18283. if (isArray(mediaOnRoot)) {
  18284. each(mediaOnRoot, function (singleMedia) {
  18285. if ("development" !== 'production') {
  18286. // Real case of wrong config.
  18287. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18288. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18289. }
  18290. }
  18291. if (singleMedia && singleMedia.option) {
  18292. if (singleMedia.query) {
  18293. mediaList.push(singleMedia);
  18294. } else if (!mediaDefault) {
  18295. // Use the first media default.
  18296. mediaDefault = singleMedia;
  18297. }
  18298. }
  18299. });
  18300. } else {
  18301. if ("development" !== 'production') {
  18302. // Real case of wrong config.
  18303. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18304. }
  18305. }
  18306. }
  18307. doPreprocess(baseOption);
  18308. each(timelineOptionsOnRoot, function (option) {
  18309. return doPreprocess(option);
  18310. });
  18311. each(mediaList, function (media) {
  18312. return doPreprocess(media.option);
  18313. });
  18314. function doPreprocess(option) {
  18315. each(optionPreprocessorFuncs, function (preProcess) {
  18316. preProcess(option, isNew);
  18317. });
  18318. }
  18319. return {
  18320. baseOption: baseOption,
  18321. timelineOptions: timelineOptionsOnRoot || [],
  18322. mediaDefault: mediaDefault,
  18323. mediaList: mediaList
  18324. };
  18325. }
  18326. /**
  18327. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18328. * Support: width, height, aspectRatio
  18329. * Can use max or min as prefix.
  18330. */
  18331. function applyMediaQuery(query, ecWidth, ecHeight) {
  18332. var realMap = {
  18333. width: ecWidth,
  18334. height: ecHeight,
  18335. aspectratio: ecWidth / ecHeight // lower case for convenience.
  18336. };
  18337. var applicable = true;
  18338. each(query, function (value, attr) {
  18339. var matched = attr.match(QUERY_REG);
  18340. if (!matched || !matched[1] || !matched[2]) {
  18341. return;
  18342. }
  18343. var operator = matched[1];
  18344. var realAttr = matched[2].toLowerCase();
  18345. if (!compare(realMap[realAttr], value, operator)) {
  18346. applicable = false;
  18347. }
  18348. });
  18349. return applicable;
  18350. }
  18351. function compare(real, expect, operator) {
  18352. if (operator === 'min') {
  18353. return real >= expect;
  18354. } else if (operator === 'max') {
  18355. return real <= expect;
  18356. } else {
  18357. // Equals
  18358. return real === expect;
  18359. }
  18360. }
  18361. function indicesEquals(indices1, indices2) {
  18362. // indices is always order by asc and has only finite number.
  18363. return indices1.join(',') === indices2.join(',');
  18364. }
  18365. var each$2 = each;
  18366. var isObject$1 = isObject;
  18367. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18368. function compatEC2ItemStyle(opt) {
  18369. var itemStyleOpt = opt && opt.itemStyle;
  18370. if (!itemStyleOpt) {
  18371. return;
  18372. }
  18373. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18374. var styleName = POSSIBLE_STYLES[i];
  18375. var normalItemStyleOpt = itemStyleOpt.normal;
  18376. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18377. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18378. if ("development" !== 'production') {
  18379. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18380. }
  18381. opt[styleName] = opt[styleName] || {};
  18382. if (!opt[styleName].normal) {
  18383. opt[styleName].normal = normalItemStyleOpt[styleName];
  18384. } else {
  18385. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18386. }
  18387. normalItemStyleOpt[styleName] = null;
  18388. }
  18389. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18390. if ("development" !== 'production') {
  18391. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18392. }
  18393. opt[styleName] = opt[styleName] || {};
  18394. if (!opt[styleName].emphasis) {
  18395. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18396. } else {
  18397. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18398. }
  18399. emphasisItemStyleOpt[styleName] = null;
  18400. }
  18401. }
  18402. }
  18403. function convertNormalEmphasis(opt, optType, useExtend) {
  18404. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18405. var normalOpt = opt[optType].normal;
  18406. var emphasisOpt = opt[optType].emphasis;
  18407. if (normalOpt) {
  18408. if ("development" !== 'production') {
  18409. // eslint-disable-next-line max-len
  18410. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18411. } // Timeline controlStyle has other properties besides normal and emphasis
  18412. if (useExtend) {
  18413. opt[optType].normal = opt[optType].emphasis = null;
  18414. defaults(opt[optType], normalOpt);
  18415. } else {
  18416. opt[optType] = normalOpt;
  18417. }
  18418. }
  18419. if (emphasisOpt) {
  18420. if ("development" !== 'production') {
  18421. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18422. }
  18423. opt.emphasis = opt.emphasis || {};
  18424. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  18425. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18426. if (emphasisOpt.focus) {
  18427. opt.emphasis.focus = emphasisOpt.focus;
  18428. }
  18429. if (emphasisOpt.blurScope) {
  18430. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18431. }
  18432. }
  18433. }
  18434. }
  18435. function removeEC3NormalStatus(opt) {
  18436. convertNormalEmphasis(opt, 'itemStyle');
  18437. convertNormalEmphasis(opt, 'lineStyle');
  18438. convertNormalEmphasis(opt, 'areaStyle');
  18439. convertNormalEmphasis(opt, 'label');
  18440. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18441. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18442. convertNormalEmphasis(opt, 'edgeLabel');
  18443. }
  18444. function compatTextStyle(opt, propName) {
  18445. // Check whether is not object (string\null\undefined ...)
  18446. var labelOptSingle = isObject$1(opt) && opt[propName];
  18447. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18448. if (textStyle) {
  18449. if ("development" !== 'production') {
  18450. // eslint-disable-next-line max-len
  18451. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18452. }
  18453. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18454. var textPropName = TEXT_STYLE_OPTIONS[i];
  18455. if (textStyle.hasOwnProperty(textPropName)) {
  18456. labelOptSingle[textPropName] = textStyle[textPropName];
  18457. }
  18458. }
  18459. }
  18460. }
  18461. function compatEC3CommonStyles(opt) {
  18462. if (opt) {
  18463. removeEC3NormalStatus(opt);
  18464. compatTextStyle(opt, 'label');
  18465. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18466. }
  18467. }
  18468. function processSeries(seriesOpt) {
  18469. if (!isObject$1(seriesOpt)) {
  18470. return;
  18471. }
  18472. compatEC2ItemStyle(seriesOpt);
  18473. removeEC3NormalStatus(seriesOpt);
  18474. compatTextStyle(seriesOpt, 'label'); // treemap
  18475. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18476. compatTextStyle(seriesOpt, 'edgeLabel');
  18477. if (seriesOpt.emphasis) {
  18478. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18479. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18480. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18481. }
  18482. var markPoint = seriesOpt.markPoint;
  18483. if (markPoint) {
  18484. compatEC2ItemStyle(markPoint);
  18485. compatEC3CommonStyles(markPoint);
  18486. }
  18487. var markLine = seriesOpt.markLine;
  18488. if (markLine) {
  18489. compatEC2ItemStyle(markLine);
  18490. compatEC3CommonStyles(markLine);
  18491. }
  18492. var markArea = seriesOpt.markArea;
  18493. if (markArea) {
  18494. compatEC3CommonStyles(markArea);
  18495. }
  18496. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18497. // then the backward compat based on option type will not be performed.
  18498. if (seriesOpt.type === 'graph') {
  18499. data = data || seriesOpt.nodes;
  18500. var edgeData = seriesOpt.links || seriesOpt.edges;
  18501. if (edgeData && !isTypedArray(edgeData)) {
  18502. for (var i = 0; i < edgeData.length; i++) {
  18503. compatEC3CommonStyles(edgeData[i]);
  18504. }
  18505. }
  18506. each(seriesOpt.categories, function (opt) {
  18507. removeEC3NormalStatus(opt);
  18508. });
  18509. }
  18510. if (data && !isTypedArray(data)) {
  18511. for (var i = 0; i < data.length; i++) {
  18512. compatEC3CommonStyles(data[i]);
  18513. }
  18514. } // mark point data
  18515. markPoint = seriesOpt.markPoint;
  18516. if (markPoint && markPoint.data) {
  18517. var mpData = markPoint.data;
  18518. for (var i = 0; i < mpData.length; i++) {
  18519. compatEC3CommonStyles(mpData[i]);
  18520. }
  18521. } // mark line data
  18522. markLine = seriesOpt.markLine;
  18523. if (markLine && markLine.data) {
  18524. var mlData = markLine.data;
  18525. for (var i = 0; i < mlData.length; i++) {
  18526. if (isArray(mlData[i])) {
  18527. compatEC3CommonStyles(mlData[i][0]);
  18528. compatEC3CommonStyles(mlData[i][1]);
  18529. } else {
  18530. compatEC3CommonStyles(mlData[i]);
  18531. }
  18532. }
  18533. } // Series
  18534. if (seriesOpt.type === 'gauge') {
  18535. compatTextStyle(seriesOpt, 'axisLabel');
  18536. compatTextStyle(seriesOpt, 'title');
  18537. compatTextStyle(seriesOpt, 'detail');
  18538. } else if (seriesOpt.type === 'treemap') {
  18539. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18540. each(seriesOpt.levels, function (opt) {
  18541. removeEC3NormalStatus(opt);
  18542. });
  18543. } else if (seriesOpt.type === 'tree') {
  18544. removeEC3NormalStatus(seriesOpt.leaves);
  18545. } // sunburst starts from ec4, so it does not need to compat levels.
  18546. }
  18547. function toArr(o) {
  18548. return isArray(o) ? o : o ? [o] : [];
  18549. }
  18550. function toObj(o) {
  18551. return (isArray(o) ? o[0] : o) || {};
  18552. }
  18553. function globalCompatStyle(option, isTheme) {
  18554. each$2(toArr(option.series), function (seriesOpt) {
  18555. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18556. });
  18557. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18558. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18559. each$2(axes, function (axisName) {
  18560. each$2(toArr(option[axisName]), function (axisOpt) {
  18561. if (axisOpt) {
  18562. compatTextStyle(axisOpt, 'axisLabel');
  18563. compatTextStyle(axisOpt.axisPointer, 'label');
  18564. }
  18565. });
  18566. });
  18567. each$2(toArr(option.parallel), function (parallelOpt) {
  18568. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18569. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18570. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18571. });
  18572. each$2(toArr(option.calendar), function (calendarOpt) {
  18573. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18574. compatTextStyle(calendarOpt, 'dayLabel');
  18575. compatTextStyle(calendarOpt, 'monthLabel');
  18576. compatTextStyle(calendarOpt, 'yearLabel');
  18577. }); // radar.name.textStyle
  18578. each$2(toArr(option.radar), function (radarOpt) {
  18579. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  18580. if (radarOpt.name && radarOpt.axisName == null) {
  18581. radarOpt.axisName = radarOpt.name;
  18582. delete radarOpt.name;
  18583. if ("development" !== 'production') {
  18584. deprecateLog('name property in radar component has been changed to axisName');
  18585. }
  18586. }
  18587. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18588. radarOpt.axisNameGap = radarOpt.nameGap;
  18589. delete radarOpt.nameGap;
  18590. if ("development" !== 'production') {
  18591. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18592. }
  18593. }
  18594. if ("development" !== 'production') {
  18595. each$2(radarOpt.indicator, function (indicatorOpt) {
  18596. if (indicatorOpt.text) {
  18597. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18598. }
  18599. });
  18600. }
  18601. });
  18602. each$2(toArr(option.geo), function (geoOpt) {
  18603. if (isObject$1(geoOpt)) {
  18604. compatEC3CommonStyles(geoOpt);
  18605. each$2(toArr(geoOpt.regions), function (regionObj) {
  18606. compatEC3CommonStyles(regionObj);
  18607. });
  18608. }
  18609. });
  18610. each$2(toArr(option.timeline), function (timelineOpt) {
  18611. compatEC3CommonStyles(timelineOpt);
  18612. convertNormalEmphasis(timelineOpt, 'label');
  18613. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18614. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18615. var data = timelineOpt.data;
  18616. isArray(data) && each(data, function (item) {
  18617. if (isObject(item)) {
  18618. convertNormalEmphasis(item, 'label');
  18619. convertNormalEmphasis(item, 'itemStyle');
  18620. }
  18621. });
  18622. });
  18623. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18624. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18625. each$2(toolboxOpt.feature, function (featureOpt) {
  18626. convertNormalEmphasis(featureOpt, 'iconStyle');
  18627. });
  18628. });
  18629. compatTextStyle(toObj(option.axisPointer), 'label');
  18630. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  18631. // storedLogs = {};
  18632. }
  18633. function get(opt, path) {
  18634. var pathArr = path.split(',');
  18635. var obj = opt;
  18636. for (var i = 0; i < pathArr.length; i++) {
  18637. obj = obj && obj[pathArr[i]];
  18638. if (obj == null) {
  18639. break;
  18640. }
  18641. }
  18642. return obj;
  18643. }
  18644. function set$1(opt, path, val, overwrite) {
  18645. var pathArr = path.split(',');
  18646. var obj = opt;
  18647. var key;
  18648. var i = 0;
  18649. for (; i < pathArr.length - 1; i++) {
  18650. key = pathArr[i];
  18651. if (obj[key] == null) {
  18652. obj[key] = {};
  18653. }
  18654. obj = obj[key];
  18655. }
  18656. if (overwrite || obj[pathArr[i]] == null) {
  18657. obj[pathArr[i]] = val;
  18658. }
  18659. }
  18660. function compatLayoutProperties(option) {
  18661. option && each(LAYOUT_PROPERTIES, function (prop) {
  18662. if (prop[0] in option && !(prop[1] in option)) {
  18663. option[prop[1]] = option[prop[0]];
  18664. }
  18665. });
  18666. }
  18667. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18668. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18669. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18670. function compatBarItemStyle(option) {
  18671. var itemStyle = option && option.itemStyle;
  18672. if (itemStyle) {
  18673. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18674. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18675. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18676. if (itemStyle[oldName] != null) {
  18677. itemStyle[newName] = itemStyle[oldName];
  18678. if ("development" !== 'production') {
  18679. deprecateReplaceLog(oldName, newName);
  18680. }
  18681. }
  18682. }
  18683. }
  18684. }
  18685. function compatPieLabel(option) {
  18686. if (!option) {
  18687. return;
  18688. }
  18689. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18690. if ("development" !== 'production') {
  18691. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18692. }
  18693. option.edgeDistance = option.margin;
  18694. }
  18695. }
  18696. function compatSunburstState(option) {
  18697. if (!option) {
  18698. return;
  18699. }
  18700. if (option.downplay && !option.blur) {
  18701. option.blur = option.downplay;
  18702. if ("development" !== 'production') {
  18703. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18704. }
  18705. }
  18706. }
  18707. function compatGraphFocus(option) {
  18708. if (!option) {
  18709. return;
  18710. }
  18711. if (option.focusNodeAdjacency != null) {
  18712. option.emphasis = option.emphasis || {};
  18713. if (option.emphasis.focus == null) {
  18714. if ("development" !== 'production') {
  18715. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18716. }
  18717. option.emphasis.focus = 'adjacency';
  18718. }
  18719. }
  18720. }
  18721. function traverseTree(data, cb) {
  18722. if (data) {
  18723. for (var i = 0; i < data.length; i++) {
  18724. cb(data[i]);
  18725. data[i] && traverseTree(data[i].children, cb);
  18726. }
  18727. }
  18728. }
  18729. function globalBackwardCompat(option, isTheme) {
  18730. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18731. option.series = normalizeToArray(option.series);
  18732. each(option.series, function (seriesOpt) {
  18733. if (!isObject(seriesOpt)) {
  18734. return;
  18735. }
  18736. var seriesType = seriesOpt.type;
  18737. if (seriesType === 'line') {
  18738. if (seriesOpt.clipOverflow != null) {
  18739. seriesOpt.clip = seriesOpt.clipOverflow;
  18740. if ("development" !== 'production') {
  18741. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18742. }
  18743. }
  18744. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18745. if (seriesOpt.clockWise != null) {
  18746. seriesOpt.clockwise = seriesOpt.clockWise;
  18747. if ("development" !== 'production') {
  18748. deprecateReplaceLog('clockWise', 'clockwise');
  18749. }
  18750. }
  18751. compatPieLabel(seriesOpt.label);
  18752. var data = seriesOpt.data;
  18753. if (data && !isTypedArray(data)) {
  18754. for (var i = 0; i < data.length; i++) {
  18755. compatPieLabel(data[i]);
  18756. }
  18757. }
  18758. if (seriesOpt.hoverOffset != null) {
  18759. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18760. if (seriesOpt.emphasis.scaleSize = null) {
  18761. if ("development" !== 'production') {
  18762. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18763. }
  18764. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18765. }
  18766. }
  18767. } else if (seriesType === 'gauge') {
  18768. var pointerColor = get(seriesOpt, 'pointer.color');
  18769. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18770. } else if (seriesType === 'bar') {
  18771. compatBarItemStyle(seriesOpt);
  18772. compatBarItemStyle(seriesOpt.backgroundStyle);
  18773. compatBarItemStyle(seriesOpt.emphasis);
  18774. var data = seriesOpt.data;
  18775. if (data && !isTypedArray(data)) {
  18776. for (var i = 0; i < data.length; i++) {
  18777. if (typeof data[i] === 'object') {
  18778. compatBarItemStyle(data[i]);
  18779. compatBarItemStyle(data[i] && data[i].emphasis);
  18780. }
  18781. }
  18782. }
  18783. } else if (seriesType === 'sunburst') {
  18784. var highlightPolicy = seriesOpt.highlightPolicy;
  18785. if (highlightPolicy) {
  18786. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18787. if (!seriesOpt.emphasis.focus) {
  18788. seriesOpt.emphasis.focus = highlightPolicy;
  18789. if ("development" !== 'production') {
  18790. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18791. }
  18792. }
  18793. }
  18794. compatSunburstState(seriesOpt);
  18795. traverseTree(seriesOpt.data, compatSunburstState);
  18796. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18797. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18798. } else if (seriesType === 'map') {
  18799. if (seriesOpt.mapType && !seriesOpt.map) {
  18800. if ("development" !== 'production') {
  18801. deprecateReplaceLog('mapType', 'map', 'map');
  18802. }
  18803. seriesOpt.map = seriesOpt.mapType;
  18804. }
  18805. if (seriesOpt.mapLocation) {
  18806. if ("development" !== 'production') {
  18807. deprecateLog('`mapLocation` is not used anymore.');
  18808. }
  18809. defaults(seriesOpt, seriesOpt.mapLocation);
  18810. }
  18811. }
  18812. if (seriesOpt.hoverAnimation != null) {
  18813. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18814. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18815. if ("development" !== 'production') {
  18816. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18817. }
  18818. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18819. }
  18820. }
  18821. compatLayoutProperties(seriesOpt);
  18822. }); // dataRange has changed to visualMap
  18823. if (option.dataRange) {
  18824. option.visualMap = option.dataRange;
  18825. }
  18826. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18827. var options = option[componentName];
  18828. if (options) {
  18829. if (!isArray(options)) {
  18830. options = [options];
  18831. }
  18832. each(options, function (option) {
  18833. compatLayoutProperties(option);
  18834. });
  18835. }
  18836. });
  18837. }
  18838. // data processing stage is blocked in stream.
  18839. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18840. // (2) Only register once when import repeatedly.
  18841. // Should be executed after series is filtered and before stack calculation.
  18842. function dataStack(ecModel) {
  18843. var stackInfoMap = createHashMap();
  18844. ecModel.eachSeries(function (seriesModel) {
  18845. var stack = seriesModel.get('stack'); // Compatible: when `stack` is set as '', do not stack.
  18846. if (stack) {
  18847. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18848. var data = seriesModel.getData();
  18849. var stackInfo = {
  18850. // Used for calculate axis extent automatically.
  18851. // TODO: Type getCalculationInfo return more specific type?
  18852. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18853. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18854. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18855. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18856. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18857. data: data,
  18858. seriesModel: seriesModel
  18859. }; // If stacked on axis that do not support data stack.
  18860. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18861. return;
  18862. }
  18863. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18864. stackInfoList.push(stackInfo);
  18865. }
  18866. });
  18867. stackInfoMap.each(calculateStack);
  18868. }
  18869. function calculateStack(stackInfoList) {
  18870. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18871. var resultVal = [];
  18872. var resultNaN = [NaN, NaN];
  18873. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18874. var targetData = targetStackInfo.data;
  18875. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18876. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign'; // Should not write on raw data, because stack series model list changes
  18877. // depending on legend selection.
  18878. targetData.modify(dims, function (v0, v1, dataIndex) {
  18879. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18880. // should also be NaN, to draw a appropriate belt area.
  18881. if (isNaN(sum)) {
  18882. return resultNaN;
  18883. }
  18884. var byValue;
  18885. var stackedDataRawIndex;
  18886. if (isStackedByIndex) {
  18887. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18888. } else {
  18889. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18890. } // If stackOver is NaN, chart view will render point on value start.
  18891. var stackedOver = NaN;
  18892. for (var j = idxInStack - 1; j >= 0; j--) {
  18893. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18894. if (!isStackedByIndex) {
  18895. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18896. }
  18897. if (stackedDataRawIndex >= 0) {
  18898. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18899. if (stackStrategy === 'all' // single stack group
  18900. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  18901. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  18902. ) {
  18903. // The sum has to be very small to be affected by the
  18904. // floating arithmetic problem. An incorrect result will probably
  18905. // cause axis min/max to be filtered incorrectly.
  18906. sum = addSafe(sum, val);
  18907. stackedOver = val;
  18908. break;
  18909. }
  18910. }
  18911. }
  18912. resultVal[0] = sum;
  18913. resultVal[1] = stackedOver;
  18914. return resultVal;
  18915. });
  18916. });
  18917. }
  18918. var SourceImpl =
  18919. /** @class */
  18920. function () {
  18921. function SourceImpl(fields) {
  18922. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18923. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18924. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18925. this.startIndex = fields.startIndex || 0;
  18926. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18927. this.metaRawOption = fields.metaRawOption;
  18928. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18929. if (dimensionsDefine) {
  18930. for (var i = 0; i < dimensionsDefine.length; i++) {
  18931. var dim = dimensionsDefine[i];
  18932. if (dim.type == null) {
  18933. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18934. dim.type = 'ordinal';
  18935. }
  18936. }
  18937. }
  18938. }
  18939. }
  18940. return SourceImpl;
  18941. }();
  18942. function isSourceInstance(val) {
  18943. return val instanceof SourceImpl;
  18944. }
  18945. /**
  18946. * Create a source from option.
  18947. * NOTE: Created source is immutable. Don't change any properties in it.
  18948. */
  18949. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18950. sourceFormat) {
  18951. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18952. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18953. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18954. var source = new SourceImpl({
  18955. data: sourceData,
  18956. sourceFormat: sourceFormat,
  18957. seriesLayoutBy: seriesLayoutBy,
  18958. dimensionsDefine: determined.dimensionsDefine,
  18959. startIndex: determined.startIndex,
  18960. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18961. metaRawOption: clone(thisMetaRawOption)
  18962. });
  18963. return source;
  18964. }
  18965. /**
  18966. * Wrap original series data for some compatibility cases.
  18967. */
  18968. function createSourceFromSeriesDataOption(data) {
  18969. return new SourceImpl({
  18970. data: data,
  18971. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18972. });
  18973. }
  18974. /**
  18975. * Clone source but excludes source data.
  18976. */
  18977. function cloneSourceShallow(source) {
  18978. return new SourceImpl({
  18979. data: source.data,
  18980. sourceFormat: source.sourceFormat,
  18981. seriesLayoutBy: source.seriesLayoutBy,
  18982. dimensionsDefine: clone(source.dimensionsDefine),
  18983. startIndex: source.startIndex,
  18984. dimensionsDetectedCount: source.dimensionsDetectedCount
  18985. });
  18986. }
  18987. /**
  18988. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18989. */
  18990. function detectSourceFormat(data) {
  18991. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18992. if (isTypedArray(data)) {
  18993. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18994. } else if (isArray(data)) {
  18995. // FIXME Whether tolerate null in top level array?
  18996. if (data.length === 0) {
  18997. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18998. }
  18999. for (var i = 0, len = data.length; i < len; i++) {
  19000. var item = data[i];
  19001. if (item == null) {
  19002. continue;
  19003. } else if (isArray(item)) {
  19004. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19005. break;
  19006. } else if (isObject(item)) {
  19007. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  19008. break;
  19009. }
  19010. }
  19011. } else if (isObject(data)) {
  19012. for (var key in data) {
  19013. if (hasOwn(data, key) && isArrayLike(data[key])) {
  19014. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  19015. break;
  19016. }
  19017. }
  19018. }
  19019. return sourceFormat;
  19020. }
  19021. /**
  19022. * Determine the source definitions from data standalone dimensions definitions
  19023. * are not specified.
  19024. */
  19025. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  19026. // {
  19027. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  19028. // }
  19029. // in `dataset` or `series`
  19030. dimensionsDefine) {
  19031. var dimensionsDetectedCount;
  19032. var startIndex; // PENDING: Could data be null/undefined here?
  19033. // currently, if `dataset.source` not specified, error thrown.
  19034. // if `series.data` not specified, nothing rendered without error thrown.
  19035. // Should test these cases.
  19036. if (!data) {
  19037. return {
  19038. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19039. startIndex: startIndex,
  19040. dimensionsDetectedCount: dimensionsDetectedCount
  19041. };
  19042. }
  19043. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19044. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  19045. // Caution: consider a line with 5 string and 1 number,
  19046. // it still can not be sure it is a head, because the
  19047. // 5 string may be 5 values of category columns.
  19048. if (sourceHeader === 'auto' || sourceHeader == null) {
  19049. arrayRowsTravelFirst(function (val) {
  19050. // '-' is regarded as null/undefined.
  19051. if (val != null && val !== '-') {
  19052. if (isString(val)) {
  19053. startIndex == null && (startIndex = 1);
  19054. } else {
  19055. startIndex = 0;
  19056. }
  19057. } // 10 is an experience number, avoid long loop.
  19058. }, seriesLayoutBy, dataArrayRows, 10);
  19059. } else {
  19060. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  19061. }
  19062. if (!dimensionsDefine && startIndex === 1) {
  19063. dimensionsDefine = [];
  19064. arrayRowsTravelFirst(function (val, index) {
  19065. dimensionsDefine[index] = val != null ? val + '' : '';
  19066. }, seriesLayoutBy, dataArrayRows, Infinity);
  19067. }
  19068. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  19069. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19070. if (!dimensionsDefine) {
  19071. dimensionsDefine = objectRowsCollectDimensions(data);
  19072. }
  19073. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  19074. if (!dimensionsDefine) {
  19075. dimensionsDefine = [];
  19076. each(data, function (colArr, key) {
  19077. dimensionsDefine.push(key);
  19078. });
  19079. }
  19080. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19081. var value0 = getDataItemValue(data[0]);
  19082. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  19083. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19084. if ("development" !== 'production') {
  19085. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  19086. }
  19087. }
  19088. return {
  19089. startIndex: startIndex,
  19090. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19091. dimensionsDetectedCount: dimensionsDetectedCount
  19092. };
  19093. }
  19094. function objectRowsCollectDimensions(data) {
  19095. var firstIndex = 0;
  19096. var obj;
  19097. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  19098. if (obj) {
  19099. return keys(obj);
  19100. }
  19101. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  19102. // which is reasonable. But dimension name is duplicated.
  19103. // Returns undefined or an array contains only object without null/undefined or string.
  19104. function normalizeDimensionsOption(dimensionsDefine) {
  19105. if (!dimensionsDefine) {
  19106. // The meaning of null/undefined is different from empty array.
  19107. return;
  19108. }
  19109. var nameMap = createHashMap();
  19110. return map(dimensionsDefine, function (rawItem, index) {
  19111. rawItem = isObject(rawItem) ? rawItem : {
  19112. name: rawItem
  19113. }; // Other fields will be discarded.
  19114. var item = {
  19115. name: rawItem.name,
  19116. displayName: rawItem.displayName,
  19117. type: rawItem.type
  19118. }; // User can set null in dimensions.
  19119. // We don't auto specify name, otherwise a given name may
  19120. // cause it to be referred unexpectedly.
  19121. if (item.name == null) {
  19122. return item;
  19123. } // Also consider number form like 2012.
  19124. item.name += ''; // User may also specify displayName.
  19125. // displayName will always exists except user not
  19126. // specified or dim name is not specified or detected.
  19127. // (A auto generated dim name will not be used as
  19128. // displayName).
  19129. if (item.displayName == null) {
  19130. item.displayName = item.name;
  19131. }
  19132. var exist = nameMap.get(item.name);
  19133. if (!exist) {
  19134. nameMap.set(item.name, {
  19135. count: 1
  19136. });
  19137. } else {
  19138. item.name += '-' + exist.count++;
  19139. }
  19140. return item;
  19141. });
  19142. }
  19143. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  19144. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  19145. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19146. cb(data[i] ? data[i][0] : null, i);
  19147. }
  19148. } else {
  19149. var value0 = data[0] || [];
  19150. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  19151. cb(value0[i], i);
  19152. }
  19153. }
  19154. }
  19155. function shouldRetrieveDataByName(source) {
  19156. var sourceFormat = source.sourceFormat;
  19157. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  19158. }
  19159. /*
  19160. * Licensed to the Apache Software Foundation (ASF) under one
  19161. * or more contributor license agreements. See the NOTICE file
  19162. * distributed with this work for additional information
  19163. * regarding copyright ownership. The ASF licenses this file
  19164. * to you under the Apache License, Version 2.0 (the
  19165. * "License"); you may not use this file except in compliance
  19166. * with the License. You may obtain a copy of the License at
  19167. *
  19168. * http://www.apache.org/licenses/LICENSE-2.0
  19169. *
  19170. * Unless required by applicable law or agreed to in writing,
  19171. * software distributed under the License is distributed on an
  19172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19173. * KIND, either express or implied. See the License for the
  19174. * specific language governing permissions and limitations
  19175. * under the License.
  19176. */
  19177. /**
  19178. * AUTO-GENERATED FILE. DO NOT MODIFY.
  19179. */
  19180. /*
  19181. * Licensed to the Apache Software Foundation (ASF) under one
  19182. * or more contributor license agreements. See the NOTICE file
  19183. * distributed with this work for additional information
  19184. * regarding copyright ownership. The ASF licenses this file
  19185. * to you under the Apache License, Version 2.0 (the
  19186. * "License"); you may not use this file except in compliance
  19187. * with the License. You may obtain a copy of the License at
  19188. *
  19189. * http://www.apache.org/licenses/LICENSE-2.0
  19190. *
  19191. * Unless required by applicable law or agreed to in writing,
  19192. * software distributed under the License is distributed on an
  19193. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19194. * KIND, either express or implied. See the License for the
  19195. * specific language governing permissions and limitations
  19196. * under the License.
  19197. */
  19198. var _a, _b, _c; // TODO
  19199. var providerMethods;
  19200. var mountMethods;
  19201. /**
  19202. * If normal array used, mutable chunk size is supported.
  19203. * If typed array used, chunk size must be fixed.
  19204. */
  19205. var DefaultDataProvider =
  19206. /** @class */
  19207. function () {
  19208. function DefaultDataProvider(sourceParam, dimSize) {
  19209. // let source: Source;
  19210. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  19211. this._source = source;
  19212. var data = this._data = source.data; // Typed array. TODO IE10+?
  19213. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19214. if ("development" !== 'production') {
  19215. if (dimSize == null) {
  19216. throw new Error('Typed array data must specify dimension size');
  19217. }
  19218. }
  19219. this._offset = 0;
  19220. this._dimSize = dimSize;
  19221. this._data = data;
  19222. }
  19223. mountMethods(this, data, source);
  19224. }
  19225. DefaultDataProvider.prototype.getSource = function () {
  19226. return this._source;
  19227. };
  19228. DefaultDataProvider.prototype.count = function () {
  19229. return 0;
  19230. };
  19231. DefaultDataProvider.prototype.getItem = function (idx, out) {
  19232. return;
  19233. };
  19234. DefaultDataProvider.prototype.appendData = function (newData) {};
  19235. DefaultDataProvider.prototype.clean = function () {};
  19236. DefaultDataProvider.protoInitialize = function () {
  19237. // PENDING: To avoid potential incompat (e.g., prototype
  19238. // is visited somewhere), still init them on prototype.
  19239. var proto = DefaultDataProvider.prototype;
  19240. proto.pure = false;
  19241. proto.persistent = true;
  19242. }();
  19243. DefaultDataProvider.internalField = function () {
  19244. var _a;
  19245. mountMethods = function (provider, data, source) {
  19246. var sourceFormat = source.sourceFormat;
  19247. var seriesLayoutBy = source.seriesLayoutBy;
  19248. var startIndex = source.startIndex;
  19249. var dimsDef = source.dimensionsDefine;
  19250. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19251. if ("development" !== 'production') {
  19252. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19253. }
  19254. extend(provider, methods);
  19255. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19256. provider.getItem = getItemForTypedArray;
  19257. provider.count = countForTypedArray;
  19258. provider.fillStorage = fillStorageForTypedArray;
  19259. } else {
  19260. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  19261. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  19262. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  19263. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  19264. }
  19265. };
  19266. var getItemForTypedArray = function (idx, out) {
  19267. idx = idx - this._offset;
  19268. out = out || [];
  19269. var data = this._data;
  19270. var dimSize = this._dimSize;
  19271. var offset = dimSize * idx;
  19272. for (var i = 0; i < dimSize; i++) {
  19273. out[i] = data[offset + i];
  19274. }
  19275. return out;
  19276. };
  19277. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19278. var data = this._data;
  19279. var dimSize = this._dimSize;
  19280. for (var dim = 0; dim < dimSize; dim++) {
  19281. var dimExtent = extent[dim];
  19282. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19283. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19284. var count = end - start;
  19285. var arr = storage[dim];
  19286. for (var i = 0; i < count; i++) {
  19287. // appendData with TypedArray will always do replace in provider.
  19288. var val = data[i * dimSize + dim];
  19289. arr[start + i] = val;
  19290. val < min && (min = val);
  19291. val > max && (max = val);
  19292. }
  19293. dimExtent[0] = min;
  19294. dimExtent[1] = max;
  19295. }
  19296. };
  19297. var countForTypedArray = function () {
  19298. return this._data ? this._data.length / this._dimSize : 0;
  19299. };
  19300. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19301. pure: true,
  19302. appendData: appendDataSimply
  19303. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19304. pure: true,
  19305. appendData: function () {
  19306. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19307. }
  19308. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19309. pure: true,
  19310. appendData: appendDataSimply
  19311. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19312. pure: true,
  19313. appendData: function (newData) {
  19314. var data = this._data;
  19315. each(newData, function (newCol, key) {
  19316. var oldCol = data[key] || (data[key] = []);
  19317. for (var i = 0; i < (newCol || []).length; i++) {
  19318. oldCol.push(newCol[i]);
  19319. }
  19320. });
  19321. }
  19322. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19323. appendData: appendDataSimply
  19324. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19325. persistent: false,
  19326. pure: true,
  19327. appendData: function (newData) {
  19328. if ("development" !== 'production') {
  19329. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19330. }
  19331. this._data = newData;
  19332. },
  19333. // Clean self if data is already used.
  19334. clean: function () {
  19335. // PENDING
  19336. this._offset += this.count();
  19337. this._data = null;
  19338. }
  19339. }, _a);
  19340. function appendDataSimply(newData) {
  19341. for (var i = 0; i < newData.length; i++) {
  19342. this._data.push(newData[i]);
  19343. }
  19344. }
  19345. }();
  19346. return DefaultDataProvider;
  19347. }();
  19348. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19349. return rawData[idx];
  19350. };
  19351. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19352. return rawData[idx + startIndex];
  19353. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19354. idx += startIndex;
  19355. var item = out || [];
  19356. var data = rawData;
  19357. for (var i = 0; i < data.length; i++) {
  19358. var row = data[i];
  19359. item[i] = row ? row[idx] : null;
  19360. }
  19361. return item;
  19362. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19363. var item = out || [];
  19364. for (var i = 0; i < dimsDef.length; i++) {
  19365. var dimName = dimsDef[i].name;
  19366. if ("development" !== 'production') {
  19367. if (dimName == null) {
  19368. throw new Error();
  19369. }
  19370. }
  19371. var col = rawData[dimName];
  19372. item[i] = col ? col[idx] : null;
  19373. }
  19374. return item;
  19375. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19376. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19377. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19378. if ("development" !== 'production') {
  19379. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19380. }
  19381. return method;
  19382. }
  19383. var countSimply = function (rawData, startIndex, dimsDef) {
  19384. return rawData.length;
  19385. };
  19386. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19387. return Math.max(0, rawData.length - startIndex);
  19388. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19389. var row = rawData[0];
  19390. return row ? Math.max(0, row.length - startIndex) : 0;
  19391. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19392. var dimName = dimsDef[0].name;
  19393. if ("development" !== 'production') {
  19394. if (dimName == null) {
  19395. throw new Error();
  19396. }
  19397. }
  19398. var col = rawData[dimName];
  19399. return col ? col.length : 0;
  19400. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19401. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19402. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19403. if ("development" !== 'production') {
  19404. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19405. }
  19406. return method;
  19407. }
  19408. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19409. return dataItem[dimIndex];
  19410. };
  19411. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19412. return dataItem[property];
  19413. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19414. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19415. // dataItem is {coord: [...]}
  19416. var value = getDataItemValue(dataItem);
  19417. return !(value instanceof Array) ? value : value[dimIndex];
  19418. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19419. function getRawSourceValueGetter(sourceFormat) {
  19420. var method = rawSourceValueGetterMap[sourceFormat];
  19421. if ("development" !== 'production') {
  19422. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19423. }
  19424. return method;
  19425. }
  19426. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19427. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19428. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19429. // Consider persistent.
  19430. // Caution: why use raw value to display on label or tooltip?
  19431. // A reason is to avoid format. For example time value we do not know
  19432. // how to format is expected. More over, if stack is used, calculated
  19433. // value may be 0.91000000001, which have brings trouble to display.
  19434. // TODO: consider how to treat null/undefined/NaN when display?
  19435. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  19436. // Otherwise, return OptionDataValue.
  19437. dim) {
  19438. if (!data) {
  19439. return;
  19440. } // Consider data may be not persistent.
  19441. var dataItem = data.getRawDataItem(dataIndex);
  19442. if (dataItem == null) {
  19443. return;
  19444. }
  19445. var store = data.getStore();
  19446. var sourceFormat = store.getSource().sourceFormat;
  19447. if (dim != null) {
  19448. var dimIndex = data.getDimensionIndex(dim);
  19449. var property = store.getDimensionProperty(dimIndex);
  19450. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19451. } else {
  19452. var result = dataItem;
  19453. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19454. result = getDataItemValue(dataItem);
  19455. }
  19456. return result;
  19457. }
  19458. }
  19459. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19460. var DataFormatMixin =
  19461. /** @class */
  19462. function () {
  19463. function DataFormatMixin() {}
  19464. /**
  19465. * Get params for formatter
  19466. */
  19467. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19468. var data = this.getData(dataType);
  19469. var rawValue = this.getRawValue(dataIndex, dataType);
  19470. var rawDataIndex = data.getRawIndex(dataIndex);
  19471. var name = data.getName(dataIndex);
  19472. var itemOpt = data.getRawDataItem(dataIndex);
  19473. var style = data.getItemVisual(dataIndex, 'style');
  19474. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19475. var borderColor = style && style.stroke;
  19476. var mainType = this.mainType;
  19477. var isSeries = mainType === 'series';
  19478. var userOutput = data.userOutput && data.userOutput.get();
  19479. return {
  19480. componentType: mainType,
  19481. componentSubType: this.subType,
  19482. componentIndex: this.componentIndex,
  19483. seriesType: isSeries ? this.subType : null,
  19484. seriesIndex: this.seriesIndex,
  19485. seriesId: isSeries ? this.id : null,
  19486. seriesName: isSeries ? this.name : null,
  19487. name: name,
  19488. dataIndex: rawDataIndex,
  19489. data: itemOpt,
  19490. dataType: dataType,
  19491. value: rawValue,
  19492. color: color,
  19493. borderColor: borderColor,
  19494. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19495. encode: userOutput ? userOutput.encode : null,
  19496. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19497. $vars: ['seriesName', 'name', 'value']
  19498. };
  19499. };
  19500. /**
  19501. * Format label
  19502. * @param dataIndex
  19503. * @param status 'normal' by default
  19504. * @param dataType
  19505. * @param labelDimIndex Only used in some chart that
  19506. * use formatter in different dimensions, like radar.
  19507. * @param formatter Formatter given outside.
  19508. * @return return null/undefined if no formatter
  19509. */
  19510. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19511. status = status || 'normal';
  19512. var data = this.getData(dataType);
  19513. var params = this.getDataParams(dataIndex, dataType);
  19514. if (extendParams) {
  19515. params.value = extendParams.interpolatedValue;
  19516. }
  19517. if (labelDimIndex != null && isArray(params.value)) {
  19518. params.value = params.value[labelDimIndex];
  19519. }
  19520. if (!formatter) {
  19521. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  19522. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19523. }
  19524. if (isFunction(formatter)) {
  19525. params.status = status;
  19526. params.dimensionIndex = labelDimIndex;
  19527. return formatter(params);
  19528. } else if (isString(formatter)) {
  19529. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19530. // Do not support '}' in dim name util have to.
  19531. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19532. var len = dimStr.length;
  19533. var dimLoose = dimStr;
  19534. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19535. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19536. if ("development" !== 'production') {
  19537. if (isNaN(dimLoose)) {
  19538. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19539. }
  19540. }
  19541. }
  19542. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19543. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19544. var dimIndex = data.getDimensionIndex(dimLoose);
  19545. if (dimIndex >= 0) {
  19546. val = extendParams.interpolatedValue[dimIndex];
  19547. }
  19548. }
  19549. return val != null ? val + '' : '';
  19550. });
  19551. }
  19552. };
  19553. /**
  19554. * Get raw value in option
  19555. */
  19556. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19557. return retrieveRawValue(this.getData(dataType), idx);
  19558. };
  19559. /**
  19560. * Should be implemented.
  19561. * @param {number} dataIndex
  19562. * @param {boolean} [multipleSeries=false]
  19563. * @param {string} [dataType]
  19564. */
  19565. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19566. // Empty function
  19567. return;
  19568. };
  19569. return DataFormatMixin;
  19570. }();
  19571. // but guess little chance has been used outside. Do we need to backward
  19572. // compat it?
  19573. // type TooltipFormatResultLegacyObject = {
  19574. // // `html` means the markup language text, either in 'html' or 'richText'.
  19575. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  19576. // // string. But still support it for backward compatibility.
  19577. // html: string;
  19578. // markers: Dictionary<ColorString>;
  19579. // };
  19580. /**
  19581. * For backward compat, normalize the return from `formatTooltip`.
  19582. */
  19583. function normalizeTooltipFormatResult(result) {
  19584. var markupText; // let markers: Dictionary<ColorString>;
  19585. var markupFragment;
  19586. if (isObject(result)) {
  19587. if (result.type) {
  19588. markupFragment = result;
  19589. } else {
  19590. if ("development" !== 'production') {
  19591. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19592. }
  19593. } // else {
  19594. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19595. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19596. // if (markersExisting) {
  19597. // markers = zrUtil.merge(markersExisting, markers);
  19598. // }
  19599. // }
  19600. } else {
  19601. markupText = result;
  19602. }
  19603. return {
  19604. text: markupText,
  19605. // markers: markers || markersExisting,
  19606. frag: markupFragment
  19607. };
  19608. }
  19609. /**
  19610. * @param {Object} define
  19611. * @return See the return of `createTask`.
  19612. */
  19613. function createTask(define) {
  19614. return new Task(define);
  19615. }
  19616. var Task =
  19617. /** @class */
  19618. function () {
  19619. function Task(define) {
  19620. define = define || {};
  19621. this._reset = define.reset;
  19622. this._plan = define.plan;
  19623. this._count = define.count;
  19624. this._onDirty = define.onDirty;
  19625. this._dirty = true;
  19626. }
  19627. /**
  19628. * @param step Specified step.
  19629. * @param skip Skip customer perform call.
  19630. * @param modBy Sampling window size.
  19631. * @param modDataCount Sampling count.
  19632. * @return whether unfinished.
  19633. */
  19634. Task.prototype.perform = function (performArgs) {
  19635. var upTask = this._upstream;
  19636. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19637. // Pull data. Must pull data each time, because context.data
  19638. // may be updated by Series.setData.
  19639. if (this._dirty && upTask) {
  19640. var context = this.context;
  19641. context.data = context.outputData = upTask.context.outputData;
  19642. }
  19643. if (this.__pipeline) {
  19644. this.__pipeline.currentTask = this;
  19645. }
  19646. var planResult;
  19647. if (this._plan && !skip) {
  19648. planResult = this._plan(this.context);
  19649. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19650. // elements uniformed distributed when progress, especially when moving or zooming.
  19651. var lastModBy = normalizeModBy(this._modBy);
  19652. var lastModDataCount = this._modDataCount || 0;
  19653. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19654. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19655. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19656. planResult = 'reset';
  19657. }
  19658. function normalizeModBy(val) {
  19659. !(val >= 1) && (val = 1); // jshint ignore:line
  19660. return val;
  19661. }
  19662. var forceFirstProgress;
  19663. if (this._dirty || planResult === 'reset') {
  19664. this._dirty = false;
  19665. forceFirstProgress = this._doReset(skip);
  19666. }
  19667. this._modBy = modBy;
  19668. this._modDataCount = modDataCount;
  19669. var step = performArgs && performArgs.step;
  19670. if (upTask) {
  19671. if ("development" !== 'production') {
  19672. assert(upTask._outputDueEnd != null);
  19673. }
  19674. this._dueEnd = upTask._outputDueEnd;
  19675. } // DataTask or overallTask
  19676. else {
  19677. if ("development" !== 'production') {
  19678. assert(!this._progress || this._count);
  19679. }
  19680. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19681. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19682. // If no progress, pass index from upstream to downstream each time plan called.
  19683. if (this._progress) {
  19684. var start = this._dueIndex;
  19685. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19686. if (!skip && (forceFirstProgress || start < end)) {
  19687. var progress = this._progress;
  19688. if (isArray(progress)) {
  19689. for (var i = 0; i < progress.length; i++) {
  19690. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19691. }
  19692. } else {
  19693. this._doProgress(progress, start, end, modBy, modDataCount);
  19694. }
  19695. }
  19696. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19697. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19698. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19699. if ("development" !== 'production') {
  19700. // ??? Can not rollback.
  19701. assert(outputDueEnd >= this._outputDueEnd);
  19702. }
  19703. this._outputDueEnd = outputDueEnd;
  19704. } else {
  19705. // (1) Some overall task has no progress.
  19706. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19707. // This should always be performed so it can be passed to downstream.
  19708. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19709. }
  19710. return this.unfinished();
  19711. };
  19712. Task.prototype.dirty = function () {
  19713. this._dirty = true;
  19714. this._onDirty && this._onDirty(this.context);
  19715. };
  19716. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19717. iterator.reset(start, end, modBy, modDataCount);
  19718. this._callingProgress = progress;
  19719. this._callingProgress({
  19720. start: start,
  19721. end: end,
  19722. count: end - start,
  19723. next: iterator.next
  19724. }, this.context);
  19725. };
  19726. Task.prototype._doReset = function (skip) {
  19727. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19728. this._settedOutputEnd = null;
  19729. var progress;
  19730. var forceFirstProgress;
  19731. if (!skip && this._reset) {
  19732. progress = this._reset(this.context);
  19733. if (progress && progress.progress) {
  19734. forceFirstProgress = progress.forceFirstProgress;
  19735. progress = progress.progress;
  19736. } // To simplify no progress checking, array must has item.
  19737. if (isArray(progress) && !progress.length) {
  19738. progress = null;
  19739. }
  19740. }
  19741. this._progress = progress;
  19742. this._modBy = this._modDataCount = null;
  19743. var downstream = this._downstream;
  19744. downstream && downstream.dirty();
  19745. return forceFirstProgress;
  19746. };
  19747. Task.prototype.unfinished = function () {
  19748. return this._progress && this._dueIndex < this._dueEnd;
  19749. };
  19750. /**
  19751. * @param downTask The downstream task.
  19752. * @return The downstream task.
  19753. */
  19754. Task.prototype.pipe = function (downTask) {
  19755. if ("development" !== 'production') {
  19756. assert(downTask && !downTask._disposed && downTask !== this);
  19757. } // If already downstream, do not dirty downTask.
  19758. if (this._downstream !== downTask || this._dirty) {
  19759. this._downstream = downTask;
  19760. downTask._upstream = this;
  19761. downTask.dirty();
  19762. }
  19763. };
  19764. Task.prototype.dispose = function () {
  19765. if (this._disposed) {
  19766. return;
  19767. }
  19768. this._upstream && (this._upstream._downstream = null);
  19769. this._downstream && (this._downstream._upstream = null);
  19770. this._dirty = false;
  19771. this._disposed = true;
  19772. };
  19773. Task.prototype.getUpstream = function () {
  19774. return this._upstream;
  19775. };
  19776. Task.prototype.getDownstream = function () {
  19777. return this._downstream;
  19778. };
  19779. Task.prototype.setOutputEnd = function (end) {
  19780. // This only happens in dataTask, dataZoom, map, currently.
  19781. // where dataZoom do not set end each time, but only set
  19782. // when reset. So we should record the set end, in case
  19783. // that the stub of dataZoom perform again and earse the
  19784. // set end by upstream.
  19785. this._outputDueEnd = this._settedOutputEnd = end;
  19786. };
  19787. return Task;
  19788. }();
  19789. var iterator = function () {
  19790. var end;
  19791. var current;
  19792. var modBy;
  19793. var modDataCount;
  19794. var winCount;
  19795. var it = {
  19796. reset: function (s, e, sStep, sCount) {
  19797. current = s;
  19798. end = e;
  19799. modBy = sStep;
  19800. modDataCount = sCount;
  19801. winCount = Math.ceil(modDataCount / modBy);
  19802. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19803. }
  19804. };
  19805. return it;
  19806. function sequentialNext() {
  19807. return current < end ? current++ : null;
  19808. }
  19809. function modNext() {
  19810. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19811. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19812. // Use normal linear rendering mode.
  19813. : current;
  19814. current++;
  19815. return result;
  19816. }
  19817. }(); // -----------------------------------------------------------------------------
  19818. // For stream debug (Should be commented out after used!)
  19819. // @usage: printTask(this, 'begin');
  19820. // @usage: printTask(this, null, {someExtraProp});
  19821. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19822. //
  19823. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19824. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19825. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19826. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19827. // let props = [];
  19828. // if (task.__pipeline) {
  19829. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19830. // props.push({text: '__idxInPipeline/total', value: val});
  19831. // } else {
  19832. // let stubCount = 0;
  19833. // task.agentStubMap.each(() => stubCount++);
  19834. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19835. // }
  19836. // props.push({text: 'uid', value: task.uidDebug});
  19837. // if (task.__pipeline) {
  19838. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19839. // task.agent && props.push(
  19840. // {text: 'stubFor', value: task.agent.uidDebug}
  19841. // );
  19842. // }
  19843. // props.push(
  19844. // {text: 'dirty', value: task._dirty},
  19845. // {text: 'dueIndex', value: task._dueIndex},
  19846. // {text: 'dueEnd', value: task._dueEnd},
  19847. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19848. // );
  19849. // if (extra) {
  19850. // Object.keys(extra).forEach(key => {
  19851. // props.push({text: key, value: extra[key]});
  19852. // });
  19853. // }
  19854. // let args = ['color: blue'];
  19855. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19856. // args.push('color: green', 'color: red'),
  19857. // `${item.text}: %c${item.value}`
  19858. // )).join('%c, ');
  19859. // console.log.apply(console, [msg].concat(args));
  19860. // // console.log(this);
  19861. // };
  19862. // window.printPipeline = function (task: any, prefix: string) {
  19863. // const pipeline = task.__pipeline;
  19864. // let currTask = pipeline.head;
  19865. // while (currTask) {
  19866. // window.printTask(currTask, prefix);
  19867. // currTask = currTask._downstream;
  19868. // }
  19869. // };
  19870. // window.showChain = function (chainHeadTask) {
  19871. // var chain = [];
  19872. // var task = chainHeadTask;
  19873. // while (task) {
  19874. // chain.push({
  19875. // task: task,
  19876. // up: task._upstream,
  19877. // down: task._downstream,
  19878. // idxInPipeline: task.__idxInPipeline
  19879. // });
  19880. // task = task._downstream;
  19881. // }
  19882. // return chain;
  19883. // };
  19884. // window.findTaskInChain = function (task, chainHeadTask) {
  19885. // let chain = window.showChain(chainHeadTask);
  19886. // let result = [];
  19887. // for (let i = 0; i < chain.length; i++) {
  19888. // let chainItem = chain[i];
  19889. // if (chainItem.task === task) {
  19890. // result.push(i);
  19891. // }
  19892. // }
  19893. // return result;
  19894. // };
  19895. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19896. // let chainA = window.showChain(chainHeadTaskA);
  19897. // for (let i = 0; i < chainA.length; i++) {
  19898. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19899. // }
  19900. // };
  19901. /**
  19902. * Convert raw the value in to inner value in List.
  19903. *
  19904. * [Performance sensitive]
  19905. *
  19906. * [Caution]: this is the key logic of user value parser.
  19907. * For backward compatibility, do not modify it until you have to!
  19908. */
  19909. function parseDataValue(value, // For high performance, do not omit the second param.
  19910. opt) {
  19911. // Performance sensitive.
  19912. var dimType = opt && opt.type;
  19913. if (dimType === 'ordinal') {
  19914. // If given value is a category string
  19915. return value;
  19916. }
  19917. if (dimType === 'time' // spead up when using timestamp
  19918. && !isNumber(value) && value != null && value !== '-') {
  19919. value = +parseDate(value);
  19920. } // dimType defaults 'number'.
  19921. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19922. // parse to NaN.
  19923. // number-like string (like ' 123 ') can be converted to a number.
  19924. // where null/undefined or other string will be converted to NaN.
  19925. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19926. // If object, also parse to NaN
  19927. : +value;
  19928. }
  19929. var valueParserMap = createHashMap({
  19930. 'number': function (val) {
  19931. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  19932. // Here the number parser can have loose rule:
  19933. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19934. return parseFloat(val);
  19935. },
  19936. 'time': function (val) {
  19937. // return timestamp.
  19938. return +parseDate(val);
  19939. },
  19940. 'trim': function (val) {
  19941. return isString(val) ? trim(val) : val;
  19942. }
  19943. });
  19944. function getRawValueParser(type) {
  19945. return valueParserMap.get(type);
  19946. }
  19947. var ORDER_COMPARISON_OP_MAP = {
  19948. lt: function (lval, rval) {
  19949. return lval < rval;
  19950. },
  19951. lte: function (lval, rval) {
  19952. return lval <= rval;
  19953. },
  19954. gt: function (lval, rval) {
  19955. return lval > rval;
  19956. },
  19957. gte: function (lval, rval) {
  19958. return lval >= rval;
  19959. }
  19960. };
  19961. var FilterOrderComparator =
  19962. /** @class */
  19963. function () {
  19964. function FilterOrderComparator(op, rval) {
  19965. if (!isNumber(rval)) {
  19966. var errMsg = '';
  19967. if ("development" !== 'production') {
  19968. errMsg = 'rvalue of "<", ">", "<=", ">=" can only be number in filter.';
  19969. }
  19970. throwError(errMsg);
  19971. }
  19972. this._opFn = ORDER_COMPARISON_OP_MAP[op];
  19973. this._rvalFloat = numericToNumber(rval);
  19974. } // Performance sensitive.
  19975. FilterOrderComparator.prototype.evaluate = function (lval) {
  19976. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19977. return isNumber(lval) ? this._opFn(lval, this._rvalFloat) : this._opFn(numericToNumber(lval), this._rvalFloat);
  19978. };
  19979. return FilterOrderComparator;
  19980. }();
  19981. var SortOrderComparator =
  19982. /** @class */
  19983. function () {
  19984. /**
  19985. * @param order by default: 'asc'
  19986. * @param incomparable by default: Always on the tail.
  19987. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19988. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  19989. */
  19990. function SortOrderComparator(order, incomparable) {
  19991. var isDesc = order === 'desc';
  19992. this._resultLT = isDesc ? 1 : -1;
  19993. if (incomparable == null) {
  19994. incomparable = isDesc ? 'min' : 'max';
  19995. }
  19996. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  19997. } // See [SORT_COMPARISON_RULE].
  19998. // Performance sensitive.
  19999. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  20000. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  20001. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  20002. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  20003. var lvalNotNumeric = isNaN(lvalFloat);
  20004. var rvalNotNumeric = isNaN(rvalFloat);
  20005. if (lvalNotNumeric) {
  20006. lvalFloat = this._incomparable;
  20007. }
  20008. if (rvalNotNumeric) {
  20009. rvalFloat = this._incomparable;
  20010. }
  20011. if (lvalNotNumeric && rvalNotNumeric) {
  20012. var lvalIsStr = isString(lval);
  20013. var rvalIsStr = isString(rval);
  20014. if (lvalIsStr) {
  20015. lvalFloat = rvalIsStr ? lval : 0;
  20016. }
  20017. if (rvalIsStr) {
  20018. rvalFloat = lvalIsStr ? rval : 0;
  20019. }
  20020. }
  20021. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  20022. };
  20023. return SortOrderComparator;
  20024. }();
  20025. var FilterEqualityComparator =
  20026. /** @class */
  20027. function () {
  20028. function FilterEqualityComparator(isEq, rval) {
  20029. this._rval = rval;
  20030. this._isEQ = isEq;
  20031. this._rvalTypeof = typeof rval;
  20032. this._rvalFloat = numericToNumber(rval);
  20033. } // Performance sensitive.
  20034. FilterEqualityComparator.prototype.evaluate = function (lval) {
  20035. var eqResult = lval === this._rval;
  20036. if (!eqResult) {
  20037. var lvalTypeof = typeof lval;
  20038. if (lvalTypeof !== this._rvalTypeof && (lvalTypeof === 'number' || this._rvalTypeof === 'number')) {
  20039. eqResult = numericToNumber(lval) === this._rvalFloat;
  20040. }
  20041. }
  20042. return this._isEQ ? eqResult : !eqResult;
  20043. };
  20044. return FilterEqualityComparator;
  20045. }();
  20046. /**
  20047. * [FILTER_COMPARISON_RULE]
  20048. * `lt`|`lte`|`gt`|`gte`:
  20049. * + rval must be a number. And lval will be converted to number (`numericToNumber`) to compare.
  20050. * `eq`:
  20051. * + If same type, compare with `===`.
  20052. * + If there is one number, convert to number (`numericToNumber`) to compare.
  20053. * + Else return `false`.
  20054. * `ne`:
  20055. * + Not `eq`.
  20056. *
  20057. *
  20058. * [SORT_COMPARISON_RULE]
  20059. * All the values are grouped into three categories:
  20060. * + "numeric" (number and numeric string)
  20061. * + "non-numeric-string" (string that excluding numeric string)
  20062. * + "others"
  20063. * "numeric" vs "numeric": values are ordered by number order.
  20064. * "non-numeric-string" vs "non-numeric-string": values are ordered by ES spec (#sec-abstract-relational-comparison).
  20065. * "others" vs "others": do not change order (always return 0).
  20066. * "numeric" vs "non-numeric-string": "non-numeric-string" is treated as "incomparable".
  20067. * "number" vs "others": "others" is treated as "incomparable".
  20068. * "non-numeric-string" vs "others": "others" is treated as "incomparable".
  20069. * "incomparable" will be seen as -Infinity or Infinity (depends on the settings).
  20070. * MEMO:
  20071. * Non-numeric string sort makes sense when we need to put the items with the same tag together.
  20072. * But if we support string sort, we still need to avoid the misleading like `'2' > '12'`,
  20073. * So we treat "numeric-string" sorted by number order rather than string comparison.
  20074. *
  20075. *
  20076. * [CHECK_LIST_OF_THE_RULE_DESIGN]
  20077. * + Do not support string comparison until required. And also need to
  20078. * avoid the misleading of "2" > "12".
  20079. * + Should avoid the misleading case:
  20080. * `" 22 " gte "22"` is `true` but `" 22 " eq "22"` is `false`.
  20081. * + JS bad case should be avoided: null <= 0, [] <= 0, ' ' <= 0, ...
  20082. * + Only "numeric" can be converted to comparable number, otherwise converted to NaN.
  20083. * See `util/number.ts#numericToNumber`.
  20084. *
  20085. * @return If `op` is not `RelationalOperator`, return null;
  20086. */
  20087. function createFilterComparator(op, rval) {
  20088. return op === 'eq' || op === 'ne' ? new FilterEqualityComparator(op === 'eq', rval) : hasOwn(ORDER_COMPARISON_OP_MAP, op) ? new FilterOrderComparator(op, rval) : null;
  20089. }
  20090. /**
  20091. * TODO: disable writable.
  20092. * This structure will be exposed to users.
  20093. */
  20094. var ExternalSource =
  20095. /** @class */
  20096. function () {
  20097. function ExternalSource() {}
  20098. ExternalSource.prototype.getRawData = function () {
  20099. // Only built-in transform available.
  20100. throw new Error('not supported');
  20101. };
  20102. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  20103. // Only built-in transform available.
  20104. throw new Error('not supported');
  20105. };
  20106. ExternalSource.prototype.cloneRawData = function () {
  20107. return;
  20108. };
  20109. /**
  20110. * @return If dimension not found, return null/undefined.
  20111. */
  20112. ExternalSource.prototype.getDimensionInfo = function (dim) {
  20113. return;
  20114. };
  20115. /**
  20116. * dimensions defined if and only if either:
  20117. * (a) dataset.dimensions are declared.
  20118. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  20119. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  20120. * the defined dimensions.
  20121. * Otherwise, `dimensionInfoAll` is determined by data columns.
  20122. * @return Always return an array (even empty array).
  20123. */
  20124. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  20125. return;
  20126. };
  20127. ExternalSource.prototype.count = function () {
  20128. return;
  20129. };
  20130. /**
  20131. * Only support by dimension index.
  20132. * No need to support by dimension name in transform function,
  20133. * because transform function is not case-specific, no need to use name literally.
  20134. */
  20135. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  20136. return;
  20137. };
  20138. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  20139. return;
  20140. };
  20141. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  20142. return parseDataValue(rawVal, dimInfo);
  20143. };
  20144. return ExternalSource;
  20145. }();
  20146. function createExternalSource(internalSource, externalTransform) {
  20147. var extSource = new ExternalSource();
  20148. var data = internalSource.data;
  20149. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  20150. var sourceHeaderCount = internalSource.startIndex;
  20151. var errMsg = '';
  20152. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  20153. // For the logic simplicity in transformer, only 'culumn' is
  20154. // supported in data transform. Otherwise, the `dimensionsDefine`
  20155. // might be detected by 'row', which probably confuses users.
  20156. if ("development" !== 'production') {
  20157. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  20158. }
  20159. throwError(errMsg);
  20160. } // [MEMO]
  20161. // Create a new dimensions structure for exposing.
  20162. // Do not expose all dimension info to users directly.
  20163. // Because the dimension is probably auto detected from data and not might reliable.
  20164. // Should not lead the transformers to think that is reliable and return it.
  20165. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20166. var dimensions = [];
  20167. var dimsByName = {};
  20168. var dimsDef = internalSource.dimensionsDefine;
  20169. if (dimsDef) {
  20170. each(dimsDef, function (dimDef, idx) {
  20171. var name = dimDef.name;
  20172. var dimDefExt = {
  20173. index: idx,
  20174. name: name,
  20175. displayName: dimDef.displayName
  20176. };
  20177. dimensions.push(dimDefExt); // Users probably do not specify dimension name. For simplicity, data transform
  20178. // does not generate dimension name.
  20179. if (name != null) {
  20180. // Dimension name should not be duplicated.
  20181. // For simplicity, data transform forbids name duplication, do not generate
  20182. // new name like module `completeDimensions.ts` did, but just tell users.
  20183. var errMsg_1 = '';
  20184. if (hasOwn(dimsByName, name)) {
  20185. if ("development" !== 'production') {
  20186. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  20187. }
  20188. throwError(errMsg_1);
  20189. }
  20190. dimsByName[name] = dimDefExt;
  20191. }
  20192. });
  20193. } // If dimension definitions are not defined and can not be detected.
  20194. // e.g., pure data `[[11, 22], ...]`.
  20195. else {
  20196. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  20197. // Do not generete name or anything others. The consequence process in
  20198. // `transform` or `series` probably have there own name generation strategry.
  20199. dimensions.push({
  20200. index: i
  20201. });
  20202. }
  20203. } // Implement public methods:
  20204. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20205. if (externalTransform.__isBuiltIn) {
  20206. extSource.getRawDataItem = function (dataIndex) {
  20207. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20208. };
  20209. extSource.getRawData = bind(getRawData, null, internalSource);
  20210. }
  20211. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  20212. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20213. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  20214. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  20215. extSource.retrieveValue = function (dataIndex, dimIndex) {
  20216. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20217. return retrieveValueFromItem(rawItem, dimIndex);
  20218. };
  20219. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  20220. if (dataItem == null) {
  20221. return;
  20222. }
  20223. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  20224. if (dimDef) {
  20225. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  20226. }
  20227. };
  20228. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  20229. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  20230. return extSource;
  20231. }
  20232. function getRawData(upstream) {
  20233. var sourceFormat = upstream.sourceFormat;
  20234. if (!isSupportedSourceFormat(sourceFormat)) {
  20235. var errMsg = '';
  20236. if ("development" !== 'production') {
  20237. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  20238. }
  20239. throwError(errMsg);
  20240. }
  20241. return upstream.data;
  20242. }
  20243. function cloneRawData(upstream) {
  20244. var sourceFormat = upstream.sourceFormat;
  20245. var data = upstream.data;
  20246. if (!isSupportedSourceFormat(sourceFormat)) {
  20247. var errMsg = '';
  20248. if ("development" !== 'production') {
  20249. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  20250. }
  20251. throwError(errMsg);
  20252. }
  20253. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  20254. var result = [];
  20255. for (var i = 0, len = data.length; i < len; i++) {
  20256. // Not strictly clone for performance
  20257. result.push(data[i].slice());
  20258. }
  20259. return result;
  20260. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  20261. var result = [];
  20262. for (var i = 0, len = data.length; i < len; i++) {
  20263. // Not strictly clone for performance
  20264. result.push(extend({}, data[i]));
  20265. }
  20266. return result;
  20267. }
  20268. }
  20269. function getDimensionInfo(dimensions, dimsByName, dim) {
  20270. if (dim == null) {
  20271. return;
  20272. } // Keep the same logic as `List::getDimension` did.
  20273. if (isNumber(dim) // If being a number-like string but not being defined a dimension name.
  20274. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  20275. return dimensions[dim];
  20276. } else if (hasOwn(dimsByName, dim)) {
  20277. return dimsByName[dim];
  20278. }
  20279. }
  20280. function cloneAllDimensionInfo(dimensions) {
  20281. return clone(dimensions);
  20282. }
  20283. var externalTransformMap = createHashMap();
  20284. function registerExternalTransform(externalTransform) {
  20285. externalTransform = clone(externalTransform);
  20286. var type = externalTransform.type;
  20287. var errMsg = '';
  20288. if (!type) {
  20289. if ("development" !== 'production') {
  20290. errMsg = 'Must have a `type` when `registerTransform`.';
  20291. }
  20292. throwError(errMsg);
  20293. }
  20294. var typeParsed = type.split(':');
  20295. if (typeParsed.length !== 2) {
  20296. if ("development" !== 'production') {
  20297. errMsg = 'Name must include namespace like "ns:regression".';
  20298. }
  20299. throwError(errMsg);
  20300. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20301. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20302. var isBuiltIn = false;
  20303. if (typeParsed[0] === 'echarts') {
  20304. type = typeParsed[1];
  20305. isBuiltIn = true;
  20306. }
  20307. externalTransform.__isBuiltIn = isBuiltIn;
  20308. externalTransformMap.set(type, externalTransform);
  20309. }
  20310. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20311. var pipedTransOption = normalizeToArray(rawTransOption);
  20312. var pipeLen = pipedTransOption.length;
  20313. var errMsg = '';
  20314. if (!pipeLen) {
  20315. if ("development" !== 'production') {
  20316. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20317. }
  20318. throwError(errMsg);
  20319. }
  20320. for (var i = 0, len = pipeLen; i < len; i++) {
  20321. var transOption = pipedTransOption[i];
  20322. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  20323. // piped transform only support single output, except the last one.
  20324. if (i !== len - 1) {
  20325. sourceList.length = Math.max(sourceList.length, 1);
  20326. }
  20327. }
  20328. return sourceList;
  20329. }
  20330. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  20331. pipeIndex) {
  20332. var errMsg = '';
  20333. if (!upSourceList.length) {
  20334. if ("development" !== 'production') {
  20335. errMsg = 'Must have at least one upstream dataset.';
  20336. }
  20337. throwError(errMsg);
  20338. }
  20339. if (!isObject(transOption)) {
  20340. if ("development" !== 'production') {
  20341. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20342. }
  20343. throwError(errMsg);
  20344. }
  20345. var transType = transOption.type;
  20346. var externalTransform = externalTransformMap.get(transType);
  20347. if (!externalTransform) {
  20348. if ("development" !== 'production') {
  20349. errMsg = 'Can not find transform on type "' + transType + '".';
  20350. }
  20351. throwError(errMsg);
  20352. } // Prepare source
  20353. var extUpSourceList = map(upSourceList, function (upSource) {
  20354. return createExternalSource(upSource, externalTransform);
  20355. });
  20356. var resultList = normalizeToArray(externalTransform.transform({
  20357. upstream: extUpSourceList[0],
  20358. upstreamList: extUpSourceList,
  20359. config: clone(transOption.config)
  20360. }));
  20361. if ("development" !== 'production') {
  20362. if (transOption.print) {
  20363. var printStrArr = map(resultList, function (extSource) {
  20364. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20365. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20366. }).join('\n');
  20367. log(printStrArr);
  20368. }
  20369. }
  20370. return map(resultList, function (result, resultIndex) {
  20371. var errMsg = '';
  20372. if (!isObject(result)) {
  20373. if ("development" !== 'production') {
  20374. errMsg = 'A transform should not return some empty results.';
  20375. }
  20376. throwError(errMsg);
  20377. }
  20378. if (!result.data) {
  20379. if ("development" !== 'production') {
  20380. errMsg = 'Transform result data should be not be null or undefined';
  20381. }
  20382. throwError(errMsg);
  20383. }
  20384. var sourceFormat = detectSourceFormat(result.data);
  20385. if (!isSupportedSourceFormat(sourceFormat)) {
  20386. if ("development" !== 'production') {
  20387. errMsg = 'Transform result data should be array rows or object rows.';
  20388. }
  20389. throwError(errMsg);
  20390. }
  20391. var resultMetaRawOption;
  20392. var firstUpSource = upSourceList[0];
  20393. /**
  20394. * Intuitively, the end users known the content of the original `dataset.source`,
  20395. * calucating the transform result in mind.
  20396. * Suppose the original `dataset.source` is:
  20397. * ```js
  20398. * [
  20399. * ['product', '2012', '2013', '2014', '2015'],
  20400. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20401. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20402. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20403. * ]
  20404. * ```
  20405. * The dimension info have to be detected from the source data.
  20406. * Some of the transformers (like filter, sort) will follow the dimension info
  20407. * of upstream, while others use new dimensions (like aggregate).
  20408. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20409. * We also allow transformers to ignore the output `dimensions` field, and
  20410. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20411. * dimensions in transformers.
  20412. *
  20413. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20414. */
  20415. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  20416. // dimensions definitions. We do not inherit anything from upstream.
  20417. && !result.dimensions) {
  20418. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result, because:
  20419. // (1) The returned data always does not contain header line and can not be used
  20420. // as dimension-detection. In this case we can not use "detected dimensions" of
  20421. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20422. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20423. // So the original detected header should be add to the result, otherwise they can not be read.
  20424. if (startIndex) {
  20425. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20426. }
  20427. resultMetaRawOption = {
  20428. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20429. sourceHeader: startIndex,
  20430. dimensions: firstUpSource.metaRawOption.dimensions
  20431. };
  20432. } else {
  20433. resultMetaRawOption = {
  20434. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20435. sourceHeader: 0,
  20436. dimensions: result.dimensions
  20437. };
  20438. }
  20439. return createSource(result.data, resultMetaRawOption, null);
  20440. });
  20441. }
  20442. function isSupportedSourceFormat(sourceFormat) {
  20443. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20444. }
  20445. var UNDEFINED = 'undefined';
  20446. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20447. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20448. // different from the Ctor of typed array.
  20449. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20450. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20451. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20452. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20453. /**
  20454. * Multi dimensional data store
  20455. */
  20456. var dataCtors = {
  20457. 'float': CtorFloat64Array,
  20458. 'int': CtorInt32Array,
  20459. // Ordinal data type can be string or int
  20460. 'ordinal': Array,
  20461. 'number': Array,
  20462. 'time': CtorFloat64Array
  20463. };
  20464. var defaultDimValueGetters;
  20465. function getIndicesCtor(rawCount) {
  20466. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20467. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20468. }
  20469. function getInitialExtent() {
  20470. return [Infinity, -Infinity];
  20471. }
  20472. function cloneChunk(originalChunk) {
  20473. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  20474. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20475. }
  20476. function prepareStore(store, dimIdx, dimType, end, append) {
  20477. var DataCtor = dataCtors[dimType || 'float'];
  20478. if (append) {
  20479. var oldStore = store[dimIdx];
  20480. var oldLen = oldStore && oldStore.length;
  20481. if (!(oldLen === end)) {
  20482. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  20483. // within the initial chunkSize.
  20484. for (var j = 0; j < oldLen; j++) {
  20485. newStore[j] = oldStore[j];
  20486. }
  20487. store[dimIdx] = newStore;
  20488. }
  20489. } else {
  20490. store[dimIdx] = new DataCtor(end);
  20491. }
  20492. }
  20493. /**
  20494. * Basically, DataStore API keep immutable.
  20495. */
  20496. var DataStore =
  20497. /** @class */
  20498. function () {
  20499. function DataStore() {
  20500. this._chunks = []; // It will not be calculated until needed.
  20501. this._rawExtent = [];
  20502. this._extent = [];
  20503. this._count = 0;
  20504. this._rawCount = 0;
  20505. this._calcDimNameToIdx = createHashMap();
  20506. }
  20507. /**
  20508. * Initialize from data
  20509. */
  20510. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20511. if ("development" !== 'production') {
  20512. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20513. }
  20514. this._provider = provider; // Clear
  20515. this._chunks = [];
  20516. this._indices = null;
  20517. this.getRawIndex = this._getRawIdxIdentity;
  20518. var source = provider.getSource();
  20519. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  20520. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  20521. this._rawExtent = [];
  20522. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20523. this._dimensions = map(inputDimensions, function (dim) {
  20524. if ("development" !== 'production') {
  20525. if (willRetrieveDataByName) {
  20526. assert(dim.property != null);
  20527. }
  20528. }
  20529. return {
  20530. // Only pick these two props. Not leak other properties like orderMeta.
  20531. type: dim.type,
  20532. property: dim.property
  20533. };
  20534. });
  20535. this._initDataFromProvider(0, provider.count());
  20536. };
  20537. DataStore.prototype.getProvider = function () {
  20538. return this._provider;
  20539. };
  20540. /**
  20541. * Caution: even when a `source` instance owned by a series, the created data store
  20542. * may still be shared by different sereis (the source hash does not use all `source`
  20543. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20544. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20545. * thus should not be fetch here.
  20546. */
  20547. DataStore.prototype.getSource = function () {
  20548. return this._provider.getSource();
  20549. };
  20550. /**
  20551. * @caution Only used in dataStack.
  20552. */
  20553. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20554. var calcDimNameToIdx = this._calcDimNameToIdx;
  20555. var dimensions = this._dimensions;
  20556. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20557. if (calcDimIdx != null) {
  20558. if (dimensions[calcDimIdx].type === type) {
  20559. return calcDimIdx;
  20560. }
  20561. } else {
  20562. calcDimIdx = dimensions.length;
  20563. }
  20564. dimensions[calcDimIdx] = {
  20565. type: type
  20566. };
  20567. calcDimNameToIdx.set(dimName, calcDimIdx);
  20568. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20569. this._rawExtent[calcDimIdx] = getInitialExtent();
  20570. return calcDimIdx;
  20571. };
  20572. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20573. var chunk = this._chunks[dimIdx];
  20574. var dim = this._dimensions[dimIdx];
  20575. var rawExtents = this._rawExtent;
  20576. var offset = dim.ordinalOffset || 0;
  20577. var len = chunk.length;
  20578. if (offset === 0) {
  20579. // We need to reset the rawExtent if collect is from start.
  20580. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20581. rawExtents[dimIdx] = getInitialExtent();
  20582. }
  20583. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  20584. for (var i = offset; i < len; i++) {
  20585. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20586. if (!isNaN(val)) {
  20587. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20588. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20589. }
  20590. }
  20591. dim.ordinalMeta = ordinalMeta;
  20592. dim.ordinalOffset = len;
  20593. dim.type = 'ordinal'; // Force to be ordinal
  20594. };
  20595. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20596. var dimInfo = this._dimensions[dimIdx];
  20597. var ordinalMeta = dimInfo.ordinalMeta;
  20598. return ordinalMeta;
  20599. };
  20600. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20601. var item = this._dimensions[dimIndex];
  20602. return item && item.property;
  20603. };
  20604. /**
  20605. * Caution: Can be only called on raw data (before `this._indices` created).
  20606. */
  20607. DataStore.prototype.appendData = function (data) {
  20608. if ("development" !== 'production') {
  20609. assert(!this._indices, 'appendData can only be called on raw data.');
  20610. }
  20611. var provider = this._provider;
  20612. var start = this.count();
  20613. provider.appendData(data);
  20614. var end = provider.count();
  20615. if (!provider.persistent) {
  20616. end += start;
  20617. }
  20618. if (start < end) {
  20619. this._initDataFromProvider(start, end, true);
  20620. }
  20621. return [start, end];
  20622. };
  20623. DataStore.prototype.appendValues = function (values, minFillLen) {
  20624. var chunks = this._chunks;
  20625. var dimensions = this._dimensions;
  20626. var dimLen = dimensions.length;
  20627. var rawExtent = this._rawExtent;
  20628. var start = this.count();
  20629. var end = start + Math.max(values.length, minFillLen || 0);
  20630. for (var i = 0; i < dimLen; i++) {
  20631. var dim = dimensions[i];
  20632. prepareStore(chunks, i, dim.type, end, true);
  20633. }
  20634. var emptyDataItem = [];
  20635. for (var idx = start; idx < end; idx++) {
  20636. var sourceIdx = idx - start; // Store the data by dimensions
  20637. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20638. var dim = dimensions[dimIdx];
  20639. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20640. chunks[dimIdx][idx] = val;
  20641. var dimRawExtent = rawExtent[dimIdx];
  20642. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20643. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20644. }
  20645. }
  20646. this._rawCount = this._count = end;
  20647. return {
  20648. start: start,
  20649. end: end
  20650. };
  20651. };
  20652. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20653. var provider = this._provider;
  20654. var chunks = this._chunks;
  20655. var dimensions = this._dimensions;
  20656. var dimLen = dimensions.length;
  20657. var rawExtent = this._rawExtent;
  20658. var dimNames = map(dimensions, function (dim) {
  20659. return dim.property;
  20660. });
  20661. for (var i = 0; i < dimLen; i++) {
  20662. var dim = dimensions[i];
  20663. if (!rawExtent[i]) {
  20664. rawExtent[i] = getInitialExtent();
  20665. }
  20666. prepareStore(chunks, i, dim.type, end, append);
  20667. }
  20668. if (provider.fillStorage) {
  20669. provider.fillStorage(start, end, chunks, rawExtent);
  20670. } else {
  20671. var dataItem = [];
  20672. for (var idx = start; idx < end; idx++) {
  20673. // NOTICE: Try not to write things into dataItem
  20674. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  20675. // [1, 2]
  20676. // 2
  20677. // Bar chart, line chart which uses category axis
  20678. // only gives the 'y' value. 'x' value is the indices of category
  20679. // Use a tempValue to normalize the value to be a (x, y) value
  20680. // Store the data by dimensions
  20681. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20682. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  20683. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20684. dimStorage[idx] = val;
  20685. var dimRawExtent = rawExtent[dimIdx];
  20686. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20687. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20688. }
  20689. }
  20690. }
  20691. if (!provider.persistent && provider.clean) {
  20692. // Clean unused data if data source is typed array.
  20693. provider.clean();
  20694. }
  20695. this._rawCount = this._count = end; // Reset data extent
  20696. this._extent = [];
  20697. };
  20698. DataStore.prototype.count = function () {
  20699. return this._count;
  20700. };
  20701. /**
  20702. * Get value. Return NaN if idx is out of range.
  20703. */
  20704. DataStore.prototype.get = function (dim, idx) {
  20705. if (!(idx >= 0 && idx < this._count)) {
  20706. return NaN;
  20707. }
  20708. var dimStore = this._chunks[dim];
  20709. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20710. };
  20711. DataStore.prototype.getValues = function (dimensions, idx) {
  20712. var values = [];
  20713. var dimArr = [];
  20714. if (idx == null) {
  20715. idx = dimensions; // TODO get all from store?
  20716. dimensions = []; // All dimensions
  20717. for (var i = 0; i < this._dimensions.length; i++) {
  20718. dimArr.push(i);
  20719. }
  20720. } else {
  20721. dimArr = dimensions;
  20722. }
  20723. for (var i = 0, len = dimArr.length; i < len; i++) {
  20724. values.push(this.get(dimArr[i], idx));
  20725. }
  20726. return values;
  20727. };
  20728. /**
  20729. * @param dim concrete dim
  20730. */
  20731. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20732. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20733. return NaN;
  20734. }
  20735. var dimStore = this._chunks[dim];
  20736. return dimStore ? dimStore[rawIdx] : NaN;
  20737. };
  20738. /**
  20739. * Get sum of data in one dimension
  20740. */
  20741. DataStore.prototype.getSum = function (dim) {
  20742. var dimData = this._chunks[dim];
  20743. var sum = 0;
  20744. if (dimData) {
  20745. for (var i = 0, len = this.count(); i < len; i++) {
  20746. var value = this.get(dim, i);
  20747. if (!isNaN(value)) {
  20748. sum += value;
  20749. }
  20750. }
  20751. }
  20752. return sum;
  20753. };
  20754. /**
  20755. * Get median of data in one dimension
  20756. */
  20757. DataStore.prototype.getMedian = function (dim) {
  20758. var dimDataArray = []; // map all data of one dimension
  20759. this.each([dim], function (val) {
  20760. if (!isNaN(val)) {
  20761. dimDataArray.push(val);
  20762. }
  20763. }); // TODO
  20764. // Use quick select?
  20765. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20766. return a - b;
  20767. });
  20768. var len = this.count(); // calculate median
  20769. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20770. };
  20771. /**
  20772. * Retrieve the index with given raw data index.
  20773. */
  20774. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20775. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20776. return -1;
  20777. }
  20778. if (!this._indices) {
  20779. return rawIndex;
  20780. } // Indices are ascending
  20781. var indices = this._indices; // If rawIndex === dataIndex
  20782. var rawDataIndex = indices[rawIndex];
  20783. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20784. return rawIndex;
  20785. }
  20786. var left = 0;
  20787. var right = this._count - 1;
  20788. while (left <= right) {
  20789. var mid = (left + right) / 2 | 0;
  20790. if (indices[mid] < rawIndex) {
  20791. left = mid + 1;
  20792. } else if (indices[mid] > rawIndex) {
  20793. right = mid - 1;
  20794. } else {
  20795. return mid;
  20796. }
  20797. }
  20798. return -1;
  20799. };
  20800. /**
  20801. * Retrieve the index of nearest value.
  20802. * @param dim
  20803. * @param value
  20804. * @param [maxDistance=Infinity]
  20805. * @return If and only if multiple indices have
  20806. * the same value, they are put to the result.
  20807. */
  20808. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20809. var chunks = this._chunks;
  20810. var dimData = chunks[dim];
  20811. var nearestIndices = [];
  20812. if (!dimData) {
  20813. return nearestIndices;
  20814. }
  20815. if (maxDistance == null) {
  20816. maxDistance = Infinity;
  20817. }
  20818. var minDist = Infinity;
  20819. var minDiff = -1;
  20820. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20821. for (var i = 0, len = this.count(); i < len; i++) {
  20822. var dataIndex = this.getRawIndex(i);
  20823. var diff = value - dimData[dataIndex];
  20824. var dist = Math.abs(diff);
  20825. if (dist <= maxDistance) {
  20826. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20827. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20828. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20829. // So we choose the one that `diff >= 0` in this case.
  20830. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20831. // should be push to `nearestIndices`.
  20832. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20833. minDist = dist;
  20834. minDiff = diff;
  20835. nearestIndicesLen = 0;
  20836. }
  20837. if (diff === minDiff) {
  20838. nearestIndices[nearestIndicesLen++] = i;
  20839. }
  20840. }
  20841. }
  20842. nearestIndices.length = nearestIndicesLen;
  20843. return nearestIndices;
  20844. };
  20845. DataStore.prototype.getIndices = function () {
  20846. var newIndices;
  20847. var indices = this._indices;
  20848. if (indices) {
  20849. var Ctor = indices.constructor;
  20850. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20851. if (Ctor === Array) {
  20852. newIndices = new Ctor(thisCount);
  20853. for (var i = 0; i < thisCount; i++) {
  20854. newIndices[i] = indices[i];
  20855. }
  20856. } else {
  20857. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20858. }
  20859. } else {
  20860. var Ctor = getIndicesCtor(this._rawCount);
  20861. newIndices = new Ctor(this.count());
  20862. for (var i = 0; i < newIndices.length; i++) {
  20863. newIndices[i] = i;
  20864. }
  20865. }
  20866. return newIndices;
  20867. };
  20868. /**
  20869. * Data filter.
  20870. */
  20871. DataStore.prototype.filter = function (dims, cb) {
  20872. if (!this._count) {
  20873. return this;
  20874. }
  20875. var newStore = this.clone();
  20876. var count = newStore.count();
  20877. var Ctor = getIndicesCtor(newStore._rawCount);
  20878. var newIndices = new Ctor(count);
  20879. var value = [];
  20880. var dimSize = dims.length;
  20881. var offset = 0;
  20882. var dim0 = dims[0];
  20883. var chunks = newStore._chunks;
  20884. for (var i = 0; i < count; i++) {
  20885. var keep = void 0;
  20886. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  20887. if (dimSize === 0) {
  20888. keep = cb(i);
  20889. } else if (dimSize === 1) {
  20890. var val = chunks[dim0][rawIdx];
  20891. keep = cb(val, i);
  20892. } else {
  20893. var k = 0;
  20894. for (; k < dimSize; k++) {
  20895. value[k] = chunks[dims[k]][rawIdx];
  20896. }
  20897. value[k] = i;
  20898. keep = cb.apply(null, value);
  20899. }
  20900. if (keep) {
  20901. newIndices[offset++] = rawIdx;
  20902. }
  20903. } // Set indices after filtered.
  20904. if (offset < count) {
  20905. newStore._indices = newIndices;
  20906. }
  20907. newStore._count = offset; // Reset data extent
  20908. newStore._extent = [];
  20909. newStore._updateGetRawIdx();
  20910. return newStore;
  20911. };
  20912. /**
  20913. * Select data in range. (For optimization of filter)
  20914. * (Manually inline code, support 5 million data filtering in data zoom.)
  20915. */
  20916. DataStore.prototype.selectRange = function (range) {
  20917. var newStore = this.clone();
  20918. var len = newStore._count;
  20919. if (!len) {
  20920. return this;
  20921. }
  20922. var dims = keys(range);
  20923. var dimSize = dims.length;
  20924. if (!dimSize) {
  20925. return this;
  20926. }
  20927. var originalCount = newStore.count();
  20928. var Ctor = getIndicesCtor(newStore._rawCount);
  20929. var newIndices = new Ctor(originalCount);
  20930. var offset = 0;
  20931. var dim0 = dims[0];
  20932. var min = range[dim0][0];
  20933. var max = range[dim0][1];
  20934. var storeArr = newStore._chunks;
  20935. var quickFinished = false;
  20936. if (!newStore._indices) {
  20937. // Extreme optimization for common case. About 2x faster in chrome.
  20938. var idx = 0;
  20939. if (dimSize === 1) {
  20940. var dimStorage = storeArr[dims[0]];
  20941. for (var i = 0; i < len; i++) {
  20942. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20943. // value indicates the line should be broken. But for the case like
  20944. // scatter plot, a data item with empty value will not be rendered,
  20945. // but the axis extent may be effected if some other dim of the data
  20946. // item has value. Fortunately it is not a significant negative effect.
  20947. if (val >= min && val <= max || isNaN(val)) {
  20948. newIndices[offset++] = idx;
  20949. }
  20950. idx++;
  20951. }
  20952. quickFinished = true;
  20953. } else if (dimSize === 2) {
  20954. var dimStorage = storeArr[dims[0]];
  20955. var dimStorage2 = storeArr[dims[1]];
  20956. var min2 = range[dims[1]][0];
  20957. var max2 = range[dims[1]][1];
  20958. for (var i = 0; i < len; i++) {
  20959. var val = dimStorage[i];
  20960. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20961. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20962. newIndices[offset++] = idx;
  20963. }
  20964. idx++;
  20965. }
  20966. quickFinished = true;
  20967. }
  20968. }
  20969. if (!quickFinished) {
  20970. if (dimSize === 1) {
  20971. for (var i = 0; i < originalCount; i++) {
  20972. var rawIndex = newStore.getRawIndex(i);
  20973. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20974. if (val >= min && val <= max || isNaN(val)) {
  20975. newIndices[offset++] = rawIndex;
  20976. }
  20977. }
  20978. } else {
  20979. for (var i = 0; i < originalCount; i++) {
  20980. var keep = true;
  20981. var rawIndex = newStore.getRawIndex(i);
  20982. for (var k = 0; k < dimSize; k++) {
  20983. var dimk = dims[k];
  20984. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20985. if (val < range[dimk][0] || val > range[dimk][1]) {
  20986. keep = false;
  20987. }
  20988. }
  20989. if (keep) {
  20990. newIndices[offset++] = newStore.getRawIndex(i);
  20991. }
  20992. }
  20993. }
  20994. } // Set indices after filtered.
  20995. if (offset < originalCount) {
  20996. newStore._indices = newIndices;
  20997. }
  20998. newStore._count = offset; // Reset data extent
  20999. newStore._extent = [];
  21000. newStore._updateGetRawIdx();
  21001. return newStore;
  21002. }; // /**
  21003. // * Data mapping to a plain array
  21004. // */
  21005. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  21006. // const result: any[] = [];
  21007. // this.each(dims, function () {
  21008. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  21009. // });
  21010. // return result;
  21011. // }
  21012. /**
  21013. * Data mapping to a new List with given dimensions
  21014. */
  21015. DataStore.prototype.map = function (dims, cb) {
  21016. // TODO only clone picked chunks.
  21017. var target = this.clone(dims);
  21018. this._updateDims(target, dims, cb);
  21019. return target;
  21020. };
  21021. /**
  21022. * @caution Danger!! Only used in dataStack.
  21023. */
  21024. DataStore.prototype.modify = function (dims, cb) {
  21025. this._updateDims(this, dims, cb);
  21026. };
  21027. DataStore.prototype._updateDims = function (target, dims, cb) {
  21028. var targetChunks = target._chunks;
  21029. var tmpRetValue = [];
  21030. var dimSize = dims.length;
  21031. var dataCount = target.count();
  21032. var values = [];
  21033. var rawExtent = target._rawExtent;
  21034. for (var i = 0; i < dims.length; i++) {
  21035. rawExtent[dims[i]] = getInitialExtent();
  21036. }
  21037. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  21038. var rawIndex = target.getRawIndex(dataIndex);
  21039. for (var k = 0; k < dimSize; k++) {
  21040. values[k] = targetChunks[dims[k]][rawIndex];
  21041. }
  21042. values[dimSize] = dataIndex;
  21043. var retValue = cb && cb.apply(null, values);
  21044. if (retValue != null) {
  21045. // a number or string (in oridinal dimension)?
  21046. if (typeof retValue !== 'object') {
  21047. tmpRetValue[0] = retValue;
  21048. retValue = tmpRetValue;
  21049. }
  21050. for (var i = 0; i < retValue.length; i++) {
  21051. var dim = dims[i];
  21052. var val = retValue[i];
  21053. var rawExtentOnDim = rawExtent[dim];
  21054. var dimStore = targetChunks[dim];
  21055. if (dimStore) {
  21056. dimStore[rawIndex] = val;
  21057. }
  21058. if (val < rawExtentOnDim[0]) {
  21059. rawExtentOnDim[0] = val;
  21060. }
  21061. if (val > rawExtentOnDim[1]) {
  21062. rawExtentOnDim[1] = val;
  21063. }
  21064. }
  21065. }
  21066. }
  21067. };
  21068. /**
  21069. * Large data down sampling using largest-triangle-three-buckets
  21070. * @param {string} valueDimension
  21071. * @param {number} targetCount
  21072. */
  21073. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  21074. var target = this.clone([valueDimension], true);
  21075. var targetStorage = target._chunks;
  21076. var dimStore = targetStorage[valueDimension];
  21077. var len = this.count();
  21078. var sampledIndex = 0;
  21079. var frameSize = Math.floor(1 / rate);
  21080. var currentRawIndex = this.getRawIndex(0);
  21081. var maxArea;
  21082. var area;
  21083. var nextRawIndex;
  21084. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len)); // First frame use the first data.
  21085. newIndices[sampledIndex++] = currentRawIndex;
  21086. for (var i = 1; i < len - 1; i += frameSize) {
  21087. var nextFrameStart = Math.min(i + frameSize, len - 1);
  21088. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  21089. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  21090. var avgY = 0;
  21091. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  21092. var rawIndex = this.getRawIndex(idx);
  21093. var y = dimStore[rawIndex];
  21094. if (isNaN(y)) {
  21095. continue;
  21096. }
  21097. avgY += y;
  21098. }
  21099. avgY /= nextFrameEnd - nextFrameStart;
  21100. var frameStart = i;
  21101. var frameEnd = Math.min(i + frameSize, len);
  21102. var pointAX = i - 1;
  21103. var pointAY = dimStore[currentRawIndex];
  21104. maxArea = -1;
  21105. nextRawIndex = frameStart;
  21106. var firstNaNIndex = -1;
  21107. var countNaN = 0; // Find a point from current frame that construct a triangle with largest area with previous selected point
  21108. // And the average of next frame.
  21109. for (var idx = frameStart; idx < frameEnd; idx++) {
  21110. var rawIndex = this.getRawIndex(idx);
  21111. var y = dimStore[rawIndex];
  21112. if (isNaN(y)) {
  21113. countNaN++;
  21114. if (firstNaNIndex < 0) {
  21115. firstNaNIndex = rawIndex;
  21116. }
  21117. continue;
  21118. } // Calculate triangle area over three buckets
  21119. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  21120. if (area > maxArea) {
  21121. maxArea = area;
  21122. nextRawIndex = rawIndex; // Next a is this b
  21123. }
  21124. }
  21125. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  21126. // Append first NaN point in every bucket.
  21127. // It is necessary to ensure the correct order of indices.
  21128. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  21129. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  21130. }
  21131. newIndices[sampledIndex++] = nextRawIndex;
  21132. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  21133. } // First frame use the last data.
  21134. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  21135. target._count = sampledIndex;
  21136. target._indices = newIndices;
  21137. target.getRawIndex = this._getRawIdx;
  21138. return target;
  21139. };
  21140. /**
  21141. * Large data down sampling on given dimension
  21142. * @param sampleIndex Sample index for name and id
  21143. */
  21144. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  21145. var target = this.clone([dimension], true);
  21146. var targetStorage = target._chunks;
  21147. var frameValues = [];
  21148. var frameSize = Math.floor(1 / rate);
  21149. var dimStore = targetStorage[dimension];
  21150. var len = this.count();
  21151. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  21152. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  21153. var offset = 0;
  21154. for (var i = 0; i < len; i += frameSize) {
  21155. // Last frame
  21156. if (frameSize > len - i) {
  21157. frameSize = len - i;
  21158. frameValues.length = frameSize;
  21159. }
  21160. for (var k = 0; k < frameSize; k++) {
  21161. var dataIdx = this.getRawIndex(i + k);
  21162. frameValues[k] = dimStore[dataIdx];
  21163. }
  21164. var value = sampleValue(frameValues);
  21165. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  21166. dimStore[sampleFrameIdx] = value;
  21167. if (value < rawExtentOnDim[0]) {
  21168. rawExtentOnDim[0] = value;
  21169. }
  21170. if (value > rawExtentOnDim[1]) {
  21171. rawExtentOnDim[1] = value;
  21172. }
  21173. newIndices[offset++] = sampleFrameIdx;
  21174. }
  21175. target._count = offset;
  21176. target._indices = newIndices;
  21177. target._updateGetRawIdx();
  21178. return target;
  21179. };
  21180. /**
  21181. * Data iteration
  21182. * @param ctx default this
  21183. * @example
  21184. * list.each('x', function (x, idx) {});
  21185. * list.each(['x', 'y'], function (x, y, idx) {});
  21186. * list.each(function (idx) {})
  21187. */
  21188. DataStore.prototype.each = function (dims, cb) {
  21189. if (!this._count) {
  21190. return;
  21191. }
  21192. var dimSize = dims.length;
  21193. var chunks = this._chunks;
  21194. for (var i = 0, len = this.count(); i < len; i++) {
  21195. var rawIdx = this.getRawIndex(i); // Simple optimization
  21196. switch (dimSize) {
  21197. case 0:
  21198. cb(i);
  21199. break;
  21200. case 1:
  21201. cb(chunks[dims[0]][rawIdx], i);
  21202. break;
  21203. case 2:
  21204. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  21205. break;
  21206. default:
  21207. var k = 0;
  21208. var value = [];
  21209. for (; k < dimSize; k++) {
  21210. value[k] = chunks[dims[k]][rawIdx];
  21211. } // Index
  21212. value[k] = i;
  21213. cb.apply(null, value);
  21214. }
  21215. }
  21216. };
  21217. /**
  21218. * Get extent of data in one dimension
  21219. */
  21220. DataStore.prototype.getDataExtent = function (dim) {
  21221. // Make sure use concrete dim as cache name.
  21222. var dimData = this._chunks[dim];
  21223. var initialExtent = getInitialExtent();
  21224. if (!dimData) {
  21225. return initialExtent;
  21226. } // Make more strict checkings to ensure hitting cache.
  21227. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  21228. // happened before filtering. We cache raw extent, which is not
  21229. // necessary to be cleared and recalculated when restore data.
  21230. var useRaw = !this._indices;
  21231. var dimExtent;
  21232. if (useRaw) {
  21233. return this._rawExtent[dim].slice();
  21234. }
  21235. dimExtent = this._extent[dim];
  21236. if (dimExtent) {
  21237. return dimExtent.slice();
  21238. }
  21239. dimExtent = initialExtent;
  21240. var min = dimExtent[0];
  21241. var max = dimExtent[1];
  21242. for (var i = 0; i < currEnd; i++) {
  21243. var rawIdx = this.getRawIndex(i);
  21244. var value = dimData[rawIdx];
  21245. value < min && (min = value);
  21246. value > max && (max = value);
  21247. }
  21248. dimExtent = [min, max];
  21249. this._extent[dim] = dimExtent;
  21250. return dimExtent;
  21251. };
  21252. /**
  21253. * Get raw data item
  21254. */
  21255. DataStore.prototype.getRawDataItem = function (idx) {
  21256. var rawIdx = this.getRawIndex(idx);
  21257. if (!this._provider.persistent) {
  21258. var val = [];
  21259. var chunks = this._chunks;
  21260. for (var i = 0; i < chunks.length; i++) {
  21261. val.push(chunks[i][rawIdx]);
  21262. }
  21263. return val;
  21264. } else {
  21265. return this._provider.getItem(rawIdx);
  21266. }
  21267. };
  21268. /**
  21269. * Clone shallow.
  21270. *
  21271. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  21272. */
  21273. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  21274. var target = new DataStore();
  21275. var chunks = this._chunks;
  21276. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  21277. obj[dimIdx] = true;
  21278. return obj;
  21279. }, {});
  21280. if (clonedDimsMap) {
  21281. for (var i = 0; i < chunks.length; i++) {
  21282. // Not clone if dim is not picked.
  21283. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  21284. }
  21285. } else {
  21286. target._chunks = chunks;
  21287. }
  21288. this._copyCommonProps(target);
  21289. if (!ignoreIndices) {
  21290. target._indices = this._cloneIndices();
  21291. }
  21292. target._updateGetRawIdx();
  21293. return target;
  21294. };
  21295. DataStore.prototype._copyCommonProps = function (target) {
  21296. target._count = this._count;
  21297. target._rawCount = this._rawCount;
  21298. target._provider = this._provider;
  21299. target._dimensions = this._dimensions;
  21300. target._extent = clone(this._extent);
  21301. target._rawExtent = clone(this._rawExtent);
  21302. };
  21303. DataStore.prototype._cloneIndices = function () {
  21304. if (this._indices) {
  21305. var Ctor = this._indices.constructor;
  21306. var indices = void 0;
  21307. if (Ctor === Array) {
  21308. var thisCount = this._indices.length;
  21309. indices = new Ctor(thisCount);
  21310. for (var i = 0; i < thisCount; i++) {
  21311. indices[i] = this._indices[i];
  21312. }
  21313. } else {
  21314. indices = new Ctor(this._indices);
  21315. }
  21316. return indices;
  21317. }
  21318. return null;
  21319. };
  21320. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21321. return idx;
  21322. };
  21323. DataStore.prototype._getRawIdx = function (idx) {
  21324. if (idx < this._count && idx >= 0) {
  21325. return this._indices[idx];
  21326. }
  21327. return -1;
  21328. };
  21329. DataStore.prototype._updateGetRawIdx = function () {
  21330. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21331. };
  21332. DataStore.internalField = function () {
  21333. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21334. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21335. }
  21336. defaultDimValueGetters = {
  21337. arrayRows: getDimValueSimply,
  21338. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21339. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21340. },
  21341. keyedColumns: getDimValueSimply,
  21342. original: function (dataItem, property, dataIndex, dimIndex) {
  21343. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21344. // If dataItem is an plain object with no value field, the let `value`
  21345. // will be assigned with the object, but it will be tread correctly
  21346. // in the `convertValue`.
  21347. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21348. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  21349. : value, this._dimensions[dimIndex]);
  21350. },
  21351. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21352. return dataItem[dimIndex];
  21353. }
  21354. };
  21355. }();
  21356. return DataStore;
  21357. }();
  21358. /**
  21359. * [REQUIREMENT_MEMO]:
  21360. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21361. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21362. * `root-dataset`. Them on `series` has higher priority.
  21363. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21364. * confuse users: whether those props indicate how to visit the upstream source or visit
  21365. * the transform result source, and some transforms has nothing to do with these props,
  21366. * and some transforms might have multiple upstream.
  21367. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21368. * declared in `root-dataset`.
  21369. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21370. * That is for reducing complexity in transforms.
  21371. * PENDING: Whether to provide transposition transform?
  21372. *
  21373. * [IMPLEMENTAION_MEMO]:
  21374. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21375. * They will not be calculated until `source` is about to be visited (to prevent from
  21376. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21377. *
  21378. * [DIMENSION_INHERIT_RULE]:
  21379. * By default the dimensions are inherited from ancestors, unless a transform return
  21380. * a new dimensions definition.
  21381. * Consider the case:
  21382. * ```js
  21383. * dataset: [{
  21384. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21385. * }, {
  21386. * transform: { type: 'filter', ... }
  21387. * }]
  21388. * dataset: [{
  21389. * dimension: ['Product', 'Sales', 'Prise'],
  21390. * source: [ ['Cookies', 321, 44.21], ...]
  21391. * }, {
  21392. * transform: { type: 'filter', ... }
  21393. * }]
  21394. * ```
  21395. * The two types of option should have the same behavior after transform.
  21396. *
  21397. *
  21398. * [SCENARIO]:
  21399. * (1) Provide source data directly:
  21400. * ```js
  21401. * series: {
  21402. * encode: {...},
  21403. * dimensions: [...]
  21404. * seriesLayoutBy: 'row',
  21405. * data: [[...]]
  21406. * }
  21407. * ```
  21408. * (2) Series refer to dataset.
  21409. * ```js
  21410. * series: [{
  21411. * encode: {...}
  21412. * // Ignore datasetIndex means `datasetIndex: 0`
  21413. * // and the dimensions defination in dataset is used
  21414. * }, {
  21415. * encode: {...},
  21416. * seriesLayoutBy: 'column',
  21417. * datasetIndex: 1
  21418. * }]
  21419. * ```
  21420. * (3) dataset transform
  21421. * ```js
  21422. * dataset: [{
  21423. * source: [...]
  21424. * }, {
  21425. * source: [...]
  21426. * }, {
  21427. * // By default from 0.
  21428. * transform: { type: 'filter', config: {...} }
  21429. * }, {
  21430. * // Piped.
  21431. * transform: [
  21432. * { type: 'filter', config: {...} },
  21433. * { type: 'sort', config: {...} }
  21434. * ]
  21435. * }, {
  21436. * id: 'regressionData',
  21437. * fromDatasetIndex: 1,
  21438. * // Third-party transform
  21439. * transform: { type: 'ecStat:regression', config: {...} }
  21440. * }, {
  21441. * // retrieve the extra result.
  21442. * id: 'regressionFormula',
  21443. * fromDatasetId: 'regressionData',
  21444. * fromTransformResult: 1
  21445. * }]
  21446. * ```
  21447. */
  21448. var SourceManager =
  21449. /** @class */
  21450. function () {
  21451. function SourceManager(sourceHost) {
  21452. // Cached source. Do not repeat calculating if not dirty.
  21453. this._sourceList = [];
  21454. this._storeList = []; // version sign of each upstream source manager.
  21455. this._upstreamSignList = [];
  21456. this._versionSignBase = 0;
  21457. this._dirty = true;
  21458. this._sourceHost = sourceHost;
  21459. }
  21460. /**
  21461. * Mark dirty.
  21462. */
  21463. SourceManager.prototype.dirty = function () {
  21464. this._setLocalSource([], []);
  21465. this._storeList = [];
  21466. this._dirty = true;
  21467. };
  21468. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21469. this._sourceList = sourceList;
  21470. this._upstreamSignList = upstreamSignList;
  21471. this._versionSignBase++;
  21472. if (this._versionSignBase > 9e10) {
  21473. this._versionSignBase = 0;
  21474. }
  21475. };
  21476. /**
  21477. * For detecting whether the upstream source is dirty, so that
  21478. * the local cached source (in `_sourceList`) should be discarded.
  21479. */
  21480. SourceManager.prototype._getVersionSign = function () {
  21481. return this._sourceHost.uid + '_' + this._versionSignBase;
  21482. };
  21483. /**
  21484. * Always return a source instance. Otherwise throw error.
  21485. */
  21486. SourceManager.prototype.prepareSource = function () {
  21487. // For the case that call `setOption` multiple time but no data changed,
  21488. // cache the result source to prevent from repeating transform.
  21489. if (this._isDirty()) {
  21490. this._createSource();
  21491. this._dirty = false;
  21492. }
  21493. };
  21494. SourceManager.prototype._createSource = function () {
  21495. this._setLocalSource([], []);
  21496. var sourceHost = this._sourceHost;
  21497. var upSourceMgrList = this._getUpstreamSourceManagers();
  21498. var hasUpstream = !!upSourceMgrList.length;
  21499. var resultSourceList;
  21500. var upstreamSignList;
  21501. if (isSeries(sourceHost)) {
  21502. var seriesModel = sourceHost;
  21503. var data = void 0;
  21504. var sourceFormat = void 0;
  21505. var upSource = void 0; // Has upstream dataset
  21506. if (hasUpstream) {
  21507. var upSourceMgr = upSourceMgrList[0];
  21508. upSourceMgr.prepareSource();
  21509. upSource = upSourceMgr.getSource();
  21510. data = upSource.data;
  21511. sourceFormat = upSource.sourceFormat;
  21512. upstreamSignList = [upSourceMgr._getVersionSign()];
  21513. } // Series data is from own.
  21514. else {
  21515. data = seriesModel.get('data', true);
  21516. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21517. upstreamSignList = [];
  21518. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21519. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21520. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21521. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21522. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21523. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21524. // but series need `seriesLayoutBy: 'row'`.
  21525. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  21526. // to avoid extra memory cost of high dimensional data.
  21527. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21528. resultSourceList = needsCreateSource ? [createSource(data, {
  21529. seriesLayoutBy: seriesLayoutBy,
  21530. sourceHeader: sourceHeader,
  21531. dimensions: dimensions
  21532. }, sourceFormat)] : [];
  21533. } else {
  21534. var datasetModel = sourceHost; // Has upstream dataset.
  21535. if (hasUpstream) {
  21536. var result = this._applyTransform(upSourceMgrList);
  21537. resultSourceList = result.sourceList;
  21538. upstreamSignList = result.upstreamSignList;
  21539. } // Is root dataset.
  21540. else {
  21541. var sourceData = datasetModel.get('source', true);
  21542. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21543. upstreamSignList = [];
  21544. }
  21545. }
  21546. if ("development" !== 'production') {
  21547. assert(resultSourceList && upstreamSignList);
  21548. }
  21549. this._setLocalSource(resultSourceList, upstreamSignList);
  21550. };
  21551. SourceManager.prototype._applyTransform = function (upMgrList) {
  21552. var datasetModel = this._sourceHost;
  21553. var transformOption = datasetModel.get('transform', true);
  21554. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21555. if ("development" !== 'production') {
  21556. assert(fromTransformResult != null || transformOption != null);
  21557. }
  21558. if (fromTransformResult != null) {
  21559. var errMsg = '';
  21560. if (upMgrList.length !== 1) {
  21561. if ("development" !== 'production') {
  21562. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21563. }
  21564. doThrow(errMsg);
  21565. }
  21566. }
  21567. var sourceList;
  21568. var upSourceList = [];
  21569. var upstreamSignList = [];
  21570. each(upMgrList, function (upMgr) {
  21571. upMgr.prepareSource();
  21572. var upSource = upMgr.getSource(fromTransformResult || 0);
  21573. var errMsg = '';
  21574. if (fromTransformResult != null && !upSource) {
  21575. if ("development" !== 'production') {
  21576. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21577. }
  21578. doThrow(errMsg);
  21579. }
  21580. upSourceList.push(upSource);
  21581. upstreamSignList.push(upMgr._getVersionSign());
  21582. });
  21583. if (transformOption) {
  21584. sourceList = applyDataTransform(transformOption, upSourceList, {
  21585. datasetIndex: datasetModel.componentIndex
  21586. });
  21587. } else if (fromTransformResult != null) {
  21588. sourceList = [cloneSourceShallow(upSourceList[0])];
  21589. }
  21590. return {
  21591. sourceList: sourceList,
  21592. upstreamSignList: upstreamSignList
  21593. };
  21594. };
  21595. SourceManager.prototype._isDirty = function () {
  21596. if (this._dirty) {
  21597. return true;
  21598. } // All sourceList is from the some upstream.
  21599. var upSourceMgrList = this._getUpstreamSourceManagers();
  21600. for (var i = 0; i < upSourceMgrList.length; i++) {
  21601. var upSrcMgr = upSourceMgrList[i];
  21602. if ( // Consider the case that there is ancestor diry, call it recursively.
  21603. // The performance is probably not an issue because usually the chain is not long.
  21604. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21605. return true;
  21606. }
  21607. }
  21608. };
  21609. /**
  21610. * @param sourceIndex By default 0, means "main source".
  21611. * In most cases there is only one source.
  21612. */
  21613. SourceManager.prototype.getSource = function (sourceIndex) {
  21614. sourceIndex = sourceIndex || 0;
  21615. var source = this._sourceList[sourceIndex];
  21616. if (!source) {
  21617. // Series may share source instance with dataset.
  21618. var upSourceMgrList = this._getUpstreamSourceManagers();
  21619. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21620. }
  21621. return source;
  21622. };
  21623. /**
  21624. *
  21625. * Get a data store which can be shared across series.
  21626. * Only available for series.
  21627. *
  21628. * @param seriesDimRequest Dimensions that are generated in series.
  21629. * Should have been sorted by `storeDimIndex` asc.
  21630. */
  21631. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21632. if ("development" !== 'production') {
  21633. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21634. }
  21635. var schema = seriesDimRequest.makeStoreSchema();
  21636. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21637. };
  21638. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21639. // TODO Can use other sourceIndex?
  21640. var sourceIndex = 0;
  21641. var storeList = this._storeList;
  21642. var cachedStoreMap = storeList[sourceIndex];
  21643. if (!cachedStoreMap) {
  21644. cachedStoreMap = storeList[sourceIndex] = {};
  21645. }
  21646. var cachedStore = cachedStoreMap[sourceReadKey];
  21647. if (!cachedStore) {
  21648. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21649. if (isSeries(this._sourceHost) && upSourceMgr) {
  21650. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21651. } else {
  21652. cachedStore = new DataStore(); // Always create store from source of series.
  21653. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21654. }
  21655. cachedStoreMap[sourceReadKey] = cachedStore;
  21656. }
  21657. return cachedStore;
  21658. };
  21659. /**
  21660. * PENDING: Is it fast enough?
  21661. * If no upstream, return empty array.
  21662. */
  21663. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21664. // Always get the relationship from the raw option.
  21665. // Do not cache the link of the dependency graph, so that
  21666. // there is no need to update them when change happens.
  21667. var sourceHost = this._sourceHost;
  21668. if (isSeries(sourceHost)) {
  21669. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21670. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21671. } else {
  21672. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21673. return datasetModel.getSourceManager();
  21674. });
  21675. }
  21676. };
  21677. SourceManager.prototype._getSourceMetaRawOption = function () {
  21678. var sourceHost = this._sourceHost;
  21679. var seriesLayoutBy;
  21680. var sourceHeader;
  21681. var dimensions;
  21682. if (isSeries(sourceHost)) {
  21683. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21684. sourceHeader = sourceHost.get('sourceHeader', true);
  21685. dimensions = sourceHost.get('dimensions', true);
  21686. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21687. else if (!this._getUpstreamSourceManagers().length) {
  21688. var model = sourceHost;
  21689. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21690. sourceHeader = model.get('sourceHeader', true);
  21691. dimensions = model.get('dimensions', true);
  21692. }
  21693. return {
  21694. seriesLayoutBy: seriesLayoutBy,
  21695. sourceHeader: sourceHeader,
  21696. dimensions: dimensions
  21697. };
  21698. };
  21699. return SourceManager;
  21700. }();
  21701. // disable the transform merge, but do not disable transform clone from rawOption.
  21702. function disableTransformOptionMerge(datasetModel) {
  21703. var transformOption = datasetModel.option.transform;
  21704. transformOption && setAsPrimitive(datasetModel.option.transform);
  21705. }
  21706. function isSeries(sourceHost) {
  21707. // Avoid circular dependency with Series.ts
  21708. return sourceHost.mainType === 'series';
  21709. }
  21710. function doThrow(errMsg) {
  21711. throw new Error(errMsg);
  21712. }
  21713. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  21714. function getTooltipTextStyle(textStyle, renderMode) {
  21715. var nameFontColor = textStyle.color || '#6e7079';
  21716. var nameFontSize = textStyle.fontSize || 12;
  21717. var nameFontWeight = textStyle.fontWeight || '400';
  21718. var valueFontColor = textStyle.color || '#464646';
  21719. var valueFontSize = textStyle.fontSize || 14;
  21720. var valueFontWeight = textStyle.fontWeight || '900';
  21721. if (renderMode === 'html') {
  21722. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21723. return {
  21724. // eslint-disable-next-line max-len
  21725. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21726. // eslint-disable-next-line max-len
  21727. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21728. };
  21729. } else {
  21730. return {
  21731. nameStyle: {
  21732. fontSize: nameFontSize,
  21733. fill: nameFontColor,
  21734. fontWeight: nameFontWeight
  21735. },
  21736. valueStyle: {
  21737. fontSize: valueFontSize,
  21738. fill: valueFontColor,
  21739. fontWeight: valueFontWeight
  21740. }
  21741. };
  21742. }
  21743. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21744. // (value from UI design)
  21745. var HTML_GAPS = [0, 10, 20, 30];
  21746. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  21747. function createTooltipMarkup(type, option) {
  21748. option.type = type;
  21749. return option;
  21750. }
  21751. function isSectionFragment(frag) {
  21752. return frag.type === 'section';
  21753. }
  21754. function getBuilder(frag) {
  21755. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21756. }
  21757. function getBlockGapLevel(frag) {
  21758. if (isSectionFragment(frag)) {
  21759. var gapLevel_1 = 0;
  21760. var subBlockLen = frag.blocks.length;
  21761. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21762. each(frag.blocks, function (subBlock) {
  21763. var subGapLevel = getBlockGapLevel(subBlock); // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21764. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21765. if (subGapLevel >= gapLevel_1) {
  21766. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && ( // 0 always can not be readable gap level.
  21767. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  21768. // look weird in case `multipleSeries`.
  21769. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21770. }
  21771. });
  21772. return gapLevel_1;
  21773. }
  21774. return 0;
  21775. }
  21776. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21777. var noHeader = fragment.noHeader;
  21778. var gaps = getGap(getBlockGapLevel(fragment));
  21779. var subMarkupTextList = [];
  21780. var subBlocks = fragment.blocks || [];
  21781. assert(!subBlocks || isArray(subBlocks));
  21782. subBlocks = subBlocks || [];
  21783. var orderMode = ctx.orderMode;
  21784. if (fragment.sortBlocks && orderMode) {
  21785. subBlocks = subBlocks.slice();
  21786. var orderMap = {
  21787. valueAsc: 'asc',
  21788. valueDesc: 'desc'
  21789. };
  21790. if (hasOwn(orderMap, orderMode)) {
  21791. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21792. subBlocks.sort(function (a, b) {
  21793. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21794. });
  21795. } // FIXME 'seriesDesc' necessary?
  21796. else if (orderMode === 'seriesDesc') {
  21797. subBlocks.reverse();
  21798. }
  21799. }
  21800. each(subBlocks, function (subBlock, idx) {
  21801. var valueFormatter = fragment.valueFormatter;
  21802. var subMarkupText = getBuilder(subBlock)( // Inherit valueFormatter
  21803. valueFormatter ? extend(extend({}, ctx), {
  21804. valueFormatter: valueFormatter
  21805. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21806. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21807. });
  21808. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21809. if (noHeader) {
  21810. return subMarkupText;
  21811. }
  21812. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21813. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21814. if (ctx.renderMode === 'richText') {
  21815. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21816. } else {
  21817. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21818. }
  21819. }
  21820. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21821. var renderMode = ctx.renderMode;
  21822. var noName = fragment.noName;
  21823. var noValue = fragment.noValue;
  21824. var noMarker = !fragment.markerType;
  21825. var name = fragment.name;
  21826. var useUTC = ctx.useUTC;
  21827. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  21828. value = isArray(value) ? value : [value];
  21829. return map(value, function (val, idx) {
  21830. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21831. });
  21832. };
  21833. if (noName && noValue) {
  21834. return;
  21835. }
  21836. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21837. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21838. var valueTypeOption = fragment.valueType;
  21839. var readableValueList = noValue ? [] : valueFormatter(fragment.value);
  21840. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  21841. var valueCloseToMarker = !noMarker && noName;
  21842. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21843. nameStyle = _a.nameStyle,
  21844. valueStyle = _a.valueStyle;
  21845. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  21846. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21847. }
  21848. /**
  21849. * @return markupText. null/undefined means no content.
  21850. */
  21851. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21852. if (!fragment) {
  21853. return;
  21854. }
  21855. var builder = getBuilder(fragment);
  21856. var ctx = {
  21857. useUTC: useUTC,
  21858. renderMode: renderMode,
  21859. orderMode: orderMode,
  21860. markupStyleCreator: markupStyleCreator,
  21861. valueFormatter: fragment.valueFormatter
  21862. };
  21863. return builder(ctx, fragment, 0, toolTipTextStyle);
  21864. }
  21865. function getGap(gapLevel) {
  21866. return {
  21867. html: HTML_GAPS[gapLevel],
  21868. richText: RICH_TEXT_GAPS[gapLevel]
  21869. };
  21870. }
  21871. function wrapBlockHTML(encodedContent, topGap) {
  21872. var clearfix = '<div style="clear:both"></div>';
  21873. var marginCSS = "margin: " + topGap + "px 0 0";
  21874. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21875. }
  21876. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21877. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21878. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21879. }
  21880. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21881. // Do not too close to marker, considering there are multiple values separated by spaces.
  21882. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21883. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21884. valueList = isArray(valueList) ? valueList : [valueList];
  21885. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  21886. + map(valueList, function (value) {
  21887. return encodeHTML(value);
  21888. }).join('&nbsp;&nbsp;') + '</span>';
  21889. }
  21890. function wrapInlineNameRichText(ctx, name, style) {
  21891. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21892. }
  21893. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  21894. var styles = [style];
  21895. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21896. alignRight && styles.push({
  21897. padding: [0, 0, 0, paddingLeft],
  21898. align: 'right'
  21899. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  21900. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  21901. }
  21902. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21903. var style = series.getData().getItemVisual(dataIndex, 'style');
  21904. var color = style[series.visualDrawType];
  21905. return convertToColorString(color);
  21906. }
  21907. function getPaddingFromTooltipModel(model, renderMode) {
  21908. var padding = model.get('padding');
  21909. return padding != null ? padding // We give slightly different to look pretty.
  21910. : renderMode === 'richText' ? [8, 10] : 10;
  21911. }
  21912. /**
  21913. * The major feature is generate styles for `renderMode: 'richText'`.
  21914. * But it also serves `renderMode: 'html'` to provide
  21915. * "renderMode-independent" API.
  21916. */
  21917. var TooltipMarkupStyleCreator =
  21918. /** @class */
  21919. function () {
  21920. function TooltipMarkupStyleCreator() {
  21921. this.richTextStyles = {}; // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  21922. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  21923. // rather than static shared by all creators (which will cause it increase to fast).
  21924. this._nextStyleNameId = getRandomIdBase();
  21925. }
  21926. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  21927. return '__EC_aUTo_' + this._nextStyleNameId++;
  21928. };
  21929. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  21930. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  21931. var marker = getTooltipMarker({
  21932. color: colorStr,
  21933. type: markerType,
  21934. renderMode: renderMode,
  21935. markerId: markerId
  21936. });
  21937. if (isString(marker)) {
  21938. return marker;
  21939. } else {
  21940. if ("development" !== 'production') {
  21941. assert(markerId);
  21942. }
  21943. this.richTextStyles[markerId] = marker.style;
  21944. return marker.content;
  21945. }
  21946. };
  21947. /**
  21948. * @usage
  21949. * ```ts
  21950. * const styledText = markupStyleCreator.wrapRichTextStyle([
  21951. * // The styles will be auto merged.
  21952. * {
  21953. * fontSize: 12,
  21954. * color: 'blue'
  21955. * },
  21956. * {
  21957. * padding: 20
  21958. * }
  21959. * ]);
  21960. * ```
  21961. */
  21962. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  21963. var finalStl = {};
  21964. if (isArray(styles)) {
  21965. each(styles, function (stl) {
  21966. return extend(finalStl, stl);
  21967. });
  21968. } else {
  21969. extend(finalStl, styles);
  21970. }
  21971. var styleName = this._generateStyleName();
  21972. this.richTextStyles[styleName] = finalStl;
  21973. return "{" + styleName + "|" + text + "}";
  21974. };
  21975. return TooltipMarkupStyleCreator;
  21976. }();
  21977. function defaultSeriesFormatTooltip(opt) {
  21978. var series = opt.series;
  21979. var dataIndex = opt.dataIndex;
  21980. var multipleSeries = opt.multipleSeries;
  21981. var data = series.getData();
  21982. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21983. var tooltipDimLen = tooltipDims.length;
  21984. var value = series.getRawValue(dataIndex);
  21985. var isValueArr = isArray(value);
  21986. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  21987. var inlineValue;
  21988. var inlineValueType;
  21989. var subBlocks;
  21990. var sortParam;
  21991. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  21992. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  21993. inlineValue = formatArrResult.inlineValues;
  21994. inlineValueType = formatArrResult.inlineValueTypes;
  21995. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  21996. sortParam = formatArrResult.inlineValues[0];
  21997. } else if (tooltipDimLen) {
  21998. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  21999. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  22000. inlineValueType = dimInfo.type;
  22001. } else {
  22002. sortParam = inlineValue = isValueArr ? value[0] : value;
  22003. } // Do not show generated series name. It might not be readable.
  22004. var seriesNameSpecified = isNameSpecified(series);
  22005. var seriesName = seriesNameSpecified && series.name || '';
  22006. var itemName = data.getName(dataIndex);
  22007. var inlineName = multipleSeries ? seriesName : itemName;
  22008. return createTooltipMarkup('section', {
  22009. header: seriesName,
  22010. // When series name is not specified, do not show a header line with only '-'.
  22011. // This case always happens in tooltip.trigger: 'item'.
  22012. noHeader: multipleSeries || !seriesNameSpecified,
  22013. sortParam: sortParam,
  22014. blocks: [createTooltipMarkup('nameValue', {
  22015. markerType: 'item',
  22016. markerColor: markerColor,
  22017. // Do not mix display seriesName and itemName in one tooltip,
  22018. // which might confuses users.
  22019. name: inlineName,
  22020. // name dimension might be auto assigned, where the name might
  22021. // be not readable. So we check trim here.
  22022. noName: !trim(inlineName),
  22023. value: inlineValue,
  22024. valueType: inlineValueType
  22025. })].concat(subBlocks || [])
  22026. });
  22027. }
  22028. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  22029. // check: category-no-encode-has-axis-data in dataset.html
  22030. var data = series.getData();
  22031. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  22032. var dimItem = data.getDimensionInfo(idx);
  22033. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  22034. }, false);
  22035. var inlineValues = [];
  22036. var inlineValueTypes = [];
  22037. var blocks = [];
  22038. tooltipDims.length ? each(tooltipDims, function (dim) {
  22039. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  22040. }) // By default, all dims is used on tooltip.
  22041. : each(value, setEachItem);
  22042. function setEachItem(val, dim) {
  22043. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  22044. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  22045. return;
  22046. }
  22047. if (isValueMultipleLine) {
  22048. blocks.push(createTooltipMarkup('nameValue', {
  22049. markerType: 'subItem',
  22050. markerColor: colorStr,
  22051. name: dimInfo.displayName,
  22052. value: val,
  22053. valueType: dimInfo.type
  22054. }));
  22055. } else {
  22056. inlineValues.push(val);
  22057. inlineValueTypes.push(dimInfo.type);
  22058. }
  22059. }
  22060. return {
  22061. inlineValues: inlineValues,
  22062. inlineValueTypes: inlineValueTypes,
  22063. blocks: blocks
  22064. };
  22065. }
  22066. var inner$1 = makeInner();
  22067. function getSelectionKey(data, dataIndex) {
  22068. return data.getName(dataIndex) || data.getId(dataIndex);
  22069. }
  22070. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  22071. var SeriesModel =
  22072. /** @class */
  22073. function (_super) {
  22074. __extends(SeriesModel, _super);
  22075. function SeriesModel() {
  22076. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  22077. // the class members must not be initialized in constructor or declaration place.
  22078. // Otherwise there is bad case:
  22079. // class A {xxx = 1;}
  22080. // enableClassExtend(A);
  22081. // class B extends A {}
  22082. // var C = B.extend({xxx: 5});
  22083. // var c = new C();
  22084. // console.log(c.xxx); // expect 5 but always 1.
  22085. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  22086. // Props about data selection
  22087. // ---------------------------------------
  22088. _this._selectedDataIndicesMap = {};
  22089. return _this;
  22090. }
  22091. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  22092. this.seriesIndex = this.componentIndex;
  22093. this.dataTask = createTask({
  22094. count: dataTaskCount,
  22095. reset: dataTaskReset
  22096. });
  22097. this.dataTask.context = {
  22098. model: this
  22099. };
  22100. this.mergeDefaultAndTheme(option, ecModel);
  22101. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  22102. sourceManager.prepareSource();
  22103. var data = this.getInitialData(option, ecModel);
  22104. wrapData(data, this);
  22105. this.dataTask.context.data = data;
  22106. if ("development" !== 'production') {
  22107. assert(data, 'getInitialData returned invalid data.');
  22108. }
  22109. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  22110. // dataBeforeProcessed by cloneShallow), cloneShallow will
  22111. // cause data.graph.data !== data when using
  22112. // module:echarts/data/Graph or module:echarts/data/Tree.
  22113. // See module:echarts/data/helper/linkSeriesData
  22114. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  22115. // init or merge stage, because the data can be restored. So we do not `restoreData`
  22116. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  22117. // Call `seriesModel.getRawData()` instead.
  22118. // this.restoreData();
  22119. autoSeriesName(this);
  22120. this._initSelectedMapFromData(data);
  22121. };
  22122. /**
  22123. * Util for merge default and theme to option
  22124. */
  22125. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  22126. var layoutMode = fetchLayoutMode(this);
  22127. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  22128. // But if name duplicate between series subType
  22129. // (for example: parallel) add component mainType,
  22130. // add suffix 'Series'.
  22131. var themeSubType = this.subType;
  22132. if (ComponentModel.hasClass(themeSubType)) {
  22133. themeSubType += 'Series';
  22134. }
  22135. merge(option, ecModel.getTheme().get(this.subType));
  22136. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  22137. defaultEmphasis(option, 'label', ['show']);
  22138. this.fillDataTextStyle(option.data);
  22139. if (layoutMode) {
  22140. mergeLayoutParam(option, inputPositionParams, layoutMode);
  22141. }
  22142. };
  22143. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  22144. // this.settingTask.dirty();
  22145. newSeriesOption = merge(this.option, newSeriesOption, true);
  22146. this.fillDataTextStyle(newSeriesOption.data);
  22147. var layoutMode = fetchLayoutMode(this);
  22148. if (layoutMode) {
  22149. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  22150. }
  22151. var sourceManager = inner$1(this).sourceManager;
  22152. sourceManager.dirty();
  22153. sourceManager.prepareSource();
  22154. var data = this.getInitialData(newSeriesOption, ecModel);
  22155. wrapData(data, this);
  22156. this.dataTask.dirty();
  22157. this.dataTask.context.data = data;
  22158. inner$1(this).dataBeforeProcessed = data;
  22159. autoSeriesName(this);
  22160. this._initSelectedMapFromData(data);
  22161. };
  22162. SeriesModel.prototype.fillDataTextStyle = function (data) {
  22163. // Default data label emphasis `show`
  22164. // FIXME Tree structure data ?
  22165. // FIXME Performance ?
  22166. if (data && !isTypedArray(data)) {
  22167. var props = ['show'];
  22168. for (var i = 0; i < data.length; i++) {
  22169. if (data[i] && data[i].label) {
  22170. defaultEmphasis(data[i], 'label', props);
  22171. }
  22172. }
  22173. }
  22174. };
  22175. /**
  22176. * Init a data structure from data related option in series
  22177. * Must be overridden.
  22178. */
  22179. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  22180. return;
  22181. };
  22182. /**
  22183. * Append data to list
  22184. */
  22185. SeriesModel.prototype.appendData = function (params) {
  22186. // FIXME ???
  22187. // (1) If data from dataset, forbidden append.
  22188. // (2) support append data of dataset.
  22189. var data = this.getRawData();
  22190. data.appendData(params.data);
  22191. };
  22192. /**
  22193. * Consider some method like `filter`, `map` need make new data,
  22194. * We should make sure that `seriesModel.getData()` get correct
  22195. * data in the stream procedure. So we fetch data from upstream
  22196. * each time `task.perform` called.
  22197. */
  22198. SeriesModel.prototype.getData = function (dataType) {
  22199. var task = getCurrentTask(this);
  22200. if (task) {
  22201. var data = task.context.data;
  22202. return dataType == null ? data : data.getLinkedData(dataType);
  22203. } else {
  22204. // When series is not alive (that may happen when click toolbox
  22205. // restore or setOption with not merge mode), series data may
  22206. // be still need to judge animation or something when graphic
  22207. // elements want to know whether fade out.
  22208. return inner$1(this).data;
  22209. }
  22210. };
  22211. SeriesModel.prototype.getAllData = function () {
  22212. var mainData = this.getData();
  22213. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  22214. data: mainData
  22215. }];
  22216. };
  22217. SeriesModel.prototype.setData = function (data) {
  22218. var task = getCurrentTask(this);
  22219. if (task) {
  22220. var context = task.context; // Consider case: filter, data sample.
  22221. // FIXME:TS never used, so comment it
  22222. // if (context.data !== data && task.modifyOutputEnd) {
  22223. // task.setOutputEnd(data.count());
  22224. // }
  22225. context.outputData = data; // Caution: setData should update context.data,
  22226. // Because getData may be called multiply in a
  22227. // single stage and expect to get the data just
  22228. // set. (For example, AxisProxy, x y both call
  22229. // getData and setDate sequentially).
  22230. // So the context.data should be fetched from
  22231. // upstream each time when a stage starts to be
  22232. // performed.
  22233. if (task !== this.dataTask) {
  22234. context.data = data;
  22235. }
  22236. }
  22237. inner$1(this).data = data;
  22238. };
  22239. SeriesModel.prototype.getEncode = function () {
  22240. var encode = this.get('encode', true);
  22241. if (encode) {
  22242. return createHashMap(encode);
  22243. }
  22244. };
  22245. SeriesModel.prototype.getSourceManager = function () {
  22246. return inner$1(this).sourceManager;
  22247. };
  22248. SeriesModel.prototype.getSource = function () {
  22249. return this.getSourceManager().getSource();
  22250. };
  22251. /**
  22252. * Get data before processed
  22253. */
  22254. SeriesModel.prototype.getRawData = function () {
  22255. return inner$1(this).dataBeforeProcessed;
  22256. };
  22257. SeriesModel.prototype.getColorBy = function () {
  22258. var colorBy = this.get('colorBy');
  22259. return colorBy || 'series';
  22260. };
  22261. SeriesModel.prototype.isColorBySeries = function () {
  22262. return this.getColorBy() === 'series';
  22263. };
  22264. /**
  22265. * Get base axis if has coordinate system and has axis.
  22266. * By default use coordSys.getBaseAxis();
  22267. * Can be overridden for some chart.
  22268. * @return {type} description
  22269. */
  22270. SeriesModel.prototype.getBaseAxis = function () {
  22271. var coordSys = this.coordinateSystem; // @ts-ignore
  22272. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  22273. };
  22274. /**
  22275. * Default tooltip formatter
  22276. *
  22277. * @param dataIndex
  22278. * @param multipleSeries
  22279. * @param dataType
  22280. * @param renderMode valid values: 'html'(by default) and 'richText'.
  22281. * 'html' is used for rendering tooltip in extra DOM form, and the result
  22282. * string is used as DOM HTML content.
  22283. * 'richText' is used for rendering tooltip in rich text form, for those where
  22284. * DOM operation is not supported.
  22285. * @return formatted tooltip with `html` and `markers`
  22286. * Notice: The override method can also return string
  22287. */
  22288. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22289. return defaultSeriesFormatTooltip({
  22290. series: this,
  22291. dataIndex: dataIndex,
  22292. multipleSeries: multipleSeries
  22293. });
  22294. };
  22295. SeriesModel.prototype.isAnimationEnabled = function () {
  22296. var ecModel = this.ecModel; // Disable animation if using echarts in node but not give ssr flag.
  22297. // In ssr mode, renderToString will generate svg with css animation.
  22298. if (env.node && !(ecModel && ecModel.ssr)) {
  22299. return false;
  22300. }
  22301. var animationEnabled = this.getShallow('animation');
  22302. if (animationEnabled) {
  22303. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22304. animationEnabled = false;
  22305. }
  22306. }
  22307. return !!animationEnabled;
  22308. };
  22309. SeriesModel.prototype.restoreData = function () {
  22310. this.dataTask.dirty();
  22311. };
  22312. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22313. var ecModel = this.ecModel; // PENDING
  22314. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22315. if (!color) {
  22316. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22317. }
  22318. return color;
  22319. };
  22320. /**
  22321. * Use `data.mapDimensionsAll(coordDim)` instead.
  22322. * @deprecated
  22323. */
  22324. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22325. return this.getRawData().mapDimensionsAll(coordDim);
  22326. };
  22327. /**
  22328. * Get progressive rendering count each step
  22329. */
  22330. SeriesModel.prototype.getProgressive = function () {
  22331. return this.get('progressive');
  22332. };
  22333. /**
  22334. * Get progressive rendering count each step
  22335. */
  22336. SeriesModel.prototype.getProgressiveThreshold = function () {
  22337. return this.get('progressiveThreshold');
  22338. }; // PENGING If selectedMode is null ?
  22339. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22340. this._innerSelect(this.getData(dataType), innerDataIndices);
  22341. };
  22342. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22343. var selectedMap = this.option.selectedMap;
  22344. if (!selectedMap) {
  22345. return;
  22346. }
  22347. var selectedMode = this.option.selectedMode;
  22348. var data = this.getData(dataType);
  22349. if (selectedMode === 'series' || selectedMap === 'all') {
  22350. this.option.selectedMap = {};
  22351. this._selectedDataIndicesMap = {};
  22352. return;
  22353. }
  22354. for (var i = 0; i < innerDataIndices.length; i++) {
  22355. var dataIndex = innerDataIndices[i];
  22356. var nameOrId = getSelectionKey(data, dataIndex);
  22357. selectedMap[nameOrId] = false;
  22358. this._selectedDataIndicesMap[nameOrId] = -1;
  22359. }
  22360. };
  22361. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22362. var tmpArr = [];
  22363. for (var i = 0; i < innerDataIndices.length; i++) {
  22364. tmpArr[0] = innerDataIndices[i];
  22365. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22366. }
  22367. };
  22368. SeriesModel.prototype.getSelectedDataIndices = function () {
  22369. if (this.option.selectedMap === 'all') {
  22370. return [].slice.call(this.getData().getIndices());
  22371. }
  22372. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22373. var nameOrIds = keys(selectedDataIndicesMap);
  22374. var dataIndices = [];
  22375. for (var i = 0; i < nameOrIds.length; i++) {
  22376. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22377. if (dataIndex >= 0) {
  22378. dataIndices.push(dataIndex);
  22379. }
  22380. }
  22381. return dataIndices;
  22382. };
  22383. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22384. var selectedMap = this.option.selectedMap;
  22385. if (!selectedMap) {
  22386. return false;
  22387. }
  22388. var data = this.getData(dataType);
  22389. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  22390. };
  22391. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22392. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22393. return true;
  22394. }
  22395. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  22396. if (!universalTransitionOpt) {
  22397. return false;
  22398. }
  22399. if (universalTransitionOpt === true) {
  22400. return true;
  22401. } // Can be simply 'universalTransition: true'
  22402. return universalTransitionOpt && universalTransitionOpt.enabled;
  22403. };
  22404. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22405. var _a, _b;
  22406. var option = this.option;
  22407. var selectedMode = option.selectedMode;
  22408. var len = innerDataIndices.length;
  22409. if (!selectedMode || !len) {
  22410. return;
  22411. }
  22412. if (selectedMode === 'series') {
  22413. option.selectedMap = 'all';
  22414. } else if (selectedMode === 'multiple') {
  22415. if (!isObject(option.selectedMap)) {
  22416. option.selectedMap = {};
  22417. }
  22418. var selectedMap = option.selectedMap;
  22419. for (var i = 0; i < len; i++) {
  22420. var dataIndex = innerDataIndices[i]; // TODO different types of data share same object.
  22421. var nameOrId = getSelectionKey(data, dataIndex);
  22422. selectedMap[nameOrId] = true;
  22423. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22424. }
  22425. } else if (selectedMode === 'single' || selectedMode === true) {
  22426. var lastDataIndex = innerDataIndices[len - 1];
  22427. var nameOrId = getSelectionKey(data, lastDataIndex);
  22428. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22429. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22430. }
  22431. };
  22432. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22433. // Ignore select info in data if selectedMap exists.
  22434. // NOTE It's only for legacy usage. edge data is not supported.
  22435. if (this.option.selectedMap) {
  22436. return;
  22437. }
  22438. var dataIndices = [];
  22439. if (data.hasItemOption) {
  22440. data.each(function (idx) {
  22441. var rawItem = data.getRawDataItem(idx);
  22442. if (rawItem && rawItem.selected) {
  22443. dataIndices.push(idx);
  22444. }
  22445. });
  22446. }
  22447. if (dataIndices.length > 0) {
  22448. this._innerSelect(data, dataIndices);
  22449. }
  22450. }; // /**
  22451. // * @see {module:echarts/stream/Scheduler}
  22452. // */
  22453. // abstract pipeTask: null
  22454. SeriesModel.registerClass = function (clz) {
  22455. return ComponentModel.registerClass(clz);
  22456. };
  22457. SeriesModel.protoInitialize = function () {
  22458. var proto = SeriesModel.prototype;
  22459. proto.type = 'series.__base__';
  22460. proto.seriesIndex = 0;
  22461. proto.ignoreStyleOnData = false;
  22462. proto.hasSymbolVisual = false;
  22463. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  22464. proto.visualStyleAccessPath = 'itemStyle';
  22465. proto.visualDrawType = 'fill';
  22466. }();
  22467. return SeriesModel;
  22468. }(ComponentModel);
  22469. mixin(SeriesModel, DataFormatMixin);
  22470. mixin(SeriesModel, PaletteMixin);
  22471. mountExtend(SeriesModel, ComponentModel);
  22472. /**
  22473. * MUST be called after `prepareSource` called
  22474. * Here we need to make auto series, especially for auto legend. But we
  22475. * do not modify series.name in option to avoid side effects.
  22476. */
  22477. function autoSeriesName(seriesModel) {
  22478. // User specified name has higher priority, otherwise it may cause
  22479. // series can not be queried unexpectedly.
  22480. var name = seriesModel.name;
  22481. if (!isNameSpecified(seriesModel)) {
  22482. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22483. }
  22484. }
  22485. function getSeriesAutoName(seriesModel) {
  22486. var data = seriesModel.getRawData();
  22487. var dataDims = data.mapDimensionsAll('seriesName');
  22488. var nameArr = [];
  22489. each(dataDims, function (dataDim) {
  22490. var dimInfo = data.getDimensionInfo(dataDim);
  22491. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22492. });
  22493. return nameArr.join(' ');
  22494. }
  22495. function dataTaskCount(context) {
  22496. return context.model.getRawData().count();
  22497. }
  22498. function dataTaskReset(context) {
  22499. var seriesModel = context.model;
  22500. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22501. return dataTaskProgress;
  22502. }
  22503. function dataTaskProgress(param, context) {
  22504. // Avoid repeat cloneShallow when data just created in reset.
  22505. if (context.outputData && param.end > context.outputData.count()) {
  22506. context.model.getRawData().cloneShallow(context.outputData);
  22507. }
  22508. } // TODO refactor
  22509. function wrapData(data, seriesModel) {
  22510. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22511. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22512. });
  22513. }
  22514. function onDataChange(seriesModel, newList) {
  22515. var task = getCurrentTask(seriesModel);
  22516. if (task) {
  22517. // Consider case: filter, selectRange
  22518. task.setOutputEnd((newList || this).count());
  22519. }
  22520. return newList;
  22521. }
  22522. function getCurrentTask(seriesModel) {
  22523. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22524. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22525. if (pipeline) {
  22526. // When pipline finished, the currrentTask keep the last
  22527. // task (renderTask).
  22528. var task = pipeline.currentTask;
  22529. if (task) {
  22530. var agentStubMap = task.agentStubMap;
  22531. if (agentStubMap) {
  22532. task = agentStubMap.get(seriesModel.uid);
  22533. }
  22534. }
  22535. return task;
  22536. }
  22537. }
  22538. var ComponentView =
  22539. /** @class */
  22540. function () {
  22541. function ComponentView() {
  22542. this.group = new Group();
  22543. this.uid = getUID('viewComponent');
  22544. }
  22545. ComponentView.prototype.init = function (ecModel, api) {};
  22546. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22547. ComponentView.prototype.dispose = function (ecModel, api) {};
  22548. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  22549. };
  22550. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  22551. };
  22552. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  22553. };
  22554. /**
  22555. * Hook for toggle blur target series.
  22556. * Can be used in marker for blur or leave blur the markers
  22557. */
  22558. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {// Do nothing;
  22559. };
  22560. /**
  22561. * Traverse the new rendered elements.
  22562. *
  22563. * It will traverse the new added element in progressive rendering.
  22564. * And traverse all in normal rendering.
  22565. */
  22566. ComponentView.prototype.eachRendered = function (cb) {
  22567. var group = this.group;
  22568. if (group) {
  22569. group.traverse(cb);
  22570. }
  22571. };
  22572. return ComponentView;
  22573. }();
  22574. enableClassExtend(ComponentView);
  22575. enableClassManagement(ComponentView);
  22576. /**
  22577. * @return {string} If large mode changed, return string 'reset';
  22578. */
  22579. function createRenderPlanner() {
  22580. var inner = makeInner();
  22581. return function (seriesModel) {
  22582. var fields = inner(seriesModel);
  22583. var pipelineContext = seriesModel.pipelineContext;
  22584. var originalLarge = !!fields.large;
  22585. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22586. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22587. // on `performRawSeries` in `Schedular.js`.
  22588. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22589. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22590. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22591. };
  22592. }
  22593. var inner$2 = makeInner();
  22594. var renderPlanner = createRenderPlanner();
  22595. var ChartView =
  22596. /** @class */
  22597. function () {
  22598. function ChartView() {
  22599. this.group = new Group();
  22600. this.uid = getUID('viewChart');
  22601. this.renderTask = createTask({
  22602. plan: renderTaskPlan,
  22603. reset: renderTaskReset
  22604. });
  22605. this.renderTask.context = {
  22606. view: this
  22607. };
  22608. }
  22609. ChartView.prototype.init = function (ecModel, api) {};
  22610. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22611. if ("development" !== 'production') {
  22612. throw new Error('render method must been implemented');
  22613. }
  22614. };
  22615. /**
  22616. * Highlight series or specified data item.
  22617. */
  22618. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22619. var data = seriesModel.getData(payload && payload.dataType);
  22620. if (!data) {
  22621. if ("development" !== 'production') {
  22622. error("Unknown dataType " + payload.dataType);
  22623. }
  22624. return;
  22625. }
  22626. toggleHighlight(data, payload, 'emphasis');
  22627. };
  22628. /**
  22629. * Downplay series or specified data item.
  22630. */
  22631. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22632. var data = seriesModel.getData(payload && payload.dataType);
  22633. if (!data) {
  22634. if ("development" !== 'production') {
  22635. error("Unknown dataType " + payload.dataType);
  22636. }
  22637. return;
  22638. }
  22639. toggleHighlight(data, payload, 'normal');
  22640. };
  22641. /**
  22642. * Remove self.
  22643. */
  22644. ChartView.prototype.remove = function (ecModel, api) {
  22645. this.group.removeAll();
  22646. };
  22647. /**
  22648. * Dispose self.
  22649. */
  22650. ChartView.prototype.dispose = function (ecModel, api) {};
  22651. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22652. this.render(seriesModel, ecModel, api, payload);
  22653. }; // FIXME never used?
  22654. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22655. this.render(seriesModel, ecModel, api, payload);
  22656. }; // FIXME never used?
  22657. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22658. this.render(seriesModel, ecModel, api, payload);
  22659. };
  22660. /**
  22661. * Traverse the new rendered elements.
  22662. *
  22663. * It will traverse the new added element in progressive rendering.
  22664. * And traverse all in normal rendering.
  22665. */
  22666. ChartView.prototype.eachRendered = function (cb) {
  22667. traverseElements(this.group, cb);
  22668. };
  22669. ChartView.markUpdateMethod = function (payload, methodName) {
  22670. inner$2(payload).updateMethod = methodName;
  22671. };
  22672. ChartView.protoInitialize = function () {
  22673. var proto = ChartView.prototype;
  22674. proto.type = 'chart';
  22675. }();
  22676. return ChartView;
  22677. }();
  22678. /**
  22679. * Set state of single element
  22680. */
  22681. function elSetState(el, state, highlightDigit) {
  22682. if (el && isHighDownDispatcher(el)) {
  22683. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22684. }
  22685. }
  22686. function toggleHighlight(data, payload, state) {
  22687. var dataIndex = queryDataIndex(data, payload);
  22688. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22689. if (dataIndex != null) {
  22690. each(normalizeToArray(dataIndex), function (dataIdx) {
  22691. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22692. });
  22693. } else {
  22694. data.eachItemGraphicEl(function (el) {
  22695. elSetState(el, state, highlightDigit);
  22696. });
  22697. }
  22698. }
  22699. enableClassExtend(ChartView, ['dispose']);
  22700. enableClassManagement(ChartView);
  22701. function renderTaskPlan(context) {
  22702. return renderPlanner(context.model);
  22703. }
  22704. function renderTaskReset(context) {
  22705. var seriesModel = context.model;
  22706. var ecModel = context.ecModel;
  22707. var api = context.api;
  22708. var payload = context.payload; // FIXME: remove updateView updateVisual
  22709. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22710. var view = context.view;
  22711. var updateMethod = payload && inner$2(payload).updateMethod;
  22712. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  22713. // is less than progressive threshold.
  22714. : 'render';
  22715. if (methodName !== 'render') {
  22716. view[methodName](seriesModel, ecModel, api, payload);
  22717. }
  22718. return progressMethodMap[methodName];
  22719. }
  22720. var progressMethodMap = {
  22721. incrementalPrepareRender: {
  22722. progress: function (params, context) {
  22723. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22724. }
  22725. },
  22726. render: {
  22727. // Put view.render in `progress` to support appendData. But in this case
  22728. // view.render should not be called in reset, otherwise it will be called
  22729. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22730. // in any cases.
  22731. forceFirstProgress: true,
  22732. progress: function (params, context) {
  22733. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22734. }
  22735. }
  22736. };
  22737. /*
  22738. * Licensed to the Apache Software Foundation (ASF) under one
  22739. * or more contributor license agreements. See the NOTICE file
  22740. * distributed with this work for additional information
  22741. * regarding copyright ownership. The ASF licenses this file
  22742. * to you under the Apache License, Version 2.0 (the
  22743. * "License"); you may not use this file except in compliance
  22744. * with the License. You may obtain a copy of the License at
  22745. *
  22746. * http://www.apache.org/licenses/LICENSE-2.0
  22747. *
  22748. * Unless required by applicable law or agreed to in writing,
  22749. * software distributed under the License is distributed on an
  22750. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22751. * KIND, either express or implied. See the License for the
  22752. * specific language governing permissions and limitations
  22753. * under the License.
  22754. */
  22755. /**
  22756. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22757. */
  22758. /*
  22759. * Licensed to the Apache Software Foundation (ASF) under one
  22760. * or more contributor license agreements. See the NOTICE file
  22761. * distributed with this work for additional information
  22762. * regarding copyright ownership. The ASF licenses this file
  22763. * to you under the Apache License, Version 2.0 (the
  22764. * "License"); you may not use this file except in compliance
  22765. * with the License. You may obtain a copy of the License at
  22766. *
  22767. * http://www.apache.org/licenses/LICENSE-2.0
  22768. *
  22769. * Unless required by applicable law or agreed to in writing,
  22770. * software distributed under the License is distributed on an
  22771. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22772. * KIND, either express or implied. See the License for the
  22773. * specific language governing permissions and limitations
  22774. * under the License.
  22775. */
  22776. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22777. var RATE = '\0__throttleRate';
  22778. var THROTTLE_TYPE = '\0__throttleType';
  22779. /**
  22780. * @public
  22781. * @param {(Function)} fn
  22782. * @param {number} [delay=0] Unit: ms.
  22783. * @param {boolean} [debounce=false]
  22784. * true: If call interval less than `delay`, only the last call works.
  22785. * false: If call interval less than `delay, call works on fixed rate.
  22786. * @return {(Function)} throttled fn.
  22787. */
  22788. function throttle(fn, delay, debounce) {
  22789. var currCall;
  22790. var lastCall = 0;
  22791. var lastExec = 0;
  22792. var timer = null;
  22793. var diff;
  22794. var scope;
  22795. var args;
  22796. var debounceNextCall;
  22797. delay = delay || 0;
  22798. function exec() {
  22799. lastExec = new Date().getTime();
  22800. timer = null;
  22801. fn.apply(scope, args || []);
  22802. }
  22803. var cb = function () {
  22804. var cbArgs = [];
  22805. for (var _i = 0; _i < arguments.length; _i++) {
  22806. cbArgs[_i] = arguments[_i];
  22807. }
  22808. currCall = new Date().getTime();
  22809. scope = this;
  22810. args = cbArgs;
  22811. var thisDelay = debounceNextCall || delay;
  22812. var thisDebounce = debounceNextCall || debounce;
  22813. debounceNextCall = null;
  22814. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22815. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  22816. // than a new call of `cb`, that is, preserving the command order. Consider
  22817. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22818. // happens, either the `exec` is called dierectly, or the call is delayed.
  22819. // But the delayed call should never be later than next call of `cb`. Under
  22820. // this assurance, we can simply update view state each time `dispatchAction`
  22821. // triggered by user roaming, but not need to add extra code to avoid the
  22822. // state being "rolled-back".
  22823. if (thisDebounce) {
  22824. timer = setTimeout(exec, thisDelay);
  22825. } else {
  22826. if (diff >= 0) {
  22827. exec();
  22828. } else {
  22829. timer = setTimeout(exec, -diff);
  22830. }
  22831. }
  22832. lastCall = currCall;
  22833. };
  22834. /**
  22835. * Clear throttle.
  22836. * @public
  22837. */
  22838. cb.clear = function () {
  22839. if (timer) {
  22840. clearTimeout(timer);
  22841. timer = null;
  22842. }
  22843. };
  22844. /**
  22845. * Enable debounce once.
  22846. */
  22847. cb.debounceNextCall = function (debounceDelay) {
  22848. debounceNextCall = debounceDelay;
  22849. };
  22850. return cb;
  22851. }
  22852. /**
  22853. * Create throttle method or update throttle rate.
  22854. *
  22855. * @example
  22856. * ComponentView.prototype.render = function () {
  22857. * ...
  22858. * throttle.createOrUpdate(
  22859. * this,
  22860. * '_dispatchAction',
  22861. * this.model.get('throttle'),
  22862. * 'fixRate'
  22863. * );
  22864. * };
  22865. * ComponentView.prototype.remove = function () {
  22866. * throttle.clear(this, '_dispatchAction');
  22867. * };
  22868. * ComponentView.prototype.dispose = function () {
  22869. * throttle.clear(this, '_dispatchAction');
  22870. * };
  22871. *
  22872. */
  22873. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22874. var fn = obj[fnAttr];
  22875. if (!fn) {
  22876. return;
  22877. }
  22878. var originFn = fn[ORIGIN_METHOD] || fn;
  22879. var lastThrottleType = fn[THROTTLE_TYPE];
  22880. var lastRate = fn[RATE];
  22881. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22882. if (rate == null || !throttleType) {
  22883. return obj[fnAttr] = originFn;
  22884. }
  22885. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  22886. fn[ORIGIN_METHOD] = originFn;
  22887. fn[THROTTLE_TYPE] = throttleType;
  22888. fn[RATE] = rate;
  22889. }
  22890. return fn;
  22891. }
  22892. /**
  22893. * Clear throttle. Example see throttle.createOrUpdate.
  22894. */
  22895. function clear(obj, fnAttr) {
  22896. var fn = obj[fnAttr];
  22897. if (fn && fn[ORIGIN_METHOD]) {
  22898. // Clear throttle
  22899. fn.clear && fn.clear();
  22900. obj[fnAttr] = fn[ORIGIN_METHOD];
  22901. }
  22902. }
  22903. var inner$3 = makeInner();
  22904. var defaultStyleMappers = {
  22905. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22906. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22907. };
  22908. var defaultColorKey = {
  22909. lineStyle: 'stroke',
  22910. itemStyle: 'fill'
  22911. };
  22912. function getStyleMapper(seriesModel, stylePath) {
  22913. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22914. if (!styleMapper) {
  22915. console.warn("Unknown style type '" + stylePath + "'.");
  22916. return defaultStyleMappers.itemStyle;
  22917. }
  22918. return styleMapper;
  22919. }
  22920. function getDefaultColorKey(seriesModel, stylePath) {
  22921. // return defaultColorKey[stylePath] ||
  22922. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22923. if (!colorKey) {
  22924. console.warn("Unknown style type '" + stylePath + "'.");
  22925. return 'fill';
  22926. }
  22927. return colorKey;
  22928. }
  22929. var seriesStyleTask = {
  22930. createOnAllSeries: true,
  22931. performRawSeries: true,
  22932. reset: function (seriesModel, ecModel) {
  22933. var data = seriesModel.getData();
  22934. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22935. var styleModel = seriesModel.getModel(stylePath);
  22936. var getStyle = getStyleMapper(seriesModel, stylePath);
  22937. var globalStyle = getStyle(styleModel);
  22938. var decalOption = styleModel.getShallow('decal');
  22939. if (decalOption) {
  22940. data.setVisual('decal', decalOption);
  22941. decalOption.dirty = true;
  22942. } // TODO
  22943. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22944. var color = globalStyle[colorKey]; // TODO style callback
  22945. var colorCallback = isFunction(color) ? color : null;
  22946. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  22947. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22948. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  22949. // make it effect palette. Because some scenarios users need to make some series
  22950. // transparent or as background, which should better not effect the palette.
  22951. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  22952. seriesModel.name, null, ecModel.getSeriesCount());
  22953. if (!globalStyle[colorKey]) {
  22954. globalStyle[colorKey] = colorPalette;
  22955. data.setVisual('colorFromPalette', true);
  22956. }
  22957. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  22958. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  22959. }
  22960. data.setVisual('style', globalStyle);
  22961. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  22962. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22963. data.setVisual('colorFromPalette', false);
  22964. return {
  22965. dataEach: function (data, idx) {
  22966. var dataParams = seriesModel.getDataParams(idx);
  22967. var itemStyle = extend({}, globalStyle);
  22968. itemStyle[colorKey] = colorCallback(dataParams);
  22969. data.setItemVisual(idx, 'style', itemStyle);
  22970. }
  22971. };
  22972. }
  22973. }
  22974. };
  22975. var sharedModel = new Model();
  22976. var dataStyleTask = {
  22977. createOnAllSeries: true,
  22978. performRawSeries: true,
  22979. reset: function (seriesModel, ecModel) {
  22980. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22981. return;
  22982. }
  22983. var data = seriesModel.getData();
  22984. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22985. var getStyle = getStyleMapper(seriesModel, stylePath);
  22986. var colorKey = data.getVisual('drawType');
  22987. return {
  22988. dataEach: data.hasItemOption ? function (data, idx) {
  22989. // Not use getItemModel for performance considuration
  22990. var rawItem = data.getRawDataItem(idx);
  22991. if (rawItem && rawItem[stylePath]) {
  22992. sharedModel.option = rawItem[stylePath];
  22993. var style = getStyle(sharedModel);
  22994. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  22995. extend(existsStyle, style);
  22996. if (sharedModel.option.decal) {
  22997. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  22998. sharedModel.option.decal.dirty = true;
  22999. }
  23000. if (colorKey in style) {
  23001. data.setItemVisual(idx, 'colorFromPalette', false);
  23002. }
  23003. }
  23004. } : null
  23005. };
  23006. }
  23007. }; // Pick color from palette for the data which has not been set with color yet.
  23008. // Note: do not support stream rendering. No such cases yet.
  23009. var dataColorPaletteTask = {
  23010. performRawSeries: true,
  23011. overallReset: function (ecModel) {
  23012. // Each type of series uses one scope.
  23013. // Pie and funnel are using different scopes.
  23014. var paletteScopeGroupByType = createHashMap();
  23015. ecModel.eachSeries(function (seriesModel) {
  23016. var colorBy = seriesModel.getColorBy();
  23017. if (seriesModel.isColorBySeries()) {
  23018. return;
  23019. }
  23020. var key = seriesModel.type + '-' + colorBy;
  23021. var colorScope = paletteScopeGroupByType.get(key);
  23022. if (!colorScope) {
  23023. colorScope = {};
  23024. paletteScopeGroupByType.set(key, colorScope);
  23025. }
  23026. inner$3(seriesModel).scope = colorScope;
  23027. });
  23028. ecModel.eachSeries(function (seriesModel) {
  23029. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  23030. return;
  23031. }
  23032. var dataAll = seriesModel.getRawData();
  23033. var idxMap = {};
  23034. var data = seriesModel.getData();
  23035. var colorScope = inner$3(seriesModel).scope;
  23036. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23037. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23038. data.each(function (idx) {
  23039. var rawIdx = data.getRawIndex(idx);
  23040. idxMap[rawIdx] = idx;
  23041. }); // Iterate on data before filtered. To make sure color from palette can be
  23042. // Consistent when toggling legend.
  23043. dataAll.each(function (rawIdx) {
  23044. var idx = idxMap[rawIdx];
  23045. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  23046. // also picked from color palette. So following situation is not in the case:
  23047. // 1. series.itemStyle.color is set
  23048. // 2. color is encoded by visualMap
  23049. if (fromPalette) {
  23050. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  23051. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  23052. var dataCount = dataAll.count();
  23053. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  23054. }
  23055. });
  23056. });
  23057. }
  23058. };
  23059. var PI$3 = Math.PI;
  23060. /**
  23061. * @param {module:echarts/ExtensionAPI} api
  23062. * @param {Object} [opts]
  23063. * @param {string} [opts.text]
  23064. * @param {string} [opts.color]
  23065. * @param {string} [opts.textColor]
  23066. * @return {module:zrender/Element}
  23067. */
  23068. function defaultLoading(api, opts) {
  23069. opts = opts || {};
  23070. defaults(opts, {
  23071. text: 'loading',
  23072. textColor: '#000',
  23073. fontSize: 12,
  23074. fontWeight: 'normal',
  23075. fontStyle: 'normal',
  23076. fontFamily: 'sans-serif',
  23077. maskColor: 'rgba(255, 255, 255, 0.8)',
  23078. showSpinner: true,
  23079. color: '#5470c6',
  23080. spinnerRadius: 10,
  23081. lineWidth: 5,
  23082. zlevel: 0
  23083. });
  23084. var group = new Group();
  23085. var mask = new Rect({
  23086. style: {
  23087. fill: opts.maskColor
  23088. },
  23089. zlevel: opts.zlevel,
  23090. z: 10000
  23091. });
  23092. group.add(mask);
  23093. var textContent = new ZRText({
  23094. style: {
  23095. text: opts.text,
  23096. fill: opts.textColor,
  23097. fontSize: opts.fontSize,
  23098. fontWeight: opts.fontWeight,
  23099. fontStyle: opts.fontStyle,
  23100. fontFamily: opts.fontFamily
  23101. },
  23102. zlevel: opts.zlevel,
  23103. z: 10001
  23104. });
  23105. var labelRect = new Rect({
  23106. style: {
  23107. fill: 'none'
  23108. },
  23109. textContent: textContent,
  23110. textConfig: {
  23111. position: 'right',
  23112. distance: 10
  23113. },
  23114. zlevel: opts.zlevel,
  23115. z: 10001
  23116. });
  23117. group.add(labelRect);
  23118. var arc;
  23119. if (opts.showSpinner) {
  23120. arc = new Arc({
  23121. shape: {
  23122. startAngle: -PI$3 / 2,
  23123. endAngle: -PI$3 / 2 + 0.1,
  23124. r: opts.spinnerRadius
  23125. },
  23126. style: {
  23127. stroke: opts.color,
  23128. lineCap: 'round',
  23129. lineWidth: opts.lineWidth
  23130. },
  23131. zlevel: opts.zlevel,
  23132. z: 10001
  23133. });
  23134. arc.animateShape(true).when(1000, {
  23135. endAngle: PI$3 * 3 / 2
  23136. }).start('circularInOut');
  23137. arc.animateShape(true).when(1000, {
  23138. startAngle: PI$3 * 3 / 2
  23139. }).delay(300).start('circularInOut');
  23140. group.add(arc);
  23141. } // Inject resize
  23142. group.resize = function () {
  23143. var textWidth = textContent.getBoundingRect().width;
  23144. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  23145. // textDistance needs to be calculated when both animation and text exist
  23146. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  23147. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  23148. + (textWidth ? 0 : r);
  23149. var cy = api.getHeight() / 2;
  23150. opts.showSpinner && arc.setShape({
  23151. cx: cx,
  23152. cy: cy
  23153. });
  23154. labelRect.setShape({
  23155. x: cx - r,
  23156. y: cy - r,
  23157. width: r * 2,
  23158. height: r * 2
  23159. });
  23160. mask.setShape({
  23161. x: 0,
  23162. y: 0,
  23163. width: api.getWidth(),
  23164. height: api.getHeight()
  23165. });
  23166. };
  23167. group.resize();
  23168. return group;
  23169. }
  23170. var Scheduler =
  23171. /** @class */
  23172. function () {
  23173. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  23174. // key: handlerUID
  23175. this._stageTaskMap = createHashMap();
  23176. this.ecInstance = ecInstance;
  23177. this.api = api; // Fix current processors in case that in some rear cases that
  23178. // processors might be registered after echarts instance created.
  23179. // Register processors incrementally for a echarts instance is
  23180. // not supported by this stream architecture.
  23181. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  23182. visualHandlers = this._visualHandlers = visualHandlers.slice();
  23183. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  23184. }
  23185. Scheduler.prototype.restoreData = function (ecModel, payload) {
  23186. // TODO: Only restore needed series and components, but not all components.
  23187. // Currently `restoreData` of all of the series and component will be called.
  23188. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  23189. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  23190. // and some components like coordinate system, axes, dataZoom, visualMap only
  23191. // need their target series refresh.
  23192. // (1) If we are implementing this feature some day, we should consider these cases:
  23193. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  23194. // on the settings of `dataZoom`), it should be re-performed if the component
  23195. // is modified by `setOption`.
  23196. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  23197. // it should be re-performed when the result array of `getTargetSeries` changed.
  23198. // We use `dependencies` to cover these issues.
  23199. // (3) How to update target series when coordinate system related components modified.
  23200. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  23201. // and this case all of the tasks will be set as dirty.
  23202. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  23203. // depends on all of the series.
  23204. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  23205. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  23206. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  23207. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  23208. // probably cause state chaos (consider `dataZoomProcessor`).
  23209. this._stageTaskMap.each(function (taskRecord) {
  23210. var overallTask = taskRecord.overallTask;
  23211. overallTask && overallTask.dirty();
  23212. });
  23213. }; // If seriesModel provided, incremental threshold is check by series data.
  23214. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  23215. // For overall task
  23216. if (!task.__pipeline) {
  23217. return;
  23218. }
  23219. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  23220. var pCtx = pipeline.context;
  23221. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  23222. var step = incremental ? pipeline.step : null;
  23223. var modDataCount = pCtx && pCtx.modDataCount;
  23224. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  23225. return {
  23226. step: step,
  23227. modBy: modBy,
  23228. modDataCount: modDataCount
  23229. };
  23230. };
  23231. Scheduler.prototype.getPipeline = function (pipelineId) {
  23232. return this._pipelineMap.get(pipelineId);
  23233. };
  23234. /**
  23235. * Current, progressive rendering starts from visual and layout.
  23236. * Always detect render mode in the same stage, avoiding that incorrect
  23237. * detection caused by data filtering.
  23238. * Caution:
  23239. * `updateStreamModes` use `seriesModel.getData()`.
  23240. */
  23241. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  23242. var pipeline = this._pipelineMap.get(seriesModel.uid);
  23243. var data = seriesModel.getData();
  23244. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  23245. // animation frame. Note that some types of series do not provide
  23246. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  23247. // use the term `incremental` but not `progressive` to describe the
  23248. // case that `chart.appendData`.
  23249. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  23250. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  23251. // see `test/candlestick-large3.html`
  23252. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  23253. seriesModel.pipelineContext = pipeline.context = {
  23254. progressiveRender: progressiveRender,
  23255. modDataCount: modDataCount,
  23256. large: large
  23257. };
  23258. };
  23259. Scheduler.prototype.restorePipelines = function (ecModel) {
  23260. var scheduler = this;
  23261. var pipelineMap = scheduler._pipelineMap = createHashMap();
  23262. ecModel.eachSeries(function (seriesModel) {
  23263. var progressive = seriesModel.getProgressive();
  23264. var pipelineId = seriesModel.uid;
  23265. pipelineMap.set(pipelineId, {
  23266. id: pipelineId,
  23267. head: null,
  23268. tail: null,
  23269. threshold: seriesModel.getProgressiveThreshold(),
  23270. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  23271. blockIndex: -1,
  23272. step: Math.round(progressive || 700),
  23273. count: 0
  23274. });
  23275. scheduler._pipe(seriesModel, seriesModel.dataTask);
  23276. });
  23277. };
  23278. Scheduler.prototype.prepareStageTasks = function () {
  23279. var stageTaskMap = this._stageTaskMap;
  23280. var ecModel = this.api.getModel();
  23281. var api = this.api;
  23282. each(this._allHandlers, function (handler) {
  23283. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  23284. var errMsg = '';
  23285. if ("development" !== 'production') {
  23286. // Currently do not need to support to sepecify them both.
  23287. errMsg = '"reset" and "overallReset" must not be both specified.';
  23288. }
  23289. assert(!(handler.reset && handler.overallReset), errMsg);
  23290. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  23291. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  23292. }, this);
  23293. };
  23294. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  23295. var renderTask = view.renderTask;
  23296. var context = renderTask.context;
  23297. context.model = model;
  23298. context.ecModel = ecModel;
  23299. context.api = api;
  23300. renderTask.__block = !view.incrementalPrepareRender;
  23301. this._pipe(model, renderTask);
  23302. };
  23303. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  23304. // If we do not use `block` here, it should be considered when to update modes.
  23305. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  23306. block: true
  23307. });
  23308. };
  23309. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  23310. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  23311. };
  23312. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  23313. opt = opt || {};
  23314. var unfinished = false;
  23315. var scheduler = this;
  23316. each(stageHandlers, function (stageHandler, idx) {
  23317. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23318. return;
  23319. }
  23320. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23321. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23322. var overallTask = stageHandlerRecord.overallTask;
  23323. if (overallTask) {
  23324. var overallNeedDirty_1;
  23325. var agentStubMap = overallTask.agentStubMap;
  23326. agentStubMap.each(function (stub) {
  23327. if (needSetDirty(opt, stub)) {
  23328. stub.dirty();
  23329. overallNeedDirty_1 = true;
  23330. }
  23331. });
  23332. overallNeedDirty_1 && overallTask.dirty();
  23333. scheduler.updatePayload(overallTask, payload);
  23334. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  23335. // then execute the overall task. And stub will call seriesModel.setData,
  23336. // which ensures that in the overallTask seriesModel.getData() will not
  23337. // return incorrect data.
  23338. agentStubMap.each(function (stub) {
  23339. stub.perform(performArgs_1);
  23340. });
  23341. if (overallTask.perform(performArgs_1)) {
  23342. unfinished = true;
  23343. }
  23344. } else if (seriesTaskMap) {
  23345. seriesTaskMap.each(function (task, pipelineId) {
  23346. if (needSetDirty(opt, task)) {
  23347. task.dirty();
  23348. }
  23349. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  23350. // if intending to declare `performRawSeries` in handlers, only
  23351. // stream-independent (specifically, data item independent) operations can be
  23352. // performed. Because if a series is filtered, most of the tasks will not
  23353. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23354. // Perhaps we should not provide a separate callback for this case instead
  23355. // of providing the config `performRawSeries`. The stream-dependent operations
  23356. // and stream-independent operations should better not be mixed.
  23357. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23358. scheduler.updatePayload(task, payload);
  23359. if (task.perform(performArgs)) {
  23360. unfinished = true;
  23361. }
  23362. });
  23363. }
  23364. });
  23365. function needSetDirty(opt, task) {
  23366. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23367. }
  23368. this.unfinished = unfinished || this.unfinished;
  23369. };
  23370. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23371. var unfinished;
  23372. ecModel.eachSeries(function (seriesModel) {
  23373. // Progress to the end for dataInit and dataRestore.
  23374. unfinished = seriesModel.dataTask.perform() || unfinished;
  23375. });
  23376. this.unfinished = unfinished || this.unfinished;
  23377. };
  23378. Scheduler.prototype.plan = function () {
  23379. // Travel pipelines, check block.
  23380. this._pipelineMap.each(function (pipeline) {
  23381. var task = pipeline.tail;
  23382. do {
  23383. if (task.__block) {
  23384. pipeline.blockIndex = task.__idxInPipeline;
  23385. break;
  23386. }
  23387. task = task.getUpstream();
  23388. } while (task);
  23389. });
  23390. };
  23391. Scheduler.prototype.updatePayload = function (task, payload) {
  23392. payload !== 'remain' && (task.context.payload = payload);
  23393. };
  23394. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23395. var scheduler = this;
  23396. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  23397. // do not need to reuse the map.
  23398. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23399. var seriesType = stageHandler.seriesType;
  23400. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23401. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23402. // it works but it may cause other irrelevant charts blocked.
  23403. if (stageHandler.createOnAllSeries) {
  23404. ecModel.eachRawSeries(create);
  23405. } else if (seriesType) {
  23406. ecModel.eachRawSeriesByType(seriesType, create);
  23407. } else if (getTargetSeries) {
  23408. getTargetSeries(ecModel, api).each(create);
  23409. }
  23410. function create(seriesModel) {
  23411. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  23412. // Reuse original task instance.
  23413. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23414. plan: seriesTaskPlan,
  23415. reset: seriesTaskReset,
  23416. count: seriesTaskCount
  23417. }));
  23418. task.context = {
  23419. model: seriesModel,
  23420. ecModel: ecModel,
  23421. api: api,
  23422. // PENDING: `useClearVisual` not used?
  23423. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23424. plan: stageHandler.plan,
  23425. reset: stageHandler.reset,
  23426. scheduler: scheduler
  23427. };
  23428. scheduler._pipe(seriesModel, task);
  23429. }
  23430. };
  23431. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23432. var scheduler = this;
  23433. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  23434. || createTask({
  23435. reset: overallTaskReset
  23436. });
  23437. overallTask.context = {
  23438. ecModel: ecModel,
  23439. api: api,
  23440. overallReset: stageHandler.overallReset,
  23441. scheduler: scheduler
  23442. };
  23443. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  23444. // do not need to reuse the map.
  23445. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23446. var seriesType = stageHandler.seriesType;
  23447. var getTargetSeries = stageHandler.getTargetSeries;
  23448. var overallProgress = true;
  23449. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  23450. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23451. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23452. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23453. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23454. // we set the pipeline block.
  23455. var errMsg = '';
  23456. if ("development" !== 'production') {
  23457. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  23458. }
  23459. assert(!stageHandler.createOnAllSeries, errMsg);
  23460. if (seriesType) {
  23461. ecModel.eachRawSeriesByType(seriesType, createStub);
  23462. } else if (getTargetSeries) {
  23463. getTargetSeries(ecModel, api).each(createStub);
  23464. } // Otherwise, (usually it is legacy case), the overall task will only be
  23465. // executed when upstream is dirty. Otherwise the progressive rendering of all
  23466. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23467. // dirty info from upstream.
  23468. else {
  23469. overallProgress = false;
  23470. each(ecModel.getSeries(), createStub);
  23471. }
  23472. function createStub(seriesModel) {
  23473. var pipelineId = seriesModel.uid;
  23474. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  23475. // should be set as dirty and re-performed.
  23476. shouldOverallTaskDirty = true, createTask({
  23477. reset: stubReset,
  23478. onDirty: stubOnDirty
  23479. })));
  23480. stub.context = {
  23481. model: seriesModel,
  23482. overallProgress: overallProgress // FIXME:TS never used, so comment it
  23483. // modifyOutputEnd: modifyOutputEnd
  23484. };
  23485. stub.agent = overallTask;
  23486. stub.__block = overallProgress;
  23487. scheduler._pipe(seriesModel, stub);
  23488. }
  23489. if (shouldOverallTaskDirty) {
  23490. overallTask.dirty();
  23491. }
  23492. };
  23493. Scheduler.prototype._pipe = function (seriesModel, task) {
  23494. var pipelineId = seriesModel.uid;
  23495. var pipeline = this._pipelineMap.get(pipelineId);
  23496. !pipeline.head && (pipeline.head = task);
  23497. pipeline.tail && pipeline.tail.pipe(task);
  23498. pipeline.tail = task;
  23499. task.__idxInPipeline = pipeline.count++;
  23500. task.__pipeline = pipeline;
  23501. };
  23502. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23503. if (isFunction(stageHandler)) {
  23504. stageHandler = {
  23505. overallReset: stageHandler,
  23506. seriesType: detectSeriseType(stageHandler)
  23507. };
  23508. }
  23509. stageHandler.uid = getUID('stageHandler');
  23510. visualType && (stageHandler.visualType = visualType);
  23511. return stageHandler;
  23512. };
  23513. return Scheduler;
  23514. }();
  23515. function overallTaskReset(context) {
  23516. context.overallReset(context.ecModel, context.api, context.payload);
  23517. }
  23518. function stubReset(context) {
  23519. return context.overallProgress && stubProgress;
  23520. }
  23521. function stubProgress() {
  23522. this.agent.dirty();
  23523. this.getDownstream().dirty();
  23524. }
  23525. function stubOnDirty() {
  23526. this.agent && this.agent.dirty();
  23527. }
  23528. function seriesTaskPlan(context) {
  23529. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23530. }
  23531. function seriesTaskReset(context) {
  23532. if (context.useClearVisual) {
  23533. context.data.clearAllVisual();
  23534. }
  23535. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23536. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23537. return makeSeriesTaskProgress(idx);
  23538. }) : singleSeriesTaskProgress;
  23539. }
  23540. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23541. function makeSeriesTaskProgress(resetDefineIdx) {
  23542. return function (params, context) {
  23543. var data = context.data;
  23544. var resetDefine = context.resetDefines[resetDefineIdx];
  23545. if (resetDefine && resetDefine.dataEach) {
  23546. for (var i = params.start; i < params.end; i++) {
  23547. resetDefine.dataEach(data, i);
  23548. }
  23549. } else if (resetDefine && resetDefine.progress) {
  23550. resetDefine.progress(params, data);
  23551. }
  23552. };
  23553. }
  23554. function seriesTaskCount(context) {
  23555. return context.data.count();
  23556. }
  23557. /**
  23558. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23559. * To ensure that they can work normally, they should work in block mode, that is,
  23560. * they should not be started util the previous tasks finished. So they cause the
  23561. * progressive rendering disabled. We try to detect the series type, to narrow down
  23562. * the block range to only the series type they concern, but not all series.
  23563. */
  23564. function detectSeriseType(legacyFunc) {
  23565. seriesType = null;
  23566. try {
  23567. // Assume there is no async when calling `eachSeriesByType`.
  23568. legacyFunc(ecModelMock, apiMock);
  23569. } catch (e) {}
  23570. return seriesType;
  23571. }
  23572. var ecModelMock = {};
  23573. var apiMock = {};
  23574. var seriesType;
  23575. mockMethods(ecModelMock, GlobalModel);
  23576. mockMethods(apiMock, ExtensionAPI);
  23577. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23578. seriesType = type;
  23579. };
  23580. ecModelMock.eachComponent = function (cond) {
  23581. if (cond.mainType === 'series' && cond.subType) {
  23582. seriesType = cond.subType;
  23583. }
  23584. };
  23585. function mockMethods(target, Clz) {
  23586. /* eslint-disable */
  23587. for (var name_1 in Clz.prototype) {
  23588. // Do not use hasOwnProperty
  23589. target[name_1] = noop;
  23590. }
  23591. /* eslint-enable */
  23592. }
  23593. /*
  23594. * Licensed to the Apache Software Foundation (ASF) under one
  23595. * or more contributor license agreements. See the NOTICE file
  23596. * distributed with this work for additional information
  23597. * regarding copyright ownership. The ASF licenses this file
  23598. * to you under the Apache License, Version 2.0 (the
  23599. * "License"); you may not use this file except in compliance
  23600. * with the License. You may obtain a copy of the License at
  23601. *
  23602. * http://www.apache.org/licenses/LICENSE-2.0
  23603. *
  23604. * Unless required by applicable law or agreed to in writing,
  23605. * software distributed under the License is distributed on an
  23606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23607. * KIND, either express or implied. See the License for the
  23608. * specific language governing permissions and limitations
  23609. * under the License.
  23610. */
  23611. /**
  23612. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23613. */
  23614. /*
  23615. * Licensed to the Apache Software Foundation (ASF) under one
  23616. * or more contributor license agreements. See the NOTICE file
  23617. * distributed with this work for additional information
  23618. * regarding copyright ownership. The ASF licenses this file
  23619. * to you under the Apache License, Version 2.0 (the
  23620. * "License"); you may not use this file except in compliance
  23621. * with the License. You may obtain a copy of the License at
  23622. *
  23623. * http://www.apache.org/licenses/LICENSE-2.0
  23624. *
  23625. * Unless required by applicable law or agreed to in writing,
  23626. * software distributed under the License is distributed on an
  23627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23628. * KIND, either express or implied. See the License for the
  23629. * specific language governing permissions and limitations
  23630. * under the License.
  23631. */
  23632. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23633. var lightTheme = {
  23634. color: colorAll,
  23635. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23636. };
  23637. /*
  23638. * Licensed to the Apache Software Foundation (ASF) under one
  23639. * or more contributor license agreements. See the NOTICE file
  23640. * distributed with this work for additional information
  23641. * regarding copyright ownership. The ASF licenses this file
  23642. * to you under the Apache License, Version 2.0 (the
  23643. * "License"); you may not use this file except in compliance
  23644. * with the License. You may obtain a copy of the License at
  23645. *
  23646. * http://www.apache.org/licenses/LICENSE-2.0
  23647. *
  23648. * Unless required by applicable law or agreed to in writing,
  23649. * software distributed under the License is distributed on an
  23650. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23651. * KIND, either express or implied. See the License for the
  23652. * specific language governing permissions and limitations
  23653. * under the License.
  23654. */
  23655. /**
  23656. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23657. */
  23658. /*
  23659. * Licensed to the Apache Software Foundation (ASF) under one
  23660. * or more contributor license agreements. See the NOTICE file
  23661. * distributed with this work for additional information
  23662. * regarding copyright ownership. The ASF licenses this file
  23663. * to you under the Apache License, Version 2.0 (the
  23664. * "License"); you may not use this file except in compliance
  23665. * with the License. You may obtain a copy of the License at
  23666. *
  23667. * http://www.apache.org/licenses/LICENSE-2.0
  23668. *
  23669. * Unless required by applicable law or agreed to in writing,
  23670. * software distributed under the License is distributed on an
  23671. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23672. * KIND, either express or implied. See the License for the
  23673. * specific language governing permissions and limitations
  23674. * under the License.
  23675. */
  23676. var contrastColor = '#B9B8CE';
  23677. var backgroundColor = '#100C2A';
  23678. var axisCommon = function () {
  23679. return {
  23680. axisLine: {
  23681. lineStyle: {
  23682. color: contrastColor
  23683. }
  23684. },
  23685. splitLine: {
  23686. lineStyle: {
  23687. color: '#484753'
  23688. }
  23689. },
  23690. splitArea: {
  23691. areaStyle: {
  23692. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23693. }
  23694. },
  23695. minorSplitLine: {
  23696. lineStyle: {
  23697. color: '#20203B'
  23698. }
  23699. }
  23700. };
  23701. };
  23702. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23703. var theme = {
  23704. darkMode: true,
  23705. color: colorPalette,
  23706. backgroundColor: backgroundColor,
  23707. axisPointer: {
  23708. lineStyle: {
  23709. color: '#817f91'
  23710. },
  23711. crossStyle: {
  23712. color: '#817f91'
  23713. },
  23714. label: {
  23715. // TODO Contrast of label backgorundColor
  23716. color: '#fff'
  23717. }
  23718. },
  23719. legend: {
  23720. textStyle: {
  23721. color: contrastColor
  23722. }
  23723. },
  23724. textStyle: {
  23725. color: contrastColor
  23726. },
  23727. title: {
  23728. textStyle: {
  23729. color: '#EEF1FA'
  23730. },
  23731. subtextStyle: {
  23732. color: '#B9B8CE'
  23733. }
  23734. },
  23735. toolbox: {
  23736. iconStyle: {
  23737. borderColor: contrastColor
  23738. }
  23739. },
  23740. dataZoom: {
  23741. borderColor: '#71708A',
  23742. textStyle: {
  23743. color: contrastColor
  23744. },
  23745. brushStyle: {
  23746. color: 'rgba(135,163,206,0.3)'
  23747. },
  23748. handleStyle: {
  23749. color: '#353450',
  23750. borderColor: '#C5CBE3'
  23751. },
  23752. moveHandleStyle: {
  23753. color: '#B0B6C3',
  23754. opacity: 0.3
  23755. },
  23756. fillerColor: 'rgba(135,163,206,0.2)',
  23757. emphasis: {
  23758. handleStyle: {
  23759. borderColor: '#91B7F2',
  23760. color: '#4D587D'
  23761. },
  23762. moveHandleStyle: {
  23763. color: '#636D9A',
  23764. opacity: 0.7
  23765. }
  23766. },
  23767. dataBackground: {
  23768. lineStyle: {
  23769. color: '#71708A',
  23770. width: 1
  23771. },
  23772. areaStyle: {
  23773. color: '#71708A'
  23774. }
  23775. },
  23776. selectedDataBackground: {
  23777. lineStyle: {
  23778. color: '#87A3CE'
  23779. },
  23780. areaStyle: {
  23781. color: '#87A3CE'
  23782. }
  23783. }
  23784. },
  23785. visualMap: {
  23786. textStyle: {
  23787. color: contrastColor
  23788. }
  23789. },
  23790. timeline: {
  23791. lineStyle: {
  23792. color: contrastColor
  23793. },
  23794. label: {
  23795. color: contrastColor
  23796. },
  23797. controlStyle: {
  23798. color: contrastColor,
  23799. borderColor: contrastColor
  23800. }
  23801. },
  23802. calendar: {
  23803. itemStyle: {
  23804. color: backgroundColor
  23805. },
  23806. dayLabel: {
  23807. color: contrastColor
  23808. },
  23809. monthLabel: {
  23810. color: contrastColor
  23811. },
  23812. yearLabel: {
  23813. color: contrastColor
  23814. }
  23815. },
  23816. timeAxis: axisCommon(),
  23817. logAxis: axisCommon(),
  23818. valueAxis: axisCommon(),
  23819. categoryAxis: axisCommon(),
  23820. line: {
  23821. symbol: 'circle'
  23822. },
  23823. graph: {
  23824. color: colorPalette
  23825. },
  23826. gauge: {
  23827. title: {
  23828. color: contrastColor
  23829. },
  23830. axisLine: {
  23831. lineStyle: {
  23832. color: [[1, 'rgba(207,212,219,0.2)']]
  23833. }
  23834. },
  23835. axisLabel: {
  23836. color: contrastColor
  23837. },
  23838. detail: {
  23839. color: '#EEF1FA'
  23840. }
  23841. },
  23842. candlestick: {
  23843. itemStyle: {
  23844. color: '#f64e56',
  23845. color0: '#54ea92',
  23846. borderColor: '#f64e56',
  23847. borderColor0: '#54ea92' // borderColor: '#ca2824',
  23848. // borderColor0: '#09a443'
  23849. }
  23850. }
  23851. };
  23852. theme.categoryAxis.splitLine.show = false;
  23853. /**
  23854. * Usage of query:
  23855. * `chart.on('click', query, handler);`
  23856. * The `query` can be:
  23857. * + The component type query string, only `mainType` or `mainType.subType`,
  23858. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23859. * + The component query object, like:
  23860. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23861. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23862. * + The data query object, like:
  23863. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23864. * + The other query object (cmponent customized query), like:
  23865. * `{element: 'some'}` (only available in custom series).
  23866. *
  23867. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23868. * same as there is no such prop in the `query` object.
  23869. */
  23870. var ECEventProcessor =
  23871. /** @class */
  23872. function () {
  23873. function ECEventProcessor() {}
  23874. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23875. var cptQuery = {};
  23876. var dataQuery = {};
  23877. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23878. if (isString(query)) {
  23879. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23880. cptQuery.mainType = condCptType.main || null;
  23881. cptQuery.subType = condCptType.sub || null;
  23882. } // `query` is an object, convert to {mainType, index, name, id}.
  23883. else {
  23884. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23885. // can not be used in `compomentModel.filterForExposedEvent`.
  23886. var suffixes_1 = ['Index', 'Name', 'Id'];
  23887. var dataKeys_1 = {
  23888. name: 1,
  23889. dataIndex: 1,
  23890. dataType: 1
  23891. };
  23892. each(query, function (val, key) {
  23893. var reserved = false;
  23894. for (var i = 0; i < suffixes_1.length; i++) {
  23895. var propSuffix = suffixes_1[i];
  23896. var suffixPos = key.lastIndexOf(propSuffix);
  23897. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23898. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23899. if (mainType !== 'data') {
  23900. cptQuery.mainType = mainType;
  23901. cptQuery[propSuffix.toLowerCase()] = val;
  23902. reserved = true;
  23903. }
  23904. }
  23905. }
  23906. if (dataKeys_1.hasOwnProperty(key)) {
  23907. dataQuery[key] = val;
  23908. reserved = true;
  23909. }
  23910. if (!reserved) {
  23911. otherQuery[key] = val;
  23912. }
  23913. });
  23914. }
  23915. return {
  23916. cptQuery: cptQuery,
  23917. dataQuery: dataQuery,
  23918. otherQuery: otherQuery
  23919. };
  23920. };
  23921. ECEventProcessor.prototype.filter = function (eventType, query) {
  23922. // They should be assigned before each trigger call.
  23923. var eventInfo = this.eventInfo;
  23924. if (!eventInfo) {
  23925. return true;
  23926. }
  23927. var targetEl = eventInfo.targetEl;
  23928. var packedEvent = eventInfo.packedEvent;
  23929. var model = eventInfo.model;
  23930. var view = eventInfo.view; // For event like 'globalout'.
  23931. if (!model || !view) {
  23932. return true;
  23933. }
  23934. var cptQuery = query.cptQuery;
  23935. var dataQuery = query.dataQuery;
  23936. 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));
  23937. function check(query, host, prop, propOnHost) {
  23938. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23939. }
  23940. };
  23941. ECEventProcessor.prototype.afterTrigger = function () {
  23942. // Make sure the eventInfo won't be used in next trigger.
  23943. this.eventInfo = null;
  23944. };
  23945. return ECEventProcessor;
  23946. }();
  23947. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  23948. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']); // Encoding visual for all series include which is filtered for legend drawing
  23949. var seriesSymbolTask = {
  23950. createOnAllSeries: true,
  23951. // For legend.
  23952. performRawSeries: true,
  23953. reset: function (seriesModel, ecModel) {
  23954. var data = seriesModel.getData();
  23955. if (seriesModel.legendIcon) {
  23956. data.setVisual('legendIcon', seriesModel.legendIcon);
  23957. }
  23958. if (!seriesModel.hasSymbolVisual) {
  23959. return;
  23960. }
  23961. var symbolOptions = {};
  23962. var symbolOptionsCb = {};
  23963. var hasCallback = false;
  23964. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  23965. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  23966. var val = seriesModel.get(symbolPropName);
  23967. if (isFunction(val)) {
  23968. hasCallback = true;
  23969. symbolOptionsCb[symbolPropName] = val;
  23970. } else {
  23971. symbolOptions[symbolPropName] = val;
  23972. }
  23973. }
  23974. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  23975. data.setVisual(extend({
  23976. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  23977. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  23978. }, symbolOptions)); // Only visible series has each data be visual encoded
  23979. if (ecModel.isSeriesFiltered(seriesModel)) {
  23980. return;
  23981. }
  23982. var symbolPropsCb = keys(symbolOptionsCb);
  23983. function dataEach(data, idx) {
  23984. var rawValue = seriesModel.getRawValue(idx);
  23985. var params = seriesModel.getDataParams(idx);
  23986. for (var i = 0; i < symbolPropsCb.length; i++) {
  23987. var symbolPropName = symbolPropsCb[i];
  23988. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  23989. }
  23990. }
  23991. return {
  23992. dataEach: hasCallback ? dataEach : null
  23993. };
  23994. }
  23995. };
  23996. var dataSymbolTask = {
  23997. createOnAllSeries: true,
  23998. // For legend.
  23999. performRawSeries: true,
  24000. reset: function (seriesModel, ecModel) {
  24001. if (!seriesModel.hasSymbolVisual) {
  24002. return;
  24003. } // Only visible series has each data be visual encoded
  24004. if (ecModel.isSeriesFiltered(seriesModel)) {
  24005. return;
  24006. }
  24007. var data = seriesModel.getData();
  24008. function dataEach(data, idx) {
  24009. var itemModel = data.getItemModel(idx);
  24010. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  24011. var symbolPropName = SYMBOL_PROPS[i];
  24012. var val = itemModel.getShallow(symbolPropName, true);
  24013. if (val != null) {
  24014. data.setItemVisual(idx, symbolPropName, val);
  24015. }
  24016. }
  24017. }
  24018. return {
  24019. dataEach: data.hasItemOption ? dataEach : null
  24020. };
  24021. }
  24022. };
  24023. /*
  24024. * Licensed to the Apache Software Foundation (ASF) under one
  24025. * or more contributor license agreements. See the NOTICE file
  24026. * distributed with this work for additional information
  24027. * regarding copyright ownership. The ASF licenses this file
  24028. * to you under the Apache License, Version 2.0 (the
  24029. * "License"); you may not use this file except in compliance
  24030. * with the License. You may obtain a copy of the License at
  24031. *
  24032. * http://www.apache.org/licenses/LICENSE-2.0
  24033. *
  24034. * Unless required by applicable law or agreed to in writing,
  24035. * software distributed under the License is distributed on an
  24036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24037. * KIND, either express or implied. See the License for the
  24038. * specific language governing permissions and limitations
  24039. * under the License.
  24040. */
  24041. /**
  24042. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24043. */
  24044. /*
  24045. * Licensed to the Apache Software Foundation (ASF) under one
  24046. * or more contributor license agreements. See the NOTICE file
  24047. * distributed with this work for additional information
  24048. * regarding copyright ownership. The ASF licenses this file
  24049. * to you under the Apache License, Version 2.0 (the
  24050. * "License"); you may not use this file except in compliance
  24051. * with the License. You may obtain a copy of the License at
  24052. *
  24053. * http://www.apache.org/licenses/LICENSE-2.0
  24054. *
  24055. * Unless required by applicable law or agreed to in writing,
  24056. * software distributed under the License is distributed on an
  24057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24058. * KIND, either express or implied. See the License for the
  24059. * specific language governing permissions and limitations
  24060. * under the License.
  24061. */
  24062. function getItemVisualFromData(data, dataIndex, key) {
  24063. switch (key) {
  24064. case 'color':
  24065. var style = data.getItemVisual(dataIndex, 'style');
  24066. return style[data.getVisual('drawType')];
  24067. case 'opacity':
  24068. return data.getItemVisual(dataIndex, 'style').opacity;
  24069. case 'symbol':
  24070. case 'symbolSize':
  24071. case 'liftZ':
  24072. return data.getItemVisual(dataIndex, key);
  24073. default:
  24074. if ("development" !== 'production') {
  24075. console.warn("Unknown visual type " + key);
  24076. }
  24077. }
  24078. }
  24079. function getVisualFromData(data, key) {
  24080. switch (key) {
  24081. case 'color':
  24082. var style = data.getVisual('style');
  24083. return style[data.getVisual('drawType')];
  24084. case 'opacity':
  24085. return data.getVisual('style').opacity;
  24086. case 'symbol':
  24087. case 'symbolSize':
  24088. case 'liftZ':
  24089. return data.getVisual(key);
  24090. default:
  24091. if ("development" !== 'production') {
  24092. console.warn("Unknown visual type " + key);
  24093. }
  24094. }
  24095. }
  24096. function setItemVisualFromData(data, dataIndex, key, value) {
  24097. switch (key) {
  24098. case 'color':
  24099. // Make sure not sharing style object.
  24100. var style = data.ensureUniqueItemVisual(dataIndex, 'style');
  24101. style[data.getVisual('drawType')] = value; // Mark the color has been changed, not from palette anymore
  24102. data.setItemVisual(dataIndex, 'colorFromPalette', false);
  24103. break;
  24104. case 'opacity':
  24105. data.ensureUniqueItemVisual(dataIndex, 'style').opacity = value;
  24106. break;
  24107. case 'symbol':
  24108. case 'symbolSize':
  24109. case 'liftZ':
  24110. data.setItemVisual(dataIndex, key, value);
  24111. break;
  24112. default:
  24113. if ("development" !== 'production') {
  24114. console.warn("Unknown visual type " + key);
  24115. }
  24116. }
  24117. }
  24118. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  24119. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  24120. function getSeriesIndices(ecModel, payload) {
  24121. var seriesIndices = [];
  24122. ecModel.eachComponent({
  24123. mainType: 'series',
  24124. subType: seriesType,
  24125. query: payload
  24126. }, function (seriesModel) {
  24127. seriesIndices.push(seriesModel.seriesIndex);
  24128. });
  24129. return seriesIndices;
  24130. }
  24131. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  24132. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  24133. payload = extend({}, payload);
  24134. if ("development" !== 'production') {
  24135. deprecateReplaceLog(payload.type, eventsMap[1]);
  24136. }
  24137. api.dispatchAction(extend(payload, {
  24138. type: eventsMap[1],
  24139. seriesIndex: getSeriesIndices(ecModel, payload)
  24140. }));
  24141. });
  24142. });
  24143. }
  24144. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  24145. var legacyEventName = type + eventPostfix;
  24146. if (!ecIns.isSilent(legacyEventName)) {
  24147. if ("development" !== 'production') {
  24148. deprecateLog("event " + legacyEventName + " is deprecated.");
  24149. }
  24150. ecModel.eachComponent({
  24151. mainType: 'series',
  24152. subType: 'pie'
  24153. }, function (seriesModel) {
  24154. var seriesIndex = seriesModel.seriesIndex;
  24155. var selectedMap = seriesModel.option.selectedMap;
  24156. var selected = payload.selected;
  24157. for (var i = 0; i < selected.length; i++) {
  24158. if (selected[i].seriesIndex === seriesIndex) {
  24159. var data = seriesModel.getData();
  24160. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  24161. ecIns.trigger(legacyEventName, {
  24162. type: legacyEventName,
  24163. seriesId: seriesModel.id,
  24164. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  24165. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  24166. });
  24167. }
  24168. }
  24169. });
  24170. }
  24171. }
  24172. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  24173. messageCenter.on('selectchanged', function (params) {
  24174. var ecModel = api.getModel();
  24175. if (params.isFromClick) {
  24176. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  24177. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  24178. } else if (params.fromAction === 'select') {
  24179. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  24180. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  24181. } else if (params.fromAction === 'unselect') {
  24182. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  24183. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  24184. }
  24185. });
  24186. }
  24187. /*
  24188. * Licensed to the Apache Software Foundation (ASF) under one
  24189. * or more contributor license agreements. See the NOTICE file
  24190. * distributed with this work for additional information
  24191. * regarding copyright ownership. The ASF licenses this file
  24192. * to you under the Apache License, Version 2.0 (the
  24193. * "License"); you may not use this file except in compliance
  24194. * with the License. You may obtain a copy of the License at
  24195. *
  24196. * http://www.apache.org/licenses/LICENSE-2.0
  24197. *
  24198. * Unless required by applicable law or agreed to in writing,
  24199. * software distributed under the License is distributed on an
  24200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24201. * KIND, either express or implied. See the License for the
  24202. * specific language governing permissions and limitations
  24203. * under the License.
  24204. */
  24205. /**
  24206. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24207. */
  24208. /*
  24209. * Licensed to the Apache Software Foundation (ASF) under one
  24210. * or more contributor license agreements. See the NOTICE file
  24211. * distributed with this work for additional information
  24212. * regarding copyright ownership. The ASF licenses this file
  24213. * to you under the Apache License, Version 2.0 (the
  24214. * "License"); you may not use this file except in compliance
  24215. * with the License. You may obtain a copy of the License at
  24216. *
  24217. * http://www.apache.org/licenses/LICENSE-2.0
  24218. *
  24219. * Unless required by applicable law or agreed to in writing,
  24220. * software distributed under the License is distributed on an
  24221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24222. * KIND, either express or implied. See the License for the
  24223. * specific language governing permissions and limitations
  24224. * under the License.
  24225. */
  24226. function findEventDispatcher(target, det, returnFirstMatch) {
  24227. var found;
  24228. while (target) {
  24229. if (det(target)) {
  24230. found = target;
  24231. if (returnFirstMatch) {
  24232. break;
  24233. }
  24234. }
  24235. target = target.__hostTarget || target.parent;
  24236. }
  24237. return found;
  24238. }
  24239. var wmUniqueIndex = Math.round(Math.random() * 9);
  24240. var supportDefineProperty = typeof Object.defineProperty === 'function';
  24241. var WeakMap = (function () {
  24242. function WeakMap() {
  24243. this._id = '__ec_inner_' + wmUniqueIndex++;
  24244. }
  24245. WeakMap.prototype.get = function (key) {
  24246. return this._guard(key)[this._id];
  24247. };
  24248. WeakMap.prototype.set = function (key, value) {
  24249. var target = this._guard(key);
  24250. if (supportDefineProperty) {
  24251. Object.defineProperty(target, this._id, {
  24252. value: value,
  24253. enumerable: false,
  24254. configurable: true
  24255. });
  24256. }
  24257. else {
  24258. target[this._id] = value;
  24259. }
  24260. return this;
  24261. };
  24262. WeakMap.prototype["delete"] = function (key) {
  24263. if (this.has(key)) {
  24264. delete this._guard(key)[this._id];
  24265. return true;
  24266. }
  24267. return false;
  24268. };
  24269. WeakMap.prototype.has = function (key) {
  24270. return !!this._guard(key)[this._id];
  24271. };
  24272. WeakMap.prototype._guard = function (key) {
  24273. if (key !== Object(key)) {
  24274. throw TypeError('Value of WeakMap is not a non-null object.');
  24275. }
  24276. return key;
  24277. };
  24278. return WeakMap;
  24279. }());
  24280. /**
  24281. * Triangle shape
  24282. * @inner
  24283. */
  24284. var Triangle = Path.extend({
  24285. type: 'triangle',
  24286. shape: {
  24287. cx: 0,
  24288. cy: 0,
  24289. width: 0,
  24290. height: 0
  24291. },
  24292. buildPath: function (path, shape) {
  24293. var cx = shape.cx;
  24294. var cy = shape.cy;
  24295. var width = shape.width / 2;
  24296. var height = shape.height / 2;
  24297. path.moveTo(cx, cy - height);
  24298. path.lineTo(cx + width, cy + height);
  24299. path.lineTo(cx - width, cy + height);
  24300. path.closePath();
  24301. }
  24302. });
  24303. /**
  24304. * Diamond shape
  24305. * @inner
  24306. */
  24307. var Diamond = Path.extend({
  24308. type: 'diamond',
  24309. shape: {
  24310. cx: 0,
  24311. cy: 0,
  24312. width: 0,
  24313. height: 0
  24314. },
  24315. buildPath: function (path, shape) {
  24316. var cx = shape.cx;
  24317. var cy = shape.cy;
  24318. var width = shape.width / 2;
  24319. var height = shape.height / 2;
  24320. path.moveTo(cx, cy - height);
  24321. path.lineTo(cx + width, cy);
  24322. path.lineTo(cx, cy + height);
  24323. path.lineTo(cx - width, cy);
  24324. path.closePath();
  24325. }
  24326. });
  24327. /**
  24328. * Pin shape
  24329. * @inner
  24330. */
  24331. var Pin = Path.extend({
  24332. type: 'pin',
  24333. shape: {
  24334. // x, y on the cusp
  24335. x: 0,
  24336. y: 0,
  24337. width: 0,
  24338. height: 0
  24339. },
  24340. buildPath: function (path, shape) {
  24341. var x = shape.x;
  24342. var y = shape.y;
  24343. var w = shape.width / 5 * 3; // Height must be larger than width
  24344. var h = Math.max(w, shape.height);
  24345. var r = w / 2; // Dist on y with tangent point and circle center
  24346. var dy = r * r / (h - r);
  24347. var cy = y - h + r + dy;
  24348. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  24349. var dx = Math.cos(angle) * r;
  24350. var tanX = Math.sin(angle);
  24351. var tanY = Math.cos(angle);
  24352. var cpLen = r * 0.6;
  24353. var cpLen2 = r * 0.7;
  24354. path.moveTo(x - dx, cy + dy);
  24355. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24356. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24357. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24358. path.closePath();
  24359. }
  24360. });
  24361. /**
  24362. * Arrow shape
  24363. * @inner
  24364. */
  24365. var Arrow = Path.extend({
  24366. type: 'arrow',
  24367. shape: {
  24368. x: 0,
  24369. y: 0,
  24370. width: 0,
  24371. height: 0
  24372. },
  24373. buildPath: function (ctx, shape) {
  24374. var height = shape.height;
  24375. var width = shape.width;
  24376. var x = shape.x;
  24377. var y = shape.y;
  24378. var dx = width / 3 * 2;
  24379. ctx.moveTo(x, y);
  24380. ctx.lineTo(x + dx, y + height);
  24381. ctx.lineTo(x, y + height / 4 * 3);
  24382. ctx.lineTo(x - dx, y + height);
  24383. ctx.lineTo(x, y);
  24384. ctx.closePath();
  24385. }
  24386. });
  24387. /**
  24388. * Map of path constructors
  24389. */
  24390. // TODO Use function to build symbol path.
  24391. var symbolCtors = {
  24392. line: Line,
  24393. rect: Rect,
  24394. roundRect: Rect,
  24395. square: Rect,
  24396. circle: Circle,
  24397. diamond: Diamond,
  24398. pin: Pin,
  24399. arrow: Arrow,
  24400. triangle: Triangle
  24401. };
  24402. var symbolShapeMakers = {
  24403. line: function (x, y, w, h, shape) {
  24404. shape.x1 = x;
  24405. shape.y1 = y + h / 2;
  24406. shape.x2 = x + w;
  24407. shape.y2 = y + h / 2;
  24408. },
  24409. rect: function (x, y, w, h, shape) {
  24410. shape.x = x;
  24411. shape.y = y;
  24412. shape.width = w;
  24413. shape.height = h;
  24414. },
  24415. roundRect: function (x, y, w, h, shape) {
  24416. shape.x = x;
  24417. shape.y = y;
  24418. shape.width = w;
  24419. shape.height = h;
  24420. shape.r = Math.min(w, h) / 4;
  24421. },
  24422. square: function (x, y, w, h, shape) {
  24423. var size = Math.min(w, h);
  24424. shape.x = x;
  24425. shape.y = y;
  24426. shape.width = size;
  24427. shape.height = size;
  24428. },
  24429. circle: function (x, y, w, h, shape) {
  24430. // Put circle in the center of square
  24431. shape.cx = x + w / 2;
  24432. shape.cy = y + h / 2;
  24433. shape.r = Math.min(w, h) / 2;
  24434. },
  24435. diamond: function (x, y, w, h, shape) {
  24436. shape.cx = x + w / 2;
  24437. shape.cy = y + h / 2;
  24438. shape.width = w;
  24439. shape.height = h;
  24440. },
  24441. pin: function (x, y, w, h, shape) {
  24442. shape.x = x + w / 2;
  24443. shape.y = y + h / 2;
  24444. shape.width = w;
  24445. shape.height = h;
  24446. },
  24447. arrow: function (x, y, w, h, shape) {
  24448. shape.x = x + w / 2;
  24449. shape.y = y + h / 2;
  24450. shape.width = w;
  24451. shape.height = h;
  24452. },
  24453. triangle: function (x, y, w, h, shape) {
  24454. shape.cx = x + w / 2;
  24455. shape.cy = y + h / 2;
  24456. shape.width = w;
  24457. shape.height = h;
  24458. }
  24459. };
  24460. var symbolBuildProxies = {};
  24461. each(symbolCtors, function (Ctor, name) {
  24462. symbolBuildProxies[name] = new Ctor();
  24463. });
  24464. var SymbolClz = Path.extend({
  24465. type: 'symbol',
  24466. shape: {
  24467. symbolType: '',
  24468. x: 0,
  24469. y: 0,
  24470. width: 0,
  24471. height: 0
  24472. },
  24473. calculateTextPosition: function (out, config, rect) {
  24474. var res = calculateTextPosition(out, config, rect);
  24475. var shape = this.shape;
  24476. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24477. res.y = rect.y + rect.height * 0.4;
  24478. }
  24479. return res;
  24480. },
  24481. buildPath: function (ctx, shape, inBundle) {
  24482. var symbolType = shape.symbolType;
  24483. if (symbolType !== 'none') {
  24484. var proxySymbol = symbolBuildProxies[symbolType];
  24485. if (!proxySymbol) {
  24486. // Default rect
  24487. symbolType = 'rect';
  24488. proxySymbol = symbolBuildProxies[symbolType];
  24489. }
  24490. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24491. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24492. }
  24493. }
  24494. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24495. function symbolPathSetColor(color, innerColor) {
  24496. if (this.type !== 'image') {
  24497. var symbolStyle = this.style;
  24498. if (this.__isEmptyBrush) {
  24499. symbolStyle.stroke = color;
  24500. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  24501. symbolStyle.lineWidth = 2;
  24502. } else if (this.shape.symbolType === 'line') {
  24503. symbolStyle.stroke = color;
  24504. } else {
  24505. symbolStyle.fill = color;
  24506. }
  24507. this.markRedraw();
  24508. }
  24509. }
  24510. /**
  24511. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24512. */
  24513. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  24514. keepAspect) {
  24515. // TODO Support image object, DynamicImage.
  24516. var isEmpty = symbolType.indexOf('empty') === 0;
  24517. if (isEmpty) {
  24518. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24519. }
  24520. var symbolPath;
  24521. if (symbolType.indexOf('image://') === 0) {
  24522. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24523. } else if (symbolType.indexOf('path://') === 0) {
  24524. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24525. } else {
  24526. symbolPath = new SymbolClz({
  24527. shape: {
  24528. symbolType: symbolType,
  24529. x: x,
  24530. y: y,
  24531. width: w,
  24532. height: h
  24533. }
  24534. });
  24535. }
  24536. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  24537. symbolPath.setColor = symbolPathSetColor;
  24538. if (color) {
  24539. symbolPath.setColor(color);
  24540. }
  24541. return symbolPath;
  24542. }
  24543. function normalizeSymbolSize(symbolSize) {
  24544. if (!isArray(symbolSize)) {
  24545. symbolSize = [+symbolSize, +symbolSize];
  24546. }
  24547. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24548. }
  24549. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24550. if (symbolOffset == null) {
  24551. return;
  24552. }
  24553. if (!isArray(symbolOffset)) {
  24554. symbolOffset = [symbolOffset, symbolOffset];
  24555. }
  24556. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24557. }
  24558. function isSafeNum(num) {
  24559. return isFinite(num);
  24560. }
  24561. function createLinearGradient(ctx, obj, rect) {
  24562. var x = obj.x == null ? 0 : obj.x;
  24563. var x2 = obj.x2 == null ? 1 : obj.x2;
  24564. var y = obj.y == null ? 0 : obj.y;
  24565. var y2 = obj.y2 == null ? 0 : obj.y2;
  24566. if (!obj.global) {
  24567. x = x * rect.width + rect.x;
  24568. x2 = x2 * rect.width + rect.x;
  24569. y = y * rect.height + rect.y;
  24570. y2 = y2 * rect.height + rect.y;
  24571. }
  24572. x = isSafeNum(x) ? x : 0;
  24573. x2 = isSafeNum(x2) ? x2 : 1;
  24574. y = isSafeNum(y) ? y : 0;
  24575. y2 = isSafeNum(y2) ? y2 : 0;
  24576. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24577. return canvasGradient;
  24578. }
  24579. function createRadialGradient(ctx, obj, rect) {
  24580. var width = rect.width;
  24581. var height = rect.height;
  24582. var min = Math.min(width, height);
  24583. var x = obj.x == null ? 0.5 : obj.x;
  24584. var y = obj.y == null ? 0.5 : obj.y;
  24585. var r = obj.r == null ? 0.5 : obj.r;
  24586. if (!obj.global) {
  24587. x = x * width + rect.x;
  24588. y = y * height + rect.y;
  24589. r = r * min;
  24590. }
  24591. x = isSafeNum(x) ? x : 0.5;
  24592. y = isSafeNum(y) ? y : 0.5;
  24593. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  24594. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24595. return canvasGradient;
  24596. }
  24597. function getCanvasGradient(ctx, obj, rect) {
  24598. var canvasGradient = obj.type === 'radial'
  24599. ? createRadialGradient(ctx, obj, rect)
  24600. : createLinearGradient(ctx, obj, rect);
  24601. var colorStops = obj.colorStops;
  24602. for (var i = 0; i < colorStops.length; i++) {
  24603. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24604. }
  24605. return canvasGradient;
  24606. }
  24607. function isClipPathChanged(clipPaths, prevClipPaths) {
  24608. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24609. return false;
  24610. }
  24611. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24612. return true;
  24613. }
  24614. for (var i = 0; i < clipPaths.length; i++) {
  24615. if (clipPaths[i] !== prevClipPaths[i]) {
  24616. return true;
  24617. }
  24618. }
  24619. return false;
  24620. }
  24621. function parseInt10(val) {
  24622. return parseInt(val, 10);
  24623. }
  24624. function getSize(root, whIdx, opts) {
  24625. var wh = ['width', 'height'][whIdx];
  24626. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24627. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24628. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24629. if (opts[wh] != null && opts[wh] !== 'auto') {
  24630. return parseFloat(opts[wh]);
  24631. }
  24632. var stl = document.defaultView.getComputedStyle(root);
  24633. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24634. - (parseInt10(stl[plt]) || 0)
  24635. - (parseInt10(stl[prb]) || 0)) | 0;
  24636. }
  24637. function normalizeLineDash(lineType, lineWidth) {
  24638. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24639. return null;
  24640. }
  24641. return lineType === 'dashed'
  24642. ? [4 * lineWidth, 2 * lineWidth]
  24643. : lineType === 'dotted'
  24644. ? [lineWidth]
  24645. : isNumber(lineType)
  24646. ? [lineType] : isArray(lineType) ? lineType : null;
  24647. }
  24648. function getLineDash(el) {
  24649. var style = el.style;
  24650. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24651. var lineDashOffset = style.lineDashOffset;
  24652. if (lineDash) {
  24653. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24654. if (lineScale_1 && lineScale_1 !== 1) {
  24655. lineDash = map(lineDash, function (rawVal) {
  24656. return rawVal / lineScale_1;
  24657. });
  24658. lineDashOffset /= lineScale_1;
  24659. }
  24660. }
  24661. return [lineDash, lineDashOffset];
  24662. }
  24663. var pathProxyForDraw = new PathProxy(true);
  24664. function styleHasStroke(style) {
  24665. var stroke = style.stroke;
  24666. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24667. }
  24668. function isValidStrokeFillStyle(strokeOrFill) {
  24669. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24670. }
  24671. function styleHasFill(style) {
  24672. var fill = style.fill;
  24673. return fill != null && fill !== 'none';
  24674. }
  24675. function doFillPath(ctx, style) {
  24676. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24677. var originalGlobalAlpha = ctx.globalAlpha;
  24678. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24679. ctx.fill();
  24680. ctx.globalAlpha = originalGlobalAlpha;
  24681. }
  24682. else {
  24683. ctx.fill();
  24684. }
  24685. }
  24686. function doStrokePath(ctx, style) {
  24687. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24688. var originalGlobalAlpha = ctx.globalAlpha;
  24689. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24690. ctx.stroke();
  24691. ctx.globalAlpha = originalGlobalAlpha;
  24692. }
  24693. else {
  24694. ctx.stroke();
  24695. }
  24696. }
  24697. function createCanvasPattern(ctx, pattern, el) {
  24698. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24699. if (isImageReady(image)) {
  24700. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24701. if (typeof DOMMatrix === 'function'
  24702. && canvasPattern
  24703. && canvasPattern.setTransform) {
  24704. var matrix = new DOMMatrix();
  24705. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24706. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24707. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24708. canvasPattern.setTransform(matrix);
  24709. }
  24710. return canvasPattern;
  24711. }
  24712. }
  24713. function brushPath(ctx, el, style, inBatch) {
  24714. var _a;
  24715. var hasStroke = styleHasStroke(style);
  24716. var hasFill = styleHasFill(style);
  24717. var strokePercent = style.strokePercent;
  24718. var strokePart = strokePercent < 1;
  24719. var firstDraw = !el.path;
  24720. if ((!el.silent || strokePart) && firstDraw) {
  24721. el.createPathProxy();
  24722. }
  24723. var path = el.path || pathProxyForDraw;
  24724. var dirtyFlag = el.__dirty;
  24725. if (!inBatch) {
  24726. var fill = style.fill;
  24727. var stroke = style.stroke;
  24728. var hasFillGradient = hasFill && !!fill.colorStops;
  24729. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24730. var hasFillPattern = hasFill && !!fill.image;
  24731. var hasStrokePattern = hasStroke && !!stroke.image;
  24732. var fillGradient = void 0;
  24733. var strokeGradient = void 0;
  24734. var fillPattern = void 0;
  24735. var strokePattern = void 0;
  24736. var rect = void 0;
  24737. if (hasFillGradient || hasStrokeGradient) {
  24738. rect = el.getBoundingRect();
  24739. }
  24740. if (hasFillGradient) {
  24741. fillGradient = dirtyFlag
  24742. ? getCanvasGradient(ctx, fill, rect)
  24743. : el.__canvasFillGradient;
  24744. el.__canvasFillGradient = fillGradient;
  24745. }
  24746. if (hasStrokeGradient) {
  24747. strokeGradient = dirtyFlag
  24748. ? getCanvasGradient(ctx, stroke, rect)
  24749. : el.__canvasStrokeGradient;
  24750. el.__canvasStrokeGradient = strokeGradient;
  24751. }
  24752. if (hasFillPattern) {
  24753. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24754. ? createCanvasPattern(ctx, fill, el)
  24755. : el.__canvasFillPattern;
  24756. el.__canvasFillPattern = fillPattern;
  24757. }
  24758. if (hasStrokePattern) {
  24759. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24760. ? createCanvasPattern(ctx, stroke, el)
  24761. : el.__canvasStrokePattern;
  24762. el.__canvasStrokePattern = fillPattern;
  24763. }
  24764. if (hasFillGradient) {
  24765. ctx.fillStyle = fillGradient;
  24766. }
  24767. else if (hasFillPattern) {
  24768. if (fillPattern) {
  24769. ctx.fillStyle = fillPattern;
  24770. }
  24771. else {
  24772. hasFill = false;
  24773. }
  24774. }
  24775. if (hasStrokeGradient) {
  24776. ctx.strokeStyle = strokeGradient;
  24777. }
  24778. else if (hasStrokePattern) {
  24779. if (strokePattern) {
  24780. ctx.strokeStyle = strokePattern;
  24781. }
  24782. else {
  24783. hasStroke = false;
  24784. }
  24785. }
  24786. }
  24787. var scale = el.getGlobalScale();
  24788. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24789. var lineDash;
  24790. var lineDashOffset;
  24791. if (ctx.setLineDash && style.lineDash) {
  24792. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24793. }
  24794. var needsRebuild = true;
  24795. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24796. path.setDPR(ctx.dpr);
  24797. if (strokePart) {
  24798. path.setContext(null);
  24799. }
  24800. else {
  24801. path.setContext(ctx);
  24802. needsRebuild = false;
  24803. }
  24804. path.reset();
  24805. el.buildPath(path, el.shape, inBatch);
  24806. path.toStatic();
  24807. el.pathUpdated();
  24808. }
  24809. if (needsRebuild) {
  24810. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24811. }
  24812. if (lineDash) {
  24813. ctx.setLineDash(lineDash);
  24814. ctx.lineDashOffset = lineDashOffset;
  24815. }
  24816. if (!inBatch) {
  24817. if (style.strokeFirst) {
  24818. if (hasStroke) {
  24819. doStrokePath(ctx, style);
  24820. }
  24821. if (hasFill) {
  24822. doFillPath(ctx, style);
  24823. }
  24824. }
  24825. else {
  24826. if (hasFill) {
  24827. doFillPath(ctx, style);
  24828. }
  24829. if (hasStroke) {
  24830. doStrokePath(ctx, style);
  24831. }
  24832. }
  24833. }
  24834. if (lineDash) {
  24835. ctx.setLineDash([]);
  24836. }
  24837. }
  24838. function brushImage(ctx, el, style) {
  24839. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24840. if (!image || !isImageReady(image)) {
  24841. return;
  24842. }
  24843. var x = style.x || 0;
  24844. var y = style.y || 0;
  24845. var width = el.getWidth();
  24846. var height = el.getHeight();
  24847. var aspect = image.width / image.height;
  24848. if (width == null && height != null) {
  24849. width = height * aspect;
  24850. }
  24851. else if (height == null && width != null) {
  24852. height = width / aspect;
  24853. }
  24854. else if (width == null && height == null) {
  24855. width = image.width;
  24856. height = image.height;
  24857. }
  24858. if (style.sWidth && style.sHeight) {
  24859. var sx = style.sx || 0;
  24860. var sy = style.sy || 0;
  24861. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24862. }
  24863. else if (style.sx && style.sy) {
  24864. var sx = style.sx;
  24865. var sy = style.sy;
  24866. var sWidth = width - sx;
  24867. var sHeight = height - sy;
  24868. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24869. }
  24870. else {
  24871. ctx.drawImage(image, x, y, width, height);
  24872. }
  24873. }
  24874. function brushText(ctx, el, style) {
  24875. var _a;
  24876. var text = style.text;
  24877. text != null && (text += '');
  24878. if (text) {
  24879. ctx.font = style.font || DEFAULT_FONT;
  24880. ctx.textAlign = style.textAlign;
  24881. ctx.textBaseline = style.textBaseline;
  24882. var lineDash = void 0;
  24883. var lineDashOffset = void 0;
  24884. if (ctx.setLineDash && style.lineDash) {
  24885. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24886. }
  24887. if (lineDash) {
  24888. ctx.setLineDash(lineDash);
  24889. ctx.lineDashOffset = lineDashOffset;
  24890. }
  24891. if (style.strokeFirst) {
  24892. if (styleHasStroke(style)) {
  24893. ctx.strokeText(text, style.x, style.y);
  24894. }
  24895. if (styleHasFill(style)) {
  24896. ctx.fillText(text, style.x, style.y);
  24897. }
  24898. }
  24899. else {
  24900. if (styleHasFill(style)) {
  24901. ctx.fillText(text, style.x, style.y);
  24902. }
  24903. if (styleHasStroke(style)) {
  24904. ctx.strokeText(text, style.x, style.y);
  24905. }
  24906. }
  24907. if (lineDash) {
  24908. ctx.setLineDash([]);
  24909. }
  24910. }
  24911. }
  24912. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24913. var STROKE_PROPS = [
  24914. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24915. ];
  24916. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24917. var styleChanged = false;
  24918. if (!forceSetAll) {
  24919. prevStyle = prevStyle || {};
  24920. if (style === prevStyle) {
  24921. return false;
  24922. }
  24923. }
  24924. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24925. flushPathDrawn(ctx, scope);
  24926. styleChanged = true;
  24927. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24928. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24929. }
  24930. if (forceSetAll || style.blend !== prevStyle.blend) {
  24931. if (!styleChanged) {
  24932. flushPathDrawn(ctx, scope);
  24933. styleChanged = true;
  24934. }
  24935. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24936. }
  24937. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24938. var propName = SHADOW_NUMBER_PROPS[i];
  24939. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24940. if (!styleChanged) {
  24941. flushPathDrawn(ctx, scope);
  24942. styleChanged = true;
  24943. }
  24944. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24945. }
  24946. }
  24947. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24948. if (!styleChanged) {
  24949. flushPathDrawn(ctx, scope);
  24950. styleChanged = true;
  24951. }
  24952. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24953. }
  24954. return styleChanged;
  24955. }
  24956. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24957. var style = getStyle(el, scope.inHover);
  24958. var prevStyle = forceSetAll
  24959. ? null
  24960. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24961. if (style === prevStyle) {
  24962. return false;
  24963. }
  24964. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24965. if (forceSetAll || style.fill !== prevStyle.fill) {
  24966. if (!styleChanged) {
  24967. flushPathDrawn(ctx, scope);
  24968. styleChanged = true;
  24969. }
  24970. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24971. }
  24972. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24973. if (!styleChanged) {
  24974. flushPathDrawn(ctx, scope);
  24975. styleChanged = true;
  24976. }
  24977. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24978. }
  24979. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24980. if (!styleChanged) {
  24981. flushPathDrawn(ctx, scope);
  24982. styleChanged = true;
  24983. }
  24984. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24985. }
  24986. if (el.hasStroke()) {
  24987. var lineWidth = style.lineWidth;
  24988. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  24989. if (ctx.lineWidth !== newLineWidth) {
  24990. if (!styleChanged) {
  24991. flushPathDrawn(ctx, scope);
  24992. styleChanged = true;
  24993. }
  24994. ctx.lineWidth = newLineWidth;
  24995. }
  24996. }
  24997. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24998. var prop = STROKE_PROPS[i];
  24999. var propName = prop[0];
  25000. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25001. if (!styleChanged) {
  25002. flushPathDrawn(ctx, scope);
  25003. styleChanged = true;
  25004. }
  25005. ctx[propName] = style[propName] || prop[1];
  25006. }
  25007. }
  25008. return styleChanged;
  25009. }
  25010. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  25011. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  25012. }
  25013. function setContextTransform(ctx, el) {
  25014. var m = el.transform;
  25015. var dpr = ctx.dpr || 1;
  25016. if (m) {
  25017. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  25018. }
  25019. else {
  25020. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  25021. }
  25022. }
  25023. function updateClipStatus(clipPaths, ctx, scope) {
  25024. var allClipped = false;
  25025. for (var i = 0; i < clipPaths.length; i++) {
  25026. var clipPath = clipPaths[i];
  25027. allClipped = allClipped || clipPath.isZeroArea();
  25028. setContextTransform(ctx, clipPath);
  25029. ctx.beginPath();
  25030. clipPath.buildPath(ctx, clipPath.shape);
  25031. ctx.clip();
  25032. }
  25033. scope.allClipped = allClipped;
  25034. }
  25035. function isTransformChanged(m0, m1) {
  25036. if (m0 && m1) {
  25037. return m0[0] !== m1[0]
  25038. || m0[1] !== m1[1]
  25039. || m0[2] !== m1[2]
  25040. || m0[3] !== m1[3]
  25041. || m0[4] !== m1[4]
  25042. || m0[5] !== m1[5];
  25043. }
  25044. else if (!m0 && !m1) {
  25045. return false;
  25046. }
  25047. return true;
  25048. }
  25049. var DRAW_TYPE_PATH = 1;
  25050. var DRAW_TYPE_IMAGE = 2;
  25051. var DRAW_TYPE_TEXT = 3;
  25052. var DRAW_TYPE_INCREMENTAL = 4;
  25053. function canPathBatch(style) {
  25054. var hasFill = styleHasFill(style);
  25055. var hasStroke = styleHasStroke(style);
  25056. return !(style.lineDash
  25057. || !(+hasFill ^ +hasStroke)
  25058. || (hasFill && typeof style.fill !== 'string')
  25059. || (hasStroke && typeof style.stroke !== 'string')
  25060. || style.strokePercent < 1
  25061. || style.strokeOpacity < 1
  25062. || style.fillOpacity < 1);
  25063. }
  25064. function flushPathDrawn(ctx, scope) {
  25065. scope.batchFill && ctx.fill();
  25066. scope.batchStroke && ctx.stroke();
  25067. scope.batchFill = '';
  25068. scope.batchStroke = '';
  25069. }
  25070. function getStyle(el, inHover) {
  25071. return inHover ? (el.__hoverStyle || el.style) : el.style;
  25072. }
  25073. function brushSingle(ctx, el) {
  25074. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  25075. }
  25076. function brush(ctx, el, scope, isLast) {
  25077. var m = el.transform;
  25078. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  25079. el.__dirty &= ~REDRAW_BIT;
  25080. el.__isRendered = false;
  25081. return;
  25082. }
  25083. var clipPaths = el.__clipPaths;
  25084. var prevElClipPaths = scope.prevElClipPaths;
  25085. var forceSetTransform = false;
  25086. var forceSetStyle = false;
  25087. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  25088. if (prevElClipPaths && prevElClipPaths.length) {
  25089. flushPathDrawn(ctx, scope);
  25090. ctx.restore();
  25091. forceSetStyle = forceSetTransform = true;
  25092. scope.prevElClipPaths = null;
  25093. scope.allClipped = false;
  25094. scope.prevEl = null;
  25095. }
  25096. if (clipPaths && clipPaths.length) {
  25097. flushPathDrawn(ctx, scope);
  25098. ctx.save();
  25099. updateClipStatus(clipPaths, ctx, scope);
  25100. forceSetTransform = true;
  25101. }
  25102. scope.prevElClipPaths = clipPaths;
  25103. }
  25104. if (scope.allClipped) {
  25105. el.__isRendered = false;
  25106. return;
  25107. }
  25108. el.beforeBrush && el.beforeBrush();
  25109. el.innerBeforeBrush();
  25110. var prevEl = scope.prevEl;
  25111. if (!prevEl) {
  25112. forceSetStyle = forceSetTransform = true;
  25113. }
  25114. var canBatchPath = el instanceof Path
  25115. && el.autoBatch
  25116. && canPathBatch(el.style);
  25117. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  25118. flushPathDrawn(ctx, scope);
  25119. setContextTransform(ctx, el);
  25120. }
  25121. else if (!canBatchPath) {
  25122. flushPathDrawn(ctx, scope);
  25123. }
  25124. var style = getStyle(el, scope.inHover);
  25125. if (el instanceof Path) {
  25126. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  25127. forceSetStyle = true;
  25128. scope.lastDrawType = DRAW_TYPE_PATH;
  25129. }
  25130. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25131. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  25132. ctx.beginPath();
  25133. }
  25134. brushPath(ctx, el, style, canBatchPath);
  25135. if (canBatchPath) {
  25136. scope.batchFill = style.fill || '';
  25137. scope.batchStroke = style.stroke || '';
  25138. }
  25139. }
  25140. else {
  25141. if (el instanceof TSpan) {
  25142. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  25143. forceSetStyle = true;
  25144. scope.lastDrawType = DRAW_TYPE_TEXT;
  25145. }
  25146. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25147. brushText(ctx, el, style);
  25148. }
  25149. else if (el instanceof ZRImage) {
  25150. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  25151. forceSetStyle = true;
  25152. scope.lastDrawType = DRAW_TYPE_IMAGE;
  25153. }
  25154. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  25155. brushImage(ctx, el, style);
  25156. }
  25157. else if (el.getTemporalDisplayables) {
  25158. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  25159. forceSetStyle = true;
  25160. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  25161. }
  25162. brushIncremental(ctx, el, scope);
  25163. }
  25164. }
  25165. if (canBatchPath && isLast) {
  25166. flushPathDrawn(ctx, scope);
  25167. }
  25168. el.innerAfterBrush();
  25169. el.afterBrush && el.afterBrush();
  25170. scope.prevEl = el;
  25171. el.__dirty = 0;
  25172. el.__isRendered = true;
  25173. }
  25174. function brushIncremental(ctx, el, scope) {
  25175. var displayables = el.getDisplayables();
  25176. var temporalDisplayables = el.getTemporalDisplayables();
  25177. ctx.save();
  25178. var innerScope = {
  25179. prevElClipPaths: null,
  25180. prevEl: null,
  25181. allClipped: false,
  25182. viewWidth: scope.viewWidth,
  25183. viewHeight: scope.viewHeight,
  25184. inHover: scope.inHover
  25185. };
  25186. var i;
  25187. var len;
  25188. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  25189. var displayable = displayables[i];
  25190. displayable.beforeBrush && displayable.beforeBrush();
  25191. displayable.innerBeforeBrush();
  25192. brush(ctx, displayable, innerScope, i === len - 1);
  25193. displayable.innerAfterBrush();
  25194. displayable.afterBrush && displayable.afterBrush();
  25195. innerScope.prevEl = displayable;
  25196. }
  25197. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  25198. var displayable = temporalDisplayables[i_1];
  25199. displayable.beforeBrush && displayable.beforeBrush();
  25200. displayable.innerBeforeBrush();
  25201. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  25202. displayable.innerAfterBrush();
  25203. displayable.afterBrush && displayable.afterBrush();
  25204. innerScope.prevEl = displayable;
  25205. }
  25206. el.clearTemporalDisplayables();
  25207. el.notClear = true;
  25208. ctx.restore();
  25209. }
  25210. var decalMap = new WeakMap();
  25211. var decalCache = new LRU(100);
  25212. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  25213. /**
  25214. * Create or update pattern image from decal options
  25215. *
  25216. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  25217. * @return {Pattern} pattern with generated image, null if no decal
  25218. */
  25219. function createOrUpdatePatternFromDecal(decalObject, api) {
  25220. if (decalObject === 'none') {
  25221. return null;
  25222. }
  25223. var dpr = api.getDevicePixelRatio();
  25224. var zr = api.getZr();
  25225. var isSVG = zr.painter.type === 'svg';
  25226. if (decalObject.dirty) {
  25227. decalMap["delete"](decalObject);
  25228. }
  25229. var oldPattern = decalMap.get(decalObject);
  25230. if (oldPattern) {
  25231. return oldPattern;
  25232. }
  25233. var decalOpt = defaults(decalObject, {
  25234. symbol: 'rect',
  25235. symbolSize: 1,
  25236. symbolKeepAspect: true,
  25237. color: 'rgba(0, 0, 0, 0.2)',
  25238. backgroundColor: null,
  25239. dashArrayX: 5,
  25240. dashArrayY: 5,
  25241. rotation: 0,
  25242. maxTileWidth: 512,
  25243. maxTileHeight: 512
  25244. });
  25245. if (decalOpt.backgroundColor === 'none') {
  25246. decalOpt.backgroundColor = null;
  25247. }
  25248. var pattern = {
  25249. repeat: 'repeat'
  25250. };
  25251. setPatternnSource(pattern);
  25252. pattern.rotation = decalOpt.rotation;
  25253. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  25254. decalMap.set(decalObject, pattern);
  25255. decalObject.dirty = false;
  25256. return pattern;
  25257. function setPatternnSource(pattern) {
  25258. var keys = [dpr];
  25259. var isValidKey = true;
  25260. for (var i = 0; i < decalKeys.length; ++i) {
  25261. var value = decalOpt[decalKeys[i]];
  25262. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  25263. isValidKey = false;
  25264. break;
  25265. }
  25266. keys.push(value);
  25267. }
  25268. var cacheKey;
  25269. if (isValidKey) {
  25270. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  25271. var cache = decalCache.get(cacheKey);
  25272. if (cache) {
  25273. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  25274. }
  25275. }
  25276. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  25277. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  25278. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  25279. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  25280. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  25281. var canvas = !isSVG && platformApi.createCanvas();
  25282. var svgRoot = isSVG && {
  25283. tag: 'g',
  25284. attrs: {},
  25285. key: 'dcl',
  25286. children: []
  25287. };
  25288. var pSize = getPatternSize();
  25289. var ctx;
  25290. if (canvas) {
  25291. canvas.width = pSize.width * dpr;
  25292. canvas.height = pSize.height * dpr;
  25293. ctx = canvas.getContext('2d');
  25294. }
  25295. brushDecal();
  25296. if (isValidKey) {
  25297. decalCache.put(cacheKey, canvas || svgRoot);
  25298. }
  25299. pattern.image = canvas;
  25300. pattern.svgElement = svgRoot;
  25301. pattern.svgWidth = pSize.width;
  25302. pattern.svgHeight = pSize.height;
  25303. /**
  25304. * Get minimum length that can make a repeatable pattern.
  25305. *
  25306. * @return {Object} pattern width and height
  25307. */
  25308. function getPatternSize() {
  25309. /**
  25310. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  25311. * |--- --- --- --- --- ...
  25312. * |-- -- -- -- -- -- -- -- ...
  25313. * |--- --- --- --- --- ...
  25314. * |-- -- -- -- -- -- -- -- ...
  25315. * So the minimum length of X is 15,
  25316. * which is the least common multiple of `3 + 2` and `2 + 1`
  25317. * |--- --- --- |--- --- ...
  25318. * |-- -- -- -- -- |-- -- -- ...
  25319. */
  25320. var width = 1;
  25321. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  25322. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  25323. }
  25324. var symbolRepeats = 1;
  25325. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25326. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25327. }
  25328. width *= symbolRepeats;
  25329. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25330. if ("development" !== 'production') {
  25331. var warn = function (attrName) {
  25332. /* eslint-disable-next-line */
  25333. 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.");
  25334. };
  25335. if (width > decalOpt.maxTileWidth) {
  25336. warn('maxTileWidth');
  25337. }
  25338. if (height > decalOpt.maxTileHeight) {
  25339. warn('maxTileHeight');
  25340. }
  25341. }
  25342. return {
  25343. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25344. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25345. };
  25346. }
  25347. function brushDecal() {
  25348. if (ctx) {
  25349. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25350. if (decalOpt.backgroundColor) {
  25351. ctx.fillStyle = decalOpt.backgroundColor;
  25352. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25353. }
  25354. }
  25355. var ySum = 0;
  25356. for (var i = 0; i < dashArrayY.length; ++i) {
  25357. ySum += dashArrayY[i];
  25358. }
  25359. if (ySum <= 0) {
  25360. // dashArrayY is 0, draw nothing
  25361. return;
  25362. }
  25363. var y = -lineBlockLengthY;
  25364. var yId = 0;
  25365. var yIdTotal = 0;
  25366. var xId0 = 0;
  25367. while (y < pSize.height) {
  25368. if (yId % 2 === 0) {
  25369. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25370. var x = 0;
  25371. var xId1 = 0;
  25372. var xId1Total = 0;
  25373. while (x < pSize.width * 2) {
  25374. var xSum = 0;
  25375. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25376. xSum += dashArrayX[xId0][i];
  25377. }
  25378. if (xSum <= 0) {
  25379. // Skip empty line
  25380. break;
  25381. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25382. if (xId1 % 2 === 0) {
  25383. var size = (1 - decalOpt.symbolSize) * 0.5;
  25384. var left = x + dashArrayX[xId0][xId1] * size;
  25385. var top_1 = y + dashArrayY[yId] * size;
  25386. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25387. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25388. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25389. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25390. }
  25391. x += dashArrayX[xId0][xId1];
  25392. ++xId1Total;
  25393. ++xId1;
  25394. if (xId1 === dashArrayX[xId0].length) {
  25395. xId1 = 0;
  25396. }
  25397. }
  25398. ++xId0;
  25399. if (xId0 === dashArrayX.length) {
  25400. xId0 = 0;
  25401. }
  25402. }
  25403. y += dashArrayY[yId];
  25404. ++yIdTotal;
  25405. ++yId;
  25406. if (yId === dashArrayY.length) {
  25407. yId = 0;
  25408. }
  25409. }
  25410. function brushSymbol(x, y, width, height, symbolType) {
  25411. var scale = isSVG ? 1 : dpr;
  25412. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25413. if (isSVG) {
  25414. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  25415. if (symbolVNode) {
  25416. svgRoot.children.push(symbolVNode);
  25417. }
  25418. } else {
  25419. // Paint to canvas for all other renderers.
  25420. brushSingle(ctx, symbol);
  25421. }
  25422. }
  25423. }
  25424. }
  25425. }
  25426. /**
  25427. * Convert symbol array into normalized array
  25428. *
  25429. * @param {string | (string | string[])[]} symbol symbol input
  25430. * @return {string[][]} normolized symbol array
  25431. */
  25432. function normalizeSymbolArray(symbol) {
  25433. if (!symbol || symbol.length === 0) {
  25434. return [['rect']];
  25435. }
  25436. if (isString(symbol)) {
  25437. return [[symbol]];
  25438. }
  25439. var isAllString = true;
  25440. for (var i = 0; i < symbol.length; ++i) {
  25441. if (!isString(symbol[i])) {
  25442. isAllString = false;
  25443. break;
  25444. }
  25445. }
  25446. if (isAllString) {
  25447. return normalizeSymbolArray([symbol]);
  25448. }
  25449. var result = [];
  25450. for (var i = 0; i < symbol.length; ++i) {
  25451. if (isString(symbol[i])) {
  25452. result.push([symbol[i]]);
  25453. } else {
  25454. result.push(symbol[i]);
  25455. }
  25456. }
  25457. return result;
  25458. }
  25459. /**
  25460. * Convert dash input into dashArray
  25461. *
  25462. * @param {DecalDashArrayX} dash dash input
  25463. * @return {number[][]} normolized dash array
  25464. */
  25465. function normalizeDashArrayX(dash) {
  25466. if (!dash || dash.length === 0) {
  25467. return [[0, 0]];
  25468. }
  25469. if (isNumber(dash)) {
  25470. var dashValue = Math.ceil(dash);
  25471. return [[dashValue, dashValue]];
  25472. }
  25473. /**
  25474. * [20, 5] should be normalized into [[20, 5]],
  25475. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25476. */
  25477. var isAllNumber = true;
  25478. for (var i = 0; i < dash.length; ++i) {
  25479. if (!isNumber(dash[i])) {
  25480. isAllNumber = false;
  25481. break;
  25482. }
  25483. }
  25484. if (isAllNumber) {
  25485. return normalizeDashArrayX([dash]);
  25486. }
  25487. var result = [];
  25488. for (var i = 0; i < dash.length; ++i) {
  25489. if (isNumber(dash[i])) {
  25490. var dashValue = Math.ceil(dash[i]);
  25491. result.push([dashValue, dashValue]);
  25492. } else {
  25493. var dashValue = map(dash[i], function (n) {
  25494. return Math.ceil(n);
  25495. });
  25496. if (dashValue.length % 2 === 1) {
  25497. // [4, 2, 1] means |---- - -- |---- - -- |
  25498. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25499. result.push(dashValue.concat(dashValue));
  25500. } else {
  25501. result.push(dashValue);
  25502. }
  25503. }
  25504. }
  25505. return result;
  25506. }
  25507. /**
  25508. * Convert dash input into dashArray
  25509. *
  25510. * @param {DecalDashArrayY} dash dash input
  25511. * @return {number[]} normolized dash array
  25512. */
  25513. function normalizeDashArrayY(dash) {
  25514. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25515. return [0, 0];
  25516. }
  25517. if (isNumber(dash)) {
  25518. var dashValue_1 = Math.ceil(dash);
  25519. return [dashValue_1, dashValue_1];
  25520. }
  25521. var dashValue = map(dash, function (n) {
  25522. return Math.ceil(n);
  25523. });
  25524. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25525. }
  25526. /**
  25527. * Get block length of each line. A block is the length of dash line and space.
  25528. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25529. * that, so the block length of this line is 5.
  25530. *
  25531. * @param {number[][]} dash dash array of X or Y
  25532. * @return {number[]} block length of each line
  25533. */
  25534. function getLineBlockLengthX(dash) {
  25535. return map(dash, function (line) {
  25536. return getLineBlockLengthY(line);
  25537. });
  25538. }
  25539. function getLineBlockLengthY(dash) {
  25540. var blockLength = 0;
  25541. for (var i = 0; i < dash.length; ++i) {
  25542. blockLength += dash[i];
  25543. }
  25544. if (dash.length % 2 === 1) {
  25545. // [4, 2, 1] means |---- - -- |---- - -- |
  25546. // So total length is (4 + 2 + 1) * 2
  25547. return blockLength * 2;
  25548. }
  25549. return blockLength;
  25550. }
  25551. function decalVisual(ecModel, api) {
  25552. ecModel.eachRawSeries(function (seriesModel) {
  25553. if (ecModel.isSeriesFiltered(seriesModel)) {
  25554. return;
  25555. }
  25556. var data = seriesModel.getData();
  25557. if (data.hasItemVisual()) {
  25558. data.each(function (idx) {
  25559. var decal = data.getItemVisual(idx, 'decal');
  25560. if (decal) {
  25561. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25562. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25563. }
  25564. });
  25565. }
  25566. var decal = data.getVisual('decal');
  25567. if (decal) {
  25568. var style = data.getVisual('style');
  25569. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25570. }
  25571. });
  25572. }
  25573. var lifecycle = new Eventful();
  25574. // The implementations will be registered when installing the component.
  25575. // Avoid these code being bundled to the core module.
  25576. var implsStore = {}; // TODO Type
  25577. function registerImpl(name, impl) {
  25578. if ("development" !== 'production') {
  25579. if (implsStore[name]) {
  25580. error("Already has an implementation of " + name + ".");
  25581. }
  25582. }
  25583. implsStore[name] = impl;
  25584. }
  25585. function getImpl(name) {
  25586. if ("development" !== 'production') {
  25587. if (!implsStore[name]) {
  25588. error("Implementation of " + name + " doesn't exists.");
  25589. }
  25590. }
  25591. return implsStore[name];
  25592. }
  25593. var version$1 = '5.4.2';
  25594. var dependencies = {
  25595. zrender: '5.4.3'
  25596. };
  25597. var TEST_FRAME_REMAIN_TIME = 1;
  25598. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  25599. // So data stack stage should be in front of data processing stage.
  25600. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  25601. // put at the beginning of data processing.
  25602. var PRIORITY_PROCESSOR_FILTER = 1000;
  25603. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25604. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25605. var PRIORITY_VISUAL_LAYOUT = 1000;
  25606. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25607. var PRIORITY_VISUAL_GLOBAL = 2000;
  25608. var PRIORITY_VISUAL_CHART = 3000;
  25609. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25610. // overwrite the viusal result of component (like `visualMap`)
  25611. // using data item specific setting (like itemStyle.xxx on data item)
  25612. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25613. // visual result like `symbolSize`.
  25614. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25615. var PRIORITY_VISUAL_BRUSH = 5000;
  25616. var PRIORITY_VISUAL_ARIA = 6000;
  25617. var PRIORITY_VISUAL_DECAL = 7000;
  25618. var PRIORITY = {
  25619. PROCESSOR: {
  25620. FILTER: PRIORITY_PROCESSOR_FILTER,
  25621. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25622. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25623. },
  25624. VISUAL: {
  25625. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25626. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25627. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25628. CHART: PRIORITY_VISUAL_CHART,
  25629. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25630. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25631. BRUSH: PRIORITY_VISUAL_BRUSH,
  25632. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25633. ARIA: PRIORITY_VISUAL_ARIA,
  25634. DECAL: PRIORITY_VISUAL_DECAL
  25635. }
  25636. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25637. // where they must not be invoked nestedly, except the only case: invoke
  25638. // dispatchAction with updateMethod "none" in main process.
  25639. // This flag is used to carry out this rule.
  25640. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25641. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25642. var PENDING_UPDATE = '__pendingUpdate';
  25643. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25644. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25645. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25646. var CONNECT_STATUS_PENDING = 0;
  25647. var CONNECT_STATUS_UPDATING = 1;
  25648. var CONNECT_STATUS_UPDATED = 2;
  25649. function createRegisterEventWithLowercaseECharts(method) {
  25650. return function () {
  25651. var args = [];
  25652. for (var _i = 0; _i < arguments.length; _i++) {
  25653. args[_i] = arguments[_i];
  25654. }
  25655. if (this.isDisposed()) {
  25656. disposedWarning(this.id);
  25657. return;
  25658. }
  25659. return toLowercaseNameAndCallEventful(this, method, args);
  25660. };
  25661. }
  25662. function createRegisterEventWithLowercaseMessageCenter(method) {
  25663. return function () {
  25664. var args = [];
  25665. for (var _i = 0; _i < arguments.length; _i++) {
  25666. args[_i] = arguments[_i];
  25667. }
  25668. return toLowercaseNameAndCallEventful(this, method, args);
  25669. };
  25670. }
  25671. function toLowercaseNameAndCallEventful(host, method, args) {
  25672. // `args[0]` is event name. Event name is all lowercase.
  25673. args[0] = args[0] && args[0].toLowerCase();
  25674. return Eventful.prototype[method].apply(host, args);
  25675. }
  25676. var MessageCenter =
  25677. /** @class */
  25678. function (_super) {
  25679. __extends(MessageCenter, _super);
  25680. function MessageCenter() {
  25681. return _super !== null && _super.apply(this, arguments) || this;
  25682. }
  25683. return MessageCenter;
  25684. }(Eventful);
  25685. var messageCenterProto = MessageCenter.prototype;
  25686. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25687. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  25688. // Internal method names for class ECharts
  25689. // ---------------------------------------
  25690. var prepare;
  25691. var prepareView;
  25692. var updateDirectly;
  25693. var updateMethods;
  25694. var doConvertPixel;
  25695. var updateStreamModes;
  25696. var doDispatchAction;
  25697. var flushPendingActions;
  25698. var triggerUpdatedEvent;
  25699. var bindRenderedEvent;
  25700. var bindMouseEvent;
  25701. var render;
  25702. var renderComponents;
  25703. var renderSeries;
  25704. var createExtensionAPI;
  25705. var enableConnect;
  25706. var markStatusToUpdate;
  25707. var applyChangedStates;
  25708. var ECharts =
  25709. /** @class */
  25710. function (_super) {
  25711. __extends(ECharts, _super);
  25712. function ECharts(dom, // Theme name or themeOption.
  25713. theme, opts) {
  25714. var _this = _super.call(this, new ECEventProcessor()) || this;
  25715. _this._chartsViews = [];
  25716. _this._chartsMap = {};
  25717. _this._componentsViews = [];
  25718. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  25719. _this._pendingActions = [];
  25720. opts = opts || {}; // Get theme by name
  25721. if (isString(theme)) {
  25722. theme = themeStorage[theme];
  25723. }
  25724. _this._dom = dom;
  25725. var defaultRenderer = 'canvas';
  25726. var defaultCoarsePointer = 'auto';
  25727. var defaultUseDirtyRect = false;
  25728. if ("development" !== 'production') {
  25729. var root =
  25730. /* eslint-disable-next-line */
  25731. env.hasGlobalWindow ? window : global;
  25732. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  25733. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  25734. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  25735. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  25736. }
  25737. var zr = _this._zr = init(dom, {
  25738. renderer: opts.renderer || defaultRenderer,
  25739. devicePixelRatio: opts.devicePixelRatio,
  25740. width: opts.width,
  25741. height: opts.height,
  25742. ssr: opts.ssr,
  25743. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  25744. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  25745. pointerSize: opts.pointerSize
  25746. });
  25747. _this._ssr = opts.ssr; // Expect 60 fps.
  25748. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25749. theme = clone(theme);
  25750. theme && globalBackwardCompat(theme, true);
  25751. _this._theme = theme;
  25752. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25753. _this._coordSysMgr = new CoordinateSystemManager();
  25754. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  25755. function prioritySortFunc(a, b) {
  25756. return a.__prio - b.__prio;
  25757. }
  25758. sort(visualFuncs, prioritySortFunc);
  25759. sort(dataProcessorFuncs, prioritySortFunc);
  25760. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25761. _this._messageCenter = new MessageCenter(); // Init mouse events
  25762. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  25763. _this.resize = bind(_this.resize, _this);
  25764. zr.animation.on('frame', _this._onframe, _this);
  25765. bindRenderedEvent(zr, _this);
  25766. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  25767. setAsPrimitive(_this);
  25768. return _this;
  25769. }
  25770. ECharts.prototype._onframe = function () {
  25771. if (this._disposed) {
  25772. return;
  25773. }
  25774. applyChangedStates(this);
  25775. var scheduler = this._scheduler; // Lazy update
  25776. if (this[PENDING_UPDATE]) {
  25777. var silent = this[PENDING_UPDATE].silent;
  25778. this[IN_MAIN_PROCESS_KEY] = true;
  25779. try {
  25780. prepare(this);
  25781. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25782. } catch (e) {
  25783. this[IN_MAIN_PROCESS_KEY] = false;
  25784. this[PENDING_UPDATE] = null;
  25785. throw e;
  25786. } // At present, in each frame, zrender performs:
  25787. // (1) animation step forward.
  25788. // (2) trigger('frame') (where this `_onframe` is called)
  25789. // (3) zrender flush (render).
  25790. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25791. // will render the final state of the elements before the real animation started.
  25792. this._zr.flush();
  25793. this[IN_MAIN_PROCESS_KEY] = false;
  25794. this[PENDING_UPDATE] = null;
  25795. flushPendingActions.call(this, silent);
  25796. triggerUpdatedEvent.call(this, silent);
  25797. } // Avoid do both lazy update and progress in one frame.
  25798. else if (scheduler.unfinished) {
  25799. // Stream progress.
  25800. var remainTime = TEST_FRAME_REMAIN_TIME;
  25801. var ecModel = this._model;
  25802. var api = this._api;
  25803. scheduler.unfinished = false;
  25804. do {
  25805. var startTime = +new Date();
  25806. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  25807. scheduler.performDataProcessorTasks(ecModel);
  25808. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  25809. // each frame is not a good user experience. So we follow the rule that
  25810. // the extent of the coordinate system is determined in the first frame (the
  25811. // frame is executed immediately after task reset.
  25812. // this._coordSysMgr.update(ecModel, api);
  25813. // console.log('--- ec frame visual ---', remainTime);
  25814. scheduler.performVisualTasks(ecModel);
  25815. renderSeries(this, this._model, api, 'remain', {});
  25816. remainTime -= +new Date() - startTime;
  25817. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  25818. if (!scheduler.unfinished) {
  25819. this._zr.flush();
  25820. } // Else, zr flushing be ensue within the same frame,
  25821. // because zr flushing is after onframe event.
  25822. }
  25823. };
  25824. ECharts.prototype.getDom = function () {
  25825. return this._dom;
  25826. };
  25827. ECharts.prototype.getId = function () {
  25828. return this.id;
  25829. };
  25830. ECharts.prototype.getZr = function () {
  25831. return this._zr;
  25832. };
  25833. ECharts.prototype.isSSR = function () {
  25834. return this._ssr;
  25835. };
  25836. /* eslint-disable-next-line */
  25837. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25838. if (this[IN_MAIN_PROCESS_KEY]) {
  25839. if ("development" !== 'production') {
  25840. error('`setOption` should not be called during main process.');
  25841. }
  25842. return;
  25843. }
  25844. if (this._disposed) {
  25845. disposedWarning(this.id);
  25846. return;
  25847. }
  25848. var silent;
  25849. var replaceMerge;
  25850. var transitionOpt;
  25851. if (isObject(notMerge)) {
  25852. lazyUpdate = notMerge.lazyUpdate;
  25853. silent = notMerge.silent;
  25854. replaceMerge = notMerge.replaceMerge;
  25855. transitionOpt = notMerge.transition;
  25856. notMerge = notMerge.notMerge;
  25857. }
  25858. this[IN_MAIN_PROCESS_KEY] = true;
  25859. if (!this._model || notMerge) {
  25860. var optionManager = new OptionManager(this._api);
  25861. var theme = this._theme;
  25862. var ecModel = this._model = new GlobalModel();
  25863. ecModel.scheduler = this._scheduler;
  25864. ecModel.ssr = this._ssr;
  25865. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25866. }
  25867. this._model.setOption(option, {
  25868. replaceMerge: replaceMerge
  25869. }, optionPreprocessorFuncs);
  25870. var updateParams = {
  25871. seriesTransition: transitionOpt,
  25872. optionChanged: true
  25873. };
  25874. if (lazyUpdate) {
  25875. this[PENDING_UPDATE] = {
  25876. silent: silent,
  25877. updateParams: updateParams
  25878. };
  25879. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25880. // It should wake it up to make sure zrender start to render at the next frame.
  25881. this.getZr().wakeUp();
  25882. } else {
  25883. try {
  25884. prepare(this);
  25885. updateMethods.update.call(this, null, updateParams);
  25886. } catch (e) {
  25887. this[PENDING_UPDATE] = null;
  25888. this[IN_MAIN_PROCESS_KEY] = false;
  25889. throw e;
  25890. } // Ensure zr refresh sychronously, and then pixel in canvas can be
  25891. // fetched after `setOption`.
  25892. if (!this._ssr) {
  25893. // not use flush when using ssr mode.
  25894. this._zr.flush();
  25895. }
  25896. this[PENDING_UPDATE] = null;
  25897. this[IN_MAIN_PROCESS_KEY] = false;
  25898. flushPendingActions.call(this, silent);
  25899. triggerUpdatedEvent.call(this, silent);
  25900. }
  25901. };
  25902. /**
  25903. * @deprecated
  25904. */
  25905. ECharts.prototype.setTheme = function () {
  25906. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25907. }; // We don't want developers to use getModel directly.
  25908. ECharts.prototype.getModel = function () {
  25909. return this._model;
  25910. };
  25911. ECharts.prototype.getOption = function () {
  25912. return this._model && this._model.getOption();
  25913. };
  25914. ECharts.prototype.getWidth = function () {
  25915. return this._zr.getWidth();
  25916. };
  25917. ECharts.prototype.getHeight = function () {
  25918. return this._zr.getHeight();
  25919. };
  25920. ECharts.prototype.getDevicePixelRatio = function () {
  25921. return this._zr.painter.dpr
  25922. /* eslint-disable-next-line */
  25923. || env.hasGlobalWindow && window.devicePixelRatio || 1;
  25924. };
  25925. /**
  25926. * Get canvas which has all thing rendered
  25927. * @deprecated Use renderToCanvas instead.
  25928. */
  25929. ECharts.prototype.getRenderedCanvas = function (opts) {
  25930. if ("development" !== 'production') {
  25931. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  25932. }
  25933. return this.renderToCanvas(opts);
  25934. };
  25935. ECharts.prototype.renderToCanvas = function (opts) {
  25936. opts = opts || {};
  25937. var painter = this._zr.painter;
  25938. if ("development" !== 'production') {
  25939. if (painter.type !== 'canvas') {
  25940. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  25941. }
  25942. }
  25943. return painter.getRenderedCanvas({
  25944. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  25945. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  25946. });
  25947. };
  25948. ECharts.prototype.renderToSVGString = function (opts) {
  25949. opts = opts || {};
  25950. var painter = this._zr.painter;
  25951. if ("development" !== 'production') {
  25952. if (painter.type !== 'svg') {
  25953. throw new Error('renderToSVGString can only be used in the svg renderer.');
  25954. }
  25955. }
  25956. return painter.renderToString({
  25957. useViewBox: opts.useViewBox
  25958. });
  25959. };
  25960. /**
  25961. * Get svg data url
  25962. */
  25963. ECharts.prototype.getSvgDataURL = function () {
  25964. if (!env.svgSupported) {
  25965. return;
  25966. }
  25967. var zr = this._zr;
  25968. var list = zr.storage.getDisplayList(); // Stop animations
  25969. each(list, function (el) {
  25970. el.stopAnimation(null, true);
  25971. });
  25972. return zr.painter.toDataURL();
  25973. };
  25974. ECharts.prototype.getDataURL = function (opts) {
  25975. if (this._disposed) {
  25976. disposedWarning(this.id);
  25977. return;
  25978. }
  25979. opts = opts || {};
  25980. var excludeComponents = opts.excludeComponents;
  25981. var ecModel = this._model;
  25982. var excludesComponentViews = [];
  25983. var self = this;
  25984. each(excludeComponents, function (componentType) {
  25985. ecModel.eachComponent({
  25986. mainType: componentType
  25987. }, function (component) {
  25988. var view = self._componentsMap[component.__viewId];
  25989. if (!view.group.ignore) {
  25990. excludesComponentViews.push(view);
  25991. view.group.ignore = true;
  25992. }
  25993. });
  25994. });
  25995. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  25996. each(excludesComponentViews, function (view) {
  25997. view.group.ignore = false;
  25998. });
  25999. return url;
  26000. };
  26001. ECharts.prototype.getConnectedDataURL = function (opts) {
  26002. if (this._disposed) {
  26003. disposedWarning(this.id);
  26004. return;
  26005. }
  26006. var isSvg = opts.type === 'svg';
  26007. var groupId = this.group;
  26008. var mathMin = Math.min;
  26009. var mathMax = Math.max;
  26010. var MAX_NUMBER = Infinity;
  26011. if (connectedGroups[groupId]) {
  26012. var left_1 = MAX_NUMBER;
  26013. var top_1 = MAX_NUMBER;
  26014. var right_1 = -MAX_NUMBER;
  26015. var bottom_1 = -MAX_NUMBER;
  26016. var canvasList_1 = [];
  26017. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  26018. each(instances$1, function (chart, id) {
  26019. if (chart.group === groupId) {
  26020. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  26021. var boundingRect = chart.getDom().getBoundingClientRect();
  26022. left_1 = mathMin(boundingRect.left, left_1);
  26023. top_1 = mathMin(boundingRect.top, top_1);
  26024. right_1 = mathMax(boundingRect.right, right_1);
  26025. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  26026. canvasList_1.push({
  26027. dom: canvas,
  26028. left: boundingRect.left,
  26029. top: boundingRect.top
  26030. });
  26031. }
  26032. });
  26033. left_1 *= dpr_1;
  26034. top_1 *= dpr_1;
  26035. right_1 *= dpr_1;
  26036. bottom_1 *= dpr_1;
  26037. var width = right_1 - left_1;
  26038. var height = bottom_1 - top_1;
  26039. var targetCanvas = platformApi.createCanvas();
  26040. var zr_1 = init(targetCanvas, {
  26041. renderer: isSvg ? 'svg' : 'canvas'
  26042. });
  26043. zr_1.resize({
  26044. width: width,
  26045. height: height
  26046. });
  26047. if (isSvg) {
  26048. var content_1 = '';
  26049. each(canvasList_1, function (item) {
  26050. var x = item.left - left_1;
  26051. var y = item.top - top_1;
  26052. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  26053. });
  26054. zr_1.painter.getSvgRoot().innerHTML = content_1;
  26055. if (opts.connectedBackgroundColor) {
  26056. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  26057. }
  26058. zr_1.refreshImmediately();
  26059. return zr_1.painter.toDataURL();
  26060. } else {
  26061. // Background between the charts
  26062. if (opts.connectedBackgroundColor) {
  26063. zr_1.add(new Rect({
  26064. shape: {
  26065. x: 0,
  26066. y: 0,
  26067. width: width,
  26068. height: height
  26069. },
  26070. style: {
  26071. fill: opts.connectedBackgroundColor
  26072. }
  26073. }));
  26074. }
  26075. each(canvasList_1, function (item) {
  26076. var img = new ZRImage({
  26077. style: {
  26078. x: item.left * dpr_1 - left_1,
  26079. y: item.top * dpr_1 - top_1,
  26080. image: item.dom
  26081. }
  26082. });
  26083. zr_1.add(img);
  26084. });
  26085. zr_1.refreshImmediately();
  26086. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  26087. }
  26088. } else {
  26089. return this.getDataURL(opts);
  26090. }
  26091. };
  26092. ECharts.prototype.convertToPixel = function (finder, value) {
  26093. return doConvertPixel(this, 'convertToPixel', finder, value);
  26094. };
  26095. ECharts.prototype.convertFromPixel = function (finder, value) {
  26096. return doConvertPixel(this, 'convertFromPixel', finder, value);
  26097. };
  26098. /**
  26099. * Is the specified coordinate systems or components contain the given pixel point.
  26100. * @param {Array|number} value
  26101. * @return {boolean} result
  26102. */
  26103. ECharts.prototype.containPixel = function (finder, value) {
  26104. if (this._disposed) {
  26105. disposedWarning(this.id);
  26106. return;
  26107. }
  26108. var ecModel = this._model;
  26109. var result;
  26110. var findResult = parseFinder(ecModel, finder);
  26111. each(findResult, function (models, key) {
  26112. key.indexOf('Models') >= 0 && each(models, function (model) {
  26113. var coordSys = model.coordinateSystem;
  26114. if (coordSys && coordSys.containPoint) {
  26115. result = result || !!coordSys.containPoint(value);
  26116. } else if (key === 'seriesModels') {
  26117. var view = this._chartsMap[model.__viewId];
  26118. if (view && view.containPoint) {
  26119. result = result || view.containPoint(value, model);
  26120. } else {
  26121. if ("development" !== 'production') {
  26122. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  26123. }
  26124. }
  26125. } else {
  26126. if ("development" !== 'production') {
  26127. warn(key + ': containPoint is not supported');
  26128. }
  26129. }
  26130. }, this);
  26131. }, this);
  26132. return !!result;
  26133. };
  26134. /**
  26135. * Get visual from series or data.
  26136. * @param finder
  26137. * If string, e.g., 'series', means {seriesIndex: 0}.
  26138. * If Object, could contain some of these properties below:
  26139. * {
  26140. * seriesIndex / seriesId / seriesName,
  26141. * dataIndex / dataIndexInside
  26142. * }
  26143. * If dataIndex is not specified, series visual will be fetched,
  26144. * but not data item visual.
  26145. * If all of seriesIndex, seriesId, seriesName are not specified,
  26146. * visual will be fetched from first series.
  26147. * @param visualType 'color', 'symbol', 'symbolSize'
  26148. */
  26149. ECharts.prototype.getVisual = function (finder, visualType) {
  26150. var ecModel = this._model;
  26151. var parsedFinder = parseFinder(ecModel, finder, {
  26152. defaultMainType: 'series'
  26153. });
  26154. var seriesModel = parsedFinder.seriesModel;
  26155. if ("development" !== 'production') {
  26156. if (!seriesModel) {
  26157. warn('There is no specified series model');
  26158. }
  26159. }
  26160. var data = seriesModel.getData();
  26161. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  26162. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  26163. };
  26164. /**
  26165. * Get view of corresponding component model
  26166. */
  26167. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  26168. return this._componentsMap[componentModel.__viewId];
  26169. };
  26170. /**
  26171. * Get view of corresponding series model
  26172. */
  26173. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  26174. return this._chartsMap[seriesModel.__viewId];
  26175. };
  26176. ECharts.prototype._initEvents = function () {
  26177. var _this = this;
  26178. each(MOUSE_EVENT_NAMES, function (eveName) {
  26179. var handler = function (e) {
  26180. var ecModel = _this.getModel();
  26181. var el = e.target;
  26182. var params;
  26183. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  26184. if (isGlobalOut) {
  26185. params = {};
  26186. } else {
  26187. el && findEventDispatcher(el, function (parent) {
  26188. var ecData = getECData(parent);
  26189. if (ecData && ecData.dataIndex != null) {
  26190. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  26191. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  26192. return true;
  26193. } // If element has custom eventData of components
  26194. else if (ecData.eventData) {
  26195. params = extend({}, ecData.eventData);
  26196. return true;
  26197. }
  26198. }, true);
  26199. } // Contract: if params prepared in mouse event,
  26200. // these properties must be specified:
  26201. // {
  26202. // componentType: string (component main type)
  26203. // componentIndex: number
  26204. // }
  26205. // Otherwise event query can not work.
  26206. if (params) {
  26207. var componentType = params.componentType;
  26208. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  26209. // markLine/markPoint/markArea, the componentType is
  26210. // 'markLine'/'markPoint'/'markArea', but we should better
  26211. // enable them to be queried by seriesIndex, since their
  26212. // option is set in each series.
  26213. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  26214. componentType = 'series';
  26215. componentIndex = params.seriesIndex;
  26216. }
  26217. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  26218. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  26219. if ("development" !== 'production') {
  26220. // `event.componentType` and `event[componentTpype + 'Index']` must not
  26221. // be missed, otherwise there is no way to distinguish source component.
  26222. // See `dataFormat.getDataParams`.
  26223. if (!isGlobalOut && !(model && view)) {
  26224. warn('model or view can not be found by params');
  26225. }
  26226. }
  26227. params.event = e;
  26228. params.type = eveName;
  26229. _this._$eventProcessor.eventInfo = {
  26230. targetEl: el,
  26231. packedEvent: params,
  26232. model: model,
  26233. view: view
  26234. };
  26235. _this.trigger(eveName, params);
  26236. }
  26237. }; // Consider that some component (like tooltip, brush, ...)
  26238. // register zr event handler, but user event handler might
  26239. // do anything, such as call `setOption` or `dispatchAction`,
  26240. // which probably update any of the content and probably
  26241. // cause problem if it is called previous other inner handlers.
  26242. handler.zrEventfulCallAtLast = true;
  26243. _this._zr.on(eveName, handler, _this);
  26244. });
  26245. each(eventActionMap, function (actionType, eventType) {
  26246. _this._messageCenter.on(eventType, function (event) {
  26247. this.trigger(eventType, event);
  26248. }, _this);
  26249. }); // Extra events
  26250. // TODO register?
  26251. each(['selectchanged'], function (eventType) {
  26252. _this._messageCenter.on(eventType, function (event) {
  26253. this.trigger(eventType, event);
  26254. }, _this);
  26255. });
  26256. handleLegacySelectEvents(this._messageCenter, this, this._api);
  26257. };
  26258. ECharts.prototype.isDisposed = function () {
  26259. return this._disposed;
  26260. };
  26261. ECharts.prototype.clear = function () {
  26262. if (this._disposed) {
  26263. disposedWarning(this.id);
  26264. return;
  26265. }
  26266. this.setOption({
  26267. series: []
  26268. }, true);
  26269. };
  26270. ECharts.prototype.dispose = function () {
  26271. if (this._disposed) {
  26272. disposedWarning(this.id);
  26273. return;
  26274. }
  26275. this._disposed = true;
  26276. var dom = this.getDom();
  26277. if (dom) {
  26278. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  26279. }
  26280. var chart = this;
  26281. var api = chart._api;
  26282. var ecModel = chart._model;
  26283. each(chart._componentsViews, function (component) {
  26284. component.dispose(ecModel, api);
  26285. });
  26286. each(chart._chartsViews, function (chart) {
  26287. chart.dispose(ecModel, api);
  26288. }); // Dispose after all views disposed
  26289. chart._zr.dispose(); // Set properties to null.
  26290. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  26291. 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;
  26292. delete instances$1[chart.id];
  26293. };
  26294. /**
  26295. * Resize the chart
  26296. */
  26297. ECharts.prototype.resize = function (opts) {
  26298. if (this[IN_MAIN_PROCESS_KEY]) {
  26299. if ("development" !== 'production') {
  26300. error('`resize` should not be called during main process.');
  26301. }
  26302. return;
  26303. }
  26304. if (this._disposed) {
  26305. disposedWarning(this.id);
  26306. return;
  26307. }
  26308. this._zr.resize(opts);
  26309. var ecModel = this._model; // Resize loading effect
  26310. this._loadingFX && this._loadingFX.resize();
  26311. if (!ecModel) {
  26312. return;
  26313. }
  26314. var needPrepare = ecModel.resetOption('media');
  26315. var silent = opts && opts.silent; // There is some real cases that:
  26316. // chart.setOption(option, { lazyUpdate: true });
  26317. // chart.resize();
  26318. if (this[PENDING_UPDATE]) {
  26319. if (silent == null) {
  26320. silent = this[PENDING_UPDATE].silent;
  26321. }
  26322. needPrepare = true;
  26323. this[PENDING_UPDATE] = null;
  26324. }
  26325. this[IN_MAIN_PROCESS_KEY] = true;
  26326. try {
  26327. needPrepare && prepare(this);
  26328. updateMethods.update.call(this, {
  26329. type: 'resize',
  26330. animation: extend({
  26331. // Disable animation
  26332. duration: 0
  26333. }, opts && opts.animation)
  26334. });
  26335. } catch (e) {
  26336. this[IN_MAIN_PROCESS_KEY] = false;
  26337. throw e;
  26338. }
  26339. this[IN_MAIN_PROCESS_KEY] = false;
  26340. flushPendingActions.call(this, silent);
  26341. triggerUpdatedEvent.call(this, silent);
  26342. };
  26343. ECharts.prototype.showLoading = function (name, cfg) {
  26344. if (this._disposed) {
  26345. disposedWarning(this.id);
  26346. return;
  26347. }
  26348. if (isObject(name)) {
  26349. cfg = name;
  26350. name = '';
  26351. }
  26352. name = name || 'default';
  26353. this.hideLoading();
  26354. if (!loadingEffects[name]) {
  26355. if ("development" !== 'production') {
  26356. warn('Loading effects ' + name + ' not exists.');
  26357. }
  26358. return;
  26359. }
  26360. var el = loadingEffects[name](this._api, cfg);
  26361. var zr = this._zr;
  26362. this._loadingFX = el;
  26363. zr.add(el);
  26364. };
  26365. /**
  26366. * Hide loading effect
  26367. */
  26368. ECharts.prototype.hideLoading = function () {
  26369. if (this._disposed) {
  26370. disposedWarning(this.id);
  26371. return;
  26372. }
  26373. this._loadingFX && this._zr.remove(this._loadingFX);
  26374. this._loadingFX = null;
  26375. };
  26376. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  26377. var payload = extend({}, eventObj);
  26378. payload.type = eventActionMap[eventObj.type];
  26379. return payload;
  26380. };
  26381. /**
  26382. * @param opt If pass boolean, means opt.silent
  26383. * @param opt.silent Default `false`. Whether trigger events.
  26384. * @param opt.flush Default `undefined`.
  26385. * true: Flush immediately, and then pixel in canvas can be fetched
  26386. * immediately. Caution: it might affect performance.
  26387. * false: Not flush.
  26388. * undefined: Auto decide whether perform flush.
  26389. */
  26390. ECharts.prototype.dispatchAction = function (payload, opt) {
  26391. if (this._disposed) {
  26392. disposedWarning(this.id);
  26393. return;
  26394. }
  26395. if (!isObject(opt)) {
  26396. opt = {
  26397. silent: !!opt
  26398. };
  26399. }
  26400. if (!actions[payload.type]) {
  26401. return;
  26402. } // Avoid dispatch action before setOption. Especially in `connect`.
  26403. if (!this._model) {
  26404. return;
  26405. } // May dispatchAction in rendering procedure
  26406. if (this[IN_MAIN_PROCESS_KEY]) {
  26407. this._pendingActions.push(payload);
  26408. return;
  26409. }
  26410. var silent = opt.silent;
  26411. doDispatchAction.call(this, payload, silent);
  26412. var flush = opt.flush;
  26413. if (flush) {
  26414. this._zr.flush();
  26415. } else if (flush !== false && env.browser.weChat) {
  26416. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  26417. // hang when sliding page (on touch event), which cause that zr does not
  26418. // refresh until user interaction finished, which is not expected.
  26419. // But `dispatchAction` may be called too frequently when pan on touch
  26420. // screen, which impacts performance if do not throttle them.
  26421. this._throttledZrFlush();
  26422. }
  26423. flushPendingActions.call(this, silent);
  26424. triggerUpdatedEvent.call(this, silent);
  26425. };
  26426. ECharts.prototype.updateLabelLayout = function () {
  26427. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  26428. // Not adding series labels.
  26429. // TODO
  26430. updatedSeries: []
  26431. });
  26432. };
  26433. ECharts.prototype.appendData = function (params) {
  26434. if (this._disposed) {
  26435. disposedWarning(this.id);
  26436. return;
  26437. }
  26438. var seriesIndex = params.seriesIndex;
  26439. var ecModel = this.getModel();
  26440. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26441. if ("development" !== 'production') {
  26442. assert(params.data && seriesModel);
  26443. }
  26444. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  26445. // system, util some scenario require that. In the expected usage of
  26446. // `appendData`, the initial extent of coordinate system should better
  26447. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26448. // the extent changed while `appendData`, the location of the painted
  26449. // graphic elements have to be changed, which make the usage of
  26450. // `appendData` meaningless.
  26451. this._scheduler.unfinished = true;
  26452. this.getZr().wakeUp();
  26453. }; // A work around for no `internal` modifier in ts yet but
  26454. // need to strictly hide private methods to JS users.
  26455. ECharts.internalField = function () {
  26456. prepare = function (ecIns) {
  26457. var scheduler = ecIns._scheduler;
  26458. scheduler.restorePipelines(ecIns._model);
  26459. scheduler.prepareStageTasks();
  26460. prepareView(ecIns, true);
  26461. prepareView(ecIns, false);
  26462. scheduler.plan();
  26463. };
  26464. /**
  26465. * Prepare view instances of charts and components
  26466. */
  26467. prepareView = function (ecIns, isComponent) {
  26468. var ecModel = ecIns._model;
  26469. var scheduler = ecIns._scheduler;
  26470. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26471. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26472. var zr = ecIns._zr;
  26473. var api = ecIns._api;
  26474. for (var i = 0; i < viewList.length; i++) {
  26475. viewList[i].__alive = false;
  26476. }
  26477. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26478. componentType !== 'series' && doPrepare(model);
  26479. }) : ecModel.eachSeries(doPrepare);
  26480. function doPrepare(model) {
  26481. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  26482. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26483. // especially no id but have the same type & name & index. See the `model.id` generation
  26484. // rule in `makeIdAndName` and `viewId` generation rule here).
  26485. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26486. // the new model has nothing to do with the old model.
  26487. var requireNewView = model.__requireNewView; // This command should not work twice.
  26488. model.__requireNewView = false; // Consider: id same and type changed.
  26489. var viewId = '_ec_' + model.id + '_' + model.type;
  26490. var view = !requireNewView && viewMap[viewId];
  26491. if (!view) {
  26492. var classType = parseClassType(model.type);
  26493. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  26494. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26495. // For backward compat, still support a chart type declared as only subType
  26496. // like "liquidfill", but recommend "series.liquidfill"
  26497. // But need a base class to make a type series.
  26498. ChartView.getClass(classType.sub);
  26499. if ("development" !== 'production') {
  26500. assert(Clazz, classType.sub + ' does not exist.');
  26501. }
  26502. view = new Clazz();
  26503. view.init(ecModel, api);
  26504. viewMap[viewId] = view;
  26505. viewList.push(view);
  26506. zr.add(view.group);
  26507. }
  26508. model.__viewId = view.__id = viewId;
  26509. view.__alive = true;
  26510. view.__model = model;
  26511. view.group.__ecComponentInfo = {
  26512. mainType: model.mainType,
  26513. index: model.componentIndex
  26514. };
  26515. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26516. }
  26517. for (var i = 0; i < viewList.length;) {
  26518. var view = viewList[i];
  26519. if (!view.__alive) {
  26520. !isComponent && view.renderTask.dispose();
  26521. zr.remove(view.group);
  26522. view.dispose(ecModel, api);
  26523. viewList.splice(i, 1);
  26524. if (viewMap[view.__id] === view) {
  26525. delete viewMap[view.__id];
  26526. }
  26527. view.__id = view.group.__ecComponentInfo = null;
  26528. } else {
  26529. i++;
  26530. }
  26531. }
  26532. };
  26533. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26534. var ecModel = ecIns._model;
  26535. ecModel.setUpdatePayload(payload); // broadcast
  26536. if (!mainType) {
  26537. // FIXME
  26538. // Chart will not be update directly here, except set dirty.
  26539. // But there is no such scenario now.
  26540. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26541. return;
  26542. }
  26543. var query = {};
  26544. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26545. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26546. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26547. var condition = {
  26548. mainType: mainType,
  26549. query: query
  26550. };
  26551. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26552. var excludeSeriesId = payload.excludeSeriesId;
  26553. var excludeSeriesIdMap;
  26554. if (excludeSeriesId != null) {
  26555. excludeSeriesIdMap = createHashMap();
  26556. each(normalizeToArray(excludeSeriesId), function (id) {
  26557. var modelId = convertOptionIdName(id, null);
  26558. if (modelId != null) {
  26559. excludeSeriesIdMap.set(modelId, true);
  26560. }
  26561. });
  26562. } // If dispatchAction before setOption, do nothing.
  26563. ecModel && ecModel.eachComponent(condition, function (model) {
  26564. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26565. if (isExcluded) {
  26566. return;
  26567. }
  26568. if (isHighDownPayload(payload)) {
  26569. if (model instanceof SeriesModel) {
  26570. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26571. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26572. }
  26573. } else {
  26574. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26575. focusSelf = _a.focusSelf,
  26576. dispatchers = _a.dispatchers;
  26577. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26578. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26579. } // PENDING:
  26580. // Whether to put this "enter emphasis" code in `ComponentView`,
  26581. // which will be the same as `ChartView` but might be not necessary
  26582. // and will be far from this logic.
  26583. if (dispatchers) {
  26584. each(dispatchers, function (dispatcher) {
  26585. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26586. });
  26587. }
  26588. }
  26589. } else if (isSelectChangePayload(payload)) {
  26590. // TODO geo
  26591. if (model instanceof SeriesModel) {
  26592. toggleSelectionFromPayload(model, payload, ecIns._api);
  26593. updateSeriesElementSelection(model);
  26594. markStatusToUpdate(ecIns);
  26595. }
  26596. }
  26597. }, ecIns);
  26598. ecModel && ecModel.eachComponent(condition, function (model) {
  26599. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26600. if (isExcluded) {
  26601. return;
  26602. }
  26603. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26604. }, ecIns);
  26605. function callView(view) {
  26606. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26607. }
  26608. };
  26609. updateMethods = {
  26610. prepareAndUpdate: function (payload) {
  26611. prepare(this);
  26612. updateMethods.update.call(this, payload, {
  26613. // Needs to mark option changed if newOption is given.
  26614. // It's from MagicType.
  26615. // TODO If use a separate flag optionChanged in payload?
  26616. optionChanged: payload.newOption != null
  26617. });
  26618. },
  26619. update: function (payload, updateParams) {
  26620. var ecModel = this._model;
  26621. var api = this._api;
  26622. var zr = this._zr;
  26623. var coordSysMgr = this._coordSysMgr;
  26624. var scheduler = this._scheduler; // update before setOption
  26625. if (!ecModel) {
  26626. return;
  26627. }
  26628. ecModel.setUpdatePayload(payload);
  26629. scheduler.restoreData(ecModel, payload);
  26630. scheduler.performSeriesTasks(ecModel); // TODO
  26631. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26632. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26633. // Create new coordinate system each update
  26634. // In LineView may save the old coordinate system and use it to get the original point.
  26635. coordSysMgr.create(ecModel, api);
  26636. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  26637. // stream modes after data processing, where the filtered data is used to
  26638. // determine whether to use progressive rendering.
  26639. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  26640. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26641. // the drawback is the full coord info can not be fetched. Fortunately this full
  26642. // coord is not required in stream mode updater currently.
  26643. coordSysMgr.update(ecModel, api);
  26644. clearColorPalette(ecModel);
  26645. scheduler.performVisualTasks(ecModel, payload);
  26646. render(this, ecModel, api, payload, updateParams); // Set background
  26647. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26648. var darkMode = ecModel.get('darkMode');
  26649. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  26650. if (darkMode != null && darkMode !== 'auto') {
  26651. zr.setDarkMode(darkMode);
  26652. }
  26653. lifecycle.trigger('afterupdate', ecModel, api);
  26654. },
  26655. updateTransform: function (payload) {
  26656. var _this = this;
  26657. var ecModel = this._model;
  26658. var api = this._api; // update before setOption
  26659. if (!ecModel) {
  26660. return;
  26661. }
  26662. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  26663. var componentDirtyList = [];
  26664. ecModel.eachComponent(function (componentType, componentModel) {
  26665. if (componentType === 'series') {
  26666. return;
  26667. }
  26668. var componentView = _this.getViewOfComponentModel(componentModel);
  26669. if (componentView && componentView.__alive) {
  26670. if (componentView.updateTransform) {
  26671. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26672. result && result.update && componentDirtyList.push(componentView);
  26673. } else {
  26674. componentDirtyList.push(componentView);
  26675. }
  26676. }
  26677. });
  26678. var seriesDirtyMap = createHashMap();
  26679. ecModel.eachSeries(function (seriesModel) {
  26680. var chartView = _this._chartsMap[seriesModel.__viewId];
  26681. if (chartView.updateTransform) {
  26682. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26683. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26684. } else {
  26685. seriesDirtyMap.set(seriesModel.uid, 1);
  26686. }
  26687. });
  26688. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26689. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26690. this._scheduler.performVisualTasks(ecModel, payload, {
  26691. setDirty: true,
  26692. dirtyMap: seriesDirtyMap
  26693. }); // Currently, not call render of components. Geo render cost a lot.
  26694. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26695. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26696. lifecycle.trigger('afterupdate', ecModel, api);
  26697. },
  26698. updateView: function (payload) {
  26699. var ecModel = this._model; // update before setOption
  26700. if (!ecModel) {
  26701. return;
  26702. }
  26703. ecModel.setUpdatePayload(payload);
  26704. ChartView.markUpdateMethod(payload, 'updateView');
  26705. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26706. this._scheduler.performVisualTasks(ecModel, payload, {
  26707. setDirty: true
  26708. });
  26709. render(this, ecModel, this._api, payload, {});
  26710. lifecycle.trigger('afterupdate', ecModel, this._api);
  26711. },
  26712. updateVisual: function (payload) {
  26713. // updateMethods.update.call(this, payload);
  26714. var _this = this;
  26715. var ecModel = this._model; // update before setOption
  26716. if (!ecModel) {
  26717. return;
  26718. }
  26719. ecModel.setUpdatePayload(payload); // clear all visual
  26720. ecModel.eachSeries(function (seriesModel) {
  26721. seriesModel.getData().clearAllVisual();
  26722. }); // Perform visual
  26723. ChartView.markUpdateMethod(payload, 'updateVisual');
  26724. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26725. this._scheduler.performVisualTasks(ecModel, payload, {
  26726. visualType: 'visual',
  26727. setDirty: true
  26728. });
  26729. ecModel.eachComponent(function (componentType, componentModel) {
  26730. if (componentType !== 'series') {
  26731. var componentView = _this.getViewOfComponentModel(componentModel);
  26732. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26733. }
  26734. });
  26735. ecModel.eachSeries(function (seriesModel) {
  26736. var chartView = _this._chartsMap[seriesModel.__viewId];
  26737. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26738. });
  26739. lifecycle.trigger('afterupdate', ecModel, this._api);
  26740. },
  26741. updateLayout: function (payload) {
  26742. updateMethods.update.call(this, payload);
  26743. }
  26744. };
  26745. doConvertPixel = function (ecIns, methodName, finder, value) {
  26746. if (ecIns._disposed) {
  26747. disposedWarning(ecIns.id);
  26748. return;
  26749. }
  26750. var ecModel = ecIns._model;
  26751. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26752. var result;
  26753. var parsedFinder = parseFinder(ecModel, finder);
  26754. for (var i = 0; i < coordSysList.length; i++) {
  26755. var coordSys = coordSysList[i];
  26756. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26757. return result;
  26758. }
  26759. }
  26760. if ("development" !== 'production') {
  26761. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26762. }
  26763. };
  26764. updateStreamModes = function (ecIns, ecModel) {
  26765. var chartsMap = ecIns._chartsMap;
  26766. var scheduler = ecIns._scheduler;
  26767. ecModel.eachSeries(function (seriesModel) {
  26768. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26769. });
  26770. };
  26771. doDispatchAction = function (payload, silent) {
  26772. var _this = this;
  26773. var ecModel = this.getModel();
  26774. var payloadType = payload.type;
  26775. var escapeConnect = payload.escapeConnect;
  26776. var actionWrap = actions[payloadType];
  26777. var actionInfo = actionWrap.actionInfo;
  26778. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26779. var updateMethod = cptTypeTmp.pop();
  26780. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26781. this[IN_MAIN_PROCESS_KEY] = true;
  26782. var payloads = [payload];
  26783. var batched = false; // Batch action
  26784. if (payload.batch) {
  26785. batched = true;
  26786. payloads = map(payload.batch, function (item) {
  26787. item = defaults(extend({}, item), payload);
  26788. item.batch = null;
  26789. return item;
  26790. });
  26791. }
  26792. var eventObjBatch = [];
  26793. var eventObj;
  26794. var isSelectChange = isSelectChangePayload(payload);
  26795. var isHighDown = isHighDownPayload(payload); // Only leave blur once if there are multiple batches.
  26796. if (isHighDown) {
  26797. allLeaveBlur(this._api);
  26798. }
  26799. each(payloads, function (batchItem) {
  26800. // Action can specify the event by return it.
  26801. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  26802. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  26803. eventObj.type = actionInfo.event || eventObj.type;
  26804. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  26805. if (isHighDown) {
  26806. var _a = preParseFinder(payload),
  26807. queryOptionMap = _a.queryOptionMap,
  26808. mainTypeSpecified = _a.mainTypeSpecified;
  26809. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  26810. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  26811. markStatusToUpdate(_this);
  26812. } else if (isSelectChange) {
  26813. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  26814. // geo still use 'geoselect'.
  26815. updateDirectly(_this, updateMethod, batchItem, 'series');
  26816. markStatusToUpdate(_this);
  26817. } else if (cptType) {
  26818. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26819. }
  26820. });
  26821. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  26822. try {
  26823. // Still dirty
  26824. if (this[PENDING_UPDATE]) {
  26825. prepare(this);
  26826. updateMethods.update.call(this, payload);
  26827. this[PENDING_UPDATE] = null;
  26828. } else {
  26829. updateMethods[updateMethod].call(this, payload);
  26830. }
  26831. } catch (e) {
  26832. this[IN_MAIN_PROCESS_KEY] = false;
  26833. throw e;
  26834. }
  26835. } // Follow the rule of action batch
  26836. if (batched) {
  26837. eventObj = {
  26838. type: actionInfo.event || payloadType,
  26839. escapeConnect: escapeConnect,
  26840. batch: eventObjBatch
  26841. };
  26842. } else {
  26843. eventObj = eventObjBatch[0];
  26844. }
  26845. this[IN_MAIN_PROCESS_KEY] = false;
  26846. if (!silent) {
  26847. var messageCenter = this._messageCenter;
  26848. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  26849. if (isSelectChange) {
  26850. var newObj = {
  26851. type: 'selectchanged',
  26852. escapeConnect: escapeConnect,
  26853. selected: getAllSelectedIndices(ecModel),
  26854. isFromClick: payload.isFromClick || false,
  26855. fromAction: payload.type,
  26856. fromActionPayload: payload
  26857. };
  26858. messageCenter.trigger(newObj.type, newObj);
  26859. }
  26860. }
  26861. };
  26862. flushPendingActions = function (silent) {
  26863. var pendingActions = this._pendingActions;
  26864. while (pendingActions.length) {
  26865. var payload = pendingActions.shift();
  26866. doDispatchAction.call(this, payload, silent);
  26867. }
  26868. };
  26869. triggerUpdatedEvent = function (silent) {
  26870. !silent && this.trigger('updated');
  26871. };
  26872. /**
  26873. * Event `rendered` is triggered when zr
  26874. * rendered. It is useful for realtime
  26875. * snapshot (reflect animation).
  26876. *
  26877. * Event `finished` is triggered when:
  26878. * (1) zrender rendering finished.
  26879. * (2) initial animation finished.
  26880. * (3) progressive rendering finished.
  26881. * (4) no pending action.
  26882. * (5) no delayed setOption needs to be processed.
  26883. */
  26884. bindRenderedEvent = function (zr, ecIns) {
  26885. zr.on('rendered', function (params) {
  26886. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatedly,
  26887. // so it should only be triggered when rendering indeed happens
  26888. // in zrender. (Consider the case that dipatchAction is keep
  26889. // triggering when mouse move).
  26890. if ( // Although zr is dirty if initial animation is not finished
  26891. // and this checking is called on frame, we also check
  26892. // animation finished for robustness.
  26893. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26894. ecIns.trigger('finished');
  26895. }
  26896. });
  26897. };
  26898. bindMouseEvent = function (zr, ecIns) {
  26899. zr.on('mouseover', function (e) {
  26900. var el = e.target;
  26901. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26902. if (dispatcher) {
  26903. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  26904. markStatusToUpdate(ecIns);
  26905. }
  26906. }).on('mouseout', function (e) {
  26907. var el = e.target;
  26908. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26909. if (dispatcher) {
  26910. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  26911. markStatusToUpdate(ecIns);
  26912. }
  26913. }).on('click', function (e) {
  26914. var el = e.target;
  26915. var dispatcher = findEventDispatcher(el, function (target) {
  26916. return getECData(target).dataIndex != null;
  26917. }, true);
  26918. if (dispatcher) {
  26919. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26920. var ecData = getECData(dispatcher);
  26921. ecIns._api.dispatchAction({
  26922. type: actionType,
  26923. dataType: ecData.dataType,
  26924. dataIndexInside: ecData.dataIndex,
  26925. seriesIndex: ecData.seriesIndex,
  26926. isFromClick: true
  26927. });
  26928. }
  26929. });
  26930. };
  26931. function clearColorPalette(ecModel) {
  26932. ecModel.clearColorPalette();
  26933. ecModel.eachSeries(function (seriesModel) {
  26934. seriesModel.clearColorPalette();
  26935. });
  26936. }
  26937. function allocateZlevels(ecModel) {
  26938. var componentZLevels = [];
  26939. var seriesZLevels = [];
  26940. var hasSeperateZLevel = false;
  26941. ecModel.eachComponent(function (componentType, componentModel) {
  26942. var zlevel = componentModel.get('zlevel') || 0;
  26943. var z = componentModel.get('z') || 0;
  26944. var zlevelKey = componentModel.getZLevelKey();
  26945. hasSeperateZLevel = hasSeperateZLevel || !!zlevelKey;
  26946. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  26947. zlevel: zlevel,
  26948. z: z,
  26949. idx: componentModel.componentIndex,
  26950. type: componentType,
  26951. key: zlevelKey
  26952. });
  26953. });
  26954. if (hasSeperateZLevel) {
  26955. // Series after component
  26956. var zLevels = componentZLevels.concat(seriesZLevels);
  26957. var lastSeriesZLevel_1;
  26958. var lastSeriesKey_1;
  26959. sort(zLevels, function (a, b) {
  26960. if (a.zlevel === b.zlevel) {
  26961. return a.z - b.z;
  26962. }
  26963. return a.zlevel - b.zlevel;
  26964. });
  26965. each(zLevels, function (item) {
  26966. var componentModel = ecModel.getComponent(item.type, item.idx);
  26967. var zlevel = item.zlevel;
  26968. var key = item.key;
  26969. if (lastSeriesZLevel_1 != null) {
  26970. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  26971. }
  26972. if (key) {
  26973. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  26974. zlevel++;
  26975. }
  26976. lastSeriesKey_1 = key;
  26977. } else if (lastSeriesKey_1) {
  26978. if (zlevel === lastSeriesZLevel_1) {
  26979. zlevel++;
  26980. }
  26981. lastSeriesKey_1 = '';
  26982. }
  26983. lastSeriesZLevel_1 = zlevel;
  26984. componentModel.setZLevel(zlevel);
  26985. });
  26986. }
  26987. }
  26988. render = function (ecIns, ecModel, api, payload, updateParams) {
  26989. allocateZlevels(ecModel);
  26990. renderComponents(ecIns, ecModel, api, payload, updateParams);
  26991. each(ecIns._chartsViews, function (chart) {
  26992. chart.__alive = false;
  26993. });
  26994. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  26995. each(ecIns._chartsViews, function (chart) {
  26996. if (!chart.__alive) {
  26997. chart.remove(ecModel, api);
  26998. }
  26999. });
  27000. };
  27001. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  27002. each(dirtyList || ecIns._componentsViews, function (componentView) {
  27003. var componentModel = componentView.__model;
  27004. clearStates(componentModel, componentView);
  27005. componentView.render(componentModel, ecModel, api, payload);
  27006. updateZ(componentModel, componentView);
  27007. updateStates(componentModel, componentView);
  27008. });
  27009. };
  27010. /**
  27011. * Render each chart and component
  27012. */
  27013. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  27014. // Render all charts
  27015. var scheduler = ecIns._scheduler;
  27016. updateParams = extend(updateParams || {}, {
  27017. updatedSeries: ecModel.getSeries()
  27018. }); // TODO progressive?
  27019. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  27020. var unfinished = false;
  27021. ecModel.eachSeries(function (seriesModel) {
  27022. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27023. chartView.__alive = true;
  27024. var renderTask = chartView.renderTask;
  27025. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  27026. clearStates(seriesModel, chartView);
  27027. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  27028. renderTask.dirty();
  27029. }
  27030. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  27031. unfinished = true;
  27032. }
  27033. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  27034. // incremental render (always render from the __startIndex each frame)
  27035. // chartView.group.markRedraw();
  27036. updateBlend(seriesModel, chartView);
  27037. updateSeriesElementSelection(seriesModel);
  27038. });
  27039. scheduler.unfinished = unfinished || scheduler.unfinished;
  27040. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  27041. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  27042. ecModel.eachSeries(function (seriesModel) {
  27043. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  27044. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  27045. // label should be in normal status when layouting.
  27046. updateStates(seriesModel, chartView);
  27047. }); // If use hover layer
  27048. updateHoverLayerStatus(ecIns, ecModel);
  27049. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  27050. };
  27051. markStatusToUpdate = function (ecIns) {
  27052. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  27053. ecIns.getZr().wakeUp();
  27054. };
  27055. applyChangedStates = function (ecIns) {
  27056. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  27057. return;
  27058. }
  27059. ecIns.getZr().storage.traverse(function (el) {
  27060. // Not applied on removed elements, it may still in fading.
  27061. if (isElementRemoved(el)) {
  27062. return;
  27063. }
  27064. applyElementStates(el);
  27065. });
  27066. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  27067. };
  27068. function applyElementStates(el) {
  27069. var newStates = [];
  27070. var oldStates = el.currentStates; // Keep other states.
  27071. for (var i = 0; i < oldStates.length; i++) {
  27072. var stateName = oldStates[i];
  27073. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  27074. newStates.push(stateName);
  27075. }
  27076. } // Only use states when it's exists.
  27077. if (el.selected && el.states.select) {
  27078. newStates.push('select');
  27079. }
  27080. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  27081. newStates.push('emphasis');
  27082. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  27083. newStates.push('blur');
  27084. }
  27085. el.useStates(newStates);
  27086. }
  27087. function updateHoverLayerStatus(ecIns, ecModel) {
  27088. var zr = ecIns._zr;
  27089. var storage = zr.storage;
  27090. var elCount = 0;
  27091. storage.traverse(function (el) {
  27092. if (!el.isGroup) {
  27093. elCount++;
  27094. }
  27095. });
  27096. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  27097. ecModel.eachSeries(function (seriesModel) {
  27098. if (seriesModel.preventUsingHoverLayer) {
  27099. return;
  27100. }
  27101. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27102. if (chartView.__alive) {
  27103. chartView.eachRendered(function (el) {
  27104. if (el.states.emphasis) {
  27105. el.states.emphasis.hoverLayer = true;
  27106. }
  27107. });
  27108. }
  27109. });
  27110. }
  27111. }
  27112. /**
  27113. * Update chart and blend.
  27114. */
  27115. function updateBlend(seriesModel, chartView) {
  27116. var blendMode = seriesModel.get('blendMode') || null;
  27117. chartView.eachRendered(function (el) {
  27118. // FIXME marker and other components
  27119. if (!el.isGroup) {
  27120. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  27121. el.style.blend = blendMode;
  27122. }
  27123. });
  27124. }
  27125. function updateZ(model, view) {
  27126. if (model.preventAutoZ) {
  27127. return;
  27128. }
  27129. var z = model.get('z') || 0;
  27130. var zlevel = model.get('zlevel') || 0; // Set z and zlevel
  27131. view.eachRendered(function (el) {
  27132. doUpdateZ(el, z, zlevel, -Infinity); // Don't traverse the children because it has been traversed in _updateZ.
  27133. return true;
  27134. });
  27135. }
  27136. function doUpdateZ(el, z, zlevel, maxZ2) {
  27137. // Group may also have textContent
  27138. var label = el.getTextContent();
  27139. var labelLine = el.getTextGuideLine();
  27140. var isGroup = el.isGroup;
  27141. if (isGroup) {
  27142. // set z & zlevel of children elements of Group
  27143. var children = el.childrenRef();
  27144. for (var i = 0; i < children.length; i++) {
  27145. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  27146. }
  27147. } else {
  27148. // not Group
  27149. el.z = z;
  27150. el.zlevel = zlevel;
  27151. maxZ2 = Math.max(el.z2, maxZ2);
  27152. } // always set z and zlevel if label/labelLine exists
  27153. if (label) {
  27154. label.z = z;
  27155. label.zlevel = zlevel; // lift z2 of text content
  27156. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  27157. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  27158. }
  27159. if (labelLine) {
  27160. var textGuideLineConfig = el.textGuideLineConfig;
  27161. labelLine.z = z;
  27162. labelLine.zlevel = zlevel;
  27163. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  27164. }
  27165. return maxZ2;
  27166. } // Clear states without animation.
  27167. // TODO States on component.
  27168. function clearStates(model, view) {
  27169. view.eachRendered(function (el) {
  27170. // Not applied on removed elements, it may still in fading.
  27171. if (isElementRemoved(el)) {
  27172. return;
  27173. }
  27174. var textContent = el.getTextContent();
  27175. var textGuide = el.getTextGuideLine();
  27176. if (el.stateTransition) {
  27177. el.stateTransition = null;
  27178. }
  27179. if (textContent && textContent.stateTransition) {
  27180. textContent.stateTransition = null;
  27181. }
  27182. if (textGuide && textGuide.stateTransition) {
  27183. textGuide.stateTransition = null;
  27184. } // TODO If el is incremental.
  27185. if (el.hasState()) {
  27186. el.prevStates = el.currentStates;
  27187. el.clearStates();
  27188. } else if (el.prevStates) {
  27189. el.prevStates = null;
  27190. }
  27191. });
  27192. }
  27193. function updateStates(model, view) {
  27194. var stateAnimationModel = model.getModel('stateAnimation');
  27195. var enableAnimation = model.isAnimationEnabled();
  27196. var duration = stateAnimationModel.get('duration');
  27197. var stateTransition = duration > 0 ? {
  27198. duration: duration,
  27199. delay: stateAnimationModel.get('delay'),
  27200. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  27201. } : null;
  27202. view.eachRendered(function (el) {
  27203. if (el.states && el.states.emphasis) {
  27204. // Not applied on removed elements, it may still in fading.
  27205. if (isElementRemoved(el)) {
  27206. return;
  27207. }
  27208. if (el instanceof Path) {
  27209. savePathStates(el);
  27210. } // Only updated on changed element. In case element is incremental and don't want to rerender.
  27211. // TODO, a more proper way?
  27212. if (el.__dirty) {
  27213. var prevStates = el.prevStates; // Restore states without animation
  27214. if (prevStates) {
  27215. el.useStates(prevStates);
  27216. }
  27217. } // Update state transition and enable animation again.
  27218. if (enableAnimation) {
  27219. el.stateTransition = stateTransition;
  27220. var textContent = el.getTextContent();
  27221. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  27222. if (textContent) {
  27223. textContent.stateTransition = stateTransition;
  27224. }
  27225. if (textGuide) {
  27226. textGuide.stateTransition = stateTransition;
  27227. }
  27228. } // Use highlighted and selected flag to toggle states.
  27229. if (el.__dirty) {
  27230. applyElementStates(el);
  27231. }
  27232. }
  27233. });
  27234. }
  27235. createExtensionAPI = function (ecIns) {
  27236. return new (
  27237. /** @class */
  27238. function (_super) {
  27239. __extends(class_1, _super);
  27240. function class_1() {
  27241. return _super !== null && _super.apply(this, arguments) || this;
  27242. }
  27243. class_1.prototype.getCoordinateSystems = function () {
  27244. return ecIns._coordSysMgr.getCoordinateSystems();
  27245. };
  27246. class_1.prototype.getComponentByElement = function (el) {
  27247. while (el) {
  27248. var modelInfo = el.__ecComponentInfo;
  27249. if (modelInfo != null) {
  27250. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  27251. }
  27252. el = el.parent;
  27253. }
  27254. };
  27255. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  27256. enterEmphasis(el, highlightDigit);
  27257. markStatusToUpdate(ecIns);
  27258. };
  27259. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  27260. leaveEmphasis(el, highlightDigit);
  27261. markStatusToUpdate(ecIns);
  27262. };
  27263. class_1.prototype.enterBlur = function (el) {
  27264. enterBlur(el);
  27265. markStatusToUpdate(ecIns);
  27266. };
  27267. class_1.prototype.leaveBlur = function (el) {
  27268. leaveBlur(el);
  27269. markStatusToUpdate(ecIns);
  27270. };
  27271. class_1.prototype.enterSelect = function (el) {
  27272. enterSelect(el);
  27273. markStatusToUpdate(ecIns);
  27274. };
  27275. class_1.prototype.leaveSelect = function (el) {
  27276. leaveSelect(el);
  27277. markStatusToUpdate(ecIns);
  27278. };
  27279. class_1.prototype.getModel = function () {
  27280. return ecIns.getModel();
  27281. };
  27282. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  27283. return ecIns.getViewOfComponentModel(componentModel);
  27284. };
  27285. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  27286. return ecIns.getViewOfSeriesModel(seriesModel);
  27287. };
  27288. return class_1;
  27289. }(ExtensionAPI))(ecIns);
  27290. };
  27291. enableConnect = function (chart) {
  27292. function updateConnectedChartsStatus(charts, status) {
  27293. for (var i = 0; i < charts.length; i++) {
  27294. var otherChart = charts[i];
  27295. otherChart[CONNECT_STATUS_KEY] = status;
  27296. }
  27297. }
  27298. each(eventActionMap, function (actionType, eventType) {
  27299. chart._messageCenter.on(eventType, function (event) {
  27300. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  27301. if (event && event.escapeConnect) {
  27302. return;
  27303. }
  27304. var action_1 = chart.makeActionFromEvent(event);
  27305. var otherCharts_1 = [];
  27306. each(instances$1, function (otherChart) {
  27307. if (otherChart !== chart && otherChart.group === chart.group) {
  27308. otherCharts_1.push(otherChart);
  27309. }
  27310. });
  27311. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  27312. each(otherCharts_1, function (otherChart) {
  27313. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  27314. otherChart.dispatchAction(action_1);
  27315. }
  27316. });
  27317. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  27318. }
  27319. });
  27320. });
  27321. };
  27322. }();
  27323. return ECharts;
  27324. }(Eventful);
  27325. var echartsProto = ECharts.prototype;
  27326. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  27327. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  27328. /**
  27329. * @deprecated
  27330. */
  27331. // @ts-ignore
  27332. echartsProto.one = function (eventName, cb, ctx) {
  27333. var self = this;
  27334. deprecateLog('ECharts#one is deprecated.');
  27335. function wrapped() {
  27336. var args2 = [];
  27337. for (var _i = 0; _i < arguments.length; _i++) {
  27338. args2[_i] = arguments[_i];
  27339. }
  27340. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  27341. self.off(eventName, wrapped);
  27342. }
  27343. this.on.call(this, eventName, wrapped, ctx);
  27344. };
  27345. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  27346. function disposedWarning(id) {
  27347. if ("development" !== 'production') {
  27348. warn('Instance ' + id + ' has been disposed');
  27349. }
  27350. }
  27351. var actions = {};
  27352. /**
  27353. * Map eventType to actionType
  27354. */
  27355. var eventActionMap = {};
  27356. var dataProcessorFuncs = [];
  27357. var optionPreprocessorFuncs = [];
  27358. var visualFuncs = [];
  27359. var themeStorage = {};
  27360. var loadingEffects = {};
  27361. var instances$1 = {};
  27362. var connectedGroups = {};
  27363. var idBase = +new Date() - 0;
  27364. var groupIdBase = +new Date() - 0;
  27365. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  27366. /**
  27367. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  27368. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  27369. * @param opts.width Use clientWidth of the input `dom` by default.
  27370. * Can be 'auto' (the same as null/undefined)
  27371. * @param opts.height Use clientHeight of the input `dom` by default.
  27372. * Can be 'auto' (the same as null/undefined)
  27373. * @param opts.locale Specify the locale.
  27374. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  27375. */
  27376. function init$1(dom, theme, opts) {
  27377. var isClient = !(opts && opts.ssr);
  27378. if (isClient) {
  27379. if ("development" !== 'production') {
  27380. if (!dom) {
  27381. throw new Error('Initialize failed: invalid dom.');
  27382. }
  27383. }
  27384. var existInstance = getInstanceByDom(dom);
  27385. if (existInstance) {
  27386. if ("development" !== 'production') {
  27387. warn('There is a chart instance already initialized on the dom.');
  27388. }
  27389. return existInstance;
  27390. }
  27391. if ("development" !== 'production') {
  27392. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  27393. 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.');
  27394. }
  27395. }
  27396. }
  27397. var chart = new ECharts(dom, theme, opts);
  27398. chart.id = 'ec_' + idBase++;
  27399. instances$1[chart.id] = chart;
  27400. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  27401. enableConnect(chart);
  27402. lifecycle.trigger('afterinit', chart);
  27403. return chart;
  27404. }
  27405. /**
  27406. * @usage
  27407. * (A)
  27408. * ```js
  27409. * let chart1 = echarts.init(dom1);
  27410. * let chart2 = echarts.init(dom2);
  27411. * chart1.group = 'xxx';
  27412. * chart2.group = 'xxx';
  27413. * echarts.connect('xxx');
  27414. * ```
  27415. * (B)
  27416. * ```js
  27417. * let chart1 = echarts.init(dom1);
  27418. * let chart2 = echarts.init(dom2);
  27419. * echarts.connect('xxx', [chart1, chart2]);
  27420. * ```
  27421. */
  27422. function connect(groupId) {
  27423. // Is array of charts
  27424. if (isArray(groupId)) {
  27425. var charts = groupId;
  27426. groupId = null; // If any chart has group
  27427. each(charts, function (chart) {
  27428. if (chart.group != null) {
  27429. groupId = chart.group;
  27430. }
  27431. });
  27432. groupId = groupId || 'g_' + groupIdBase++;
  27433. each(charts, function (chart) {
  27434. chart.group = groupId;
  27435. });
  27436. }
  27437. connectedGroups[groupId] = true;
  27438. return groupId;
  27439. }
  27440. /**
  27441. * @deprecated
  27442. */
  27443. function disConnect(groupId) {
  27444. connectedGroups[groupId] = false;
  27445. }
  27446. /**
  27447. * Alias and backward compatibility
  27448. */
  27449. var disconnect = disConnect;
  27450. /**
  27451. * Dispose a chart instance
  27452. */
  27453. function dispose$1(chart) {
  27454. if (isString(chart)) {
  27455. chart = instances$1[chart];
  27456. } else if (!(chart instanceof ECharts)) {
  27457. // Try to treat as dom
  27458. chart = getInstanceByDom(chart);
  27459. }
  27460. if (chart instanceof ECharts && !chart.isDisposed()) {
  27461. chart.dispose();
  27462. }
  27463. }
  27464. function getInstanceByDom(dom) {
  27465. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27466. }
  27467. function getInstanceById(key) {
  27468. return instances$1[key];
  27469. }
  27470. /**
  27471. * Register theme
  27472. */
  27473. function registerTheme(name, theme) {
  27474. themeStorage[name] = theme;
  27475. }
  27476. /**
  27477. * Register option preprocessor
  27478. */
  27479. function registerPreprocessor(preprocessorFunc) {
  27480. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27481. optionPreprocessorFuncs.push(preprocessorFunc);
  27482. }
  27483. }
  27484. function registerProcessor(priority, processor) {
  27485. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27486. }
  27487. /**
  27488. * Register postIniter
  27489. * @param {Function} postInitFunc
  27490. */
  27491. function registerPostInit(postInitFunc) {
  27492. registerUpdateLifecycle('afterinit', postInitFunc);
  27493. }
  27494. /**
  27495. * Register postUpdater
  27496. * @param {Function} postUpdateFunc
  27497. */
  27498. function registerPostUpdate(postUpdateFunc) {
  27499. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27500. }
  27501. function registerUpdateLifecycle(name, cb) {
  27502. lifecycle.on(name, cb);
  27503. }
  27504. function registerAction(actionInfo, eventName, action) {
  27505. if (isFunction(eventName)) {
  27506. action = eventName;
  27507. eventName = '';
  27508. }
  27509. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27510. event: eventName
  27511. }][0]; // Event name is all lowercase
  27512. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27513. eventName = actionInfo.event;
  27514. if (eventActionMap[eventName]) {
  27515. // Already registered.
  27516. return;
  27517. } // Validate action type and event name.
  27518. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27519. if (!actions[actionType]) {
  27520. actions[actionType] = {
  27521. action: action,
  27522. actionInfo: actionInfo
  27523. };
  27524. }
  27525. eventActionMap[eventName] = actionType;
  27526. }
  27527. function registerCoordinateSystem(type, coordSysCreator) {
  27528. CoordinateSystemManager.register(type, coordSysCreator);
  27529. }
  27530. /**
  27531. * Get dimensions of specified coordinate system.
  27532. * @param {string} type
  27533. * @return {Array.<string|Object>}
  27534. */
  27535. function getCoordinateSystemDimensions(type) {
  27536. var coordSysCreator = CoordinateSystemManager.get(type);
  27537. if (coordSysCreator) {
  27538. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27539. }
  27540. }
  27541. function registerLayout(priority, layoutTask) {
  27542. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27543. }
  27544. function registerVisual(priority, visualTask) {
  27545. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27546. }
  27547. var registeredTasks = [];
  27548. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27549. if (isFunction(priority) || isObject(priority)) {
  27550. fn = priority;
  27551. priority = defaultPriority;
  27552. }
  27553. if ("development" !== 'production') {
  27554. if (isNaN(priority) || priority == null) {
  27555. throw new Error('Illegal priority');
  27556. } // Check duplicate
  27557. each(targetList, function (wrap) {
  27558. assert(wrap.__raw !== fn);
  27559. });
  27560. } // Already registered
  27561. if (indexOf(registeredTasks, fn) >= 0) {
  27562. return;
  27563. }
  27564. registeredTasks.push(fn);
  27565. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27566. stageHandler.__prio = priority;
  27567. stageHandler.__raw = fn;
  27568. targetList.push(stageHandler);
  27569. }
  27570. function registerLoading(name, loadingFx) {
  27571. loadingEffects[name] = loadingFx;
  27572. }
  27573. /**
  27574. * ZRender need a canvas context to do measureText.
  27575. * But in node environment canvas may be created by node-canvas.
  27576. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27577. *
  27578. *
  27579. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27580. *
  27581. * @example
  27582. * let Canvas = require('canvas');
  27583. * let echarts = require('echarts');
  27584. * echarts.setCanvasCreator(function () {
  27585. * // Small size is enough.
  27586. * return new Canvas(32, 32);
  27587. * });
  27588. */
  27589. function setCanvasCreator(creator) {
  27590. if ("development" !== 'production') {
  27591. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27592. }
  27593. setPlatformAPI({
  27594. createCanvas: creator
  27595. });
  27596. }
  27597. /**
  27598. * The parameters and usage: see `geoSourceManager.registerMap`.
  27599. * Compatible with previous `echarts.registerMap`.
  27600. */
  27601. function registerMap(mapName, geoJson, specialAreas) {
  27602. var registerMap = getImpl('registerMap');
  27603. registerMap && registerMap(mapName, geoJson, specialAreas);
  27604. }
  27605. function getMap(mapName) {
  27606. var getMap = getImpl('getMap');
  27607. return getMap && getMap(mapName);
  27608. }
  27609. var registerTransform = registerExternalTransform;
  27610. /**
  27611. * Globa dispatchAction to a specified chart instance.
  27612. */
  27613. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27614. // if (!payload || !payload.chartId) {
  27615. // // Must have chartId to find chart
  27616. // return;
  27617. // }
  27618. // const chart = instances[payload.chartId];
  27619. // if (chart) {
  27620. // chart.dispatchAction(payload, opt);
  27621. // }
  27622. // }
  27623. // Builtin global visual
  27624. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27625. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27626. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27627. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27628. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27629. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27630. registerPreprocessor(globalBackwardCompat);
  27631. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27632. registerLoading('default', defaultLoading); // Default actions
  27633. registerAction({
  27634. type: HIGHLIGHT_ACTION_TYPE,
  27635. event: HIGHLIGHT_ACTION_TYPE,
  27636. update: HIGHLIGHT_ACTION_TYPE
  27637. }, noop);
  27638. registerAction({
  27639. type: DOWNPLAY_ACTION_TYPE,
  27640. event: DOWNPLAY_ACTION_TYPE,
  27641. update: DOWNPLAY_ACTION_TYPE
  27642. }, noop);
  27643. registerAction({
  27644. type: SELECT_ACTION_TYPE,
  27645. event: SELECT_ACTION_TYPE,
  27646. update: SELECT_ACTION_TYPE
  27647. }, noop);
  27648. registerAction({
  27649. type: UNSELECT_ACTION_TYPE,
  27650. event: UNSELECT_ACTION_TYPE,
  27651. update: UNSELECT_ACTION_TYPE
  27652. }, noop);
  27653. registerAction({
  27654. type: TOGGLE_SELECT_ACTION_TYPE,
  27655. event: TOGGLE_SELECT_ACTION_TYPE,
  27656. update: TOGGLE_SELECT_ACTION_TYPE
  27657. }, noop); // Default theme
  27658. registerTheme('light', lightTheme);
  27659. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  27660. // be mounted on `echarts` is the extension `dataTool` is imported.
  27661. var dataTool = {};
  27662. var extensions = [];
  27663. var extensionRegisters = {
  27664. registerPreprocessor: registerPreprocessor,
  27665. registerProcessor: registerProcessor,
  27666. registerPostInit: registerPostInit,
  27667. registerPostUpdate: registerPostUpdate,
  27668. registerUpdateLifecycle: registerUpdateLifecycle,
  27669. registerAction: registerAction,
  27670. registerCoordinateSystem: registerCoordinateSystem,
  27671. registerLayout: registerLayout,
  27672. registerVisual: registerVisual,
  27673. registerTransform: registerTransform,
  27674. registerLoading: registerLoading,
  27675. registerMap: registerMap,
  27676. registerImpl: registerImpl,
  27677. PRIORITY: PRIORITY,
  27678. ComponentModel: ComponentModel,
  27679. ComponentView: ComponentView,
  27680. SeriesModel: SeriesModel,
  27681. ChartView: ChartView,
  27682. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27683. registerComponentModel: function (ComponentModelClass) {
  27684. ComponentModel.registerClass(ComponentModelClass);
  27685. },
  27686. registerComponentView: function (ComponentViewClass) {
  27687. ComponentView.registerClass(ComponentViewClass);
  27688. },
  27689. registerSeriesModel: function (SeriesModelClass) {
  27690. SeriesModel.registerClass(SeriesModelClass);
  27691. },
  27692. registerChartView: function (ChartViewClass) {
  27693. ChartView.registerClass(ChartViewClass);
  27694. },
  27695. registerSubTypeDefaulter: function (componentType, defaulter) {
  27696. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27697. },
  27698. registerPainter: function (painterType, PainterCtor) {
  27699. registerPainter(painterType, PainterCtor);
  27700. }
  27701. };
  27702. function use(ext) {
  27703. if (isArray(ext)) {
  27704. // use([ChartLine, ChartBar]);
  27705. each(ext, function (singleExt) {
  27706. use(singleExt);
  27707. });
  27708. return;
  27709. }
  27710. if (indexOf(extensions, ext) >= 0) {
  27711. return;
  27712. }
  27713. extensions.push(ext);
  27714. if (isFunction(ext)) {
  27715. ext = {
  27716. install: ext
  27717. };
  27718. }
  27719. ext.install(extensionRegisters);
  27720. }
  27721. /*
  27722. * Licensed to the Apache Software Foundation (ASF) under one
  27723. * or more contributor license agreements. See the NOTICE file
  27724. * distributed with this work for additional information
  27725. * regarding copyright ownership. The ASF licenses this file
  27726. * to you under the Apache License, Version 2.0 (the
  27727. * "License"); you may not use this file except in compliance
  27728. * with the License. You may obtain a copy of the License at
  27729. *
  27730. * http://www.apache.org/licenses/LICENSE-2.0
  27731. *
  27732. * Unless required by applicable law or agreed to in writing,
  27733. * software distributed under the License is distributed on an
  27734. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27735. * KIND, either express or implied. See the License for the
  27736. * specific language governing permissions and limitations
  27737. * under the License.
  27738. */
  27739. /**
  27740. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27741. */
  27742. /*
  27743. * Licensed to the Apache Software Foundation (ASF) under one
  27744. * or more contributor license agreements. See the NOTICE file
  27745. * distributed with this work for additional information
  27746. * regarding copyright ownership. The ASF licenses this file
  27747. * to you under the Apache License, Version 2.0 (the
  27748. * "License"); you may not use this file except in compliance
  27749. * with the License. You may obtain a copy of the License at
  27750. *
  27751. * http://www.apache.org/licenses/LICENSE-2.0
  27752. *
  27753. * Unless required by applicable law or agreed to in writing,
  27754. * software distributed under the License is distributed on an
  27755. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27756. * KIND, either express or implied. See the License for the
  27757. * specific language governing permissions and limitations
  27758. * under the License.
  27759. */
  27760. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27761. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27762. }
  27763. function defaultKeyGetter(item) {
  27764. return item;
  27765. }
  27766. var DataDiffer =
  27767. /** @class */
  27768. function () {
  27769. /**
  27770. * @param context Can be visited by this.context in callback.
  27771. */
  27772. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  27773. diffMode) {
  27774. this._old = oldArr;
  27775. this._new = newArr;
  27776. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27777. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  27778. this.context = context;
  27779. this._diffModeMultiple = diffMode === 'multiple';
  27780. }
  27781. /**
  27782. * Callback function when add a data
  27783. */
  27784. DataDiffer.prototype.add = function (func) {
  27785. this._add = func;
  27786. return this;
  27787. };
  27788. /**
  27789. * Callback function when update a data
  27790. */
  27791. DataDiffer.prototype.update = function (func) {
  27792. this._update = func;
  27793. return this;
  27794. };
  27795. /**
  27796. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27797. */
  27798. DataDiffer.prototype.updateManyToOne = function (func) {
  27799. this._updateManyToOne = func;
  27800. return this;
  27801. };
  27802. /**
  27803. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27804. */
  27805. DataDiffer.prototype.updateOneToMany = function (func) {
  27806. this._updateOneToMany = func;
  27807. return this;
  27808. };
  27809. /**
  27810. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27811. */
  27812. DataDiffer.prototype.updateManyToMany = function (func) {
  27813. this._updateManyToMany = func;
  27814. return this;
  27815. };
  27816. /**
  27817. * Callback function when remove a data
  27818. */
  27819. DataDiffer.prototype.remove = function (func) {
  27820. this._remove = func;
  27821. return this;
  27822. };
  27823. DataDiffer.prototype.execute = function () {
  27824. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27825. };
  27826. DataDiffer.prototype._executeOneToOne = function () {
  27827. var oldArr = this._old;
  27828. var newArr = this._new;
  27829. var newDataIndexMap = {};
  27830. var oldDataKeyArr = new Array(oldArr.length);
  27831. var newDataKeyArr = new Array(newArr.length);
  27832. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27833. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27834. for (var i = 0; i < oldArr.length; i++) {
  27835. var oldKey = oldDataKeyArr[i];
  27836. var newIdxMapVal = newDataIndexMap[oldKey];
  27837. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  27838. if (newIdxMapValLen > 1) {
  27839. // Consider there is duplicate key (for example, use dataItem.name as key).
  27840. // We should make sure every item in newArr and oldArr can be visited.
  27841. var newIdx = newIdxMapVal.shift();
  27842. if (newIdxMapVal.length === 1) {
  27843. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27844. }
  27845. this._update && this._update(newIdx, i);
  27846. } else if (newIdxMapValLen === 1) {
  27847. newDataIndexMap[oldKey] = null;
  27848. this._update && this._update(newIdxMapVal, i);
  27849. } else {
  27850. this._remove && this._remove(i);
  27851. }
  27852. }
  27853. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27854. };
  27855. /**
  27856. * For example, consider the case:
  27857. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27858. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27859. * Where:
  27860. * o0, o1, n0 has key 'a' (many to one)
  27861. * o5, n4, n5, n6 has key 'b' (one to many)
  27862. * o2, n1 has key 'c' (one to one)
  27863. * n2, n3 has key 'd' (add)
  27864. * o3, o4 has key 'e' (remove)
  27865. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27866. * Then:
  27867. * (The order of the following directives are not ensured.)
  27868. * this._updateManyToOne(n0, [o0, o1]);
  27869. * this._updateOneToMany([n4, n5, n6], o5);
  27870. * this._update(n1, o2);
  27871. * this._remove(o3);
  27872. * this._remove(o4);
  27873. * this._remove(o6);
  27874. * this._remove(o7);
  27875. * this._add(n2);
  27876. * this._add(n3);
  27877. * this._add(n7);
  27878. * this._add(n8);
  27879. */
  27880. DataDiffer.prototype._executeMultiple = function () {
  27881. var oldArr = this._old;
  27882. var newArr = this._new;
  27883. var oldDataIndexMap = {};
  27884. var newDataIndexMap = {};
  27885. var oldDataKeyArr = [];
  27886. var newDataKeyArr = [];
  27887. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27888. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27889. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27890. var oldKey = oldDataKeyArr[i];
  27891. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27892. var newIdxMapVal = newDataIndexMap[oldKey];
  27893. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27894. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27895. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27896. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27897. newDataIndexMap[oldKey] = null;
  27898. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27899. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27900. newDataIndexMap[oldKey] = null;
  27901. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27902. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27903. newDataIndexMap[oldKey] = null;
  27904. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  27905. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  27906. newDataIndexMap[oldKey] = null;
  27907. } else if (oldIdxMapValLen > 1) {
  27908. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27909. this._remove && this._remove(oldIdxMapVal[i_1]);
  27910. }
  27911. } else {
  27912. this._remove && this._remove(oldIdxMapVal);
  27913. }
  27914. }
  27915. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27916. };
  27917. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27918. for (var i = 0; i < newDataKeyArr.length; i++) {
  27919. var newKey = newDataKeyArr[i];
  27920. var newIdxMapVal = newDataIndexMap[newKey];
  27921. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27922. if (idxMapValLen > 1) {
  27923. for (var j = 0; j < idxMapValLen; j++) {
  27924. this._add && this._add(newIdxMapVal[j]);
  27925. }
  27926. } else if (idxMapValLen === 1) {
  27927. this._add && this._add(newIdxMapVal);
  27928. } // Support both `newDataKeyArr` are duplication removed or not removed.
  27929. newDataIndexMap[newKey] = null;
  27930. }
  27931. };
  27932. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  27933. map, // In 'byKey', the output `keyArr` is duplication removed.
  27934. // In 'byIndex', the output `keyArr` is not duplication removed and
  27935. // its indices are accurately corresponding to `arr`.
  27936. keyArr, keyGetterName) {
  27937. var cbModeMultiple = this._diffModeMultiple;
  27938. for (var i = 0; i < arr.length; i++) {
  27939. // Add prefix to avoid conflict with Object.prototype.
  27940. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27941. if (!cbModeMultiple) {
  27942. keyArr[i] = key;
  27943. }
  27944. if (!map) {
  27945. continue;
  27946. }
  27947. var idxMapVal = map[key];
  27948. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27949. if (idxMapValLen === 0) {
  27950. // Simple optimize: in most cases, one index has one key,
  27951. // do not need array.
  27952. map[key] = i;
  27953. if (cbModeMultiple) {
  27954. keyArr.push(key);
  27955. }
  27956. } else if (idxMapValLen === 1) {
  27957. map[key] = [idxMapVal, i];
  27958. } else {
  27959. idxMapVal.push(i);
  27960. }
  27961. }
  27962. };
  27963. return DataDiffer;
  27964. }();
  27965. var DimensionUserOuput =
  27966. /** @class */
  27967. function () {
  27968. function DimensionUserOuput(encode, dimRequest) {
  27969. this._encode = encode;
  27970. this._schema = dimRequest;
  27971. }
  27972. DimensionUserOuput.prototype.get = function () {
  27973. return {
  27974. // Do not generate full dimension name until fist used.
  27975. fullDimensions: this._getFullDimensionNames(),
  27976. encode: this._encode
  27977. };
  27978. };
  27979. /**
  27980. * Get all data store dimension names.
  27981. * Theoretically a series data store is defined both by series and used dataset (if any).
  27982. * If some dimensions are omitted for performance reason in `this.dimensions`,
  27983. * the dimension name may not be auto-generated if user does not specify a dimension name.
  27984. * In this case, the dimension name is `null`/`undefined`.
  27985. */
  27986. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  27987. if (!this._cachedDimNames) {
  27988. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  27989. }
  27990. return this._cachedDimNames;
  27991. };
  27992. return DimensionUserOuput;
  27993. }();
  27994. function summarizeDimensions(data, schema) {
  27995. var summary = {};
  27996. var encode = summary.encode = {};
  27997. var notExtraCoordDimMap = createHashMap();
  27998. var defaultedLabel = [];
  27999. var defaultedTooltip = [];
  28000. var userOutputEncode = {};
  28001. each(data.dimensions, function (dimName) {
  28002. var dimItem = data.getDimensionInfo(dimName);
  28003. var coordDim = dimItem.coordDim;
  28004. if (coordDim) {
  28005. if ("development" !== 'production') {
  28006. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  28007. }
  28008. var coordDimIndex = dimItem.coordDimIndex;
  28009. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  28010. if (!dimItem.isExtraCoord) {
  28011. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  28012. // because when dataset is used, it is hard to guess which dimension
  28013. // can be value dimension. If both show x, y on label is not look good,
  28014. // and conventionally y axis is focused more.
  28015. if (mayLabelDimType(dimItem.type)) {
  28016. defaultedLabel[0] = dimName;
  28017. } // User output encode do not contain generated coords.
  28018. // And it only has index. User can use index to retrieve value from the raw item array.
  28019. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  28020. }
  28021. if (dimItem.defaultTooltip) {
  28022. defaultedTooltip.push(dimName);
  28023. }
  28024. }
  28025. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  28026. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  28027. var dimIndex = dimItem.otherDims[otherDim];
  28028. if (dimIndex != null && dimIndex !== false) {
  28029. encodeArr[dimIndex] = dimItem.name;
  28030. }
  28031. });
  28032. });
  28033. var dataDimsOnCoord = [];
  28034. var encodeFirstDimNotExtra = {};
  28035. notExtraCoordDimMap.each(function (v, coordDim) {
  28036. var dimArr = encode[coordDim];
  28037. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  28038. // dim canot on more than one coordDim.
  28039. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  28040. });
  28041. summary.dataDimsOnCoord = dataDimsOnCoord;
  28042. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  28043. return data.getDimensionInfo(dimName).storeDimIndex;
  28044. });
  28045. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  28046. var encodeLabel = encode.label; // FIXME `encode.label` is not recommended, because formatter cannot be set
  28047. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  28048. if (encodeLabel && encodeLabel.length) {
  28049. defaultedLabel = encodeLabel.slice();
  28050. }
  28051. var encodeTooltip = encode.tooltip;
  28052. if (encodeTooltip && encodeTooltip.length) {
  28053. defaultedTooltip = encodeTooltip.slice();
  28054. } else if (!defaultedTooltip.length) {
  28055. defaultedTooltip = defaultedLabel.slice();
  28056. }
  28057. encode.defaultedLabel = defaultedLabel;
  28058. encode.defaultedTooltip = defaultedTooltip;
  28059. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  28060. return summary;
  28061. }
  28062. function getOrCreateEncodeArr(encode, dim) {
  28063. if (!encode.hasOwnProperty(dim)) {
  28064. encode[dim] = [];
  28065. }
  28066. return encode[dim];
  28067. } // FIXME:TS should be type `AxisType`
  28068. function getDimensionTypeByAxis(axisType) {
  28069. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  28070. }
  28071. function mayLabelDimType(dimType) {
  28072. // In most cases, ordinal and time do not suitable for label.
  28073. // Ordinal info can be displayed on axis. Time is too long.
  28074. return !(dimType === 'ordinal' || dimType === 'time');
  28075. } // function findTheLastDimMayLabel(data) {
  28076. // // Get last value dim
  28077. // let dimensions = data.dimensions.slice();
  28078. // let valueType;
  28079. // let valueDim;
  28080. // while (dimensions.length && (
  28081. // valueDim = dimensions.pop(),
  28082. // valueType = data.getDimensionInfo(valueDim).type,
  28083. // valueType === 'ordinal' || valueType === 'time'
  28084. // )) {} // jshint ignore:line
  28085. // return valueDim;
  28086. // }
  28087. var SeriesDimensionDefine =
  28088. /** @class */
  28089. function () {
  28090. /**
  28091. * @param opt All of the fields will be shallow copied.
  28092. */
  28093. function SeriesDimensionDefine(opt) {
  28094. /**
  28095. * The format of `otherDims` is:
  28096. * ```js
  28097. * {
  28098. * tooltip?: number
  28099. * label?: number
  28100. * itemName?: number
  28101. * seriesName?: number
  28102. * }
  28103. * ```
  28104. *
  28105. * A `series.encode` can specified these fields:
  28106. * ```js
  28107. * encode: {
  28108. * // "3, 1, 5" is the index of data dimension.
  28109. * tooltip: [3, 1, 5],
  28110. * label: [0, 3],
  28111. * ...
  28112. * }
  28113. * ```
  28114. * `otherDims` is the parse result of the `series.encode` above, like:
  28115. * ```js
  28116. * // Suppose the index of this data dimension is `3`.
  28117. * this.otherDims = {
  28118. * // `3` is at the index `0` of the `encode.tooltip`
  28119. * tooltip: 0,
  28120. * // `3` is at the index `1` of the `encode.label`
  28121. * label: 1
  28122. * };
  28123. * ```
  28124. *
  28125. * This prop should never be `null`/`undefined` after initialized.
  28126. */
  28127. this.otherDims = {};
  28128. if (opt != null) {
  28129. extend(this, opt);
  28130. }
  28131. }
  28132. return SeriesDimensionDefine;
  28133. }();
  28134. var inner$4 = makeInner();
  28135. var dimTypeShort = {
  28136. float: 'f',
  28137. int: 'i',
  28138. ordinal: 'o',
  28139. number: 'n',
  28140. time: 't'
  28141. };
  28142. /**
  28143. * Represents the dimension requirement of a series.
  28144. *
  28145. * NOTICE:
  28146. * When there are too many dimensions in dataset and many series, only the used dimensions
  28147. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  28148. * But users may query data by other unused dimension names.
  28149. * In this case, users can only query data if and only if they have defined dimension names
  28150. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  28151. * `source` dimensions.
  28152. */
  28153. var SeriesDataSchema =
  28154. /** @class */
  28155. function () {
  28156. function SeriesDataSchema(opt) {
  28157. this.dimensions = opt.dimensions;
  28158. this._dimOmitted = opt.dimensionOmitted;
  28159. this.source = opt.source;
  28160. this._fullDimCount = opt.fullDimensionCount;
  28161. this._updateDimOmitted(opt.dimensionOmitted);
  28162. }
  28163. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  28164. return this._dimOmitted;
  28165. };
  28166. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  28167. this._dimOmitted = dimensionOmitted;
  28168. if (!dimensionOmitted) {
  28169. return;
  28170. }
  28171. if (!this._dimNameMap) {
  28172. this._dimNameMap = ensureSourceDimNameMap(this.source);
  28173. }
  28174. };
  28175. /**
  28176. * @caution Can only be used when `dimensionOmitted: true`.
  28177. *
  28178. * Get index by user defined dimension name (i.e., not internal generate name).
  28179. * That is, get index from `dimensionsDefine`.
  28180. * If no `dimensionsDefine`, or no name get, return -1.
  28181. */
  28182. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  28183. return retrieve2(this._dimNameMap.get(dimName), -1);
  28184. };
  28185. /**
  28186. * @caution Can only be used when `dimensionOmitted: true`.
  28187. *
  28188. * Notice: may return `null`/`undefined` if user not specify dimension names.
  28189. */
  28190. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  28191. var dimensionsDefine = this.source.dimensionsDefine;
  28192. if (dimensionsDefine) {
  28193. return dimensionsDefine[dimIndex];
  28194. }
  28195. };
  28196. SeriesDataSchema.prototype.makeStoreSchema = function () {
  28197. var dimCount = this._fullDimCount;
  28198. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  28199. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  28200. // Generate from seriesDimList directly
  28201. var dimHash = '';
  28202. var dims = [];
  28203. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  28204. var property = void 0;
  28205. var type = void 0;
  28206. var ordinalMeta = void 0;
  28207. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  28208. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28209. property = willRetrieveDataByName ? seriesDimDef.name : null;
  28210. type = seriesDimDef.type;
  28211. ordinalMeta = seriesDimDef.ordinalMeta;
  28212. seriesDimIdx++;
  28213. } else {
  28214. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28215. if (sourceDimDef) {
  28216. property = willRetrieveDataByName ? sourceDimDef.name : null;
  28217. type = sourceDimDef.type;
  28218. }
  28219. }
  28220. dims.push({
  28221. property: property,
  28222. type: type,
  28223. ordinalMeta: ordinalMeta
  28224. }); // If retrieving data by index,
  28225. // use <index, type, ordinalMeta> to determine whether data can be shared.
  28226. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  28227. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  28228. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  28229. // use <property, type, ordinalMeta> in hash.
  28230. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  28231. // So we do not add property to hash to make sure they can share this store.
  28232. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  28233. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  28234. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  28235. : property;
  28236. }
  28237. dimHash += '$';
  28238. dimHash += dimTypeShort[type] || 'f';
  28239. if (ordinalMeta) {
  28240. dimHash += ordinalMeta.uid;
  28241. }
  28242. dimHash += '$';
  28243. } // Source from endpoint(usually series) will be read differently
  28244. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  28245. // So we use this three props as key.
  28246. var source = this.source;
  28247. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  28248. return {
  28249. dimensions: dims,
  28250. hash: hash
  28251. };
  28252. };
  28253. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  28254. var result = [];
  28255. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  28256. var name_1 = void 0;
  28257. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  28258. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28259. if (!seriesDimDef.isCalculationCoord) {
  28260. name_1 = seriesDimDef.name;
  28261. }
  28262. seriesDimIdx++;
  28263. } else {
  28264. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28265. if (sourceDimDef) {
  28266. name_1 = sourceDimDef.name;
  28267. }
  28268. }
  28269. result.push(name_1);
  28270. }
  28271. return result;
  28272. };
  28273. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  28274. this.dimensions.push(dimDef);
  28275. dimDef.isCalculationCoord = true;
  28276. this._fullDimCount++; // If append dimension on a data store, consider the store
  28277. // might be shared by different series, series dimensions not
  28278. // really map to store dimensions.
  28279. this._updateDimOmitted(true);
  28280. };
  28281. return SeriesDataSchema;
  28282. }();
  28283. function isSeriesDataSchema(schema) {
  28284. return schema instanceof SeriesDataSchema;
  28285. }
  28286. function createDimNameMap(dimsDef) {
  28287. var dataDimNameMap = createHashMap();
  28288. for (var i = 0; i < (dimsDef || []).length; i++) {
  28289. var dimDefItemRaw = dimsDef[i];
  28290. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  28291. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28292. dataDimNameMap.set(userDimName, i);
  28293. }
  28294. }
  28295. return dataDimNameMap;
  28296. }
  28297. function ensureSourceDimNameMap(source) {
  28298. var innerSource = inner$4(source);
  28299. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  28300. }
  28301. function shouldOmitUnusedDimensions(dimCount) {
  28302. return dimCount > 30;
  28303. }
  28304. var isObject$2 = isObject;
  28305. var map$1 = map;
  28306. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  28307. // which will cause weird update animation.
  28308. var ID_PREFIX = 'e\0\0';
  28309. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  28310. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  28311. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  28312. // Internal method declarations:
  28313. // -----------------------------
  28314. var prepareInvertedIndex;
  28315. var getId;
  28316. var getIdNameFromStore;
  28317. var normalizeDimensions;
  28318. var transferProperties;
  28319. var cloneListForMapAndSample;
  28320. var makeIdFromName;
  28321. var SeriesData =
  28322. /** @class */
  28323. function () {
  28324. /**
  28325. * @param dimensionsInput.dimensions
  28326. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  28327. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  28328. */
  28329. function SeriesData(dimensionsInput, hostModel) {
  28330. this.type = 'list';
  28331. this._dimOmitted = false;
  28332. this._nameList = [];
  28333. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  28334. // Never used yet (not used yet).
  28335. // private _optionModels: Model[] = [];
  28336. // Global visual properties after visual coding
  28337. this._visual = {}; // Global layout properties.
  28338. this._layout = {}; // Item visual properties after visual coding
  28339. this._itemVisuals = []; // Item layout properties after layout
  28340. this._itemLayouts = []; // Graphic elements
  28341. this._graphicEls = []; // key: dim, value: extent
  28342. this._approximateExtent = {};
  28343. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  28344. // (in type `OptionDataItemObject`).
  28345. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  28346. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  28347. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  28348. // Notice that those method should `RETURN` the new list.
  28349. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  28350. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28351. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  28352. var dimensions;
  28353. var assignStoreDimIdx = false;
  28354. if (isSeriesDataSchema(dimensionsInput)) {
  28355. dimensions = dimensionsInput.dimensions;
  28356. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  28357. this._schema = dimensionsInput;
  28358. } else {
  28359. assignStoreDimIdx = true;
  28360. dimensions = dimensionsInput;
  28361. }
  28362. dimensions = dimensions || ['x', 'y'];
  28363. var dimensionInfos = {};
  28364. var dimensionNames = [];
  28365. var invertedIndicesMap = {};
  28366. var needsHasOwn = false;
  28367. var emptyObj = {};
  28368. for (var i = 0; i < dimensions.length; i++) {
  28369. // Use the original dimensions[i], where other flag props may exists.
  28370. var dimInfoInput = dimensions[i];
  28371. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  28372. name: dimInfoInput
  28373. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  28374. var dimensionName = dimensionInfo.name;
  28375. dimensionInfo.type = dimensionInfo.type || 'float';
  28376. if (!dimensionInfo.coordDim) {
  28377. dimensionInfo.coordDim = dimensionName;
  28378. dimensionInfo.coordDimIndex = 0;
  28379. }
  28380. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  28381. dimensionNames.push(dimensionName);
  28382. dimensionInfos[dimensionName] = dimensionInfo;
  28383. if (emptyObj[dimensionName] != null) {
  28384. needsHasOwn = true;
  28385. }
  28386. if (dimensionInfo.createInvertedIndices) {
  28387. invertedIndicesMap[dimensionName] = [];
  28388. }
  28389. if (otherDims.itemName === 0) {
  28390. this._nameDimIdx = i;
  28391. }
  28392. if (otherDims.itemId === 0) {
  28393. this._idDimIdx = i;
  28394. }
  28395. if ("development" !== 'production') {
  28396. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  28397. }
  28398. if (assignStoreDimIdx) {
  28399. dimensionInfo.storeDimIndex = i;
  28400. }
  28401. }
  28402. this.dimensions = dimensionNames;
  28403. this._dimInfos = dimensionInfos;
  28404. this._initGetDimensionInfo(needsHasOwn);
  28405. this.hostModel = hostModel;
  28406. this._invertedIndicesMap = invertedIndicesMap;
  28407. if (this._dimOmitted) {
  28408. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  28409. each(dimensionNames, function (dimName) {
  28410. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  28411. });
  28412. }
  28413. }
  28414. /**
  28415. *
  28416. * Get concrete dimension name by dimension name or dimension index.
  28417. * If input a dimension name, do not validate whether the dimension name exits.
  28418. *
  28419. * @caution
  28420. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  28421. * Because only those dimensions will have auto-generated dimension names if not
  28422. * have a user-specified name, and other dimensions will get a return of null/undefined.
  28423. *
  28424. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  28425. * ```js
  28426. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  28427. * ```
  28428. *
  28429. * @return Concrete dim name.
  28430. */
  28431. SeriesData.prototype.getDimension = function (dim) {
  28432. var dimIdx = this._recognizeDimIndex(dim);
  28433. if (dimIdx == null) {
  28434. return dim;
  28435. }
  28436. dimIdx = dim;
  28437. if (!this._dimOmitted) {
  28438. return this.dimensions[dimIdx];
  28439. } // Retrieve from series dimension definition because it probably contains
  28440. // generated dimension name (like 'x', 'y').
  28441. var dimName = this._dimIdxToName.get(dimIdx);
  28442. if (dimName != null) {
  28443. return dimName;
  28444. }
  28445. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28446. if (sourceDimDef) {
  28447. return sourceDimDef.name;
  28448. }
  28449. };
  28450. /**
  28451. * Get dimension index in data store. Return -1 if not found.
  28452. * Can be used to index value from getRawValue.
  28453. */
  28454. SeriesData.prototype.getDimensionIndex = function (dim) {
  28455. var dimIdx = this._recognizeDimIndex(dim);
  28456. if (dimIdx != null) {
  28457. return dimIdx;
  28458. }
  28459. if (dim == null) {
  28460. return -1;
  28461. }
  28462. var dimInfo = this._getDimInfo(dim);
  28463. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28464. };
  28465. /**
  28466. * The meanings of the input parameter `dim`:
  28467. *
  28468. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28469. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28470. * + If dim is a number-like string (e.g., `"1"`):
  28471. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28472. * it means that concrete name.
  28473. * + If not, it will be converted to a number, which means the index of the dimension.
  28474. * (why? because of the backward compatibility. We have been tolerating number-like string in
  28475. * dimension setting, although now it seems that it is not a good idea.)
  28476. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28477. * if no dimension name is defined as `"1"`.
  28478. * + If dim is a not-number-like string, it means the concrete dim name.
  28479. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28480. * or customized in `dimensions` property of option like `"age"`.
  28481. *
  28482. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28483. */
  28484. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28485. if (isNumber(dim) // If being a number-like string but not being defined as a dimension name.
  28486. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28487. return +dim;
  28488. }
  28489. };
  28490. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28491. var dimIdx = this.getDimensionIndex(dim);
  28492. if ("development" !== 'production') {
  28493. if (dimIdx == null) {
  28494. throw new Error('Unknown dimension ' + dim);
  28495. }
  28496. }
  28497. return dimIdx;
  28498. };
  28499. /**
  28500. * Get type and calculation info of particular dimension
  28501. * @param dim
  28502. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28503. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28504. */
  28505. SeriesData.prototype.getDimensionInfo = function (dim) {
  28506. // Do not clone, because there may be categories in dimInfo.
  28507. return this._getDimInfo(this.getDimension(dim));
  28508. };
  28509. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28510. var dimensionInfos = this._dimInfos;
  28511. this._getDimInfo = needsHasOwn ? function (dimName) {
  28512. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28513. } : function (dimName) {
  28514. return dimensionInfos[dimName];
  28515. };
  28516. };
  28517. /**
  28518. * concrete dimension name list on coord.
  28519. */
  28520. SeriesData.prototype.getDimensionsOnCoord = function () {
  28521. return this._dimSummary.dataDimsOnCoord.slice();
  28522. };
  28523. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28524. var dimensionsSummary = this._dimSummary;
  28525. if (idx == null) {
  28526. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28527. }
  28528. var dims = dimensionsSummary.encode[coordDim];
  28529. return dims ? dims[idx] : null;
  28530. };
  28531. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28532. var dimensionsSummary = this._dimSummary;
  28533. var dims = dimensionsSummary.encode[coordDim];
  28534. return (dims || []).slice();
  28535. };
  28536. SeriesData.prototype.getStore = function () {
  28537. return this._store;
  28538. };
  28539. /**
  28540. * Initialize from data
  28541. * @param data source or data or data store.
  28542. * @param nameList The name of a datum is used on data diff and
  28543. * default label/tooltip.
  28544. * A name can be specified in encode.itemName,
  28545. * or dataItem.name (only for series option data),
  28546. * or provided in nameList from outside.
  28547. */
  28548. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28549. var _this = this;
  28550. var store;
  28551. if (data instanceof DataStore) {
  28552. store = data;
  28553. }
  28554. if (!store) {
  28555. var dimensions = this.dimensions;
  28556. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28557. store = new DataStore();
  28558. var dimensionInfos = map$1(dimensions, function (dimName) {
  28559. return {
  28560. type: _this._dimInfos[dimName].type,
  28561. property: dimName
  28562. };
  28563. });
  28564. store.initData(provider, dimensionInfos, dimValueGetter);
  28565. }
  28566. this._store = store; // Reset
  28567. this._nameList = (nameList || []).slice();
  28568. this._idList = [];
  28569. this._nameRepeatCount = {};
  28570. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  28571. // Needs to be initialized after store is prepared.
  28572. this._dimSummary = summarizeDimensions(this, this._schema);
  28573. this.userOutput = this._dimSummary.userOutput;
  28574. };
  28575. /**
  28576. * Caution: Can be only called on raw data (before `this._indices` created).
  28577. */
  28578. SeriesData.prototype.appendData = function (data) {
  28579. var range = this._store.appendData(data);
  28580. this._doInit(range[0], range[1]);
  28581. };
  28582. /**
  28583. * Caution: Can be only called on raw data (before `this._indices` created).
  28584. * This method does not modify `rawData` (`dataProvider`), but only
  28585. * add values to store.
  28586. *
  28587. * The final count will be increased by `Math.max(values.length, names.length)`.
  28588. *
  28589. * @param values That is the SourceType: 'arrayRows', like
  28590. * [
  28591. * [12, 33, 44],
  28592. * [NaN, 43, 1],
  28593. * ['-', 'asdf', 0]
  28594. * ]
  28595. * Each item is exactly corresponding to a dimension.
  28596. */
  28597. SeriesData.prototype.appendValues = function (values, names) {
  28598. var _a = this._store.appendValues(values, names.length),
  28599. start = _a.start,
  28600. end = _a.end;
  28601. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28602. this._updateOrdinalMeta();
  28603. if (names) {
  28604. for (var idx = start; idx < end; idx++) {
  28605. var sourceIdx = idx - start;
  28606. this._nameList[idx] = names[sourceIdx];
  28607. if (shouldMakeIdFromName) {
  28608. makeIdFromName(this, idx);
  28609. }
  28610. }
  28611. }
  28612. };
  28613. SeriesData.prototype._updateOrdinalMeta = function () {
  28614. var store = this._store;
  28615. var dimensions = this.dimensions;
  28616. for (var i = 0; i < dimensions.length; i++) {
  28617. var dimInfo = this._dimInfos[dimensions[i]];
  28618. if (dimInfo.ordinalMeta) {
  28619. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28620. }
  28621. }
  28622. };
  28623. SeriesData.prototype._shouldMakeIdFromName = function () {
  28624. var provider = this._store.getProvider();
  28625. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28626. };
  28627. SeriesData.prototype._doInit = function (start, end) {
  28628. if (start >= end) {
  28629. return;
  28630. }
  28631. var store = this._store;
  28632. var provider = store.getProvider();
  28633. this._updateOrdinalMeta();
  28634. var nameList = this._nameList;
  28635. var idList = this._idList;
  28636. var sourceFormat = provider.getSource().sourceFormat;
  28637. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  28638. // [1, 2]
  28639. // 2
  28640. // Bar chart, line chart which uses category axis
  28641. // only gives the 'y' value. 'x' value is the indices of category
  28642. // Use a tempValue to normalize the value to be a (x, y) value
  28643. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28644. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28645. if (isFormatOriginal && !provider.pure) {
  28646. var sharedDataItem = [];
  28647. for (var idx = start; idx < end; idx++) {
  28648. // NOTICE: Try not to write things into dataItem
  28649. var dataItem = provider.getItem(idx, sharedDataItem);
  28650. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28651. this.hasItemOption = true;
  28652. }
  28653. if (dataItem) {
  28654. var itemName = dataItem.name;
  28655. if (nameList[idx] == null && itemName != null) {
  28656. nameList[idx] = convertOptionIdName(itemName, null);
  28657. }
  28658. var itemId = dataItem.id;
  28659. if (idList[idx] == null && itemId != null) {
  28660. idList[idx] = convertOptionIdName(itemId, null);
  28661. }
  28662. }
  28663. }
  28664. }
  28665. if (this._shouldMakeIdFromName()) {
  28666. for (var idx = start; idx < end; idx++) {
  28667. makeIdFromName(this, idx);
  28668. }
  28669. }
  28670. prepareInvertedIndex(this);
  28671. };
  28672. /**
  28673. * PENDING: In fact currently this function is only used to short-circuit
  28674. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28675. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28676. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28677. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28678. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28679. * be still needed.
  28680. *
  28681. * Optimize for the scenario that data is filtered by a given extent.
  28682. * Consider that if data amount is more than hundreds of thousand,
  28683. * extent calculation will cost more than 10ms and the cache will
  28684. * be erased because of the filtering.
  28685. */
  28686. SeriesData.prototype.getApproximateExtent = function (dim) {
  28687. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28688. };
  28689. /**
  28690. * Calculate extent on a filtered data might be time consuming.
  28691. * Approximate extent is only used for: calculate extent of filtered data outside.
  28692. */
  28693. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28694. dim = this.getDimension(dim);
  28695. this._approximateExtent[dim] = extent.slice();
  28696. };
  28697. SeriesData.prototype.getCalculationInfo = function (key) {
  28698. return this._calculationInfo[key];
  28699. };
  28700. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28701. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28702. };
  28703. /**
  28704. * @return Never be null/undefined. `number` will be converted to string. Because:
  28705. * In most cases, name is used in display, where returning a string is more convenient.
  28706. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28707. * rule that name `2` equals to name `'2'`.
  28708. */
  28709. SeriesData.prototype.getName = function (idx) {
  28710. var rawIndex = this.getRawIndex(idx);
  28711. var name = this._nameList[rawIndex];
  28712. if (name == null && this._nameDimIdx != null) {
  28713. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  28714. }
  28715. if (name == null) {
  28716. name = '';
  28717. }
  28718. return name;
  28719. };
  28720. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  28721. var ordinal = this._store.get(dimIdx, idx);
  28722. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  28723. if (ordinalMeta) {
  28724. return ordinalMeta.categories[ordinal];
  28725. }
  28726. return ordinal;
  28727. };
  28728. /**
  28729. * @return Never null/undefined. `number` will be converted to string. Because:
  28730. * In all cases having encountered at present, id is used in making diff comparison, which
  28731. * are usually based on hash map. We can keep the rule that the internal id are always string
  28732. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28733. */
  28734. SeriesData.prototype.getId = function (idx) {
  28735. return getId(this, this.getRawIndex(idx));
  28736. };
  28737. SeriesData.prototype.count = function () {
  28738. return this._store.count();
  28739. };
  28740. /**
  28741. * Get value. Return NaN if idx is out of range.
  28742. *
  28743. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  28744. */
  28745. SeriesData.prototype.get = function (dim, idx) {
  28746. var store = this._store;
  28747. var dimInfo = this._dimInfos[dim];
  28748. if (dimInfo) {
  28749. return store.get(dimInfo.storeDimIndex, idx);
  28750. }
  28751. };
  28752. /**
  28753. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  28754. */
  28755. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  28756. var store = this._store;
  28757. var dimInfo = this._dimInfos[dim];
  28758. if (dimInfo) {
  28759. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  28760. }
  28761. };
  28762. SeriesData.prototype.getIndices = function () {
  28763. return this._store.getIndices();
  28764. };
  28765. SeriesData.prototype.getDataExtent = function (dim) {
  28766. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  28767. };
  28768. SeriesData.prototype.getSum = function (dim) {
  28769. return this._store.getSum(this._getStoreDimIndex(dim));
  28770. };
  28771. SeriesData.prototype.getMedian = function (dim) {
  28772. return this._store.getMedian(this._getStoreDimIndex(dim));
  28773. };
  28774. SeriesData.prototype.getValues = function (dimensions, idx) {
  28775. var _this = this;
  28776. var store = this._store;
  28777. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  28778. return _this._getStoreDimIndex(dim);
  28779. }), idx) : store.getValues(dimensions);
  28780. };
  28781. /**
  28782. * If value is NaN. Including '-'
  28783. * Only check the coord dimensions.
  28784. */
  28785. SeriesData.prototype.hasValue = function (idx) {
  28786. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  28787. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  28788. // Ordinal type originally can be string or number.
  28789. // But when an ordinal type is used on coord, it can
  28790. // not be string but only number. So we can also use isNaN.
  28791. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  28792. return false;
  28793. }
  28794. }
  28795. return true;
  28796. };
  28797. /**
  28798. * Retrieve the index with given name
  28799. */
  28800. SeriesData.prototype.indexOfName = function (name) {
  28801. for (var i = 0, len = this._store.count(); i < len; i++) {
  28802. if (this.getName(i) === name) {
  28803. return i;
  28804. }
  28805. }
  28806. return -1;
  28807. };
  28808. SeriesData.prototype.getRawIndex = function (idx) {
  28809. return this._store.getRawIndex(idx);
  28810. };
  28811. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  28812. return this._store.indexOfRawIndex(rawIndex);
  28813. };
  28814. /**
  28815. * Only support the dimension which inverted index created.
  28816. * Do not support other cases until required.
  28817. * @param dim concrete dim
  28818. * @param value ordinal index
  28819. * @return rawIndex
  28820. */
  28821. SeriesData.prototype.rawIndexOf = function (dim, value) {
  28822. var invertedIndices = dim && this._invertedIndicesMap[dim];
  28823. if ("development" !== 'production') {
  28824. if (!invertedIndices) {
  28825. throw new Error('Do not supported yet');
  28826. }
  28827. }
  28828. var rawIndex = invertedIndices[value];
  28829. if (rawIndex == null || isNaN(rawIndex)) {
  28830. return INDEX_NOT_FOUND;
  28831. }
  28832. return rawIndex;
  28833. };
  28834. /**
  28835. * Retrieve the index of nearest value
  28836. * @param dim
  28837. * @param value
  28838. * @param [maxDistance=Infinity]
  28839. * @return If and only if multiple indices has
  28840. * the same value, they are put to the result.
  28841. */
  28842. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28843. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  28844. };
  28845. SeriesData.prototype.each = function (dims, cb, ctx) {
  28846. if (isFunction(dims)) {
  28847. ctx = cb;
  28848. cb = dims;
  28849. dims = [];
  28850. } // ctxCompat just for compat echarts3
  28851. var fCtx = ctx || this;
  28852. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28853. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28854. };
  28855. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  28856. if (isFunction(dims)) {
  28857. ctx = cb;
  28858. cb = dims;
  28859. dims = [];
  28860. } // ctxCompat just for compat echarts3
  28861. var fCtx = ctx || this;
  28862. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28863. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28864. return this;
  28865. };
  28866. /**
  28867. * Select data in range. (For optimization of filter)
  28868. * (Manually inline code, support 5 million data filtering in data zoom.)
  28869. */
  28870. SeriesData.prototype.selectRange = function (range) {
  28871. var _this = this;
  28872. var innerRange = {};
  28873. var dims = keys(range);
  28874. each(dims, function (dim) {
  28875. var dimIdx = _this._getStoreDimIndex(dim);
  28876. innerRange[dimIdx] = range[dim];
  28877. });
  28878. this._store = this._store.selectRange(innerRange);
  28879. return this;
  28880. };
  28881. /* eslint-enable max-len */
  28882. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  28883. if (isFunction(dims)) {
  28884. ctx = cb;
  28885. cb = dims;
  28886. dims = [];
  28887. } // ctxCompat just for compat echarts3
  28888. ctx = ctx || this;
  28889. var result = [];
  28890. this.each(dims, function () {
  28891. result.push(cb && cb.apply(this, arguments));
  28892. }, ctx);
  28893. return result;
  28894. };
  28895. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28896. var fCtx = ctx || ctxCompat || this;
  28897. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28898. var list = cloneListForMapAndSample(this);
  28899. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28900. return list;
  28901. };
  28902. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  28903. var _this = this; // ctxCompat just for compat echarts3
  28904. var fCtx = ctx || ctxCompat || this;
  28905. if ("development" !== 'production') {
  28906. each(normalizeDimensions(dims), function (dim) {
  28907. var dimInfo = _this.getDimensionInfo(dim);
  28908. if (!dimInfo.isCalculationCoord) {
  28909. console.error('Danger: only stack dimension can be modified');
  28910. }
  28911. });
  28912. }
  28913. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  28914. // it still cost lots of memory, because `_store.dimensions` are not shared.
  28915. // We should consider there probably be shallow clone happen in each series
  28916. // in consequent filter/map.
  28917. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28918. };
  28919. /**
  28920. * Large data down sampling on given dimension
  28921. * @param sampleIndex Sample index for name and id
  28922. */
  28923. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28924. var list = cloneListForMapAndSample(this);
  28925. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  28926. return list;
  28927. };
  28928. /**
  28929. * Large data down sampling using largest-triangle-three-buckets
  28930. * @param {string} valueDimension
  28931. * @param {number} targetCount
  28932. */
  28933. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  28934. var list = cloneListForMapAndSample(this);
  28935. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  28936. return list;
  28937. };
  28938. SeriesData.prototype.getRawDataItem = function (idx) {
  28939. return this._store.getRawDataItem(idx);
  28940. };
  28941. /**
  28942. * Get model of one data item.
  28943. */
  28944. // TODO: Type of data item
  28945. SeriesData.prototype.getItemModel = function (idx) {
  28946. var hostModel = this.hostModel;
  28947. var dataItem = this.getRawDataItem(idx);
  28948. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28949. };
  28950. /**
  28951. * Create a data differ
  28952. */
  28953. SeriesData.prototype.diff = function (otherList) {
  28954. var thisList = this;
  28955. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  28956. return getId(otherList, idx);
  28957. }, function (idx) {
  28958. return getId(thisList, idx);
  28959. });
  28960. };
  28961. /**
  28962. * Get visual property.
  28963. */
  28964. SeriesData.prototype.getVisual = function (key) {
  28965. var visual = this._visual;
  28966. return visual && visual[key];
  28967. };
  28968. SeriesData.prototype.setVisual = function (kvObj, val) {
  28969. this._visual = this._visual || {};
  28970. if (isObject$2(kvObj)) {
  28971. extend(this._visual, kvObj);
  28972. } else {
  28973. this._visual[kvObj] = val;
  28974. }
  28975. };
  28976. /**
  28977. * Get visual property of single data item
  28978. */
  28979. // eslint-disable-next-line
  28980. SeriesData.prototype.getItemVisual = function (idx, key) {
  28981. var itemVisual = this._itemVisuals[idx];
  28982. var val = itemVisual && itemVisual[key];
  28983. if (val == null) {
  28984. // Use global visual property
  28985. return this.getVisual(key);
  28986. }
  28987. return val;
  28988. };
  28989. /**
  28990. * If exists visual property of single data item
  28991. */
  28992. SeriesData.prototype.hasItemVisual = function () {
  28993. return this._itemVisuals.length > 0;
  28994. };
  28995. /**
  28996. * Make sure itemVisual property is unique
  28997. */
  28998. // TODO: use key to save visual to reduce memory.
  28999. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  29000. var itemVisuals = this._itemVisuals;
  29001. var itemVisual = itemVisuals[idx];
  29002. if (!itemVisual) {
  29003. itemVisual = itemVisuals[idx] = {};
  29004. }
  29005. var val = itemVisual[key];
  29006. if (val == null) {
  29007. val = this.getVisual(key); // TODO Performance?
  29008. if (isArray(val)) {
  29009. val = val.slice();
  29010. } else if (isObject$2(val)) {
  29011. val = extend({}, val);
  29012. }
  29013. itemVisual[key] = val;
  29014. }
  29015. return val;
  29016. }; // eslint-disable-next-line
  29017. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  29018. var itemVisual = this._itemVisuals[idx] || {};
  29019. this._itemVisuals[idx] = itemVisual;
  29020. if (isObject$2(key)) {
  29021. extend(itemVisual, key);
  29022. } else {
  29023. itemVisual[key] = value;
  29024. }
  29025. };
  29026. /**
  29027. * Clear itemVisuals and list visual.
  29028. */
  29029. SeriesData.prototype.clearAllVisual = function () {
  29030. this._visual = {};
  29031. this._itemVisuals = [];
  29032. };
  29033. SeriesData.prototype.setLayout = function (key, val) {
  29034. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  29035. };
  29036. /**
  29037. * Get layout property.
  29038. */
  29039. SeriesData.prototype.getLayout = function (key) {
  29040. return this._layout[key];
  29041. };
  29042. /**
  29043. * Get layout of single data item
  29044. */
  29045. SeriesData.prototype.getItemLayout = function (idx) {
  29046. return this._itemLayouts[idx];
  29047. };
  29048. /**
  29049. * Set layout of single data item
  29050. */
  29051. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  29052. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  29053. };
  29054. /**
  29055. * Clear all layout of single data item
  29056. */
  29057. SeriesData.prototype.clearItemLayouts = function () {
  29058. this._itemLayouts.length = 0;
  29059. };
  29060. /**
  29061. * Set graphic element relative to data. It can be set as null
  29062. */
  29063. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  29064. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  29065. setCommonECData(seriesIndex, this.dataType, idx, el);
  29066. this._graphicEls[idx] = el;
  29067. };
  29068. SeriesData.prototype.getItemGraphicEl = function (idx) {
  29069. return this._graphicEls[idx];
  29070. };
  29071. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  29072. each(this._graphicEls, function (el, idx) {
  29073. if (el) {
  29074. cb && cb.call(context, el, idx);
  29075. }
  29076. });
  29077. };
  29078. /**
  29079. * Shallow clone a new list except visual and layout properties, and graph elements.
  29080. * New list only change the indices.
  29081. */
  29082. SeriesData.prototype.cloneShallow = function (list) {
  29083. if (!list) {
  29084. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  29085. }
  29086. transferProperties(list, this);
  29087. list._store = this._store;
  29088. return list;
  29089. };
  29090. /**
  29091. * Wrap some method to add more feature
  29092. */
  29093. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  29094. var originalMethod = this[methodName];
  29095. if (!isFunction(originalMethod)) {
  29096. return;
  29097. }
  29098. this.__wrappedMethods = this.__wrappedMethods || [];
  29099. this.__wrappedMethods.push(methodName);
  29100. this[methodName] = function () {
  29101. var res = originalMethod.apply(this, arguments);
  29102. return injectFunction.apply(this, [res].concat(slice(arguments)));
  29103. };
  29104. }; // ----------------------------------------------------------
  29105. // A work around for internal method visiting private member.
  29106. // ----------------------------------------------------------
  29107. SeriesData.internalField = function () {
  29108. prepareInvertedIndex = function (data) {
  29109. var invertedIndicesMap = data._invertedIndicesMap;
  29110. each(invertedIndicesMap, function (invertedIndices, dim) {
  29111. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  29112. var ordinalMeta = dimInfo.ordinalMeta;
  29113. var store = data._store;
  29114. if (ordinalMeta) {
  29115. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  29116. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  29117. for (var i = 0; i < invertedIndices.length; i++) {
  29118. invertedIndices[i] = INDEX_NOT_FOUND;
  29119. }
  29120. for (var i = 0; i < store.count(); i++) {
  29121. // Only support the case that all values are distinct.
  29122. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  29123. }
  29124. }
  29125. });
  29126. };
  29127. getIdNameFromStore = function (data, dimIdx, idx) {
  29128. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  29129. };
  29130. /**
  29131. * @see the comment of `List['getId']`.
  29132. */
  29133. getId = function (data, rawIndex) {
  29134. var id = data._idList[rawIndex];
  29135. if (id == null && data._idDimIdx != null) {
  29136. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  29137. }
  29138. if (id == null) {
  29139. id = ID_PREFIX + rawIndex;
  29140. }
  29141. return id;
  29142. };
  29143. normalizeDimensions = function (dimensions) {
  29144. if (!isArray(dimensions)) {
  29145. dimensions = dimensions != null ? [dimensions] : [];
  29146. }
  29147. return dimensions;
  29148. };
  29149. /**
  29150. * Data in excludeDimensions is copied, otherwise transferred.
  29151. */
  29152. cloneListForMapAndSample = function (original) {
  29153. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  29154. transferProperties(list, original);
  29155. return list;
  29156. };
  29157. transferProperties = function (target, source) {
  29158. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  29159. if (source.hasOwnProperty(propName)) {
  29160. target[propName] = source[propName];
  29161. }
  29162. });
  29163. target.__wrappedMethods = source.__wrappedMethods;
  29164. each(CLONE_PROPERTIES, function (propName) {
  29165. target[propName] = clone(source[propName]);
  29166. });
  29167. target._calculationInfo = extend({}, source._calculationInfo);
  29168. };
  29169. makeIdFromName = function (data, idx) {
  29170. var nameList = data._nameList;
  29171. var idList = data._idList;
  29172. var nameDimIdx = data._nameDimIdx;
  29173. var idDimIdx = data._idDimIdx;
  29174. var name = nameList[idx];
  29175. var id = idList[idx];
  29176. if (name == null && nameDimIdx != null) {
  29177. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  29178. }
  29179. if (id == null && idDimIdx != null) {
  29180. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  29181. }
  29182. if (id == null && name != null) {
  29183. var nameRepeatCount = data._nameRepeatCount;
  29184. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  29185. id = name;
  29186. if (nmCnt > 1) {
  29187. id += '__ec__' + nmCnt;
  29188. }
  29189. idList[idx] = id;
  29190. }
  29191. };
  29192. }();
  29193. return SeriesData;
  29194. }();
  29195. /**
  29196. * For outside usage compat (like echarts-gl are using it).
  29197. */
  29198. function createDimensions(source, opt) {
  29199. return prepareSeriesDataSchema(source, opt).dimensions;
  29200. }
  29201. /**
  29202. * This method builds the relationship between:
  29203. * + "what the coord sys or series requires (see `coordDimensions`)",
  29204. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  29205. * + "what the data source provids (see `source`)".
  29206. *
  29207. * Some guess strategy will be adapted if user does not define something.
  29208. * If no 'value' dimension specified, the first no-named dimension will be
  29209. * named as 'value'.
  29210. *
  29211. * @return The results are always sorted by `storeDimIndex` asc.
  29212. */
  29213. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  29214. source, opt) {
  29215. if (!isSourceInstance(source)) {
  29216. source = createSourceFromSeriesDataOption(source);
  29217. }
  29218. opt = opt || {};
  29219. var sysDims = opt.coordDimensions || [];
  29220. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  29221. var coordDimNameMap = createHashMap();
  29222. var resultList = [];
  29223. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unused dimensions if sharing a high dimension datastore
  29224. // 30 is an experience value.
  29225. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  29226. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  29227. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  29228. var encodeDef = opt.encodeDefine;
  29229. if (!encodeDef && opt.encodeDefaulter) {
  29230. encodeDef = opt.encodeDefaulter(source, dimCount);
  29231. }
  29232. var encodeDefMap = createHashMap(encodeDef);
  29233. var indicesMap = new CtorInt32Array(dimCount);
  29234. for (var i = 0; i < indicesMap.length; i++) {
  29235. indicesMap[i] = -1;
  29236. }
  29237. function getResultItem(dimIdx) {
  29238. var idx = indicesMap[dimIdx];
  29239. if (idx < 0) {
  29240. var dimDefItemRaw = dimsDef[dimIdx];
  29241. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  29242. name: dimDefItemRaw
  29243. };
  29244. var resultItem = new SeriesDimensionDefine();
  29245. var userDimName = dimDefItem.name;
  29246. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  29247. // Only if `series.dimensions` is defined in option
  29248. // displayName, will be set, and dimension will be displayed vertically in
  29249. // tooltip by default.
  29250. resultItem.name = resultItem.displayName = userDimName;
  29251. }
  29252. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  29253. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  29254. var newIdx = resultList.length;
  29255. indicesMap[dimIdx] = newIdx;
  29256. resultItem.storeDimIndex = dimIdx;
  29257. resultList.push(resultItem);
  29258. return resultItem;
  29259. }
  29260. return resultList[idx];
  29261. }
  29262. if (!omitUnusedDimensions) {
  29263. for (var i = 0; i < dimCount; i++) {
  29264. getResultItem(i);
  29265. }
  29266. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  29267. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  29268. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  29269. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  29270. // this case.
  29271. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  29272. encodeDefMap.set(coordDim, false);
  29273. return;
  29274. }
  29275. var validDataDims = encodeDefMap.set(coordDim, []);
  29276. each(dataDims, function (resultDimIdxOrName, idx) {
  29277. // The input resultDimIdx can be dim name or index.
  29278. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  29279. if (resultDimIdx != null && resultDimIdx < dimCount) {
  29280. validDataDims[idx] = resultDimIdx;
  29281. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  29282. }
  29283. });
  29284. }); // Apply templates and default order from `sysDims`.
  29285. var availDimIdx = 0;
  29286. each(sysDims, function (sysDimItemRaw) {
  29287. var coordDim;
  29288. var sysDimItemDimsDef;
  29289. var sysDimItemOtherDims;
  29290. var sysDimItem;
  29291. if (isString(sysDimItemRaw)) {
  29292. coordDim = sysDimItemRaw;
  29293. sysDimItem = {};
  29294. } else {
  29295. sysDimItem = sysDimItemRaw;
  29296. coordDim = sysDimItem.name;
  29297. var ordinalMeta = sysDimItem.ordinalMeta;
  29298. sysDimItem.ordinalMeta = null;
  29299. sysDimItem = extend({}, sysDimItem);
  29300. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  29301. sysDimItemDimsDef = sysDimItem.dimsDef;
  29302. sysDimItemOtherDims = sysDimItem.otherDims;
  29303. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  29304. }
  29305. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  29306. if (dataDims === false) {
  29307. return;
  29308. }
  29309. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  29310. if (!dataDims.length) {
  29311. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  29312. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  29313. availDimIdx++;
  29314. }
  29315. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  29316. }
  29317. } // Apply templates.
  29318. each(dataDims, function (resultDimIdx, coordDimIndex) {
  29319. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  29320. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  29321. resultItem.type = sysDimItem.type;
  29322. }
  29323. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  29324. if (resultItem.name == null && sysDimItemDimsDef) {
  29325. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  29326. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  29327. name: sysDimItemDimsDefItem
  29328. });
  29329. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  29330. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  29331. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  29332. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  29333. });
  29334. });
  29335. function applyDim(resultItem, coordDim, coordDimIndex) {
  29336. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  29337. resultItem.otherDims[coordDim] = coordDimIndex;
  29338. } else {
  29339. resultItem.coordDim = coordDim;
  29340. resultItem.coordDimIndex = coordDimIndex;
  29341. coordDimNameMap.set(coordDim, true);
  29342. }
  29343. } // Make sure the first extra dim is 'value'.
  29344. var generateCoord = opt.generateCoord;
  29345. var generateCoordCount = opt.generateCoordCount;
  29346. var fromZero = generateCoordCount != null;
  29347. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29348. var extra = generateCoord || 'value';
  29349. function ifNoNameFillWithCoordName(resultItem) {
  29350. if (resultItem.name == null) {
  29351. // Duplication will be removed in the next step.
  29352. resultItem.name = resultItem.coordDim;
  29353. }
  29354. } // Set dim `name` and other `coordDim` and other props.
  29355. if (!omitUnusedDimensions) {
  29356. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29357. var resultItem = getResultItem(resultDimIdx);
  29358. var coordDim = resultItem.coordDim;
  29359. if (coordDim == null) {
  29360. // TODO no need to generate coordDim for isExtraCoord?
  29361. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  29362. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  29363. if (!generateCoord || generateCoordCount <= 0) {
  29364. resultItem.isExtraCoord = true;
  29365. }
  29366. generateCoordCount--;
  29367. }
  29368. ifNoNameFillWithCoordName(resultItem);
  29369. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  29370. // {
  29371. // dataset: {source: [
  29372. // ['2001', 123],
  29373. // ['2002', 456],
  29374. // ...
  29375. // ['The others', 987],
  29376. // ]},
  29377. // series: {type: 'pie'}
  29378. // }
  29379. // The first column should better be treated as a "ordinal" although it
  29380. // might not be detected as an "ordinal" by `guessOrdinal`.
  29381. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29382. resultItem.type = 'ordinal';
  29383. }
  29384. }
  29385. } else {
  29386. each(resultList, function (resultItem) {
  29387. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  29388. ifNoNameFillWithCoordName(resultItem);
  29389. }); // Sort dimensions: there are some rule that use the last dim as label,
  29390. // and for some latter travel process easier.
  29391. resultList.sort(function (item0, item1) {
  29392. return item0.storeDimIndex - item1.storeDimIndex;
  29393. });
  29394. }
  29395. removeDuplication(resultList);
  29396. return new SeriesDataSchema({
  29397. source: source,
  29398. dimensions: resultList,
  29399. fullDimensionCount: dimCount,
  29400. dimensionOmitted: omitUnusedDimensions
  29401. });
  29402. }
  29403. function removeDuplication(result) {
  29404. var duplicationMap = createHashMap();
  29405. for (var i = 0; i < result.length; i++) {
  29406. var dim = result[i];
  29407. var dimOriginalName = dim.name;
  29408. var count = duplicationMap.get(dimOriginalName) || 0;
  29409. if (count > 0) {
  29410. // Starts from 0.
  29411. dim.name = dimOriginalName + (count - 1);
  29412. }
  29413. count++;
  29414. duplicationMap.set(dimOriginalName, count);
  29415. }
  29416. } // ??? TODO
  29417. // Originally detect dimCount by data[0]. Should we
  29418. // optimize it to only by sysDims and dimensions and encode.
  29419. // So only necessary dims will be initialized.
  29420. // But
  29421. // (1) custom series should be considered. where other dims
  29422. // may be visited.
  29423. // (2) sometimes user need to calculate bubble size or use visualMap
  29424. // on other dimensions besides coordSys needed.
  29425. // So, dims that is not used by system, should be shared in data store?
  29426. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29427. // Note that the result dimCount should not small than columns count
  29428. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29429. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29430. each(sysDims, function (sysDimItem) {
  29431. var sysDimItemDimsDef;
  29432. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29433. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29434. }
  29435. });
  29436. return dimCount;
  29437. }
  29438. function genCoordDimName(name, map, fromZero) {
  29439. if (fromZero || map.hasKey(name)) {
  29440. var i = 0;
  29441. while (map.hasKey(name + i)) {
  29442. i++;
  29443. }
  29444. name += i;
  29445. }
  29446. map.set(name, true);
  29447. return name;
  29448. }
  29449. /**
  29450. * @class
  29451. * For example:
  29452. * {
  29453. * coordSysName: 'cartesian2d',
  29454. * coordSysDims: ['x', 'y', ...],
  29455. * axisMap: HashMap({
  29456. * x: xAxisModel,
  29457. * y: yAxisModel
  29458. * }),
  29459. * categoryAxisMap: HashMap({
  29460. * x: xAxisModel,
  29461. * y: undefined
  29462. * }),
  29463. * // The index of the first category axis in `coordSysDims`.
  29464. * // `null/undefined` means no category axis exists.
  29465. * firstCategoryDimIndex: 1,
  29466. * // To replace user specified encode.
  29467. * }
  29468. */
  29469. var CoordSysInfo =
  29470. /** @class */
  29471. function () {
  29472. function CoordSysInfo(coordSysName) {
  29473. this.coordSysDims = [];
  29474. this.axisMap = createHashMap();
  29475. this.categoryAxisMap = createHashMap();
  29476. this.coordSysName = coordSysName;
  29477. }
  29478. return CoordSysInfo;
  29479. }();
  29480. function getCoordSysInfoBySeries(seriesModel) {
  29481. var coordSysName = seriesModel.get('coordinateSystem');
  29482. var result = new CoordSysInfo(coordSysName);
  29483. var fetch = fetchers[coordSysName];
  29484. if (fetch) {
  29485. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29486. return result;
  29487. }
  29488. }
  29489. var fetchers = {
  29490. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29491. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29492. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29493. if ("development" !== 'production') {
  29494. if (!xAxisModel) {
  29495. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29496. }
  29497. if (!yAxisModel) {
  29498. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29499. }
  29500. }
  29501. result.coordSysDims = ['x', 'y'];
  29502. axisMap.set('x', xAxisModel);
  29503. axisMap.set('y', yAxisModel);
  29504. if (isCategory(xAxisModel)) {
  29505. categoryAxisMap.set('x', xAxisModel);
  29506. result.firstCategoryDimIndex = 0;
  29507. }
  29508. if (isCategory(yAxisModel)) {
  29509. categoryAxisMap.set('y', yAxisModel);
  29510. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29511. }
  29512. },
  29513. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29514. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29515. if ("development" !== 'production') {
  29516. if (!singleAxisModel) {
  29517. throw new Error('singleAxis should be specified.');
  29518. }
  29519. }
  29520. result.coordSysDims = ['single'];
  29521. axisMap.set('single', singleAxisModel);
  29522. if (isCategory(singleAxisModel)) {
  29523. categoryAxisMap.set('single', singleAxisModel);
  29524. result.firstCategoryDimIndex = 0;
  29525. }
  29526. },
  29527. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29528. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29529. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29530. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29531. if ("development" !== 'production') {
  29532. if (!angleAxisModel) {
  29533. throw new Error('angleAxis option not found');
  29534. }
  29535. if (!radiusAxisModel) {
  29536. throw new Error('radiusAxis option not found');
  29537. }
  29538. }
  29539. result.coordSysDims = ['radius', 'angle'];
  29540. axisMap.set('radius', radiusAxisModel);
  29541. axisMap.set('angle', angleAxisModel);
  29542. if (isCategory(radiusAxisModel)) {
  29543. categoryAxisMap.set('radius', radiusAxisModel);
  29544. result.firstCategoryDimIndex = 0;
  29545. }
  29546. if (isCategory(angleAxisModel)) {
  29547. categoryAxisMap.set('angle', angleAxisModel);
  29548. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29549. }
  29550. },
  29551. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29552. result.coordSysDims = ['lng', 'lat'];
  29553. },
  29554. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29555. var ecModel = seriesModel.ecModel;
  29556. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29557. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29558. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29559. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29560. var axisDim = coordSysDims[index];
  29561. axisMap.set(axisDim, axisModel);
  29562. if (isCategory(axisModel)) {
  29563. categoryAxisMap.set(axisDim, axisModel);
  29564. if (result.firstCategoryDimIndex == null) {
  29565. result.firstCategoryDimIndex = index;
  29566. }
  29567. }
  29568. });
  29569. }
  29570. };
  29571. function isCategory(axisModel) {
  29572. return axisModel.get('type') === 'category';
  29573. }
  29574. /**
  29575. * Note that it is too complicated to support 3d stack by value
  29576. * (have to create two-dimension inverted index), so in 3d case
  29577. * we just support that stacked by index.
  29578. *
  29579. * @param seriesModel
  29580. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  29581. * The input will be modified.
  29582. * @param opt
  29583. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29584. * @param opt.byIndex=false
  29585. * @return calculationInfo
  29586. * {
  29587. * stackedDimension: string
  29588. * stackedByDimension: string
  29589. * isStackedByIndex: boolean
  29590. * stackedOverDimension: string
  29591. * stackResultDimension: string
  29592. * }
  29593. */
  29594. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29595. opt = opt || {};
  29596. var byIndex = opt.byIndex;
  29597. var stackedCoordDimension = opt.stackedCoordDimension;
  29598. var dimensionDefineList;
  29599. var schema;
  29600. var store;
  29601. if (isLegacyDimensionsInput(dimensionsInput)) {
  29602. dimensionDefineList = dimensionsInput;
  29603. } else {
  29604. schema = dimensionsInput.schema;
  29605. dimensionDefineList = schema.dimensions;
  29606. store = dimensionsInput.store;
  29607. } // Compatibal: when `stack` is set as '', do not stack.
  29608. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29609. var stackedByDimInfo;
  29610. var stackedDimInfo;
  29611. var stackResultDimension;
  29612. var stackedOverDimension;
  29613. each(dimensionDefineList, function (dimensionInfo, index) {
  29614. if (isString(dimensionInfo)) {
  29615. dimensionDefineList[index] = dimensionInfo = {
  29616. name: dimensionInfo
  29617. };
  29618. }
  29619. if (mayStack && !dimensionInfo.isExtraCoord) {
  29620. // Find the first ordinal dimension as the stackedByDimInfo.
  29621. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29622. stackedByDimInfo = dimensionInfo;
  29623. } // Find the first stackable dimension as the stackedDimInfo.
  29624. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29625. stackedDimInfo = dimensionInfo;
  29626. }
  29627. }
  29628. });
  29629. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29630. // Compatible with previous design, value axis (time axis) only stack by index.
  29631. // It may make sense if the user provides elaborately constructed data.
  29632. byIndex = true;
  29633. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29634. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29635. // might not be a good way.
  29636. if (stackedDimInfo) {
  29637. // Use a weird name that not duplicated with other names.
  29638. // Also need to use seriesModel.id as postfix because different
  29639. // series may share same data store. The stack dimension needs to be distinguished.
  29640. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29641. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  29642. if (stackedByDimInfo) {
  29643. stackedByDimInfo.createInvertedIndices = true;
  29644. }
  29645. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29646. var stackedDimType = stackedDimInfo.type;
  29647. var stackedDimCoordIndex_1 = 0;
  29648. each(dimensionDefineList, function (dimensionInfo) {
  29649. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29650. stackedDimCoordIndex_1++;
  29651. }
  29652. });
  29653. var stackedOverDimensionDefine = {
  29654. name: stackResultDimension,
  29655. coordDim: stackedDimCoordDim_1,
  29656. coordDimIndex: stackedDimCoordIndex_1,
  29657. type: stackedDimType,
  29658. isExtraCoord: true,
  29659. isCalculationCoord: true,
  29660. storeDimIndex: dimensionDefineList.length
  29661. };
  29662. var stackResultDimensionDefine = {
  29663. name: stackedOverDimension,
  29664. // This dimension contains stack base (generally, 0), so do not set it as
  29665. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29666. coordDim: stackedOverDimension,
  29667. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29668. type: stackedDimType,
  29669. isExtraCoord: true,
  29670. isCalculationCoord: true,
  29671. storeDimIndex: dimensionDefineList.length + 1
  29672. };
  29673. if (schema) {
  29674. if (store) {
  29675. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29676. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29677. }
  29678. schema.appendCalculationDimension(stackedOverDimensionDefine);
  29679. schema.appendCalculationDimension(stackResultDimensionDefine);
  29680. } else {
  29681. dimensionDefineList.push(stackedOverDimensionDefine);
  29682. dimensionDefineList.push(stackResultDimensionDefine);
  29683. }
  29684. }
  29685. return {
  29686. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29687. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29688. isStackedByIndex: byIndex,
  29689. stackedOverDimension: stackedOverDimension,
  29690. stackResultDimension: stackResultDimension
  29691. };
  29692. }
  29693. function isLegacyDimensionsInput(dimensionsInput) {
  29694. return !isSeriesDataSchema(dimensionsInput.schema);
  29695. }
  29696. function isDimensionStacked(data, stackedDim) {
  29697. // Each single series only maps to one pair of axis. So we do not need to
  29698. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29699. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29700. }
  29701. function getStackedDimension(data, targetDim) {
  29702. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29703. }
  29704. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  29705. var coordSysName = seriesModel.get('coordinateSystem');
  29706. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29707. var coordSysDimDefs;
  29708. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29709. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29710. var dimInfo = {
  29711. name: dim
  29712. };
  29713. var axisModel = coordSysInfo.axisMap.get(dim);
  29714. if (axisModel) {
  29715. var axisType = axisModel.get('type');
  29716. dimInfo.type = getDimensionTypeByAxis(axisType);
  29717. }
  29718. return dimInfo;
  29719. });
  29720. }
  29721. if (!coordSysDimDefs) {
  29722. // Get dimensions from registered coordinate system
  29723. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29724. }
  29725. return coordSysDimDefs;
  29726. }
  29727. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  29728. var firstCategoryDimIndex;
  29729. var hasNameEncode;
  29730. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29731. var coordDim = dimInfo.coordDim;
  29732. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29733. if (categoryAxisModel) {
  29734. if (firstCategoryDimIndex == null) {
  29735. firstCategoryDimIndex = dimIndex;
  29736. }
  29737. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29738. if (createInvertedIndices) {
  29739. dimInfo.createInvertedIndices = true;
  29740. }
  29741. }
  29742. if (dimInfo.otherDims.itemName != null) {
  29743. hasNameEncode = true;
  29744. }
  29745. });
  29746. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29747. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29748. }
  29749. return firstCategoryDimIndex;
  29750. }
  29751. /**
  29752. * Caution: there are side effects to `sourceManager` in this method.
  29753. * Should better only be called in `Series['getInitialData']`.
  29754. */
  29755. function createSeriesData(sourceRaw, seriesModel, opt) {
  29756. opt = opt || {};
  29757. var sourceManager = seriesModel.getSourceManager();
  29758. var source;
  29759. var isOriginalSource = false;
  29760. if (sourceRaw) {
  29761. isOriginalSource = true;
  29762. source = createSourceFromSeriesDataOption(sourceRaw);
  29763. } else {
  29764. source = sourceManager.getSource(); // Is series.data. not dataset.
  29765. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29766. }
  29767. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29768. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  29769. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29770. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  29771. var createDimensionOptions = {
  29772. coordDimensions: coordSysDimDefs,
  29773. generateCoord: opt.generateCoord,
  29774. encodeDefine: seriesModel.getEncode(),
  29775. encodeDefaulter: encodeDefaulter,
  29776. canOmitUnusedDimensions: !isOriginalSource
  29777. };
  29778. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  29779. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  29780. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  29781. var stackCalculationInfo = enableDataStack(seriesModel, {
  29782. schema: schema,
  29783. store: store
  29784. });
  29785. var data = new SeriesData(schema, seriesModel);
  29786. data.setCalculationInfo(stackCalculationInfo);
  29787. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29788. // Use dataIndex as ordinal value in categoryAxis
  29789. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29790. } : null;
  29791. data.hasItemOption = false;
  29792. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  29793. isOriginalSource ? source : store, null, dimValueGetter);
  29794. return data;
  29795. }
  29796. function isNeedCompleteOrdinalData(source) {
  29797. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29798. var sampleItem = firstDataNotNull(source.data || []);
  29799. return !isArray(getDataItemValue(sampleItem));
  29800. }
  29801. }
  29802. function firstDataNotNull(arr) {
  29803. var i = 0;
  29804. while (i < arr.length && arr[i] == null) {
  29805. i++;
  29806. }
  29807. return arr[i];
  29808. }
  29809. var Scale =
  29810. /** @class */
  29811. function () {
  29812. function Scale(setting) {
  29813. this._setting = setting || {};
  29814. this._extent = [Infinity, -Infinity];
  29815. }
  29816. Scale.prototype.getSetting = function (name) {
  29817. return this._setting[name];
  29818. };
  29819. /**
  29820. * Set extent from data
  29821. */
  29822. Scale.prototype.unionExtent = function (other) {
  29823. var extent = this._extent;
  29824. other[0] < extent[0] && (extent[0] = other[0]);
  29825. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29826. // this.setExtent(extent[0], extent[1]);
  29827. };
  29828. /**
  29829. * Set extent from data
  29830. */
  29831. Scale.prototype.unionExtentFromData = function (data, dim) {
  29832. this.unionExtent(data.getApproximateExtent(dim));
  29833. };
  29834. /**
  29835. * Get extent
  29836. *
  29837. * Extent is always in increase order.
  29838. */
  29839. Scale.prototype.getExtent = function () {
  29840. return this._extent.slice();
  29841. };
  29842. /**
  29843. * Set extent
  29844. */
  29845. Scale.prototype.setExtent = function (start, end) {
  29846. var thisExtent = this._extent;
  29847. if (!isNaN(start)) {
  29848. thisExtent[0] = start;
  29849. }
  29850. if (!isNaN(end)) {
  29851. thisExtent[1] = end;
  29852. }
  29853. };
  29854. /**
  29855. * If value is in extent range
  29856. */
  29857. Scale.prototype.isInExtentRange = function (value) {
  29858. return this._extent[0] <= value && this._extent[1] >= value;
  29859. };
  29860. /**
  29861. * When axis extent depends on data and no data exists,
  29862. * axis ticks should not be drawn, which is named 'blank'.
  29863. */
  29864. Scale.prototype.isBlank = function () {
  29865. return this._isBlank;
  29866. };
  29867. /**
  29868. * When axis extent depends on data and no data exists,
  29869. * axis ticks should not be drawn, which is named 'blank'.
  29870. */
  29871. Scale.prototype.setBlank = function (isBlank) {
  29872. this._isBlank = isBlank;
  29873. };
  29874. return Scale;
  29875. }();
  29876. enableClassManagement(Scale);
  29877. var uidBase = 0;
  29878. var OrdinalMeta =
  29879. /** @class */
  29880. function () {
  29881. function OrdinalMeta(opt) {
  29882. this.categories = opt.categories || [];
  29883. this._needCollect = opt.needCollect;
  29884. this._deduplication = opt.deduplication;
  29885. this.uid = ++uidBase;
  29886. }
  29887. OrdinalMeta.createByAxisModel = function (axisModel) {
  29888. var option = axisModel.option;
  29889. var data = option.data;
  29890. var categories = data && map(data, getName);
  29891. return new OrdinalMeta({
  29892. categories: categories,
  29893. needCollect: !categories,
  29894. // deduplication is default in axis.
  29895. deduplication: option.dedplication !== false
  29896. });
  29897. };
  29898. OrdinalMeta.prototype.getOrdinal = function (category) {
  29899. // @ts-ignore
  29900. return this._getOrCreateMap().get(category);
  29901. };
  29902. /**
  29903. * @return The ordinal. If not found, return NaN.
  29904. */
  29905. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29906. var index;
  29907. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29908. // This feature is only supported when !needCollect, because we should
  29909. // consider a common case: a value is 2017, which is a number but is
  29910. // expected to be tread as a category. This case usually happen in dataset,
  29911. // where it happent to be no need of the index feature.
  29912. if (!isString(category) && !needCollect) {
  29913. return category;
  29914. } // Optimize for the scenario:
  29915. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29916. // data has been ensured not duplicate and is large data.
  29917. // Notice, if a dataset dimension provide categroies, usually echarts
  29918. // should remove duplication except user tell echarts dont do that
  29919. // (set axis.deduplication = false), because echarts do not know whether
  29920. // the values in the category dimension has duplication (consider the
  29921. // parallel-aqi example)
  29922. if (needCollect && !this._deduplication) {
  29923. index = this.categories.length;
  29924. this.categories[index] = category;
  29925. return index;
  29926. }
  29927. var map = this._getOrCreateMap(); // @ts-ignore
  29928. index = map.get(category);
  29929. if (index == null) {
  29930. if (needCollect) {
  29931. index = this.categories.length;
  29932. this.categories[index] = category; // @ts-ignore
  29933. map.set(category, index);
  29934. } else {
  29935. index = NaN;
  29936. }
  29937. }
  29938. return index;
  29939. }; // Consider big data, do not create map until needed.
  29940. OrdinalMeta.prototype._getOrCreateMap = function () {
  29941. return this._map || (this._map = createHashMap(this.categories));
  29942. };
  29943. return OrdinalMeta;
  29944. }();
  29945. function getName(obj) {
  29946. if (isObject(obj) && obj.value != null) {
  29947. return obj.value;
  29948. } else {
  29949. return obj + '';
  29950. }
  29951. }
  29952. function isValueNice(val) {
  29953. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  29954. var f = Math.abs(val / exp10);
  29955. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  29956. }
  29957. function isIntervalOrLogScale(scale) {
  29958. return scale.type === 'interval' || scale.type === 'log';
  29959. }
  29960. /**
  29961. * @param extent Both extent[0] and extent[1] should be valid number.
  29962. * Should be extent[0] < extent[1].
  29963. * @param splitNumber splitNumber should be >= 1.
  29964. */
  29965. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29966. var result = {};
  29967. var span = extent[1] - extent[0];
  29968. var interval = result.interval = nice(span / splitNumber, true);
  29969. if (minInterval != null && interval < minInterval) {
  29970. interval = result.interval = minInterval;
  29971. }
  29972. if (maxInterval != null && interval > maxInterval) {
  29973. interval = result.interval = maxInterval;
  29974. } // Tow more digital for tick.
  29975. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29976. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  29977. fixExtent(niceTickExtent, extent);
  29978. return result;
  29979. }
  29980. function increaseInterval(interval) {
  29981. var exp10 = Math.pow(10, quantityExponent(interval)); // Increase interval
  29982. var f = interval / exp10;
  29983. if (!f) {
  29984. f = 1;
  29985. } else if (f === 2) {
  29986. f = 3;
  29987. } else if (f === 3) {
  29988. f = 5;
  29989. } else {
  29990. // f is 1 or 5
  29991. f *= 2;
  29992. }
  29993. return round(f * exp10);
  29994. }
  29995. /**
  29996. * @return interval precision
  29997. */
  29998. function getIntervalPrecision(interval) {
  29999. // Tow more digital for tick.
  30000. return getPrecision(interval) + 2;
  30001. }
  30002. function clamp(niceTickExtent, idx, extent) {
  30003. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30004. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30005. function fixExtent(niceTickExtent, extent) {
  30006. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30007. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30008. clamp(niceTickExtent, 0, extent);
  30009. clamp(niceTickExtent, 1, extent);
  30010. if (niceTickExtent[0] > niceTickExtent[1]) {
  30011. niceTickExtent[0] = niceTickExtent[1];
  30012. }
  30013. }
  30014. function contain$1(val, extent) {
  30015. return val >= extent[0] && val <= extent[1];
  30016. }
  30017. function normalize$1(val, extent) {
  30018. if (extent[1] === extent[0]) {
  30019. return 0.5;
  30020. }
  30021. return (val - extent[0]) / (extent[1] - extent[0]);
  30022. }
  30023. function scale$2(val, extent) {
  30024. return val * (extent[1] - extent[0]) + extent[0];
  30025. }
  30026. var OrdinalScale =
  30027. /** @class */
  30028. function (_super) {
  30029. __extends(OrdinalScale, _super);
  30030. function OrdinalScale(setting) {
  30031. var _this = _super.call(this, setting) || this;
  30032. _this.type = 'ordinal';
  30033. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  30034. // import approach to get OrdinalMeta class.
  30035. if (!ordinalMeta) {
  30036. ordinalMeta = new OrdinalMeta({});
  30037. }
  30038. if (isArray(ordinalMeta)) {
  30039. ordinalMeta = new OrdinalMeta({
  30040. categories: map(ordinalMeta, function (item) {
  30041. return isObject(item) ? item.value : item;
  30042. })
  30043. });
  30044. }
  30045. _this._ordinalMeta = ordinalMeta;
  30046. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  30047. return _this;
  30048. }
  30049. OrdinalScale.prototype.parse = function (val) {
  30050. // Caution: Math.round(null) will return `0` rather than `NaN`
  30051. if (val == null) {
  30052. return NaN;
  30053. }
  30054. return isString(val) ? this._ordinalMeta.getOrdinal(val) // val might be float.
  30055. : Math.round(val);
  30056. };
  30057. OrdinalScale.prototype.contain = function (rank) {
  30058. rank = this.parse(rank);
  30059. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  30060. };
  30061. /**
  30062. * Normalize given rank or name to linear [0, 1]
  30063. * @param val raw ordinal number.
  30064. * @return normalized value in [0, 1].
  30065. */
  30066. OrdinalScale.prototype.normalize = function (val) {
  30067. val = this._getTickNumber(this.parse(val));
  30068. return normalize$1(val, this._extent);
  30069. };
  30070. /**
  30071. * @param val normalized value in [0, 1].
  30072. * @return raw ordinal number.
  30073. */
  30074. OrdinalScale.prototype.scale = function (val) {
  30075. val = Math.round(scale$2(val, this._extent));
  30076. return this.getRawOrdinalNumber(val);
  30077. };
  30078. OrdinalScale.prototype.getTicks = function () {
  30079. var ticks = [];
  30080. var extent = this._extent;
  30081. var rank = extent[0];
  30082. while (rank <= extent[1]) {
  30083. ticks.push({
  30084. value: rank
  30085. });
  30086. rank++;
  30087. }
  30088. return ticks;
  30089. };
  30090. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  30091. // Not support.
  30092. return;
  30093. };
  30094. /**
  30095. * @see `Ordinal['_ordinalNumbersByTick']`
  30096. */
  30097. OrdinalScale.prototype.setSortInfo = function (info) {
  30098. if (info == null) {
  30099. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  30100. return;
  30101. }
  30102. var infoOrdinalNumbers = info.ordinalNumbers;
  30103. var ordinalsByTick = this._ordinalNumbersByTick = [];
  30104. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  30105. var tickNum = 0;
  30106. var allCategoryLen = this._ordinalMeta.categories.length;
  30107. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  30108. var ordinalNumber = infoOrdinalNumbers[tickNum];
  30109. ordinalsByTick[tickNum] = ordinalNumber;
  30110. ticksByOrdinal[ordinalNumber] = tickNum;
  30111. } // Handle that `series.data` only covers part of the `axis.category.data`.
  30112. var unusedOrdinal = 0;
  30113. for (; tickNum < allCategoryLen; ++tickNum) {
  30114. while (ticksByOrdinal[unusedOrdinal] != null) {
  30115. unusedOrdinal++;
  30116. }
  30117. ordinalsByTick.push(unusedOrdinal);
  30118. ticksByOrdinal[unusedOrdinal] = tickNum;
  30119. }
  30120. };
  30121. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  30122. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  30123. // where ordinal numbers are used as tick value directly.
  30124. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  30125. };
  30126. /**
  30127. * @usage
  30128. * ```js
  30129. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  30130. *
  30131. * // case0
  30132. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  30133. * // case1
  30134. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  30135. * // case2
  30136. * const coord = axis.dataToCoord(ordinalNumber);
  30137. * ```
  30138. *
  30139. * @param {OrdinalNumber} tickNumber index of display
  30140. */
  30141. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  30142. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  30143. // where ordinal numbers are used as tick value directly.
  30144. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  30145. };
  30146. /**
  30147. * Get item on tick
  30148. */
  30149. OrdinalScale.prototype.getLabel = function (tick) {
  30150. if (!this.isBlank()) {
  30151. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  30152. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  30153. // Return empty if it's not exist.
  30154. return cateogry == null ? '' : cateogry + '';
  30155. }
  30156. };
  30157. OrdinalScale.prototype.count = function () {
  30158. return this._extent[1] - this._extent[0] + 1;
  30159. };
  30160. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  30161. this.unionExtent(data.getApproximateExtent(dim));
  30162. };
  30163. /**
  30164. * @override
  30165. * If value is in extent range
  30166. */
  30167. OrdinalScale.prototype.isInExtentRange = function (value) {
  30168. value = this._getTickNumber(value);
  30169. return this._extent[0] <= value && this._extent[1] >= value;
  30170. };
  30171. OrdinalScale.prototype.getOrdinalMeta = function () {
  30172. return this._ordinalMeta;
  30173. };
  30174. OrdinalScale.prototype.calcNiceTicks = function () {};
  30175. OrdinalScale.prototype.calcNiceExtent = function () {};
  30176. OrdinalScale.type = 'ordinal';
  30177. return OrdinalScale;
  30178. }(Scale);
  30179. Scale.registerClass(OrdinalScale);
  30180. var roundNumber = round;
  30181. var IntervalScale =
  30182. /** @class */
  30183. function (_super) {
  30184. __extends(IntervalScale, _super);
  30185. function IntervalScale() {
  30186. var _this = _super !== null && _super.apply(this, arguments) || this;
  30187. _this.type = 'interval'; // Step is calculated in adjustExtent.
  30188. _this._interval = 0;
  30189. _this._intervalPrecision = 2;
  30190. return _this;
  30191. }
  30192. IntervalScale.prototype.parse = function (val) {
  30193. return val;
  30194. };
  30195. IntervalScale.prototype.contain = function (val) {
  30196. return contain$1(val, this._extent);
  30197. };
  30198. IntervalScale.prototype.normalize = function (val) {
  30199. return normalize$1(val, this._extent);
  30200. };
  30201. IntervalScale.prototype.scale = function (val) {
  30202. return scale$2(val, this._extent);
  30203. };
  30204. IntervalScale.prototype.setExtent = function (start, end) {
  30205. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  30206. if (!isNaN(start)) {
  30207. thisExtent[0] = parseFloat(start);
  30208. }
  30209. if (!isNaN(end)) {
  30210. thisExtent[1] = parseFloat(end);
  30211. }
  30212. };
  30213. IntervalScale.prototype.unionExtent = function (other) {
  30214. var extent = this._extent;
  30215. other[0] < extent[0] && (extent[0] = other[0]);
  30216. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  30217. this.setExtent(extent[0], extent[1]);
  30218. };
  30219. IntervalScale.prototype.getInterval = function () {
  30220. return this._interval;
  30221. };
  30222. IntervalScale.prototype.setInterval = function (interval) {
  30223. this._interval = interval; // Dropped auto calculated niceExtent and use user-set extent.
  30224. // We assume user wants to set both interval, min, max to get a better result.
  30225. this._niceExtent = this._extent.slice();
  30226. this._intervalPrecision = getIntervalPrecision(interval);
  30227. };
  30228. /**
  30229. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30230. */
  30231. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  30232. var interval = this._interval;
  30233. var extent = this._extent;
  30234. var niceTickExtent = this._niceExtent;
  30235. var intervalPrecision = this._intervalPrecision;
  30236. var ticks = []; // If interval is 0, return [];
  30237. if (!interval) {
  30238. return ticks;
  30239. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  30240. var safeLimit = 10000;
  30241. if (extent[0] < niceTickExtent[0]) {
  30242. if (expandToNicedExtent) {
  30243. ticks.push({
  30244. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  30245. });
  30246. } else {
  30247. ticks.push({
  30248. value: extent[0]
  30249. });
  30250. }
  30251. }
  30252. var tick = niceTickExtent[0];
  30253. while (tick <= niceTickExtent[1]) {
  30254. ticks.push({
  30255. value: tick
  30256. }); // Avoid rounding error
  30257. tick = roundNumber(tick + interval, intervalPrecision);
  30258. if (tick === ticks[ticks.length - 1].value) {
  30259. // Consider out of safe float point, e.g.,
  30260. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30261. break;
  30262. }
  30263. if (ticks.length > safeLimit) {
  30264. return [];
  30265. }
  30266. } // Consider this case: the last item of ticks is smaller
  30267. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30268. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  30269. if (extent[1] > lastNiceTick) {
  30270. if (expandToNicedExtent) {
  30271. ticks.push({
  30272. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  30273. });
  30274. } else {
  30275. ticks.push({
  30276. value: extent[1]
  30277. });
  30278. }
  30279. }
  30280. return ticks;
  30281. };
  30282. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  30283. var ticks = this.getTicks(true);
  30284. var minorTicks = [];
  30285. var extent = this.getExtent();
  30286. for (var i = 1; i < ticks.length; i++) {
  30287. var nextTick = ticks[i];
  30288. var prevTick = ticks[i - 1];
  30289. var count = 0;
  30290. var minorTicksGroup = [];
  30291. var interval = nextTick.value - prevTick.value;
  30292. var minorInterval = interval / splitNumber;
  30293. while (count < splitNumber - 1) {
  30294. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  30295. if (minorTick > extent[0] && minorTick < extent[1]) {
  30296. minorTicksGroup.push(minorTick);
  30297. }
  30298. count++;
  30299. }
  30300. minorTicks.push(minorTicksGroup);
  30301. }
  30302. return minorTicks;
  30303. };
  30304. /**
  30305. * @param opt.precision If 'auto', use nice presision.
  30306. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  30307. */
  30308. IntervalScale.prototype.getLabel = function (data, opt) {
  30309. if (data == null) {
  30310. return '';
  30311. }
  30312. var precision = opt && opt.precision;
  30313. if (precision == null) {
  30314. precision = getPrecision(data.value) || 0;
  30315. } else if (precision === 'auto') {
  30316. // Should be more precise then tick.
  30317. precision = this._intervalPrecision;
  30318. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30319. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30320. var dataNum = roundNumber(data.value, precision, true);
  30321. return addCommas(dataNum);
  30322. };
  30323. /**
  30324. * @param splitNumber By default `5`.
  30325. */
  30326. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  30327. splitNumber = splitNumber || 5;
  30328. var extent = this._extent;
  30329. var span = extent[1] - extent[0];
  30330. if (!isFinite(span)) {
  30331. return;
  30332. } // User may set axis min 0 and data are all negative
  30333. // FIXME If it needs to reverse ?
  30334. if (span < 0) {
  30335. span = -span;
  30336. extent.reverse();
  30337. }
  30338. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  30339. this._intervalPrecision = result.intervalPrecision;
  30340. this._interval = result.interval;
  30341. this._niceExtent = result.niceTickExtent;
  30342. };
  30343. IntervalScale.prototype.calcNiceExtent = function (opt) {
  30344. var extent = this._extent; // If extent start and end are same, expand them
  30345. if (extent[0] === extent[1]) {
  30346. if (extent[0] !== 0) {
  30347. // Expand extent
  30348. // Note that extents can be both negative. See #13154
  30349. var expandSize = Math.abs(extent[0]); // In the fowllowing case
  30350. // Axis has been fixed max 100
  30351. // Plus data are all 100 and axis extent are [100, 100].
  30352. // Extend to the both side will cause expanded max is larger than fixed max.
  30353. // So only expand to the smaller side.
  30354. if (!opt.fixMax) {
  30355. extent[1] += expandSize / 2;
  30356. extent[0] -= expandSize / 2;
  30357. } else {
  30358. extent[0] -= expandSize / 2;
  30359. }
  30360. } else {
  30361. extent[1] = 1;
  30362. }
  30363. }
  30364. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  30365. if (!isFinite(span)) {
  30366. extent[0] = 0;
  30367. extent[1] = 1;
  30368. }
  30369. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  30370. var interval = this._interval;
  30371. if (!opt.fixMin) {
  30372. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30373. }
  30374. if (!opt.fixMax) {
  30375. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30376. }
  30377. };
  30378. IntervalScale.prototype.setNiceExtent = function (min, max) {
  30379. this._niceExtent = [min, max];
  30380. };
  30381. IntervalScale.type = 'interval';
  30382. return IntervalScale;
  30383. }(Scale);
  30384. Scale.registerClass(IntervalScale);
  30385. /* global Float32Array */
  30386. var supportFloat32Array = typeof Float32Array !== 'undefined';
  30387. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  30388. function createFloat32Array(arg) {
  30389. if (isArray(arg)) {
  30390. // Return self directly if don't support TypedArray.
  30391. return supportFloat32Array ? new Float32Array(arg) : arg;
  30392. } // Else is number
  30393. return new Float32ArrayCtor(arg);
  30394. }
  30395. var STACK_PREFIX = '__ec_stack_';
  30396. function getSeriesStackId(seriesModel) {
  30397. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30398. }
  30399. function getAxisKey(axis) {
  30400. return axis.dim + axis.index;
  30401. }
  30402. /**
  30403. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  30404. */
  30405. function getLayoutOnAxis(opt) {
  30406. var params = [];
  30407. var baseAxis = opt.axis;
  30408. var axisKey = 'axis0';
  30409. if (baseAxis.type !== 'category') {
  30410. return;
  30411. }
  30412. var bandWidth = baseAxis.getBandWidth();
  30413. for (var i = 0; i < opt.count || 0; i++) {
  30414. params.push(defaults({
  30415. bandWidth: bandWidth,
  30416. axisKey: axisKey,
  30417. stackId: STACK_PREFIX + i
  30418. }, opt));
  30419. }
  30420. var widthAndOffsets = doCalBarWidthAndOffset(params);
  30421. var result = [];
  30422. for (var i = 0; i < opt.count; i++) {
  30423. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  30424. item.offsetCenter = item.offset + item.width / 2;
  30425. result.push(item);
  30426. }
  30427. return result;
  30428. }
  30429. function prepareLayoutBarSeries(seriesType, ecModel) {
  30430. var seriesModels = [];
  30431. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30432. // Check series coordinate, do layout for cartesian2d only
  30433. if (isOnCartesian(seriesModel)) {
  30434. seriesModels.push(seriesModel);
  30435. }
  30436. });
  30437. return seriesModels;
  30438. }
  30439. /**
  30440. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30441. * values.
  30442. * This works for time axes, value axes, and log axes.
  30443. * For a single time axis, return value is in the form like
  30444. * {'x_0': [1000000]}.
  30445. * The value of 1000000 is in milliseconds.
  30446. */
  30447. function getValueAxesMinGaps(barSeries) {
  30448. /**
  30449. * Map from axis.index to values.
  30450. * For a single time axis, axisValues is in the form like
  30451. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30452. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30453. * series.
  30454. */
  30455. var axisValues = {};
  30456. each(barSeries, function (seriesModel) {
  30457. var cartesian = seriesModel.coordinateSystem;
  30458. var baseAxis = cartesian.getBaseAxis();
  30459. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30460. return;
  30461. }
  30462. var data = seriesModel.getData();
  30463. var key = baseAxis.dim + '_' + baseAxis.index;
  30464. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30465. var store = data.getStore();
  30466. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30467. var value = store.get(dimIdx, i);
  30468. if (!axisValues[key]) {
  30469. // No previous data for the axis
  30470. axisValues[key] = [value];
  30471. } else {
  30472. // No value in previous series
  30473. axisValues[key].push(value);
  30474. } // Ignore duplicated time values in the same axis
  30475. }
  30476. });
  30477. var axisMinGaps = {};
  30478. for (var key in axisValues) {
  30479. if (axisValues.hasOwnProperty(key)) {
  30480. var valuesInAxis = axisValues[key];
  30481. if (valuesInAxis) {
  30482. // Sort axis values into ascending order to calculate gaps
  30483. valuesInAxis.sort(function (a, b) {
  30484. return a - b;
  30485. });
  30486. var min = null;
  30487. for (var j = 1; j < valuesInAxis.length; ++j) {
  30488. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30489. if (delta > 0) {
  30490. // Ignore 0 delta because they are of the same axis value
  30491. min = min === null ? delta : Math.min(min, delta);
  30492. }
  30493. } // Set to null if only have one data
  30494. axisMinGaps[key] = min;
  30495. }
  30496. }
  30497. }
  30498. return axisMinGaps;
  30499. }
  30500. function makeColumnLayout(barSeries) {
  30501. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30502. var seriesInfoList = [];
  30503. each(barSeries, function (seriesModel) {
  30504. var cartesian = seriesModel.coordinateSystem;
  30505. var baseAxis = cartesian.getBaseAxis();
  30506. var axisExtent = baseAxis.getExtent();
  30507. var bandWidth;
  30508. if (baseAxis.type === 'category') {
  30509. bandWidth = baseAxis.getBandWidth();
  30510. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30511. var key = baseAxis.dim + '_' + baseAxis.index;
  30512. var minGap = axisMinGaps[key];
  30513. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30514. var scale = baseAxis.scale.getExtent();
  30515. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30516. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30517. } else {
  30518. var data = seriesModel.getData();
  30519. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30520. }
  30521. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30522. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30523. var barMinWidth = parsePercent$1( // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30524. // the auto-calculated bar width might be less than 0.5 / 1.
  30525. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30526. var barGap = seriesModel.get('barGap');
  30527. var barCategoryGap = seriesModel.get('barCategoryGap');
  30528. seriesInfoList.push({
  30529. bandWidth: bandWidth,
  30530. barWidth: barWidth,
  30531. barMaxWidth: barMaxWidth,
  30532. barMinWidth: barMinWidth,
  30533. barGap: barGap,
  30534. barCategoryGap: barCategoryGap,
  30535. axisKey: getAxisKey(baseAxis),
  30536. stackId: getSeriesStackId(seriesModel)
  30537. });
  30538. });
  30539. return doCalBarWidthAndOffset(seriesInfoList);
  30540. }
  30541. function doCalBarWidthAndOffset(seriesInfoList) {
  30542. // Columns info on each category axis. Key is cartesian name
  30543. var columnsMap = {};
  30544. each(seriesInfoList, function (seriesInfo, idx) {
  30545. var axisKey = seriesInfo.axisKey;
  30546. var bandWidth = seriesInfo.bandWidth;
  30547. var columnsOnAxis = columnsMap[axisKey] || {
  30548. bandWidth: bandWidth,
  30549. remainedWidth: bandWidth,
  30550. autoWidthCount: 0,
  30551. categoryGap: null,
  30552. gap: '20%',
  30553. stacks: {}
  30554. };
  30555. var stacks = columnsOnAxis.stacks;
  30556. columnsMap[axisKey] = columnsOnAxis;
  30557. var stackId = seriesInfo.stackId;
  30558. if (!stacks[stackId]) {
  30559. columnsOnAxis.autoWidthCount++;
  30560. }
  30561. stacks[stackId] = stacks[stackId] || {
  30562. width: 0,
  30563. maxWidth: 0
  30564. }; // Caution: In a single coordinate system, these barGrid attributes
  30565. // will be shared by series. Consider that they have default values,
  30566. // only the attributes set on the last series will work.
  30567. // Do not change this fact unless there will be a break change.
  30568. var barWidth = seriesInfo.barWidth;
  30569. if (barWidth && !stacks[stackId].width) {
  30570. // See #6312, do not restrict width.
  30571. stacks[stackId].width = barWidth;
  30572. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30573. columnsOnAxis.remainedWidth -= barWidth;
  30574. }
  30575. var barMaxWidth = seriesInfo.barMaxWidth;
  30576. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30577. var barMinWidth = seriesInfo.barMinWidth;
  30578. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30579. var barGap = seriesInfo.barGap;
  30580. barGap != null && (columnsOnAxis.gap = barGap);
  30581. var barCategoryGap = seriesInfo.barCategoryGap;
  30582. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30583. });
  30584. var result = {};
  30585. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30586. result[coordSysName] = {};
  30587. var stacks = columnsOnAxis.stacks;
  30588. var bandWidth = columnsOnAxis.bandWidth;
  30589. var categoryGapPercent = columnsOnAxis.categoryGap;
  30590. if (categoryGapPercent == null) {
  30591. var columnCount = keys(stacks).length; // More columns in one group
  30592. // the spaces between group is smaller. Or the column will be too thin.
  30593. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30594. }
  30595. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30596. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30597. var remainedWidth = columnsOnAxis.remainedWidth;
  30598. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30599. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30600. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  30601. each(stacks, function (column) {
  30602. var maxWidth = column.maxWidth;
  30603. var minWidth = column.minWidth;
  30604. if (!column.width) {
  30605. var finalWidth = autoWidth;
  30606. if (maxWidth && maxWidth < finalWidth) {
  30607. finalWidth = Math.min(maxWidth, remainedWidth);
  30608. } // `minWidth` has higher priority. `minWidth` decide that whether the
  30609. // bar is able to be visible. So `minWidth` should not be restricted
  30610. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30611. // the extreme cases for `value` axis, bars are allowed to overlap
  30612. // with each other if `minWidth` specified.
  30613. if (minWidth && minWidth > finalWidth) {
  30614. finalWidth = minWidth;
  30615. }
  30616. if (finalWidth !== autoWidth) {
  30617. column.width = finalWidth;
  30618. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30619. autoWidthCount--;
  30620. }
  30621. } else {
  30622. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30623. // CSS does. Because barWidth can be a percent value, where
  30624. // `barMaxWidth` can be used to restrict the final width.
  30625. var finalWidth = column.width;
  30626. if (maxWidth) {
  30627. finalWidth = Math.min(finalWidth, maxWidth);
  30628. } // `minWidth` has higher priority, as described above
  30629. if (minWidth) {
  30630. finalWidth = Math.max(finalWidth, minWidth);
  30631. }
  30632. column.width = finalWidth;
  30633. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30634. autoWidthCount--;
  30635. }
  30636. }); // Recalculate width again
  30637. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30638. autoWidth = Math.max(autoWidth, 0);
  30639. var widthSum = 0;
  30640. var lastColumn;
  30641. each(stacks, function (column, idx) {
  30642. if (!column.width) {
  30643. column.width = autoWidth;
  30644. }
  30645. lastColumn = column;
  30646. widthSum += column.width * (1 + barGapPercent);
  30647. });
  30648. if (lastColumn) {
  30649. widthSum -= lastColumn.width * barGapPercent;
  30650. }
  30651. var offset = -widthSum / 2;
  30652. each(stacks, function (column, stackId) {
  30653. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30654. bandWidth: bandWidth,
  30655. offset: offset,
  30656. width: column.width
  30657. };
  30658. offset += column.width * (1 + barGapPercent);
  30659. });
  30660. });
  30661. return result;
  30662. }
  30663. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30664. if (barWidthAndOffset && axis) {
  30665. var result = barWidthAndOffset[getAxisKey(axis)];
  30666. if (result != null && seriesModel != null) {
  30667. return result[getSeriesStackId(seriesModel)];
  30668. }
  30669. return result;
  30670. }
  30671. }
  30672. function layout(seriesType, ecModel) {
  30673. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30674. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30675. each(seriesModels, function (seriesModel) {
  30676. var data = seriesModel.getData();
  30677. var cartesian = seriesModel.coordinateSystem;
  30678. var baseAxis = cartesian.getBaseAxis();
  30679. var stackId = getSeriesStackId(seriesModel);
  30680. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30681. var columnOffset = columnLayoutInfo.offset;
  30682. var columnWidth = columnLayoutInfo.width;
  30683. data.setLayout({
  30684. bandWidth: columnLayoutInfo.bandWidth,
  30685. offset: columnOffset,
  30686. size: columnWidth
  30687. });
  30688. });
  30689. } // TODO: Do not support stack in large mode yet.
  30690. function createProgressiveLayout(seriesType) {
  30691. return {
  30692. seriesType: seriesType,
  30693. plan: createRenderPlanner(),
  30694. reset: function (seriesModel) {
  30695. if (!isOnCartesian(seriesModel)) {
  30696. return;
  30697. }
  30698. var data = seriesModel.getData();
  30699. var cartesian = seriesModel.coordinateSystem;
  30700. var baseAxis = cartesian.getBaseAxis();
  30701. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30702. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  30703. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30704. var drawBackground = seriesModel.get('showBackground', true);
  30705. var valueDim = data.mapDimension(valueAxis.dim);
  30706. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30707. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  30708. var isValueAxisH = valueAxis.isHorizontal();
  30709. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30710. var isLarge = isInLargeMode(seriesModel);
  30711. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30712. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim); // Layout info.
  30713. var columnWidth = data.getLayout('size');
  30714. var columnOffset = data.getLayout('offset');
  30715. return {
  30716. progress: function (params, data) {
  30717. var count = params.count;
  30718. var largePoints = isLarge && createFloat32Array(count * 3);
  30719. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  30720. var largeDataIndices = isLarge && createFloat32Array(count);
  30721. var coordLayout = cartesian.master.getRect();
  30722. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  30723. var dataIndex;
  30724. var store = data.getStore();
  30725. var idxOffset = 0;
  30726. while ((dataIndex = params.next()) != null) {
  30727. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  30728. var baseValue = store.get(baseDimIdx, dataIndex);
  30729. var baseCoord = valueAxisStart;
  30730. var startValue = void 0; // Because of the barMinHeight, we can not use the value in
  30731. // stackResultDimension directly.
  30732. if (stacked) {
  30733. startValue = +value - store.get(valueDimIdx, dataIndex);
  30734. }
  30735. var x = void 0;
  30736. var y = void 0;
  30737. var width = void 0;
  30738. var height = void 0;
  30739. if (isValueAxisH) {
  30740. var coord = cartesian.dataToPoint([value, baseValue]);
  30741. if (stacked) {
  30742. var startCoord = cartesian.dataToPoint([startValue, baseValue]);
  30743. baseCoord = startCoord[0];
  30744. }
  30745. x = baseCoord;
  30746. y = coord[1] + columnOffset;
  30747. width = coord[0] - baseCoord;
  30748. height = columnWidth;
  30749. if (Math.abs(width) < barMinHeight) {
  30750. width = (width < 0 ? -1 : 1) * barMinHeight;
  30751. }
  30752. } else {
  30753. var coord = cartesian.dataToPoint([baseValue, value]);
  30754. if (stacked) {
  30755. var startCoord = cartesian.dataToPoint([baseValue, startValue]);
  30756. baseCoord = startCoord[1];
  30757. }
  30758. x = coord[0] + columnOffset;
  30759. y = baseCoord;
  30760. width = columnWidth;
  30761. height = coord[1] - baseCoord;
  30762. if (Math.abs(height) < barMinHeight) {
  30763. // Include zero to has a positive bar
  30764. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30765. }
  30766. }
  30767. if (!isLarge) {
  30768. data.setItemLayout(dataIndex, {
  30769. x: x,
  30770. y: y,
  30771. width: width,
  30772. height: height
  30773. });
  30774. } else {
  30775. largePoints[idxOffset] = x;
  30776. largePoints[idxOffset + 1] = y;
  30777. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  30778. if (largeBackgroundPoints) {
  30779. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  30780. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  30781. largeBackgroundPoints[idxOffset + 2] = bgSize;
  30782. }
  30783. largeDataIndices[dataIndex] = dataIndex;
  30784. }
  30785. idxOffset += 3;
  30786. }
  30787. if (isLarge) {
  30788. data.setLayout({
  30789. largePoints: largePoints,
  30790. largeDataIndices: largeDataIndices,
  30791. largeBackgroundPoints: largeBackgroundPoints,
  30792. valueAxisHorizontal: isValueAxisH
  30793. });
  30794. }
  30795. }
  30796. };
  30797. }
  30798. };
  30799. }
  30800. function isOnCartesian(seriesModel) {
  30801. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30802. }
  30803. function isInLargeMode(seriesModel) {
  30804. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30805. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30806. function getValueAxisStart(baseAxis, valueAxis) {
  30807. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30808. }
  30809. var bisect = function (a, x, lo, hi) {
  30810. while (lo < hi) {
  30811. var mid = lo + hi >>> 1;
  30812. if (a[mid][1] < x) {
  30813. lo = mid + 1;
  30814. } else {
  30815. hi = mid;
  30816. }
  30817. }
  30818. return lo;
  30819. };
  30820. var TimeScale =
  30821. /** @class */
  30822. function (_super) {
  30823. __extends(TimeScale, _super);
  30824. function TimeScale(settings) {
  30825. var _this = _super.call(this, settings) || this;
  30826. _this.type = 'time';
  30827. return _this;
  30828. }
  30829. /**
  30830. * Get label is mainly for other components like dataZoom, tooltip.
  30831. */
  30832. TimeScale.prototype.getLabel = function (tick) {
  30833. var useUTC = this.getSetting('useUTC');
  30834. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30835. };
  30836. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30837. var isUTC = this.getSetting('useUTC');
  30838. var lang = this.getSetting('locale');
  30839. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30840. };
  30841. /**
  30842. * @override
  30843. */
  30844. TimeScale.prototype.getTicks = function () {
  30845. var interval = this._interval;
  30846. var extent = this._extent;
  30847. var ticks = []; // If interval is 0, return [];
  30848. if (!interval) {
  30849. return ticks;
  30850. }
  30851. ticks.push({
  30852. value: extent[0],
  30853. level: 0
  30854. });
  30855. var useUTC = this.getSetting('useUTC');
  30856. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30857. ticks = ticks.concat(innerTicks);
  30858. ticks.push({
  30859. value: extent[1],
  30860. level: 0
  30861. });
  30862. return ticks;
  30863. };
  30864. TimeScale.prototype.calcNiceExtent = function (opt) {
  30865. var extent = this._extent; // If extent start and end are same, expand them
  30866. if (extent[0] === extent[1]) {
  30867. // Expand extent
  30868. extent[0] -= ONE_DAY;
  30869. extent[1] += ONE_DAY;
  30870. } // If there are no data and extent are [Infinity, -Infinity]
  30871. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30872. var d = new Date();
  30873. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30874. extent[0] = extent[1] - ONE_DAY;
  30875. }
  30876. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30877. };
  30878. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  30879. approxTickNum = approxTickNum || 10;
  30880. var extent = this._extent;
  30881. var span = extent[1] - extent[0];
  30882. this._approxInterval = span / approxTickNum;
  30883. if (minInterval != null && this._approxInterval < minInterval) {
  30884. this._approxInterval = minInterval;
  30885. }
  30886. if (maxInterval != null && this._approxInterval > maxInterval) {
  30887. this._approxInterval = maxInterval;
  30888. }
  30889. var scaleIntervalsLen = scaleIntervals.length;
  30890. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30891. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30892. // We check one more level to avoid the ticks are to sparse in some case.
  30893. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30894. };
  30895. TimeScale.prototype.parse = function (val) {
  30896. // val might be float.
  30897. return isNumber(val) ? val : +parseDate(val);
  30898. };
  30899. TimeScale.prototype.contain = function (val) {
  30900. return contain$1(this.parse(val), this._extent);
  30901. };
  30902. TimeScale.prototype.normalize = function (val) {
  30903. return normalize$1(this.parse(val), this._extent);
  30904. };
  30905. TimeScale.prototype.scale = function (val) {
  30906. return scale$2(val, this._extent);
  30907. };
  30908. TimeScale.type = 'time';
  30909. return TimeScale;
  30910. }(IntervalScale);
  30911. /**
  30912. * This implementation was originally copied from "d3.js"
  30913. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30914. * with some modifications made for this program.
  30915. * See the license statement at the head of this file.
  30916. */
  30917. var scaleIntervals = [// Format interval
  30918. ['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
  30919. ];
  30920. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30921. var dateA = parseDate(valueA);
  30922. var dateB = parseDate(valueB);
  30923. var isSame = function (unit) {
  30924. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30925. };
  30926. var isSameYear = function () {
  30927. return isSame('year');
  30928. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30929. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30930. var isSameMonth = function () {
  30931. return isSameYear() && isSame('month');
  30932. };
  30933. var isSameDay = function () {
  30934. return isSameMonth() && isSame('day');
  30935. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30936. var isSameHour = function () {
  30937. return isSameDay() && isSame('hour');
  30938. };
  30939. var isSameMinute = function () {
  30940. return isSameHour() && isSame('minute');
  30941. };
  30942. var isSameSecond = function () {
  30943. return isSameMinute() && isSame('second');
  30944. };
  30945. var isSameMilliSecond = function () {
  30946. return isSameSecond() && isSame('millisecond');
  30947. };
  30948. switch (unit) {
  30949. case 'year':
  30950. return isSameYear();
  30951. case 'month':
  30952. return isSameMonth();
  30953. case 'day':
  30954. return isSameDay();
  30955. case 'hour':
  30956. return isSameHour();
  30957. case 'minute':
  30958. return isSameMinute();
  30959. case 'second':
  30960. return isSameSecond();
  30961. case 'millisecond':
  30962. return isSameMilliSecond();
  30963. }
  30964. } // const primaryUnitGetters = {
  30965. // year: fullYearGetterName(),
  30966. // month: monthGetterName(),
  30967. // day: dateGetterName(),
  30968. // hour: hoursGetterName(),
  30969. // minute: minutesGetterName(),
  30970. // second: secondsGetterName(),
  30971. // millisecond: millisecondsGetterName()
  30972. // };
  30973. // const primaryUnitUTCGetters = {
  30974. // year: fullYearGetterName(true),
  30975. // month: monthGetterName(true),
  30976. // day: dateGetterName(true),
  30977. // hour: hoursGetterName(true),
  30978. // minute: minutesGetterName(true),
  30979. // second: secondsGetterName(true),
  30980. // millisecond: millisecondsGetterName(true)
  30981. // };
  30982. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30983. // step = step || 1;
  30984. // switch (getPrimaryTimeUnit(unitName)) {
  30985. // case 'year':
  30986. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30987. // break;
  30988. // case 'month':
  30989. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30990. // break;
  30991. // case 'day':
  30992. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30993. // break;
  30994. // case 'hour':
  30995. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  30996. // break;
  30997. // case 'minute':
  30998. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  30999. // break;
  31000. // case 'second':
  31001. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  31002. // break;
  31003. // case 'millisecond':
  31004. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  31005. // break;
  31006. // }
  31007. // return date.getTime();
  31008. // }
  31009. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  31010. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  31011. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  31012. function getDateInterval(approxInterval, daysInMonth) {
  31013. approxInterval /= ONE_DAY;
  31014. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  31015. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  31016. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  31017. }
  31018. function getMonthInterval(approxInterval) {
  31019. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  31020. approxInterval /= APPROX_ONE_MONTH;
  31021. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  31022. }
  31023. function getHourInterval(approxInterval) {
  31024. approxInterval /= ONE_HOUR;
  31025. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  31026. }
  31027. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  31028. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  31029. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  31030. }
  31031. function getMillisecondsInterval(approxInterval) {
  31032. return nice(approxInterval, true);
  31033. }
  31034. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  31035. var outDate = new Date(date);
  31036. switch (getPrimaryTimeUnit(unitName)) {
  31037. case 'year':
  31038. case 'month':
  31039. outDate[monthSetterName(isUTC)](0);
  31040. case 'day':
  31041. outDate[dateSetterName(isUTC)](1);
  31042. case 'hour':
  31043. outDate[hoursSetterName(isUTC)](0);
  31044. case 'minute':
  31045. outDate[minutesSetterName(isUTC)](0);
  31046. case 'second':
  31047. outDate[secondsSetterName(isUTC)](0);
  31048. outDate[millisecondsSetterName(isUTC)](0);
  31049. }
  31050. return outDate.getTime();
  31051. }
  31052. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  31053. var safeLimit = 10000;
  31054. var unitNames = timeUnits;
  31055. var iter = 0;
  31056. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  31057. var date = new Date(minTimestamp);
  31058. var dateTime = minTimestamp;
  31059. var d = date[getMethodName](); // if (isDate) {
  31060. // d -= 1; // Starts with 0; PENDING
  31061. // }
  31062. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  31063. out.push({
  31064. value: dateTime
  31065. });
  31066. d += interval;
  31067. date[setMethodName](d);
  31068. dateTime = date.getTime();
  31069. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  31070. out.push({
  31071. value: dateTime,
  31072. notAdd: true
  31073. });
  31074. }
  31075. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  31076. var newAddedTicks = [];
  31077. var isFirstLevel = !lastLevelTicks.length;
  31078. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  31079. return;
  31080. }
  31081. if (isFirstLevel) {
  31082. lastLevelTicks = [{
  31083. // TODO Optimize. Not include so may ticks.
  31084. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  31085. }, {
  31086. value: extent[1]
  31087. }];
  31088. }
  31089. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  31090. var startTick = lastLevelTicks[i].value;
  31091. var endTick = lastLevelTicks[i + 1].value;
  31092. if (startTick === endTick) {
  31093. continue;
  31094. }
  31095. var interval = void 0;
  31096. var getterName = void 0;
  31097. var setterName = void 0;
  31098. var isDate = false;
  31099. switch (unitName) {
  31100. case 'year':
  31101. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  31102. getterName = fullYearGetterName(isUTC);
  31103. setterName = fullYearSetterName(isUTC);
  31104. break;
  31105. case 'half-year':
  31106. case 'quarter':
  31107. case 'month':
  31108. interval = getMonthInterval(approxInterval);
  31109. getterName = monthGetterName(isUTC);
  31110. setterName = monthSetterName(isUTC);
  31111. break;
  31112. case 'week': // PENDING If week is added. Ignore day.
  31113. case 'half-week':
  31114. case 'day':
  31115. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  31116. getterName = dateGetterName(isUTC);
  31117. setterName = dateSetterName(isUTC);
  31118. isDate = true;
  31119. break;
  31120. case 'half-day':
  31121. case 'quarter-day':
  31122. case 'hour':
  31123. interval = getHourInterval(approxInterval);
  31124. getterName = hoursGetterName(isUTC);
  31125. setterName = hoursSetterName(isUTC);
  31126. break;
  31127. case 'minute':
  31128. interval = getMinutesAndSecondsInterval(approxInterval, true);
  31129. getterName = minutesGetterName(isUTC);
  31130. setterName = minutesSetterName(isUTC);
  31131. break;
  31132. case 'second':
  31133. interval = getMinutesAndSecondsInterval(approxInterval, false);
  31134. getterName = secondsGetterName(isUTC);
  31135. setterName = secondsSetterName(isUTC);
  31136. break;
  31137. case 'millisecond':
  31138. interval = getMillisecondsInterval(approxInterval);
  31139. getterName = millisecondsGetterName(isUTC);
  31140. setterName = millisecondsSetterName(isUTC);
  31141. break;
  31142. }
  31143. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  31144. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  31145. // Add nearest years to the left extent.
  31146. levelTicks.unshift({
  31147. value: levelTicks[0].value - interval
  31148. });
  31149. }
  31150. }
  31151. for (var i = 0; i < newAddedTicks.length; i++) {
  31152. levelTicks.push(newAddedTicks[i]);
  31153. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  31154. return newAddedTicks;
  31155. }
  31156. var levelsTicks = [];
  31157. var currentLevelTicks = [];
  31158. var tickCount = 0;
  31159. var lastLevelTickCount = 0;
  31160. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  31161. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  31162. if (!isPrimaryTimeUnit(unitNames[i])) {
  31163. // TODO
  31164. continue;
  31165. }
  31166. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  31167. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  31168. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  31169. if (currentLevelTicks.length) {
  31170. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  31171. currentLevelTicks.sort(function (a, b) {
  31172. return a.value - b.value;
  31173. });
  31174. var levelTicksRemoveDuplicated = [];
  31175. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  31176. var tickValue = currentLevelTicks[i_1].value;
  31177. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  31178. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  31179. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  31180. tickCount++;
  31181. }
  31182. }
  31183. }
  31184. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  31185. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  31186. break;
  31187. } // Only treat primary time unit as one level.
  31188. levelsTicks.push(levelTicksRemoveDuplicated);
  31189. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  31190. break;
  31191. }
  31192. } // Reset if next unitName is primary
  31193. currentLevelTicks = [];
  31194. }
  31195. }
  31196. if ("development" !== 'production') {
  31197. if (iter >= safeLimit) {
  31198. warn('Exceed safe limit.');
  31199. }
  31200. }
  31201. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  31202. return filter(levelTicks, function (tick) {
  31203. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  31204. });
  31205. }), function (levelTicks) {
  31206. return levelTicks.length > 0;
  31207. });
  31208. var ticks = [];
  31209. var maxLevel = levelsTicksInExtent.length - 1;
  31210. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  31211. var levelTicks = levelsTicksInExtent[i];
  31212. for (var k = 0; k < levelTicks.length; ++k) {
  31213. ticks.push({
  31214. value: levelTicks[k].value,
  31215. level: maxLevel - i
  31216. });
  31217. }
  31218. }
  31219. ticks.sort(function (a, b) {
  31220. return a.value - b.value;
  31221. }); // Remove duplicates
  31222. var result = [];
  31223. for (var i = 0; i < ticks.length; ++i) {
  31224. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  31225. result.push(ticks[i]);
  31226. }
  31227. }
  31228. return result;
  31229. }
  31230. Scale.registerClass(TimeScale);
  31231. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  31232. var intervalScaleProto = IntervalScale.prototype;
  31233. var roundingErrorFix = round;
  31234. var mathFloor = Math.floor;
  31235. var mathCeil = Math.ceil;
  31236. var mathPow$1 = Math.pow;
  31237. var mathLog = Math.log;
  31238. var LogScale =
  31239. /** @class */
  31240. function (_super) {
  31241. __extends(LogScale, _super);
  31242. function LogScale() {
  31243. var _this = _super !== null && _super.apply(this, arguments) || this;
  31244. _this.type = 'log';
  31245. _this.base = 10;
  31246. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  31247. _this._interval = 0;
  31248. return _this;
  31249. }
  31250. /**
  31251. * @param Whether expand the ticks to niced extent.
  31252. */
  31253. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  31254. var originalScale = this._originalScale;
  31255. var extent = this._extent;
  31256. var originalExtent = originalScale.getExtent();
  31257. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  31258. return map(ticks, function (tick) {
  31259. var val = tick.value;
  31260. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  31261. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  31262. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  31263. return {
  31264. value: powVal
  31265. };
  31266. }, this);
  31267. };
  31268. LogScale.prototype.setExtent = function (start, end) {
  31269. var base = mathLog(this.base); // log(-Infinity) is NaN, so safe guard here
  31270. start = mathLog(Math.max(0, start)) / base;
  31271. end = mathLog(Math.max(0, end)) / base;
  31272. intervalScaleProto.setExtent.call(this, start, end);
  31273. };
  31274. /**
  31275. * @return {number} end
  31276. */
  31277. LogScale.prototype.getExtent = function () {
  31278. var base = this.base;
  31279. var extent = scaleProto.getExtent.call(this);
  31280. extent[0] = mathPow$1(base, extent[0]);
  31281. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  31282. var originalScale = this._originalScale;
  31283. var originalExtent = originalScale.getExtent();
  31284. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  31285. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  31286. return extent;
  31287. };
  31288. LogScale.prototype.unionExtent = function (extent) {
  31289. this._originalScale.unionExtent(extent);
  31290. var base = this.base;
  31291. extent[0] = mathLog(extent[0]) / mathLog(base);
  31292. extent[1] = mathLog(extent[1]) / mathLog(base);
  31293. scaleProto.unionExtent.call(this, extent);
  31294. };
  31295. LogScale.prototype.unionExtentFromData = function (data, dim) {
  31296. // TODO
  31297. // filter value that <= 0
  31298. this.unionExtent(data.getApproximateExtent(dim));
  31299. };
  31300. /**
  31301. * Update interval and extent of intervals for nice ticks
  31302. * @param approxTickNum default 10 Given approx tick number
  31303. */
  31304. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  31305. approxTickNum = approxTickNum || 10;
  31306. var extent = this._extent;
  31307. var span = extent[1] - extent[0];
  31308. if (span === Infinity || span <= 0) {
  31309. return;
  31310. }
  31311. var interval = quantity(span);
  31312. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  31313. if (err <= 0.5) {
  31314. interval *= 10;
  31315. } // Interval should be integer
  31316. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31317. interval *= 10;
  31318. }
  31319. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  31320. this._interval = interval;
  31321. this._niceExtent = niceExtent;
  31322. };
  31323. LogScale.prototype.calcNiceExtent = function (opt) {
  31324. intervalScaleProto.calcNiceExtent.call(this, opt);
  31325. this._fixMin = opt.fixMin;
  31326. this._fixMax = opt.fixMax;
  31327. };
  31328. LogScale.prototype.parse = function (val) {
  31329. return val;
  31330. };
  31331. LogScale.prototype.contain = function (val) {
  31332. val = mathLog(val) / mathLog(this.base);
  31333. return contain$1(val, this._extent);
  31334. };
  31335. LogScale.prototype.normalize = function (val) {
  31336. val = mathLog(val) / mathLog(this.base);
  31337. return normalize$1(val, this._extent);
  31338. };
  31339. LogScale.prototype.scale = function (val) {
  31340. val = scale$2(val, this._extent);
  31341. return mathPow$1(this.base, val);
  31342. };
  31343. LogScale.type = 'log';
  31344. return LogScale;
  31345. }(Scale);
  31346. var proto = LogScale.prototype;
  31347. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  31348. proto.getLabel = intervalScaleProto.getLabel;
  31349. function fixRoundingError(val, originalVal) {
  31350. return roundingErrorFix(val, getPrecision(originalVal));
  31351. }
  31352. Scale.registerClass(LogScale);
  31353. var ScaleRawExtentInfo =
  31354. /** @class */
  31355. function () {
  31356. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31357. originalExtent) {
  31358. this._prepareParams(scale, model, originalExtent);
  31359. }
  31360. /**
  31361. * Parameters depending on outside (like model, user callback)
  31362. * are prepared and fixed here.
  31363. */
  31364. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  31365. dataExtent) {
  31366. if (dataExtent[1] < dataExtent[0]) {
  31367. dataExtent = [NaN, NaN];
  31368. }
  31369. this._dataMin = dataExtent[0];
  31370. this._dataMax = dataExtent[1];
  31371. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  31372. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  31373. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  31374. if (isFunction(modelMinRaw)) {
  31375. // This callback always provides users the full data extent (before data is filtered).
  31376. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  31377. min: dataExtent[0],
  31378. max: dataExtent[1]
  31379. }));
  31380. } else if (modelMinRaw !== 'dataMin') {
  31381. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  31382. }
  31383. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  31384. if (isFunction(modelMaxRaw)) {
  31385. // This callback always provides users the full data extent (before data is filtered).
  31386. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  31387. min: dataExtent[0],
  31388. max: dataExtent[1]
  31389. }));
  31390. } else if (modelMaxRaw !== 'dataMax') {
  31391. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  31392. }
  31393. if (isOrdinal) {
  31394. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  31395. // and progressive rendering is using, here the category result might just only contain
  31396. // the processed chunk rather than the entire result.
  31397. this._axisDataLen = model.getCategories().length;
  31398. } else {
  31399. var boundaryGap = model.get('boundaryGap');
  31400. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  31401. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  31402. if ("development" !== 'production') {
  31403. 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.');
  31404. }
  31405. this._boundaryGapInner = [0, 0];
  31406. } else {
  31407. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  31408. }
  31409. }
  31410. };
  31411. /**
  31412. * Calculate extent by prepared parameters.
  31413. * This method has no external dependency and can be called duplicatedly,
  31414. * getting the same result.
  31415. * If parameters changed, should call this method to recalcuate.
  31416. */
  31417. ScaleRawExtentInfo.prototype.calculate = function () {
  31418. // Notice: When min/max is not set (that is, when there are null/undefined,
  31419. // which is the most common case), these cases should be ensured:
  31420. // (1) For 'ordinal', show all axis.data.
  31421. // (2) For others:
  31422. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31423. // disabled).
  31424. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31425. // be the result that originalExtent enlarged by boundaryGap.
  31426. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31427. var isOrdinal = this._isOrdinal;
  31428. var dataMin = this._dataMin;
  31429. var dataMax = this._dataMax;
  31430. var axisDataLen = this._axisDataLen;
  31431. var boundaryGapInner = this._boundaryGapInner;
  31432. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  31433. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  31434. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  31435. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  31436. var minFixed = min != null;
  31437. var maxFixed = max != null;
  31438. if (min == null) {
  31439. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31440. }
  31441. if (max == null) {
  31442. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31443. }
  31444. (min == null || !isFinite(min)) && (min = NaN);
  31445. (max == null || !isFinite(max)) && (max = NaN);
  31446. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  31447. if (this._needCrossZero) {
  31448. // Axis is over zero and min is not set
  31449. if (min > 0 && max > 0 && !minFixed) {
  31450. min = 0; // minFixed = true;
  31451. } // Axis is under zero and max is not set
  31452. if (min < 0 && max < 0 && !maxFixed) {
  31453. max = 0; // maxFixed = true;
  31454. } // PENDING:
  31455. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31456. // that the results processed by boundaryGap are positive/negative?
  31457. // If so, here `minFixed`/`maxFixed` need to be set.
  31458. }
  31459. var determinedMin = this._determinedMin;
  31460. var determinedMax = this._determinedMax;
  31461. if (determinedMin != null) {
  31462. min = determinedMin;
  31463. minFixed = true;
  31464. }
  31465. if (determinedMax != null) {
  31466. max = determinedMax;
  31467. maxFixed = true;
  31468. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31469. // `NaN` means min/max axis is blank.
  31470. return {
  31471. min: min,
  31472. max: max,
  31473. minFixed: minFixed,
  31474. maxFixed: maxFixed,
  31475. isBlank: isBlank
  31476. };
  31477. };
  31478. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31479. if ("development" !== 'production') {
  31480. assert(!this.frozen);
  31481. }
  31482. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31483. };
  31484. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31485. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31486. if ("development" !== 'production') {
  31487. assert(!this.frozen // Earse them usually means logic flaw.
  31488. && this[attr] == null);
  31489. }
  31490. this[attr] = val;
  31491. };
  31492. ScaleRawExtentInfo.prototype.freeze = function () {
  31493. // @ts-ignore
  31494. this.frozen = true;
  31495. };
  31496. return ScaleRawExtentInfo;
  31497. }();
  31498. var DETERMINED_MIN_MAX_ATTR = {
  31499. min: '_determinedMin',
  31500. max: '_determinedMax'
  31501. };
  31502. var DATA_MIN_MAX_ATTR = {
  31503. min: '_dataMin',
  31504. max: '_dataMax'
  31505. };
  31506. /**
  31507. * Get scale min max and related info only depends on model settings.
  31508. * This method can be called after coordinate system created.
  31509. * For example, in data processing stage.
  31510. *
  31511. * Scale extent info probably be required multiple times during a workflow.
  31512. * For example:
  31513. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31514. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31515. * (3) `coordSys.update` use it to finally decide the scale extent.
  31516. * But the callback of `min`/`max` should not be called multiple times.
  31517. * The code below should not be implemented repeatedly either.
  31518. * So we cache the result in the scale instance, which will be recreated at the beginning
  31519. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31520. */
  31521. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31522. originalExtent) {
  31523. // Do not permit to recreate.
  31524. var rawExtentInfo = scale.rawExtentInfo;
  31525. if (rawExtentInfo) {
  31526. return rawExtentInfo;
  31527. }
  31528. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  31529. scale.rawExtentInfo = rawExtentInfo;
  31530. return rawExtentInfo;
  31531. }
  31532. function parseAxisModelMinMax(scale, minMax) {
  31533. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31534. }
  31535. /**
  31536. * Get axis scale extent before niced.
  31537. * Item of returned array can only be number (including Infinity and NaN).
  31538. *
  31539. * Caution:
  31540. * Precondition of calling this method:
  31541. * The scale extent has been initialized using series data extent via
  31542. * `scale.setExtent` or `scale.unionExtentFromData`;
  31543. */
  31544. function getScaleExtent(scale, model) {
  31545. var scaleType = scale.type;
  31546. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31547. scale.setBlank(rawExtentResult.isBlank);
  31548. var min = rawExtentResult.min;
  31549. var max = rawExtentResult.max; // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31550. // is base axis
  31551. // FIXME
  31552. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31553. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31554. // Should not depend on series type `bar`?
  31555. // (3) Fix that might overlap when using dataZoom.
  31556. // (4) Consider other chart types using `barGrid`?
  31557. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31558. var ecModel = model.ecModel;
  31559. if (ecModel && scaleType === 'time'
  31560. /* || scaleType === 'interval' */
  31561. ) {
  31562. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31563. var isBaseAxisAndHasBarSeries_1 = false;
  31564. each(barSeriesModels, function (seriesModel) {
  31565. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31566. });
  31567. if (isBaseAxisAndHasBarSeries_1) {
  31568. // Calculate placement of bars on axis. TODO should be decoupled
  31569. // with barLayout
  31570. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  31571. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31572. min = adjustedScale.min;
  31573. max = adjustedScale.max;
  31574. }
  31575. }
  31576. return {
  31577. extent: [min, max],
  31578. // "fix" means "fixed", the value should not be
  31579. // changed in the subsequent steps.
  31580. fixMin: rawExtentResult.minFixed,
  31581. fixMax: rawExtentResult.maxFixed
  31582. };
  31583. }
  31584. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  31585. barWidthAndOffset) {
  31586. // Get Axis Length
  31587. var axisExtent = model.axis.getExtent();
  31588. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  31589. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31590. if (barsOnCurrentAxis === undefined) {
  31591. return {
  31592. min: min,
  31593. max: max
  31594. };
  31595. }
  31596. var minOverflow = Infinity;
  31597. each(barsOnCurrentAxis, function (item) {
  31598. minOverflow = Math.min(item.offset, minOverflow);
  31599. });
  31600. var maxOverflow = -Infinity;
  31601. each(barsOnCurrentAxis, function (item) {
  31602. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31603. });
  31604. minOverflow = Math.abs(minOverflow);
  31605. maxOverflow = Math.abs(maxOverflow);
  31606. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  31607. var oldRange = max - min;
  31608. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31609. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31610. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31611. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31612. return {
  31613. min: min,
  31614. max: max
  31615. };
  31616. } // Precondition of calling this method:
  31617. // The scale extent has been initialized using series data extent via
  31618. // `scale.setExtent` or `scale.unionExtentFromData`;
  31619. function niceScaleExtent(scale, inModel) {
  31620. var model = inModel;
  31621. var extentInfo = getScaleExtent(scale, model);
  31622. var extent = extentInfo.extent;
  31623. var splitNumber = model.get('splitNumber');
  31624. if (scale instanceof LogScale) {
  31625. scale.base = model.get('logBase');
  31626. }
  31627. var scaleType = scale.type;
  31628. var interval = model.get('interval');
  31629. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  31630. scale.setExtent(extent[0], extent[1]);
  31631. scale.calcNiceExtent({
  31632. splitNumber: splitNumber,
  31633. fixMin: extentInfo.fixMin,
  31634. fixMax: extentInfo.fixMax,
  31635. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  31636. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  31637. }); // If some one specified the min, max. And the default calculated interval
  31638. // is not good enough. He can specify the interval. It is often appeared
  31639. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31640. // to be 60.
  31641. // FIXME
  31642. if (interval != null) {
  31643. scale.setInterval && scale.setInterval(interval);
  31644. }
  31645. }
  31646. /**
  31647. * @param axisType Default retrieve from model.type
  31648. */
  31649. function createScaleByModel(model, axisType) {
  31650. axisType = axisType || model.get('type');
  31651. if (axisType) {
  31652. switch (axisType) {
  31653. // Buildin scale
  31654. case 'category':
  31655. return new OrdinalScale({
  31656. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31657. extent: [Infinity, -Infinity]
  31658. });
  31659. case 'time':
  31660. return new TimeScale({
  31661. locale: model.ecModel.getLocaleModel(),
  31662. useUTC: model.ecModel.get('useUTC')
  31663. });
  31664. default:
  31665. // case 'value'/'interval', 'log', or others.
  31666. return new (Scale.getClass(axisType) || IntervalScale)();
  31667. }
  31668. }
  31669. }
  31670. /**
  31671. * Check if the axis cross 0
  31672. */
  31673. function ifAxisCrossZero(axis) {
  31674. var dataExtent = axis.scale.getExtent();
  31675. var min = dataExtent[0];
  31676. var max = dataExtent[1];
  31677. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31678. }
  31679. /**
  31680. * @param axis
  31681. * @return Label formatter function.
  31682. * param: {number} tickValue,
  31683. * param: {number} idx, the index in all ticks.
  31684. * If category axis, this param is not required.
  31685. * return: {string} label string.
  31686. */
  31687. function makeLabelFormatter(axis) {
  31688. var labelFormatter = axis.getLabelModel().get('formatter');
  31689. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31690. if (axis.scale.type === 'time') {
  31691. return function (tpl) {
  31692. return function (tick, idx) {
  31693. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31694. };
  31695. }(labelFormatter);
  31696. } else if (isString(labelFormatter)) {
  31697. return function (tpl) {
  31698. return function (tick) {
  31699. // For category axis, get raw value; for numeric axis,
  31700. // get formatted label like '1,333,444'.
  31701. var label = axis.scale.getLabel(tick);
  31702. var text = tpl.replace('{value}', label != null ? label : '');
  31703. return text;
  31704. };
  31705. }(labelFormatter);
  31706. } else if (isFunction(labelFormatter)) {
  31707. return function (cb) {
  31708. return function (tick, idx) {
  31709. // The original intention of `idx` is "the index of the tick in all ticks".
  31710. // But the previous implementation of category axis do not consider the
  31711. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31712. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31713. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31714. // the definition here for back compatibility.
  31715. if (categoryTickStart != null) {
  31716. idx = tick.value - categoryTickStart;
  31717. }
  31718. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31719. level: tick.level
  31720. } : null);
  31721. };
  31722. }(labelFormatter);
  31723. } else {
  31724. return function (tick) {
  31725. return axis.scale.getLabel(tick);
  31726. };
  31727. }
  31728. }
  31729. function getAxisRawValue(axis, tick) {
  31730. // In category axis with data zoom, tick is not the original
  31731. // index of axis.data. So tick should not be exposed to user
  31732. // in category axis.
  31733. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31734. }
  31735. /**
  31736. * @param axis
  31737. * @return Be null/undefined if no labels.
  31738. */
  31739. function estimateLabelUnionRect(axis) {
  31740. var axisModel = axis.model;
  31741. var scale = axis.scale;
  31742. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31743. return;
  31744. }
  31745. var realNumberScaleTicks;
  31746. var tickCount;
  31747. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31748. if (scale instanceof OrdinalScale) {
  31749. tickCount = scale.count();
  31750. } else {
  31751. realNumberScaleTicks = scale.getTicks();
  31752. tickCount = realNumberScaleTicks.length;
  31753. }
  31754. var axisLabelModel = axis.getLabelModel();
  31755. var labelFormatter = makeLabelFormatter(axis);
  31756. var rect;
  31757. var step = 1; // Simple optimization for large amount of labels
  31758. if (tickCount > 40) {
  31759. step = Math.ceil(tickCount / 40);
  31760. }
  31761. for (var i = 0; i < tickCount; i += step) {
  31762. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31763. value: categoryScaleExtent[0] + i
  31764. };
  31765. var label = labelFormatter(tick, i);
  31766. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31767. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31768. rect ? rect.union(singleRect) : rect = singleRect;
  31769. }
  31770. return rect;
  31771. }
  31772. function rotateTextRect(textRect, rotate) {
  31773. var rotateRadians = rotate * Math.PI / 180;
  31774. var beforeWidth = textRect.width;
  31775. var beforeHeight = textRect.height;
  31776. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31777. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31778. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31779. return rotatedRect;
  31780. }
  31781. /**
  31782. * @param model axisLabelModel or axisTickModel
  31783. * @return {number|String} Can be null|'auto'|number|function
  31784. */
  31785. function getOptionCategoryInterval(model) {
  31786. var interval = model.get('interval');
  31787. return interval == null ? 'auto' : interval;
  31788. }
  31789. /**
  31790. * Set `categoryInterval` as 0 implicitly indicates that
  31791. * show all labels regardless of overlap.
  31792. * @param {Object} axis axisModel.axis
  31793. */
  31794. function shouldShowAllLabels(axis) {
  31795. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31796. }
  31797. function getDataDimensionsOnAxis(data, axisDim) {
  31798. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31799. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31800. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31801. // there has been stacked result dim?
  31802. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31803. // For example, the extent of the original dimension
  31804. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31805. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31806. // because there is no graphic corresponding to [0.1, 0.5].
  31807. // See the case in `test/area-stack.html` `main1`, where area line
  31808. // stack needs `yAxis` not start from 0.
  31809. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31810. });
  31811. return keys(dataDimMap);
  31812. }
  31813. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31814. if (data) {
  31815. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31816. var seriesExtent = data.getApproximateExtent(dim);
  31817. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31818. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31819. });
  31820. }
  31821. }
  31822. /*
  31823. * Licensed to the Apache Software Foundation (ASF) under one
  31824. * or more contributor license agreements. See the NOTICE file
  31825. * distributed with this work for additional information
  31826. * regarding copyright ownership. The ASF licenses this file
  31827. * to you under the Apache License, Version 2.0 (the
  31828. * "License"); you may not use this file except in compliance
  31829. * with the License. You may obtain a copy of the License at
  31830. *
  31831. * http://www.apache.org/licenses/LICENSE-2.0
  31832. *
  31833. * Unless required by applicable law or agreed to in writing,
  31834. * software distributed under the License is distributed on an
  31835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31836. * KIND, either express or implied. See the License for the
  31837. * specific language governing permissions and limitations
  31838. * under the License.
  31839. */
  31840. /**
  31841. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31842. */
  31843. /*
  31844. * Licensed to the Apache Software Foundation (ASF) under one
  31845. * or more contributor license agreements. See the NOTICE file
  31846. * distributed with this work for additional information
  31847. * regarding copyright ownership. The ASF licenses this file
  31848. * to you under the Apache License, Version 2.0 (the
  31849. * "License"); you may not use this file except in compliance
  31850. * with the License. You may obtain a copy of the License at
  31851. *
  31852. * http://www.apache.org/licenses/LICENSE-2.0
  31853. *
  31854. * Unless required by applicable law or agreed to in writing,
  31855. * software distributed under the License is distributed on an
  31856. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31857. * KIND, either express or implied. See the License for the
  31858. * specific language governing permissions and limitations
  31859. * under the License.
  31860. */
  31861. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  31862. var AxisModelCommonMixin =
  31863. /** @class */
  31864. function () {
  31865. function AxisModelCommonMixin() {}
  31866. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31867. var option = this.option;
  31868. return !option.scale;
  31869. };
  31870. /**
  31871. * Should be implemented by each axis model if necessary.
  31872. * @return coordinate system model
  31873. */
  31874. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31875. return;
  31876. };
  31877. return AxisModelCommonMixin;
  31878. }();
  31879. /**
  31880. * Create a multi dimension List structure from seriesModel.
  31881. */
  31882. function createList(seriesModel) {
  31883. return createSeriesData(null, seriesModel);
  31884. } // export function createGraph(seriesModel) {
  31885. var dataStack$1 = {
  31886. isDimensionStacked: isDimensionStacked,
  31887. enableDataStack: enableDataStack,
  31888. getStackedDimension: getStackedDimension
  31889. };
  31890. /**
  31891. * Create scale
  31892. * @param {Array.<number>} dataExtent
  31893. * @param {Object|module:echarts/Model} option If `optoin.type`
  31894. * is secified, it can only be `'value'` currently.
  31895. */
  31896. function createScale(dataExtent, option) {
  31897. var axisModel = option;
  31898. if (!(option instanceof Model)) {
  31899. axisModel = new Model(option); // FIXME
  31900. // Currently AxisModelCommonMixin has nothing to do with the
  31901. // the requirements of `axisHelper.createScaleByModel`. For
  31902. // example the methods `getCategories` and `getOrdinalMeta`
  31903. // are required for `'category'` axis, and ecModel is required
  31904. // for `'time'` axis. But occasionally echarts-gl happened
  31905. // to only use `'value'` axis.
  31906. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31907. }
  31908. var scale = createScaleByModel(axisModel);
  31909. scale.setExtent(dataExtent[0], dataExtent[1]);
  31910. niceScaleExtent(scale, axisModel);
  31911. return scale;
  31912. }
  31913. /**
  31914. * Mixin common methods to axis model,
  31915. *
  31916. * Include methods
  31917. * `getFormattedLabels() => Array.<string>`
  31918. * `getCategories() => Array.<string>`
  31919. * `getMin(origin: boolean) => number`
  31920. * `getMax(origin: boolean) => number`
  31921. * `getNeedCrossZero() => boolean`
  31922. */
  31923. function mixinAxisModelCommonMethods(Model) {
  31924. mixin(Model, AxisModelCommonMixin);
  31925. }
  31926. function createTextStyle$1(textStyleModel, opts) {
  31927. opts = opts || {};
  31928. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31929. }
  31930. var helper = /*#__PURE__*/Object.freeze({
  31931. __proto__: null,
  31932. createList: createList,
  31933. getLayoutRect: getLayoutRect,
  31934. dataStack: dataStack$1,
  31935. createScale: createScale,
  31936. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31937. getECData: getECData,
  31938. createTextStyle: createTextStyle$1,
  31939. createDimensions: createDimensions,
  31940. createSymbol: createSymbol,
  31941. enableHoverEmphasis: enableHoverEmphasis
  31942. });
  31943. var EPSILON$4 = 1e-8;
  31944. function isAroundEqual$1(a, b) {
  31945. return Math.abs(a - b) < EPSILON$4;
  31946. }
  31947. function contain$2(points, x, y) {
  31948. var w = 0;
  31949. var p = points[0];
  31950. if (!p) {
  31951. return false;
  31952. }
  31953. for (var i = 1; i < points.length; i++) {
  31954. var p2 = points[i];
  31955. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31956. p = p2;
  31957. }
  31958. var p0 = points[0];
  31959. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31960. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31961. }
  31962. return w !== 0;
  31963. }
  31964. var TMP_TRANSFORM = [];
  31965. function transformPoints(points, transform) {
  31966. for (var p = 0; p < points.length; p++) {
  31967. applyTransform(points[p], points[p], transform);
  31968. }
  31969. }
  31970. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  31971. for (var i = 0; i < points.length; i++) {
  31972. var p = points[i];
  31973. if (projection) {
  31974. // projection may return null point.
  31975. p = projection.project(p);
  31976. }
  31977. if (p && isFinite(p[0]) && isFinite(p[1])) {
  31978. min(min$1, min$1, p);
  31979. max(max$1, max$1, p);
  31980. }
  31981. }
  31982. }
  31983. function centroid(points) {
  31984. var signedArea = 0;
  31985. var cx = 0;
  31986. var cy = 0;
  31987. var len = points.length;
  31988. var x0 = points[len - 1][0];
  31989. var y0 = points[len - 1][1]; // Polygon should been closed.
  31990. for (var i = 0; i < len; i++) {
  31991. var x1 = points[i][0];
  31992. var y1 = points[i][1];
  31993. var a = x0 * y1 - x1 * y0;
  31994. signedArea += a;
  31995. cx += (x0 + x1) * a;
  31996. cy += (y0 + y1) * a;
  31997. x0 = x1;
  31998. y0 = y1;
  31999. }
  32000. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  32001. }
  32002. var Region =
  32003. /** @class */
  32004. function () {
  32005. function Region(name) {
  32006. this.name = name;
  32007. }
  32008. Region.prototype.setCenter = function (center) {
  32009. this._center = center;
  32010. };
  32011. /**
  32012. * Get center point in data unit. That is,
  32013. * for GeoJSONRegion, the unit is lat/lng,
  32014. * for GeoSVGRegion, the unit is SVG local coord.
  32015. */
  32016. Region.prototype.getCenter = function () {
  32017. var center = this._center;
  32018. if (!center) {
  32019. // In most cases there are no need to calculate this center.
  32020. // So calculate only when called.
  32021. center = this._center = this.calcCenter();
  32022. }
  32023. return center;
  32024. };
  32025. return Region;
  32026. }();
  32027. var GeoJSONPolygonGeometry =
  32028. /** @class */
  32029. function () {
  32030. function GeoJSONPolygonGeometry(exterior, interiors) {
  32031. this.type = 'polygon';
  32032. this.exterior = exterior;
  32033. this.interiors = interiors;
  32034. }
  32035. return GeoJSONPolygonGeometry;
  32036. }();
  32037. var GeoJSONLineStringGeometry =
  32038. /** @class */
  32039. function () {
  32040. function GeoJSONLineStringGeometry(points) {
  32041. this.type = 'linestring';
  32042. this.points = points;
  32043. }
  32044. return GeoJSONLineStringGeometry;
  32045. }();
  32046. var GeoJSONRegion =
  32047. /** @class */
  32048. function (_super) {
  32049. __extends(GeoJSONRegion, _super);
  32050. function GeoJSONRegion(name, geometries, cp) {
  32051. var _this = _super.call(this, name) || this;
  32052. _this.type = 'geoJSON';
  32053. _this.geometries = geometries;
  32054. _this._center = cp && [cp[0], cp[1]];
  32055. return _this;
  32056. }
  32057. GeoJSONRegion.prototype.calcCenter = function () {
  32058. var geometries = this.geometries;
  32059. var largestGeo;
  32060. var largestGeoSize = 0;
  32061. for (var i = 0; i < geometries.length; i++) {
  32062. var geo = geometries[i];
  32063. var exterior = geo.exterior; // Simple trick to use points count instead of polygon area as region size.
  32064. // Ignore linestring
  32065. var size = exterior && exterior.length;
  32066. if (size > largestGeoSize) {
  32067. largestGeo = geo;
  32068. largestGeoSize = size;
  32069. }
  32070. }
  32071. if (largestGeo) {
  32072. return centroid(largestGeo.exterior);
  32073. } // from bounding rect by default.
  32074. var rect = this.getBoundingRect();
  32075. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32076. };
  32077. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  32078. var rect = this._rect; // Always recalculate if using projection.
  32079. if (rect && !projection) {
  32080. return rect;
  32081. }
  32082. var min = [Infinity, Infinity];
  32083. var max = [-Infinity, -Infinity];
  32084. var geometries = this.geometries;
  32085. each(geometries, function (geo) {
  32086. if (geo.type === 'polygon') {
  32087. // Doesn't consider hole
  32088. updateBBoxFromPoints(geo.exterior, min, max, projection);
  32089. } else {
  32090. each(geo.points, function (points) {
  32091. updateBBoxFromPoints(points, min, max, projection);
  32092. });
  32093. }
  32094. }); // Normalie invalid bounding.
  32095. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  32096. min[0] = min[1] = max[0] = max[1] = 0;
  32097. }
  32098. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  32099. if (!projection) {
  32100. this._rect = rect;
  32101. }
  32102. return rect;
  32103. };
  32104. GeoJSONRegion.prototype.contain = function (coord) {
  32105. var rect = this.getBoundingRect();
  32106. var geometries = this.geometries;
  32107. if (!rect.contain(coord[0], coord[1])) {
  32108. return false;
  32109. }
  32110. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  32111. var geo = geometries[i]; // Only support polygon.
  32112. if (geo.type !== 'polygon') {
  32113. continue;
  32114. }
  32115. var exterior = geo.exterior;
  32116. var interiors = geo.interiors;
  32117. if (contain$2(exterior, coord[0], coord[1])) {
  32118. // Not in the region if point is in the hole.
  32119. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  32120. if (contain$2(interiors[k], coord[0], coord[1])) {
  32121. continue loopGeo;
  32122. }
  32123. }
  32124. return true;
  32125. }
  32126. }
  32127. return false;
  32128. };
  32129. /**
  32130. * Transform the raw coords to target bounding.
  32131. * @param x
  32132. * @param y
  32133. * @param width
  32134. * @param height
  32135. */
  32136. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  32137. var rect = this.getBoundingRect();
  32138. var aspect = rect.width / rect.height;
  32139. if (!width) {
  32140. width = aspect * height;
  32141. } else if (!height) {
  32142. height = width / aspect;
  32143. }
  32144. var target = new BoundingRect(x, y, width, height);
  32145. var transform = rect.calculateTransform(target);
  32146. var geometries = this.geometries;
  32147. for (var i = 0; i < geometries.length; i++) {
  32148. var geo = geometries[i];
  32149. if (geo.type === 'polygon') {
  32150. transformPoints(geo.exterior, transform);
  32151. each(geo.interiors, function (interior) {
  32152. transformPoints(interior, transform);
  32153. });
  32154. } else {
  32155. each(geo.points, function (points) {
  32156. transformPoints(points, transform);
  32157. });
  32158. }
  32159. }
  32160. rect = this._rect;
  32161. rect.copy(target); // Update center
  32162. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32163. };
  32164. GeoJSONRegion.prototype.cloneShallow = function (name) {
  32165. name == null && (name = this.name);
  32166. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  32167. newRegion._rect = this._rect;
  32168. newRegion.transformTo = null; // Simply avoid to be called.
  32169. return newRegion;
  32170. };
  32171. return GeoJSONRegion;
  32172. }(Region);
  32173. var GeoSVGRegion =
  32174. /** @class */
  32175. function (_super) {
  32176. __extends(GeoSVGRegion, _super);
  32177. function GeoSVGRegion(name, elOnlyForCalculate) {
  32178. var _this = _super.call(this, name) || this;
  32179. _this.type = 'geoSVG';
  32180. _this._elOnlyForCalculate = elOnlyForCalculate;
  32181. return _this;
  32182. }
  32183. GeoSVGRegion.prototype.calcCenter = function () {
  32184. var el = this._elOnlyForCalculate;
  32185. var rect = el.getBoundingRect();
  32186. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32187. var mat = identity(TMP_TRANSFORM);
  32188. var target = el;
  32189. while (target && !target.isGeoSVGGraphicRoot) {
  32190. mul$1(mat, target.getLocalTransform(), mat);
  32191. target = target.parent;
  32192. }
  32193. invert(mat, mat);
  32194. applyTransform(center, center, mat);
  32195. return center;
  32196. };
  32197. return GeoSVGRegion;
  32198. }(Region);
  32199. function decode(json) {
  32200. if (!json.UTF8Encoding) {
  32201. return json;
  32202. }
  32203. var jsonCompressed = json;
  32204. var encodeScale = jsonCompressed.UTF8Scale;
  32205. if (encodeScale == null) {
  32206. encodeScale = 1024;
  32207. }
  32208. var features = jsonCompressed.features;
  32209. each(features, function (feature) {
  32210. var geometry = feature.geometry;
  32211. var encodeOffsets = geometry.encodeOffsets;
  32212. var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
  32213. // In this case this geometry is usually not encoded.
  32214. if (!encodeOffsets) {
  32215. return;
  32216. }
  32217. switch (geometry.type) {
  32218. case 'LineString':
  32219. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  32220. break;
  32221. case 'Polygon':
  32222. decodeRings(coordinates, encodeOffsets, encodeScale);
  32223. break;
  32224. case 'MultiLineString':
  32225. decodeRings(coordinates, encodeOffsets, encodeScale);
  32226. break;
  32227. case 'MultiPolygon':
  32228. each(coordinates, function (rings, idx) {
  32229. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  32230. });
  32231. }
  32232. }); // Has been decoded
  32233. jsonCompressed.UTF8Encoding = false;
  32234. return jsonCompressed;
  32235. }
  32236. function decodeRings(rings, encodeOffsets, encodeScale) {
  32237. for (var c = 0; c < rings.length; c++) {
  32238. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  32239. }
  32240. }
  32241. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  32242. var result = [];
  32243. var prevX = encodeOffsets[0];
  32244. var prevY = encodeOffsets[1];
  32245. for (var i = 0; i < coordinate.length; i += 2) {
  32246. var x = coordinate.charCodeAt(i) - 64;
  32247. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  32248. x = x >> 1 ^ -(x & 1);
  32249. y = y >> 1 ^ -(y & 1); // Delta deocding
  32250. x += prevX;
  32251. y += prevY;
  32252. prevX = x;
  32253. prevY = y; // Dequantize
  32254. result.push([x / encodeScale, y / encodeScale]);
  32255. }
  32256. return result;
  32257. }
  32258. function parseGeoJSON(geoJson, nameProperty) {
  32259. geoJson = decode(geoJson);
  32260. return map(filter(geoJson.features, function (featureObj) {
  32261. // Output of mapshaper may have geometry null
  32262. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  32263. }), function (featureObj) {
  32264. var properties = featureObj.properties;
  32265. var geo = featureObj.geometry;
  32266. var geometries = [];
  32267. switch (geo.type) {
  32268. case 'Polygon':
  32269. var coordinates = geo.coordinates; // According to the GeoJSON specification.
  32270. // First must be exterior, and the rest are all interior(holes).
  32271. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  32272. break;
  32273. case 'MultiPolygon':
  32274. each(geo.coordinates, function (item) {
  32275. if (item[0]) {
  32276. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  32277. }
  32278. });
  32279. break;
  32280. case 'LineString':
  32281. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  32282. break;
  32283. case 'MultiLineString':
  32284. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  32285. }
  32286. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  32287. region.properties = properties;
  32288. return region;
  32289. });
  32290. }
  32291. var number = /*#__PURE__*/Object.freeze({
  32292. __proto__: null,
  32293. linearMap: linearMap,
  32294. round: round,
  32295. asc: asc,
  32296. getPrecision: getPrecision,
  32297. getPrecisionSafe: getPrecisionSafe,
  32298. getPixelPrecision: getPixelPrecision,
  32299. getPercentWithPrecision: getPercentWithPrecision,
  32300. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  32301. remRadian: remRadian,
  32302. isRadianAroundZero: isRadianAroundZero,
  32303. parseDate: parseDate,
  32304. quantity: quantity,
  32305. quantityExponent: quantityExponent,
  32306. nice: nice,
  32307. quantile: quantile,
  32308. reformIntervals: reformIntervals,
  32309. isNumeric: isNumeric,
  32310. numericToNumber: numericToNumber
  32311. });
  32312. var time = /*#__PURE__*/Object.freeze({
  32313. __proto__: null,
  32314. parse: parseDate,
  32315. format: format
  32316. });
  32317. var graphic$1 = /*#__PURE__*/Object.freeze({
  32318. __proto__: null,
  32319. extendShape: extendShape,
  32320. extendPath: extendPath,
  32321. makePath: makePath,
  32322. makeImage: makeImage,
  32323. mergePath: mergePath$1,
  32324. resizePath: resizePath,
  32325. createIcon: createIcon,
  32326. updateProps: updateProps,
  32327. initProps: initProps,
  32328. getTransform: getTransform,
  32329. clipPointsByRect: clipPointsByRect,
  32330. clipRectByRect: clipRectByRect,
  32331. registerShape: registerShape,
  32332. getShapeClass: getShapeClass,
  32333. Group: Group,
  32334. Image: ZRImage,
  32335. Text: ZRText,
  32336. Circle: Circle,
  32337. Ellipse: Ellipse,
  32338. Sector: Sector,
  32339. Ring: Ring,
  32340. Polygon: Polygon,
  32341. Polyline: Polyline,
  32342. Rect: Rect,
  32343. Line: Line,
  32344. BezierCurve: BezierCurve,
  32345. Arc: Arc,
  32346. IncrementalDisplayable: IncrementalDisplayable,
  32347. CompoundPath: CompoundPath,
  32348. LinearGradient: LinearGradient,
  32349. RadialGradient: RadialGradient,
  32350. BoundingRect: BoundingRect
  32351. });
  32352. var format$1 = /*#__PURE__*/Object.freeze({
  32353. __proto__: null,
  32354. addCommas: addCommas,
  32355. toCamelCase: toCamelCase,
  32356. normalizeCssArray: normalizeCssArray$1,
  32357. encodeHTML: encodeHTML,
  32358. formatTpl: formatTpl,
  32359. getTooltipMarker: getTooltipMarker,
  32360. formatTime: formatTime,
  32361. capitalFirst: capitalFirst,
  32362. truncateText: truncateText,
  32363. getTextRect: getTextRect
  32364. });
  32365. var util$1 = /*#__PURE__*/Object.freeze({
  32366. __proto__: null,
  32367. map: map,
  32368. each: each,
  32369. indexOf: indexOf,
  32370. inherits: inherits,
  32371. reduce: reduce,
  32372. filter: filter,
  32373. bind: bind,
  32374. curry: curry,
  32375. isArray: isArray,
  32376. isString: isString,
  32377. isObject: isObject,
  32378. isFunction: isFunction,
  32379. extend: extend,
  32380. defaults: defaults,
  32381. clone: clone,
  32382. merge: merge
  32383. });
  32384. var inner$5 = makeInner();
  32385. function createAxisLabels(axis) {
  32386. // Only ordinal scale support tick interval
  32387. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  32388. }
  32389. /**
  32390. * @param {module:echats/coord/Axis} axis
  32391. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  32392. * @return {Object} {
  32393. * ticks: Array.<number>
  32394. * tickCategoryInterval: number
  32395. * }
  32396. */
  32397. function createAxisTicks(axis, tickModel) {
  32398. // Only ordinal scale support tick interval
  32399. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  32400. ticks: map(axis.scale.getTicks(), function (tick) {
  32401. return tick.value;
  32402. })
  32403. };
  32404. }
  32405. function makeCategoryLabels(axis) {
  32406. var labelModel = axis.getLabelModel();
  32407. var result = makeCategoryLabelsActually(axis, labelModel);
  32408. return !labelModel.get('show') || axis.scale.isBlank() ? {
  32409. labels: [],
  32410. labelCategoryInterval: result.labelCategoryInterval
  32411. } : result;
  32412. }
  32413. function makeCategoryLabelsActually(axis, labelModel) {
  32414. var labelsCache = getListCache(axis, 'labels');
  32415. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  32416. var result = listCacheGet(labelsCache, optionLabelInterval);
  32417. if (result) {
  32418. return result;
  32419. }
  32420. var labels;
  32421. var numericLabelInterval;
  32422. if (isFunction(optionLabelInterval)) {
  32423. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32424. } else {
  32425. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32426. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32427. } // Cache to avoid calling interval function repeatedly.
  32428. return listCacheSet(labelsCache, optionLabelInterval, {
  32429. labels: labels,
  32430. labelCategoryInterval: numericLabelInterval
  32431. });
  32432. }
  32433. function makeCategoryTicks(axis, tickModel) {
  32434. var ticksCache = getListCache(axis, 'ticks');
  32435. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32436. var result = listCacheGet(ticksCache, optionTickInterval);
  32437. if (result) {
  32438. return result;
  32439. }
  32440. var ticks;
  32441. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  32442. // we should not return all ticks.
  32443. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32444. ticks = [];
  32445. }
  32446. if (isFunction(optionTickInterval)) {
  32447. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32448. } // Always use label interval by default despite label show. Consider this
  32449. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32450. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32451. else if (optionTickInterval === 'auto') {
  32452. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32453. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32454. ticks = map(labelsResult.labels, function (labelItem) {
  32455. return labelItem.tickValue;
  32456. });
  32457. } else {
  32458. tickCategoryInterval = optionTickInterval;
  32459. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32460. } // Cache to avoid calling interval function repeatedly.
  32461. return listCacheSet(ticksCache, optionTickInterval, {
  32462. ticks: ticks,
  32463. tickCategoryInterval: tickCategoryInterval
  32464. });
  32465. }
  32466. function makeRealNumberLabels(axis) {
  32467. var ticks = axis.scale.getTicks();
  32468. var labelFormatter = makeLabelFormatter(axis);
  32469. return {
  32470. labels: map(ticks, function (tick, idx) {
  32471. return {
  32472. level: tick.level,
  32473. formattedLabel: labelFormatter(tick, idx),
  32474. rawLabel: axis.scale.getLabel(tick),
  32475. tickValue: tick.value
  32476. };
  32477. })
  32478. };
  32479. }
  32480. function getListCache(axis, prop) {
  32481. // Because key can be a function, and cache size always is small, we use array cache.
  32482. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  32483. }
  32484. function listCacheGet(cache, key) {
  32485. for (var i = 0; i < cache.length; i++) {
  32486. if (cache[i].key === key) {
  32487. return cache[i].value;
  32488. }
  32489. }
  32490. }
  32491. function listCacheSet(cache, key, value) {
  32492. cache.push({
  32493. key: key,
  32494. value: value
  32495. });
  32496. return value;
  32497. }
  32498. function makeAutoCategoryInterval(axis) {
  32499. var result = inner$5(axis).autoInterval;
  32500. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32501. }
  32502. /**
  32503. * Calculate interval for category axis ticks and labels.
  32504. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32505. * should be implemented in axis.
  32506. */
  32507. function calculateCategoryInterval(axis) {
  32508. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32509. var labelFormatter = makeLabelFormatter(axis);
  32510. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32511. var ordinalScale = axis.scale;
  32512. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  32513. // avoid generating a long array by `getTicks`
  32514. // in large category data case.
  32515. var tickCount = ordinalScale.count();
  32516. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32517. return 0;
  32518. }
  32519. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  32520. if (tickCount > 40) {
  32521. step = Math.max(1, Math.floor(tickCount / 40));
  32522. }
  32523. var tickValue = ordinalExtent[0];
  32524. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32525. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32526. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32527. var maxW = 0;
  32528. var maxH = 0; // Caution: Performance sensitive for large category data.
  32529. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32530. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32531. var width = 0;
  32532. var height = 0; // Not precise, do not consider align and vertical align
  32533. // and each distance from axis line yet.
  32534. var rect = getBoundingRect(labelFormatter({
  32535. value: tickValue
  32536. }), params.font, 'center', 'top'); // Magic number
  32537. width = rect.width * 1.3;
  32538. height = rect.height * 1.3; // Min size, void long loop.
  32539. maxW = Math.max(maxW, width, 7);
  32540. maxH = Math.max(maxH, height, 7);
  32541. }
  32542. var dw = maxW / unitW;
  32543. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  32544. isNaN(dw) && (dw = Infinity);
  32545. isNaN(dh) && (dh = Infinity);
  32546. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32547. var cache = inner$5(axis.model);
  32548. var axisExtent = axis.getExtent();
  32549. var lastAutoInterval = cache.lastAutoInterval;
  32550. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  32551. // otherwise the calculated interval might jitter when the zoom
  32552. // window size is close to the interval-changing size.
  32553. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32554. // The jitter will cause that sometimes the displayed labels are
  32555. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32556. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  32557. // point is not the same when zooming in or zooming out.
  32558. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  32559. // be used. Otherwise some hidden labels might not be shown again.
  32560. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32561. interval = lastAutoInterval;
  32562. } // Only update cache if cache not used, otherwise the
  32563. // changing of interval is too insensitive.
  32564. else {
  32565. cache.lastTickCount = tickCount;
  32566. cache.lastAutoInterval = interval;
  32567. cache.axisExtent0 = axisExtent[0];
  32568. cache.axisExtent1 = axisExtent[1];
  32569. }
  32570. return interval;
  32571. }
  32572. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32573. var labelModel = axis.getLabelModel();
  32574. return {
  32575. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32576. labelRotate: labelModel.get('rotate') || 0,
  32577. font: labelModel.getFont()
  32578. };
  32579. }
  32580. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32581. var labelFormatter = makeLabelFormatter(axis);
  32582. var ordinalScale = axis.scale;
  32583. var ordinalExtent = ordinalScale.getExtent();
  32584. var labelModel = axis.getLabelModel();
  32585. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32586. var step = Math.max((categoryInterval || 0) + 1, 1);
  32587. var startTick = ordinalExtent[0];
  32588. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  32589. // while zooming and moving while interval > 0. Otherwise the selection
  32590. // of displayable ticks and symbols probably keep changing.
  32591. // 3 is empirical value.
  32592. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32593. startTick = Math.round(Math.ceil(startTick / step) * step);
  32594. } // (1) Only add min max label here but leave overlap checking
  32595. // to render stage, which also ensure the returned list
  32596. // suitable for splitLine and splitArea rendering.
  32597. // (2) Scales except category always contain min max label so
  32598. // do not need to perform this process.
  32599. var showAllLabel = shouldShowAllLabels(axis);
  32600. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32601. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32602. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32603. addItem(ordinalExtent[0]);
  32604. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32605. var tickValue = startTick;
  32606. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32607. addItem(tickValue);
  32608. }
  32609. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32610. addItem(ordinalExtent[1]);
  32611. }
  32612. function addItem(tickValue) {
  32613. var tickObj = {
  32614. value: tickValue
  32615. };
  32616. result.push(onlyTick ? tickValue : {
  32617. formattedLabel: labelFormatter(tickObj),
  32618. rawLabel: ordinalScale.getLabel(tickObj),
  32619. tickValue: tickValue
  32620. });
  32621. }
  32622. return result;
  32623. }
  32624. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32625. var ordinalScale = axis.scale;
  32626. var labelFormatter = makeLabelFormatter(axis);
  32627. var result = [];
  32628. each(ordinalScale.getTicks(), function (tick) {
  32629. var rawLabel = ordinalScale.getLabel(tick);
  32630. var tickValue = tick.value;
  32631. if (categoryInterval(tick.value, rawLabel)) {
  32632. result.push(onlyTick ? tickValue : {
  32633. formattedLabel: labelFormatter(tick),
  32634. rawLabel: rawLabel,
  32635. tickValue: tickValue
  32636. });
  32637. }
  32638. });
  32639. return result;
  32640. }
  32641. var NORMALIZED_EXTENT = [0, 1];
  32642. /**
  32643. * Base class of Axis.
  32644. */
  32645. var Axis =
  32646. /** @class */
  32647. function () {
  32648. function Axis(dim, scale, extent) {
  32649. this.onBand = false;
  32650. this.inverse = false;
  32651. this.dim = dim;
  32652. this.scale = scale;
  32653. this._extent = extent || [0, 0];
  32654. }
  32655. /**
  32656. * If axis extent contain given coord
  32657. */
  32658. Axis.prototype.contain = function (coord) {
  32659. var extent = this._extent;
  32660. var min = Math.min(extent[0], extent[1]);
  32661. var max = Math.max(extent[0], extent[1]);
  32662. return coord >= min && coord <= max;
  32663. };
  32664. /**
  32665. * If axis extent contain given data
  32666. */
  32667. Axis.prototype.containData = function (data) {
  32668. return this.scale.contain(data);
  32669. };
  32670. /**
  32671. * Get coord extent.
  32672. */
  32673. Axis.prototype.getExtent = function () {
  32674. return this._extent.slice();
  32675. };
  32676. /**
  32677. * Get precision used for formatting
  32678. */
  32679. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32680. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32681. };
  32682. /**
  32683. * Set coord extent
  32684. */
  32685. Axis.prototype.setExtent = function (start, end) {
  32686. var extent = this._extent;
  32687. extent[0] = start;
  32688. extent[1] = end;
  32689. };
  32690. /**
  32691. * Convert data to coord. Data is the rank if it has an ordinal scale
  32692. */
  32693. Axis.prototype.dataToCoord = function (data, clamp) {
  32694. var extent = this._extent;
  32695. var scale = this.scale;
  32696. data = scale.normalize(data);
  32697. if (this.onBand && scale.type === 'ordinal') {
  32698. extent = extent.slice();
  32699. fixExtentWithBands(extent, scale.count());
  32700. }
  32701. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32702. };
  32703. /**
  32704. * Convert coord to data. Data is the rank if it has an ordinal scale
  32705. */
  32706. Axis.prototype.coordToData = function (coord, clamp) {
  32707. var extent = this._extent;
  32708. var scale = this.scale;
  32709. if (this.onBand && scale.type === 'ordinal') {
  32710. extent = extent.slice();
  32711. fixExtentWithBands(extent, scale.count());
  32712. }
  32713. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32714. return this.scale.scale(t);
  32715. };
  32716. /**
  32717. * Convert pixel point to data in axis
  32718. */
  32719. Axis.prototype.pointToData = function (point, clamp) {
  32720. // Should be implemented in derived class if necessary.
  32721. return;
  32722. };
  32723. /**
  32724. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32725. * `axis.getTicksCoords` considers `onBand`, which is used by
  32726. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32727. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32728. * @param opt.clamp If `true`, the first and the last
  32729. * tick must be at the axis end points. Otherwise, clip ticks
  32730. * that outside the axis extent.
  32731. */
  32732. Axis.prototype.getTicksCoords = function (opt) {
  32733. opt = opt || {};
  32734. var tickModel = opt.tickModel || this.getTickModel();
  32735. var result = createAxisTicks(this, tickModel);
  32736. var ticks = result.ticks;
  32737. var ticksCoords = map(ticks, function (tickVal) {
  32738. return {
  32739. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32740. tickValue: tickVal
  32741. };
  32742. }, this);
  32743. var alignWithLabel = tickModel.get('alignWithLabel');
  32744. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32745. return ticksCoords;
  32746. };
  32747. Axis.prototype.getMinorTicksCoords = function () {
  32748. if (this.scale.type === 'ordinal') {
  32749. // Category axis doesn't support minor ticks
  32750. return [];
  32751. }
  32752. var minorTickModel = this.model.getModel('minorTick');
  32753. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  32754. if (!(splitNumber > 0 && splitNumber < 100)) {
  32755. splitNumber = 5;
  32756. }
  32757. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32758. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32759. return map(minorTicksGroup, function (minorTick) {
  32760. return {
  32761. coord: this.dataToCoord(minorTick),
  32762. tickValue: minorTick
  32763. };
  32764. }, this);
  32765. }, this);
  32766. return minorTicksCoords;
  32767. };
  32768. Axis.prototype.getViewLabels = function () {
  32769. return createAxisLabels(this).labels;
  32770. };
  32771. Axis.prototype.getLabelModel = function () {
  32772. return this.model.getModel('axisLabel');
  32773. };
  32774. /**
  32775. * Notice here we only get the default tick model. For splitLine
  32776. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32777. * manually when calling `getTicksCoords`.
  32778. * In GL, this method may be overridden to:
  32779. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32780. */
  32781. Axis.prototype.getTickModel = function () {
  32782. return this.model.getModel('axisTick');
  32783. };
  32784. /**
  32785. * Get width of band
  32786. */
  32787. Axis.prototype.getBandWidth = function () {
  32788. var axisExtent = this._extent;
  32789. var dataExtent = this.scale.getExtent();
  32790. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  32791. len === 0 && (len = 1);
  32792. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32793. return Math.abs(size) / len;
  32794. };
  32795. /**
  32796. * Only be called in category axis.
  32797. * Can be overridden, consider other axes like in 3D.
  32798. * @return Auto interval for cateogry axis tick and label
  32799. */
  32800. Axis.prototype.calculateCategoryInterval = function () {
  32801. return calculateCategoryInterval(this);
  32802. };
  32803. return Axis;
  32804. }();
  32805. function fixExtentWithBands(extent, nTick) {
  32806. var size = extent[1] - extent[0];
  32807. var len = nTick;
  32808. var margin = size / len / 2;
  32809. extent[0] += margin;
  32810. extent[1] -= margin;
  32811. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32812. // |---1---|---2---|---3---|---4---|.
  32813. // So the displayed ticks and splitLine/splitArea should between
  32814. // each data item, otherwise cause misleading (e.g., split tow bars
  32815. // of a single data item when there are two bar series).
  32816. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32817. // splitLine/spliteArea should layout appropriately corresponding
  32818. // to displayed labels. (So we should not use `getBandWidth` in this
  32819. // case).
  32820. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32821. var ticksLen = ticksCoords.length;
  32822. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32823. return;
  32824. }
  32825. var axisExtent = axis.getExtent();
  32826. var last;
  32827. var diffSize;
  32828. if (ticksLen === 1) {
  32829. ticksCoords[0].coord = axisExtent[0];
  32830. last = ticksCoords[1] = {
  32831. coord: axisExtent[0]
  32832. };
  32833. } else {
  32834. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32835. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32836. each(ticksCoords, function (ticksItem) {
  32837. ticksItem.coord -= shift_1 / 2;
  32838. });
  32839. var dataExtent = axis.scale.getExtent();
  32840. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32841. last = {
  32842. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32843. };
  32844. ticksCoords.push(last);
  32845. }
  32846. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32847. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32848. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32849. }
  32850. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32851. ticksCoords.unshift({
  32852. coord: axisExtent[0]
  32853. });
  32854. }
  32855. if (littleThan(axisExtent[1], last.coord)) {
  32856. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32857. }
  32858. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32859. ticksCoords.push({
  32860. coord: axisExtent[1]
  32861. });
  32862. }
  32863. function littleThan(a, b) {
  32864. // Avoid rounding error cause calculated tick coord different with extent.
  32865. // It may cause an extra unnecessary tick added.
  32866. a = round(a);
  32867. b = round(b);
  32868. return inverse ? a > b : a < b;
  32869. }
  32870. }
  32871. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32872. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32873. // class Bar3DModel extends ComponentModel {}
  32874. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  32875. // echarts.use(install);
  32876. function extendComponentModel(proto) {
  32877. var Model = ComponentModel.extend(proto);
  32878. ComponentModel.registerClass(Model);
  32879. return Model;
  32880. }
  32881. function extendComponentView(proto) {
  32882. var View = ComponentView.extend(proto);
  32883. ComponentView.registerClass(View);
  32884. return View;
  32885. }
  32886. function extendSeriesModel(proto) {
  32887. var Model = SeriesModel.extend(proto);
  32888. SeriesModel.registerClass(Model);
  32889. return Model;
  32890. }
  32891. function extendChartView(proto) {
  32892. var View = ChartView.extend(proto);
  32893. ChartView.registerClass(View);
  32894. return View;
  32895. }
  32896. var PI2$6 = Math.PI * 2;
  32897. var CMD$3 = PathProxy.CMD;
  32898. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  32899. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  32900. var width = rect.width;
  32901. var height = rect.height;
  32902. switch (pos) {
  32903. case 'top':
  32904. outPt.set(rect.x + width / 2, rect.y - distance);
  32905. outDir.set(0, -1);
  32906. break;
  32907. case 'bottom':
  32908. outPt.set(rect.x + width / 2, rect.y + height + distance);
  32909. outDir.set(0, 1);
  32910. break;
  32911. case 'left':
  32912. outPt.set(rect.x - distance, rect.y + height / 2);
  32913. outDir.set(-1, 0);
  32914. break;
  32915. case 'right':
  32916. outPt.set(rect.x + width + distance, rect.y + height / 2);
  32917. outDir.set(1, 0);
  32918. break;
  32919. }
  32920. }
  32921. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  32922. x -= cx;
  32923. y -= cy;
  32924. var d = Math.sqrt(x * x + y * y);
  32925. x /= d;
  32926. y /= d; // Intersect point.
  32927. var ox = x * r + cx;
  32928. var oy = y * r + cy;
  32929. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  32930. // Is a circle
  32931. out[0] = ox;
  32932. out[1] = oy;
  32933. return d - r;
  32934. }
  32935. if (anticlockwise) {
  32936. var tmp = startAngle;
  32937. startAngle = normalizeRadian(endAngle);
  32938. endAngle = normalizeRadian(tmp);
  32939. } else {
  32940. startAngle = normalizeRadian(startAngle);
  32941. endAngle = normalizeRadian(endAngle);
  32942. }
  32943. if (startAngle > endAngle) {
  32944. endAngle += PI2$6;
  32945. }
  32946. var angle = Math.atan2(y, x);
  32947. if (angle < 0) {
  32948. angle += PI2$6;
  32949. }
  32950. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  32951. // Project point is on the arc.
  32952. out[0] = ox;
  32953. out[1] = oy;
  32954. return d - r;
  32955. }
  32956. var x1 = r * Math.cos(startAngle) + cx;
  32957. var y1 = r * Math.sin(startAngle) + cy;
  32958. var x2 = r * Math.cos(endAngle) + cx;
  32959. var y2 = r * Math.sin(endAngle) + cy;
  32960. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  32961. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  32962. if (d1 < d2) {
  32963. out[0] = x1;
  32964. out[1] = y1;
  32965. return Math.sqrt(d1);
  32966. } else {
  32967. out[0] = x2;
  32968. out[1] = y2;
  32969. return Math.sqrt(d2);
  32970. }
  32971. }
  32972. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  32973. var dx = x - x1;
  32974. var dy = y - y1;
  32975. var dx1 = x2 - x1;
  32976. var dy1 = y2 - y1;
  32977. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  32978. dx1 /= lineLen;
  32979. dy1 /= lineLen; // dot product
  32980. var projectedLen = dx * dx1 + dy * dy1;
  32981. var t = projectedLen / lineLen;
  32982. if (limitToEnds) {
  32983. t = Math.min(Math.max(t, 0), 1);
  32984. }
  32985. t *= lineLen;
  32986. var ox = out[0] = x1 + t * dx1;
  32987. var oy = out[1] = y1 + t * dy1;
  32988. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  32989. }
  32990. function projectPointToRect(x1, y1, width, height, x, y, out) {
  32991. if (width < 0) {
  32992. x1 = x1 + width;
  32993. width = -width;
  32994. }
  32995. if (height < 0) {
  32996. y1 = y1 + height;
  32997. height = -height;
  32998. }
  32999. var x2 = x1 + width;
  33000. var y2 = y1 + height;
  33001. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  33002. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  33003. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33004. }
  33005. var tmpPt = [];
  33006. function nearestPointOnRect(pt, rect, out) {
  33007. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  33008. out.set(tmpPt[0], tmpPt[1]);
  33009. return dist;
  33010. }
  33011. /**
  33012. * Calculate min distance corresponding point.
  33013. * This method won't evaluate if point is in the path.
  33014. */
  33015. function nearestPointOnPath(pt, path, out) {
  33016. var xi = 0;
  33017. var yi = 0;
  33018. var x0 = 0;
  33019. var y0 = 0;
  33020. var x1;
  33021. var y1;
  33022. var minDist = Infinity;
  33023. var data = path.data;
  33024. var x = pt.x;
  33025. var y = pt.y;
  33026. for (var i = 0; i < data.length;) {
  33027. var cmd = data[i++];
  33028. if (i === 1) {
  33029. xi = data[i];
  33030. yi = data[i + 1];
  33031. x0 = xi;
  33032. y0 = yi;
  33033. }
  33034. var d = minDist;
  33035. switch (cmd) {
  33036. case CMD$3.M:
  33037. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  33038. // 在 closePath 的时候使用
  33039. x0 = data[i++];
  33040. y0 = data[i++];
  33041. xi = x0;
  33042. yi = y0;
  33043. break;
  33044. case CMD$3.L:
  33045. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  33046. xi = data[i++];
  33047. yi = data[i++];
  33048. break;
  33049. case CMD$3.C:
  33050. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33051. xi = data[i++];
  33052. yi = data[i++];
  33053. break;
  33054. case CMD$3.Q:
  33055. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33056. xi = data[i++];
  33057. yi = data[i++];
  33058. break;
  33059. case CMD$3.A:
  33060. // TODO Arc 判断的开销比较大
  33061. var cx = data[i++];
  33062. var cy = data[i++];
  33063. var rx = data[i++];
  33064. var ry = data[i++];
  33065. var theta = data[i++];
  33066. var dTheta = data[i++]; // TODO Arc 旋转
  33067. i += 1;
  33068. var anticlockwise = !!(1 - data[i++]);
  33069. x1 = Math.cos(theta) * rx + cx;
  33070. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  33071. if (i <= 1) {
  33072. // 第一个命令起点还未定义
  33073. x0 = x1;
  33074. y0 = y1;
  33075. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  33076. var _x = (x - cx) * ry / rx + cx;
  33077. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  33078. xi = Math.cos(theta + dTheta) * rx + cx;
  33079. yi = Math.sin(theta + dTheta) * ry + cy;
  33080. break;
  33081. case CMD$3.R:
  33082. x0 = xi = data[i++];
  33083. y0 = yi = data[i++];
  33084. var width = data[i++];
  33085. var height = data[i++];
  33086. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  33087. break;
  33088. case CMD$3.Z:
  33089. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  33090. xi = x0;
  33091. yi = y0;
  33092. break;
  33093. }
  33094. if (d < minDist) {
  33095. minDist = d;
  33096. out.set(tmpPt[0], tmpPt[1]);
  33097. }
  33098. }
  33099. return minDist;
  33100. } // Temporal variable for intermediate usage.
  33101. var pt0 = new Point();
  33102. var pt1 = new Point();
  33103. var pt2 = new Point();
  33104. var dir = new Point();
  33105. var dir2 = new Point();
  33106. /**
  33107. * Calculate a proper guide line based on the label position and graphic element definition
  33108. * @param label
  33109. * @param labelRect
  33110. * @param target
  33111. * @param targetRect
  33112. */
  33113. function updateLabelLinePoints(target, labelLineModel) {
  33114. if (!target) {
  33115. return;
  33116. }
  33117. var labelLine = target.getTextGuideLine();
  33118. var label = target.getTextContent(); // Needs to create text guide in each charts.
  33119. if (!(label && labelLine)) {
  33120. return;
  33121. }
  33122. var labelGuideConfig = target.textGuideLineConfig || {};
  33123. var points = [[0, 0], [0, 0], [0, 0]];
  33124. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  33125. var labelRect = label.getBoundingRect().clone();
  33126. labelRect.applyTransform(label.getComputedTransform());
  33127. var minDist = Infinity;
  33128. var anchorPoint = labelGuideConfig.anchor;
  33129. var targetTransform = target.getComputedTransform();
  33130. var targetInversedTransform = targetTransform && invert([], targetTransform);
  33131. var len = labelLineModel.get('length2') || 0;
  33132. if (anchorPoint) {
  33133. pt2.copy(anchorPoint);
  33134. }
  33135. for (var i = 0; i < searchSpace.length; i++) {
  33136. var candidate = searchSpace[i];
  33137. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  33138. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  33139. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  33140. var boundingRect = target.getBoundingRect();
  33141. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  33142. if (dist < minDist) {
  33143. minDist = dist; // Transform back to global space.
  33144. pt1.transform(targetTransform);
  33145. pt2.transform(targetTransform);
  33146. pt2.toArray(points[0]);
  33147. pt1.toArray(points[1]);
  33148. pt0.toArray(points[2]);
  33149. }
  33150. }
  33151. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  33152. labelLine.setShape({
  33153. points: points
  33154. });
  33155. } // Temporal variable for the limitTurnAngle function
  33156. var tmpArr = [];
  33157. var tmpProjPoint = new Point();
  33158. /**
  33159. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  33160. * @param linePoints
  33161. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  33162. */
  33163. function limitTurnAngle(linePoints, minTurnAngle) {
  33164. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  33165. return;
  33166. }
  33167. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  33168. // /pt1----pt2 (label)
  33169. // /
  33170. // pt0/
  33171. pt0.fromArray(linePoints[0]);
  33172. pt1.fromArray(linePoints[1]);
  33173. pt2.fromArray(linePoints[2]);
  33174. Point.sub(dir, pt0, pt1);
  33175. Point.sub(dir2, pt2, pt1);
  33176. var len1 = dir.len();
  33177. var len2 = dir2.len();
  33178. if (len1 < 1e-3 || len2 < 1e-3) {
  33179. return;
  33180. }
  33181. dir.scale(1 / len1);
  33182. dir2.scale(1 / len2);
  33183. var angleCos = dir.dot(dir2);
  33184. var minTurnAngleCos = Math.cos(minTurnAngle);
  33185. if (minTurnAngleCos < angleCos) {
  33186. // Smaller than minTurnAngle
  33187. // Calculate project point of pt0 on pt1-pt2
  33188. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33189. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  33190. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33191. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33192. if (isNaN(t)) {
  33193. return;
  33194. }
  33195. if (t < 0) {
  33196. Point.copy(tmpProjPoint, pt1);
  33197. } else if (t > 1) {
  33198. Point.copy(tmpProjPoint, pt2);
  33199. }
  33200. tmpProjPoint.toArray(linePoints[1]);
  33201. }
  33202. }
  33203. /**
  33204. * Limit the angle of line and the surface
  33205. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  33206. */
  33207. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  33208. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  33209. return;
  33210. }
  33211. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  33212. pt0.fromArray(linePoints[0]);
  33213. pt1.fromArray(linePoints[1]);
  33214. pt2.fromArray(linePoints[2]);
  33215. Point.sub(dir, pt1, pt0);
  33216. Point.sub(dir2, pt2, pt1);
  33217. var len1 = dir.len();
  33218. var len2 = dir2.len();
  33219. if (len1 < 1e-3 || len2 < 1e-3) {
  33220. return;
  33221. }
  33222. dir.scale(1 / len1);
  33223. dir2.scale(1 / len2);
  33224. var angleCos = dir.dot(surfaceNormal);
  33225. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  33226. if (angleCos < maxSurfaceAngleCos) {
  33227. // Calculate project point of pt0 on pt1-pt2
  33228. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33229. tmpProjPoint.fromArray(tmpArr);
  33230. var HALF_PI = Math.PI / 2;
  33231. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  33232. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  33233. if (newAngle >= HALF_PI) {
  33234. // parallel
  33235. Point.copy(tmpProjPoint, pt2);
  33236. } else {
  33237. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33238. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33239. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33240. if (isNaN(t)) {
  33241. return;
  33242. }
  33243. if (t < 0) {
  33244. Point.copy(tmpProjPoint, pt1);
  33245. } else if (t > 1) {
  33246. Point.copy(tmpProjPoint, pt2);
  33247. }
  33248. }
  33249. tmpProjPoint.toArray(linePoints[1]);
  33250. }
  33251. }
  33252. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  33253. var isNormal = stateName === 'normal';
  33254. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  33255. stateObj.ignore = ignore; // Set smooth
  33256. var smooth = stateModel.get('smooth');
  33257. if (smooth && smooth === true) {
  33258. smooth = 0.3;
  33259. }
  33260. stateObj.shape = stateObj.shape || {};
  33261. if (smooth > 0) {
  33262. stateObj.shape.smooth = smooth;
  33263. }
  33264. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  33265. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  33266. }
  33267. function buildLabelLinePath(path, shape) {
  33268. var smooth = shape.smooth;
  33269. var points = shape.points;
  33270. if (!points) {
  33271. return;
  33272. }
  33273. path.moveTo(points[0][0], points[0][1]);
  33274. if (smooth > 0 && points.length >= 3) {
  33275. var len1 = dist(points[0], points[1]);
  33276. var len2 = dist(points[1], points[2]);
  33277. if (!len1 || !len2) {
  33278. path.lineTo(points[1][0], points[1][1]);
  33279. path.lineTo(points[2][0], points[2][1]);
  33280. return;
  33281. }
  33282. var moveLen = Math.min(len1, len2) * smooth;
  33283. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  33284. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  33285. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  33286. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  33287. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  33288. } else {
  33289. for (var i = 1; i < points.length; i++) {
  33290. path.lineTo(points[i][0], points[i][1]);
  33291. }
  33292. }
  33293. }
  33294. /**
  33295. * Create a label line if necessary and set it's style.
  33296. */
  33297. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  33298. var labelLine = targetEl.getTextGuideLine();
  33299. var label = targetEl.getTextContent();
  33300. if (!label) {
  33301. // Not show label line if there is no label.
  33302. if (labelLine) {
  33303. targetEl.removeTextGuideLine();
  33304. }
  33305. return;
  33306. }
  33307. var normalModel = statesModels.normal;
  33308. var showNormal = normalModel.get('show');
  33309. var labelIgnoreNormal = label.ignore;
  33310. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  33311. var stateName = DISPLAY_STATES[i];
  33312. var stateModel = statesModels[stateName];
  33313. var isNormal = stateName === 'normal';
  33314. if (stateModel) {
  33315. var stateShow = stateModel.get('show');
  33316. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  33317. if (isLabelIgnored // Not show when label is not shown in this state.
  33318. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  33319. ) {
  33320. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  33321. if (stateObj) {
  33322. stateObj.ignore = true;
  33323. }
  33324. continue;
  33325. } // Create labelLine if not exists
  33326. if (!labelLine) {
  33327. labelLine = new Polyline();
  33328. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  33329. // NOTE: NORMAL should always been the first!
  33330. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  33331. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  33332. } // Use same state proxy.
  33333. if (targetEl.stateProxy) {
  33334. labelLine.stateProxy = targetEl.stateProxy;
  33335. }
  33336. }
  33337. setLabelLineState(labelLine, false, stateName, stateModel);
  33338. }
  33339. }
  33340. if (labelLine) {
  33341. defaults(labelLine.style, defaultStyle); // Not fill.
  33342. labelLine.style.fill = null;
  33343. var showAbove = normalModel.get('showAbove');
  33344. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  33345. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  33346. labelLine.buildPath = buildLabelLinePath;
  33347. }
  33348. }
  33349. function getLabelLineStatesModels(itemModel, labelLineName) {
  33350. labelLineName = labelLineName || 'labelLine';
  33351. var statesModels = {
  33352. normal: itemModel.getModel(labelLineName)
  33353. };
  33354. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  33355. var stateName = SPECIAL_STATES[i];
  33356. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  33357. }
  33358. return statesModels;
  33359. }
  33360. function prepareLayoutList(input) {
  33361. var list = [];
  33362. for (var i = 0; i < input.length; i++) {
  33363. var rawItem = input[i];
  33364. if (rawItem.defaultAttr.ignore) {
  33365. continue;
  33366. }
  33367. var label = rawItem.label;
  33368. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  33369. var localRect = label.getBoundingRect();
  33370. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  33371. var minMargin = label.style.margin || 0;
  33372. var globalRect = localRect.clone();
  33373. globalRect.applyTransform(transform);
  33374. globalRect.x -= minMargin / 2;
  33375. globalRect.y -= minMargin / 2;
  33376. globalRect.width += minMargin;
  33377. globalRect.height += minMargin;
  33378. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  33379. list.push({
  33380. label: label,
  33381. labelLine: rawItem.labelLine,
  33382. rect: globalRect,
  33383. localRect: localRect,
  33384. obb: obb,
  33385. priority: rawItem.priority,
  33386. defaultAttr: rawItem.defaultAttr,
  33387. layoutOption: rawItem.computedLayoutOption,
  33388. axisAligned: isAxisAligned,
  33389. transform: transform
  33390. });
  33391. }
  33392. return list;
  33393. }
  33394. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  33395. var len = list.length;
  33396. if (len < 2) {
  33397. return;
  33398. }
  33399. list.sort(function (a, b) {
  33400. return a.rect[xyDim] - b.rect[xyDim];
  33401. });
  33402. var lastPos = 0;
  33403. var delta;
  33404. var adjusted = false;
  33405. var totalShifts = 0;
  33406. for (var i = 0; i < len; i++) {
  33407. var item = list[i];
  33408. var rect = item.rect;
  33409. delta = rect[xyDim] - lastPos;
  33410. if (delta < 0) {
  33411. // shiftForward(i, len, -delta);
  33412. rect[xyDim] -= delta;
  33413. item.label[xyDim] -= delta;
  33414. adjusted = true;
  33415. }
  33416. var shift = Math.max(-delta, 0);
  33417. totalShifts += shift;
  33418. lastPos = rect[xyDim] + rect[sizeDim];
  33419. }
  33420. if (totalShifts > 0 && balanceShift) {
  33421. // Shift back to make the distribution more equally.
  33422. shiftList(-totalShifts / len, 0, len);
  33423. } // TODO bleedMargin?
  33424. var first = list[0];
  33425. var last = list[len - 1];
  33426. var minGap;
  33427. var maxGap;
  33428. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  33429. minGap < 0 && squeezeGaps(-minGap, 0.8);
  33430. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  33431. updateMinMaxGap();
  33432. takeBoundsGap(minGap, maxGap, 1);
  33433. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  33434. updateMinMaxGap();
  33435. if (minGap < 0) {
  33436. squeezeWhenBailout(-minGap);
  33437. }
  33438. if (maxGap < 0) {
  33439. squeezeWhenBailout(maxGap);
  33440. }
  33441. function updateMinMaxGap() {
  33442. minGap = first.rect[xyDim] - minBound;
  33443. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  33444. }
  33445. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  33446. if (gapThisBound < 0) {
  33447. // Move from other gap if can.
  33448. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  33449. if (moveFromMaxGap > 0) {
  33450. shiftList(moveFromMaxGap * moveDir, 0, len);
  33451. var remained = moveFromMaxGap + gapThisBound;
  33452. if (remained < 0) {
  33453. squeezeGaps(-remained * moveDir, 1);
  33454. }
  33455. } else {
  33456. squeezeGaps(-gapThisBound * moveDir, 1);
  33457. }
  33458. }
  33459. }
  33460. function shiftList(delta, start, end) {
  33461. if (delta !== 0) {
  33462. adjusted = true;
  33463. }
  33464. for (var i = start; i < end; i++) {
  33465. var item = list[i];
  33466. var rect = item.rect;
  33467. rect[xyDim] += delta;
  33468. item.label[xyDim] += delta;
  33469. }
  33470. } // Squeeze gaps if the labels exceed margin.
  33471. function squeezeGaps(delta, maxSqeezePercent) {
  33472. var gaps = [];
  33473. var totalGaps = 0;
  33474. for (var i = 1; i < len; i++) {
  33475. var prevItemRect = list[i - 1].rect;
  33476. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  33477. gaps.push(gap);
  33478. totalGaps += gap;
  33479. }
  33480. if (!totalGaps) {
  33481. return;
  33482. }
  33483. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  33484. if (delta > 0) {
  33485. for (var i = 0; i < len - 1; i++) {
  33486. // Distribute the shift delta to all gaps.
  33487. var movement = gaps[i] * squeezePercent; // Forward
  33488. shiftList(movement, 0, i + 1);
  33489. }
  33490. } else {
  33491. // Backward
  33492. for (var i = len - 1; i > 0; i--) {
  33493. // Distribute the shift delta to all gaps.
  33494. var movement = gaps[i - 1] * squeezePercent;
  33495. shiftList(-movement, i, len);
  33496. }
  33497. }
  33498. }
  33499. /**
  33500. * Squeeze to allow overlap if there is no more space available.
  33501. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  33502. */
  33503. function squeezeWhenBailout(delta) {
  33504. var dir = delta < 0 ? -1 : 1;
  33505. delta = Math.abs(delta);
  33506. var moveForEachLabel = Math.ceil(delta / (len - 1));
  33507. for (var i = 0; i < len - 1; i++) {
  33508. if (dir > 0) {
  33509. // Forward
  33510. shiftList(moveForEachLabel, 0, i + 1);
  33511. } else {
  33512. // Backward
  33513. shiftList(-moveForEachLabel, len - i - 1, len);
  33514. }
  33515. delta -= moveForEachLabel;
  33516. if (delta <= 0) {
  33517. return;
  33518. }
  33519. }
  33520. }
  33521. return adjusted;
  33522. }
  33523. /**
  33524. * Adjust labels on x direction to avoid overlap.
  33525. */
  33526. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  33527. // TODO: Not sure if should enable it.
  33528. // Pros: The angle of lines will distribute more equally
  33529. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  33530. balanceShift) {
  33531. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  33532. }
  33533. /**
  33534. * Adjust labels on y direction to avoid overlap.
  33535. */
  33536. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  33537. balanceShift) {
  33538. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  33539. }
  33540. function hideOverlap(labelList) {
  33541. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  33542. labelList.sort(function (a, b) {
  33543. return b.priority - a.priority;
  33544. });
  33545. var globalRect = new BoundingRect(0, 0, 0, 0);
  33546. function hideEl(el) {
  33547. if (!el.ignore) {
  33548. // Show on emphasis.
  33549. var emphasisState = el.ensureState('emphasis');
  33550. if (emphasisState.ignore == null) {
  33551. emphasisState.ignore = false;
  33552. }
  33553. }
  33554. el.ignore = true;
  33555. }
  33556. for (var i = 0; i < labelList.length; i++) {
  33557. var labelItem = labelList[i];
  33558. var isAxisAligned = labelItem.axisAligned;
  33559. var localRect = labelItem.localRect;
  33560. var transform = labelItem.transform;
  33561. var label = labelItem.label;
  33562. var labelLine = labelItem.labelLine;
  33563. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  33564. globalRect.width -= 0.1;
  33565. globalRect.height -= 0.1;
  33566. globalRect.x += 0.05;
  33567. globalRect.y += 0.05;
  33568. var obb = labelItem.obb;
  33569. var overlapped = false;
  33570. for (var j = 0; j < displayedLabels.length; j++) {
  33571. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  33572. if (!globalRect.intersect(existsTextCfg.rect)) {
  33573. continue;
  33574. }
  33575. if (isAxisAligned && existsTextCfg.axisAligned) {
  33576. // Is overlapped
  33577. overlapped = true;
  33578. break;
  33579. }
  33580. if (!existsTextCfg.obb) {
  33581. // If self is not axis aligned. But other is.
  33582. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  33583. }
  33584. if (!obb) {
  33585. // If self is axis aligned. But other is not.
  33586. obb = new OrientedBoundingRect(localRect, transform);
  33587. }
  33588. if (obb.intersect(existsTextCfg.obb)) {
  33589. overlapped = true;
  33590. break;
  33591. }
  33592. } // TODO Callback to determine if this overlap should be handled?
  33593. if (overlapped) {
  33594. hideEl(label);
  33595. labelLine && hideEl(labelLine);
  33596. } else {
  33597. label.attr('ignore', labelItem.defaultAttr.ignore);
  33598. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  33599. displayedLabels.push(labelItem);
  33600. }
  33601. }
  33602. }
  33603. function cloneArr(points) {
  33604. if (points) {
  33605. var newPoints = [];
  33606. for (var i = 0; i < points.length; i++) {
  33607. newPoints.push(points[i].slice());
  33608. }
  33609. return newPoints;
  33610. }
  33611. }
  33612. function prepareLayoutCallbackParams(labelItem, hostEl) {
  33613. var label = labelItem.label;
  33614. var labelLine = hostEl && hostEl.getTextGuideLine();
  33615. return {
  33616. dataIndex: labelItem.dataIndex,
  33617. dataType: labelItem.dataType,
  33618. seriesIndex: labelItem.seriesModel.seriesIndex,
  33619. text: labelItem.label.style.text,
  33620. rect: labelItem.hostRect,
  33621. labelRect: labelItem.rect,
  33622. // x: labelAttr.x,
  33623. // y: labelAttr.y,
  33624. align: label.style.align,
  33625. verticalAlign: label.style.verticalAlign,
  33626. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  33627. };
  33628. }
  33629. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  33630. var dummyTransformable = new Transformable();
  33631. var labelLayoutInnerStore = makeInner();
  33632. var labelLineAnimationStore = makeInner();
  33633. function extendWithKeys(target, source, keys) {
  33634. for (var i = 0; i < keys.length; i++) {
  33635. var key = keys[i];
  33636. if (source[key] != null) {
  33637. target[key] = source[key];
  33638. }
  33639. }
  33640. }
  33641. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  33642. var LabelManager =
  33643. /** @class */
  33644. function () {
  33645. function LabelManager() {
  33646. this._labelList = [];
  33647. this._chartViewList = [];
  33648. }
  33649. LabelManager.prototype.clearLabels = function () {
  33650. this._labelList = [];
  33651. this._chartViewList = [];
  33652. };
  33653. /**
  33654. * Add label to manager
  33655. */
  33656. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  33657. var labelStyle = label.style;
  33658. var hostEl = label.__hostTarget;
  33659. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  33660. var labelTransform = label.getComputedTransform();
  33661. var labelRect = label.getBoundingRect().plain();
  33662. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  33663. if (labelTransform) {
  33664. dummyTransformable.setLocalTransform(labelTransform);
  33665. } else {
  33666. // Identity transform.
  33667. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  33668. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  33669. }
  33670. var host = label.__hostTarget;
  33671. var hostRect;
  33672. if (host) {
  33673. hostRect = host.getBoundingRect().plain();
  33674. var transform = host.getComputedTransform();
  33675. BoundingRect.applyTransform(hostRect, hostRect, transform);
  33676. }
  33677. var labelGuide = hostRect && host.getTextGuideLine();
  33678. this._labelList.push({
  33679. label: label,
  33680. labelLine: labelGuide,
  33681. seriesModel: seriesModel,
  33682. dataIndex: dataIndex,
  33683. dataType: dataType,
  33684. layoutOption: layoutOption,
  33685. computedLayoutOption: null,
  33686. rect: labelRect,
  33687. hostRect: hostRect,
  33688. // Label with lower priority will be hidden when overlapped
  33689. // Use rect size as default priority
  33690. priority: hostRect ? hostRect.width * hostRect.height : 0,
  33691. // Save default label attributes.
  33692. // For restore if developers want get back to default value in callback.
  33693. defaultAttr: {
  33694. ignore: label.ignore,
  33695. labelGuideIgnore: labelGuide && labelGuide.ignore,
  33696. x: dummyTransformable.x,
  33697. y: dummyTransformable.y,
  33698. scaleX: dummyTransformable.scaleX,
  33699. scaleY: dummyTransformable.scaleY,
  33700. rotation: dummyTransformable.rotation,
  33701. style: {
  33702. x: labelStyle.x,
  33703. y: labelStyle.y,
  33704. align: labelStyle.align,
  33705. verticalAlign: labelStyle.verticalAlign,
  33706. width: labelStyle.width,
  33707. height: labelStyle.height,
  33708. fontSize: labelStyle.fontSize
  33709. },
  33710. cursor: label.cursor,
  33711. attachedPos: textConfig.position,
  33712. attachedRot: textConfig.rotation
  33713. }
  33714. });
  33715. };
  33716. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  33717. var _this = this;
  33718. this._chartViewList.push(chartView);
  33719. var seriesModel = chartView.__model;
  33720. var layoutOption = seriesModel.get('labelLayout');
  33721. /**
  33722. * Ignore layouting if it's not specified anything.
  33723. */
  33724. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  33725. return;
  33726. }
  33727. chartView.group.traverse(function (child) {
  33728. if (child.ignore) {
  33729. return true; // Stop traverse descendants.
  33730. } // Only support label being hosted on graphic elements.
  33731. var textEl = child.getTextContent();
  33732. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  33733. if (textEl && !textEl.disableLabelLayout) {
  33734. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  33735. }
  33736. });
  33737. };
  33738. LabelManager.prototype.updateLayoutConfig = function (api) {
  33739. var width = api.getWidth();
  33740. var height = api.getHeight();
  33741. function createDragHandler(el, labelLineModel) {
  33742. return function () {
  33743. updateLabelLinePoints(el, labelLineModel);
  33744. };
  33745. }
  33746. for (var i = 0; i < this._labelList.length; i++) {
  33747. var labelItem = this._labelList[i];
  33748. var label = labelItem.label;
  33749. var hostEl = label.__hostTarget;
  33750. var defaultLabelAttr = labelItem.defaultAttr;
  33751. var layoutOption = void 0; // TODO A global layout option?
  33752. if (isFunction(labelItem.layoutOption)) {
  33753. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  33754. } else {
  33755. layoutOption = labelItem.layoutOption;
  33756. }
  33757. layoutOption = layoutOption || {};
  33758. labelItem.computedLayoutOption = layoutOption;
  33759. var degreeToRadian = Math.PI / 180; // TODO hostEl should always exists.
  33760. // Or label should not have parent because the x, y is all in global space.
  33761. if (hostEl) {
  33762. hostEl.setTextConfig({
  33763. // Force to set local false.
  33764. local: false,
  33765. // Ignore position and rotation config on the host el if x or y is changed.
  33766. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  33767. // Ignore rotation config on the host el if rotation is changed.
  33768. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  33769. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  33770. });
  33771. }
  33772. var needsUpdateLabelLine = false;
  33773. if (layoutOption.x != null) {
  33774. // TODO width of chart view.
  33775. label.x = parsePercent$1(layoutOption.x, width);
  33776. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  33777. needsUpdateLabelLine = true;
  33778. } else {
  33779. label.x = defaultLabelAttr.x;
  33780. label.setStyle('x', defaultLabelAttr.style.x);
  33781. }
  33782. if (layoutOption.y != null) {
  33783. // TODO height of chart view.
  33784. label.y = parsePercent$1(layoutOption.y, height);
  33785. label.setStyle('y', 0); // Ignore movement in style.
  33786. needsUpdateLabelLine = true;
  33787. } else {
  33788. label.y = defaultLabelAttr.y;
  33789. label.setStyle('y', defaultLabelAttr.style.y);
  33790. }
  33791. if (layoutOption.labelLinePoints) {
  33792. var guideLine = hostEl.getTextGuideLine();
  33793. if (guideLine) {
  33794. guideLine.setShape({
  33795. points: layoutOption.labelLinePoints
  33796. }); // Not update
  33797. needsUpdateLabelLine = false;
  33798. }
  33799. }
  33800. var labelLayoutStore = labelLayoutInnerStore(label);
  33801. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  33802. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  33803. label.scaleX = defaultLabelAttr.scaleX;
  33804. label.scaleY = defaultLabelAttr.scaleY;
  33805. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  33806. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  33807. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  33808. }
  33809. if (layoutOption.draggable) {
  33810. label.draggable = true;
  33811. label.cursor = 'move';
  33812. if (hostEl) {
  33813. var hostModel = labelItem.seriesModel;
  33814. if (labelItem.dataIndex != null) {
  33815. var data = labelItem.seriesModel.getData(labelItem.dataType);
  33816. hostModel = data.getItemModel(labelItem.dataIndex);
  33817. }
  33818. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  33819. }
  33820. } else {
  33821. // TODO Other drag functions?
  33822. label.off('drag');
  33823. label.cursor = defaultLabelAttr.cursor;
  33824. }
  33825. }
  33826. };
  33827. LabelManager.prototype.layout = function (api) {
  33828. var width = api.getWidth();
  33829. var height = api.getHeight();
  33830. var labelList = prepareLayoutList(this._labelList);
  33831. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  33832. return item.layoutOption.moveOverlap === 'shiftX';
  33833. });
  33834. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  33835. return item.layoutOption.moveOverlap === 'shiftY';
  33836. });
  33837. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  33838. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  33839. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  33840. return item.layoutOption.hideOverlap;
  33841. });
  33842. hideOverlap(labelsNeedsHideOverlap);
  33843. };
  33844. /**
  33845. * Process all labels. Not only labels with layoutOption.
  33846. */
  33847. LabelManager.prototype.processLabelsOverall = function () {
  33848. var _this = this;
  33849. each(this._chartViewList, function (chartView) {
  33850. var seriesModel = chartView.__model;
  33851. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  33852. var animationEnabled = seriesModel.isAnimationEnabled();
  33853. chartView.group.traverse(function (child) {
  33854. if (child.ignore && !child.forceLabelAnimation) {
  33855. return true; // Stop traverse descendants.
  33856. }
  33857. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  33858. var label = child.getTextContent();
  33859. if (!needsUpdateLabelLine && label) {
  33860. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  33861. }
  33862. if (needsUpdateLabelLine) {
  33863. _this._updateLabelLine(child, seriesModel);
  33864. }
  33865. if (animationEnabled) {
  33866. _this._animateLabels(child, seriesModel);
  33867. }
  33868. });
  33869. });
  33870. };
  33871. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  33872. // Only support label being hosted on graphic elements.
  33873. var textEl = el.getTextContent(); // Update label line style.
  33874. var ecData = getECData(el);
  33875. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  33876. if (textEl && dataIndex != null) {
  33877. var data = seriesModel.getData(ecData.dataType);
  33878. var itemModel = data.getItemModel(dataIndex);
  33879. var defaultStyle = {};
  33880. var visualStyle = data.getItemVisual(dataIndex, 'style');
  33881. var visualType = data.getVisual('drawType'); // Default to be same with main color
  33882. defaultStyle.stroke = visualStyle[visualType];
  33883. var labelLineModel = itemModel.getModel('labelLine');
  33884. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  33885. updateLabelLinePoints(el, labelLineModel);
  33886. }
  33887. };
  33888. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  33889. var textEl = el.getTextContent();
  33890. var guideLine = el.getTextGuideLine(); // Animate
  33891. if (textEl // `forceLabelAnimation` has the highest priority
  33892. && (el.forceLabelAnimation || !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el))) {
  33893. var layoutStore = labelLayoutInnerStore(textEl);
  33894. var oldLayout = layoutStore.oldLayout;
  33895. var ecData = getECData(el);
  33896. var dataIndex = ecData.dataIndex;
  33897. var newProps = {
  33898. x: textEl.x,
  33899. y: textEl.y,
  33900. rotation: textEl.rotation
  33901. };
  33902. var data = seriesModel.getData(ecData.dataType);
  33903. if (!oldLayout) {
  33904. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  33905. if (!labelInner(textEl).valueAnimation) {
  33906. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  33907. textEl.style.opacity = 0;
  33908. initProps(textEl, {
  33909. style: {
  33910. opacity: oldOpacity
  33911. }
  33912. }, seriesModel, dataIndex);
  33913. }
  33914. } else {
  33915. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  33916. var prevStates = el.prevStates;
  33917. if (prevStates) {
  33918. if (indexOf(prevStates, 'select') >= 0) {
  33919. textEl.attr(layoutStore.oldLayoutSelect);
  33920. }
  33921. if (indexOf(prevStates, 'emphasis') >= 0) {
  33922. textEl.attr(layoutStore.oldLayoutEmphasis);
  33923. }
  33924. }
  33925. updateProps(textEl, newProps, seriesModel, dataIndex);
  33926. }
  33927. layoutStore.oldLayout = newProps;
  33928. if (textEl.states.select) {
  33929. var layoutSelect = layoutStore.oldLayoutSelect = {};
  33930. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  33931. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  33932. }
  33933. if (textEl.states.emphasis) {
  33934. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  33935. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  33936. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  33937. }
  33938. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  33939. }
  33940. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  33941. var layoutStore = labelLineAnimationStore(guideLine);
  33942. var oldLayout = layoutStore.oldLayout;
  33943. var newLayout = {
  33944. points: guideLine.shape.points
  33945. };
  33946. if (!oldLayout) {
  33947. guideLine.setShape(newLayout);
  33948. guideLine.style.strokePercent = 0;
  33949. initProps(guideLine, {
  33950. style: {
  33951. strokePercent: 1
  33952. }
  33953. }, seriesModel);
  33954. } else {
  33955. guideLine.attr({
  33956. shape: oldLayout
  33957. });
  33958. updateProps(guideLine, {
  33959. shape: newLayout
  33960. }, seriesModel);
  33961. }
  33962. layoutStore.oldLayout = newLayout;
  33963. }
  33964. };
  33965. return LabelManager;
  33966. }();
  33967. var getLabelManager = makeInner();
  33968. function installLabelLayout(registers) {
  33969. registers.registerUpdateLifecycle('series:beforeupdate', function (ecModel, api, params) {
  33970. // TODO api provide an namespace that can save stuff per instance
  33971. var labelManager = getLabelManager(api).labelManager;
  33972. if (!labelManager) {
  33973. labelManager = getLabelManager(api).labelManager = new LabelManager();
  33974. }
  33975. labelManager.clearLabels();
  33976. });
  33977. registers.registerUpdateLifecycle('series:layoutlabels', function (ecModel, api, params) {
  33978. var labelManager = getLabelManager(api).labelManager;
  33979. params.updatedSeries.forEach(function (series) {
  33980. labelManager.addLabelsOfSeries(api.getViewOfSeriesModel(series));
  33981. });
  33982. labelManager.updateLayoutConfig(api);
  33983. labelManager.layout(api);
  33984. labelManager.processLabelsOverall();
  33985. });
  33986. }
  33987. var mathSin$4 = Math.sin;
  33988. var mathCos$4 = Math.cos;
  33989. var PI$4 = Math.PI;
  33990. var PI2$7 = Math.PI * 2;
  33991. var degree = 180 / PI$4;
  33992. var SVGPathRebuilder = (function () {
  33993. function SVGPathRebuilder() {
  33994. }
  33995. SVGPathRebuilder.prototype.reset = function (precision) {
  33996. this._start = true;
  33997. this._d = [];
  33998. this._str = '';
  33999. this._p = Math.pow(10, precision || 4);
  34000. };
  34001. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  34002. this._add('M', x, y);
  34003. };
  34004. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  34005. this._add('L', x, y);
  34006. };
  34007. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  34008. this._add('C', x, y, x2, y2, x3, y3);
  34009. };
  34010. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  34011. this._add('Q', x, y, x2, y2);
  34012. };
  34013. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  34014. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  34015. };
  34016. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  34017. var dTheta = endAngle - startAngle;
  34018. var clockwise = !anticlockwise;
  34019. var dThetaPositive = Math.abs(dTheta);
  34020. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  34021. || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7);
  34022. var unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : (dTheta % PI2$7 + PI2$7);
  34023. var large = false;
  34024. if (isCircle) {
  34025. large = true;
  34026. }
  34027. else if (isAroundZero$1(dThetaPositive)) {
  34028. large = false;
  34029. }
  34030. else {
  34031. large = (unifiedTheta >= PI$4) === !!clockwise;
  34032. }
  34033. var x0 = cx + rx * mathCos$4(startAngle);
  34034. var y0 = cy + ry * mathSin$4(startAngle);
  34035. if (this._start) {
  34036. this._add('M', x0, y0);
  34037. }
  34038. var xRot = Math.round(psi * degree);
  34039. if (isCircle) {
  34040. var p = 1 / this._p;
  34041. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$7 - p);
  34042. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  34043. if (p > 1e-2) {
  34044. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  34045. }
  34046. }
  34047. else {
  34048. var x = cx + rx * mathCos$4(endAngle);
  34049. var y = cy + ry * mathSin$4(endAngle);
  34050. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  34051. }
  34052. };
  34053. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  34054. this._add('M', x, y);
  34055. this._add('l', w, 0);
  34056. this._add('l', 0, h);
  34057. this._add('l', -w, 0);
  34058. this._add('Z');
  34059. };
  34060. SVGPathRebuilder.prototype.closePath = function () {
  34061. if (this._d.length > 0) {
  34062. this._add('Z');
  34063. }
  34064. };
  34065. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  34066. var vals = [];
  34067. var p = this._p;
  34068. for (var i = 1; i < arguments.length; i++) {
  34069. var val = arguments[i];
  34070. if (isNaN(val)) {
  34071. this._invalid = true;
  34072. return;
  34073. }
  34074. vals.push(Math.round(val * p) / p);
  34075. }
  34076. this._d.push(cmd + vals.join(' '));
  34077. this._start = cmd === 'Z';
  34078. };
  34079. SVGPathRebuilder.prototype.generateStr = function () {
  34080. this._str = this._invalid ? '' : this._d.join('');
  34081. this._d = [];
  34082. };
  34083. SVGPathRebuilder.prototype.getStr = function () {
  34084. return this._str;
  34085. };
  34086. return SVGPathRebuilder;
  34087. }());
  34088. var NONE = 'none';
  34089. var mathRound$1 = Math.round;
  34090. function pathHasFill(style) {
  34091. var fill = style.fill;
  34092. return fill != null && fill !== NONE;
  34093. }
  34094. function pathHasStroke(style) {
  34095. var stroke = style.stroke;
  34096. return stroke != null && stroke !== NONE;
  34097. }
  34098. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  34099. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  34100. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  34101. var opacity = style.opacity == null ? 1 : style.opacity;
  34102. if (el instanceof ZRImage) {
  34103. updateAttr('opacity', opacity);
  34104. return;
  34105. }
  34106. if (pathHasFill(style)) {
  34107. var fill = normalizeColor(style.fill);
  34108. updateAttr('fill', fill.color);
  34109. var fillOpacity = style.fillOpacity != null
  34110. ? style.fillOpacity * fill.opacity * opacity
  34111. : fill.opacity * opacity;
  34112. if (forceUpdate || fillOpacity < 1) {
  34113. updateAttr('fill-opacity', fillOpacity);
  34114. }
  34115. }
  34116. else {
  34117. updateAttr('fill', NONE);
  34118. }
  34119. if (pathHasStroke(style)) {
  34120. var stroke = normalizeColor(style.stroke);
  34121. updateAttr('stroke', stroke.color);
  34122. var strokeScale = style.strokeNoScale
  34123. ? el.getLineScale()
  34124. : 1;
  34125. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  34126. var strokeOpacity = style.strokeOpacity != null
  34127. ? style.strokeOpacity * stroke.opacity * opacity
  34128. : stroke.opacity * opacity;
  34129. var strokeFirst = style.strokeFirst;
  34130. if (forceUpdate || strokeWidth !== 1) {
  34131. updateAttr('stroke-width', strokeWidth);
  34132. }
  34133. if (forceUpdate || strokeFirst) {
  34134. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  34135. }
  34136. if (forceUpdate || strokeOpacity < 1) {
  34137. updateAttr('stroke-opacity', strokeOpacity);
  34138. }
  34139. if (style.lineDash) {
  34140. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  34141. if (lineDash) {
  34142. lineDashOffset = mathRound$1(lineDashOffset || 0);
  34143. updateAttr('stroke-dasharray', lineDash.join(','));
  34144. if (lineDashOffset || forceUpdate) {
  34145. updateAttr('stroke-dashoffset', lineDashOffset);
  34146. }
  34147. }
  34148. }
  34149. else if (forceUpdate) {
  34150. updateAttr('stroke-dasharray', NONE);
  34151. }
  34152. for (var i = 0; i < strokeProps.length; i++) {
  34153. var propName = strokeProps[i];
  34154. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  34155. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  34156. val && updateAttr(svgStrokeProps[i], val);
  34157. }
  34158. }
  34159. }
  34160. else if (forceUpdate) {
  34161. updateAttr('stroke', NONE);
  34162. }
  34163. }
  34164. var SVGNS = 'http://www.w3.org/2000/svg';
  34165. var XLINKNS = 'http://www.w3.org/1999/xlink';
  34166. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  34167. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  34168. function createElement(name) {
  34169. return document.createElementNS(SVGNS, name);
  34170. }
  34171. function createVNode(tag, key, attrs, children, text) {
  34172. return {
  34173. tag: tag,
  34174. attrs: attrs || {},
  34175. children: children,
  34176. text: text,
  34177. key: key
  34178. };
  34179. }
  34180. function createElementOpen(name, attrs) {
  34181. var attrsStr = [];
  34182. if (attrs) {
  34183. for (var key in attrs) {
  34184. var val = attrs[key];
  34185. var part = key;
  34186. if (val === false) {
  34187. continue;
  34188. }
  34189. else if (val !== true && val != null) {
  34190. part += "=\"" + val + "\"";
  34191. }
  34192. attrsStr.push(part);
  34193. }
  34194. }
  34195. return "<" + name + " " + attrsStr.join(' ') + ">";
  34196. }
  34197. function createElementClose(name) {
  34198. return "</" + name + ">";
  34199. }
  34200. function vNodeToString(el, opts) {
  34201. opts = opts || {};
  34202. var S = opts.newline ? '\n' : '';
  34203. function convertElToString(el) {
  34204. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  34205. return createElementOpen(tag, attrs)
  34206. + (tag !== 'style' ? encodeHTML(text) : text || '')
  34207. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  34208. + createElementClose(tag);
  34209. }
  34210. return convertElToString(el);
  34211. }
  34212. function getCssString(selectorNodes, animationNodes, opts) {
  34213. opts = opts || {};
  34214. var S = opts.newline ? '\n' : '';
  34215. var bracketBegin = " {" + S;
  34216. var bracketEnd = S + "}";
  34217. var selectors = map(keys(selectorNodes), function (className) {
  34218. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  34219. return attrName + ":" + selectorNodes[className][attrName] + ";";
  34220. }).join(S) + bracketEnd;
  34221. }).join(S);
  34222. var animations = map(keys(animationNodes), function (animationName) {
  34223. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  34224. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  34225. var val = animationNodes[animationName][percent][attrName];
  34226. if (attrName === 'd') {
  34227. val = "path(\"" + val + "\")";
  34228. }
  34229. return attrName + ":" + val + ";";
  34230. }).join(S) + bracketEnd;
  34231. }).join(S) + bracketEnd;
  34232. }).join(S);
  34233. if (!selectors && !animations) {
  34234. return '';
  34235. }
  34236. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  34237. }
  34238. function createBrushScope(zrId) {
  34239. return {
  34240. zrId: zrId,
  34241. shadowCache: {},
  34242. patternCache: {},
  34243. gradientCache: {},
  34244. clipPathCache: {},
  34245. defs: {},
  34246. cssNodes: {},
  34247. cssAnims: {},
  34248. cssClassIdx: 0,
  34249. cssAnimIdx: 0,
  34250. shadowIdx: 0,
  34251. gradientIdx: 0,
  34252. patternIdx: 0,
  34253. clipPathIdx: 0
  34254. };
  34255. }
  34256. function createSVGVNode(width, height, children, useViewBox) {
  34257. return createVNode('svg', 'root', {
  34258. 'width': width,
  34259. 'height': height,
  34260. 'xmlns': SVGNS,
  34261. 'xmlns:xlink': XLINKNS,
  34262. 'version': '1.1',
  34263. 'baseProfile': 'full',
  34264. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  34265. }, children);
  34266. }
  34267. var EASING_MAP = {
  34268. cubicIn: '0.32,0,0.67,0',
  34269. cubicOut: '0.33,1,0.68,1',
  34270. cubicInOut: '0.65,0,0.35,1',
  34271. quadraticIn: '0.11,0,0.5,0',
  34272. quadraticOut: '0.5,1,0.89,1',
  34273. quadraticInOut: '0.45,0,0.55,1',
  34274. quarticIn: '0.5,0,0.75,0',
  34275. quarticOut: '0.25,1,0.5,1',
  34276. quarticInOut: '0.76,0,0.24,1',
  34277. quinticIn: '0.64,0,0.78,0',
  34278. quinticOut: '0.22,1,0.36,1',
  34279. quinticInOut: '0.83,0,0.17,1',
  34280. sinusoidalIn: '0.12,0,0.39,0',
  34281. sinusoidalOut: '0.61,1,0.88,1',
  34282. sinusoidalInOut: '0.37,0,0.63,1',
  34283. exponentialIn: '0.7,0,0.84,0',
  34284. exponentialOut: '0.16,1,0.3,1',
  34285. exponentialInOut: '0.87,0,0.13,1',
  34286. circularIn: '0.55,0,1,0.45',
  34287. circularOut: '0,0.55,0.45,1',
  34288. circularInOut: '0.85,0,0.15,1'
  34289. };
  34290. var transformOriginKey = 'transform-origin';
  34291. function buildPathString(el, kfShape, path) {
  34292. var shape = extend({}, el.shape);
  34293. extend(shape, kfShape);
  34294. el.buildPath(path, shape);
  34295. var svgPathBuilder = new SVGPathRebuilder();
  34296. svgPathBuilder.reset(getPathPrecision(el));
  34297. path.rebuildPath(svgPathBuilder, 1);
  34298. svgPathBuilder.generateStr();
  34299. return svgPathBuilder.getStr();
  34300. }
  34301. function setTransformOrigin(target, transform) {
  34302. var originX = transform.originX, originY = transform.originY;
  34303. if (originX || originY) {
  34304. target[transformOriginKey] = originX + "px " + originY + "px";
  34305. }
  34306. }
  34307. var ANIMATE_STYLE_MAP = {
  34308. fill: 'fill',
  34309. opacity: 'opacity',
  34310. lineWidth: 'stroke-width',
  34311. lineDashOffset: 'stroke-dashoffset'
  34312. };
  34313. function addAnimation(cssAnim, scope) {
  34314. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  34315. scope.cssAnims[animationName] = cssAnim;
  34316. return animationName;
  34317. }
  34318. function createCompoundPathCSSAnimation(el, attrs, scope) {
  34319. var paths = el.shape.paths;
  34320. var composedAnim = {};
  34321. var cssAnimationCfg;
  34322. var cssAnimationName;
  34323. each(paths, function (path) {
  34324. var subScope = createBrushScope(scope.zrId);
  34325. subScope.animation = true;
  34326. createCSSAnimation(path, {}, subScope, true);
  34327. var cssAnims = subScope.cssAnims;
  34328. var cssNodes = subScope.cssNodes;
  34329. var animNames = keys(cssAnims);
  34330. var len = animNames.length;
  34331. if (!len) {
  34332. return;
  34333. }
  34334. cssAnimationName = animNames[len - 1];
  34335. var lastAnim = cssAnims[cssAnimationName];
  34336. for (var percent in lastAnim) {
  34337. var kf = lastAnim[percent];
  34338. composedAnim[percent] = composedAnim[percent] || { d: '' };
  34339. composedAnim[percent].d += kf.d || '';
  34340. }
  34341. for (var className in cssNodes) {
  34342. var val = cssNodes[className].animation;
  34343. if (val.indexOf(cssAnimationName) >= 0) {
  34344. cssAnimationCfg = val;
  34345. }
  34346. }
  34347. });
  34348. if (!cssAnimationCfg) {
  34349. return;
  34350. }
  34351. attrs.d = false;
  34352. var animationName = addAnimation(composedAnim, scope);
  34353. return cssAnimationCfg.replace(cssAnimationName, animationName);
  34354. }
  34355. function getEasingFunc(easing) {
  34356. return isString(easing)
  34357. ? EASING_MAP[easing]
  34358. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  34359. : createCubicEasingFunc(easing) ? easing : ''
  34360. : '';
  34361. }
  34362. function createCSSAnimation(el, attrs, scope, onlyShape) {
  34363. var animators = el.animators;
  34364. var len = animators.length;
  34365. var cssAnimations = [];
  34366. if (el instanceof CompoundPath) {
  34367. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  34368. if (animationCfg) {
  34369. cssAnimations.push(animationCfg);
  34370. }
  34371. else if (!len) {
  34372. return;
  34373. }
  34374. }
  34375. else if (!len) {
  34376. return;
  34377. }
  34378. var groupAnimators = {};
  34379. for (var i = 0; i < len; i++) {
  34380. var animator = animators[i];
  34381. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  34382. var easing = getEasingFunc(animator.getClip().easing);
  34383. var delay = animator.getDelay();
  34384. if (easing) {
  34385. cfgArr.push(easing);
  34386. }
  34387. else {
  34388. cfgArr.push('linear');
  34389. }
  34390. if (delay) {
  34391. cfgArr.push(delay / 1000 + 's');
  34392. }
  34393. if (animator.getLoop()) {
  34394. cfgArr.push('infinite');
  34395. }
  34396. var cfg = cfgArr.join(' ');
  34397. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  34398. groupAnimators[cfg][1].push(animator);
  34399. }
  34400. function createSingleCSSAnimation(groupAnimator) {
  34401. var animators = groupAnimator[1];
  34402. var len = animators.length;
  34403. var transformKfs = {};
  34404. var shapeKfs = {};
  34405. var finalKfs = {};
  34406. var animationTimingFunctionAttrName = 'animation-timing-function';
  34407. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  34408. var tracks = animator.getTracks();
  34409. var maxTime = animator.getMaxTime();
  34410. for (var k = 0; k < tracks.length; k++) {
  34411. var track = tracks[k];
  34412. if (track.needsAnimate()) {
  34413. var kfs = track.keyframes;
  34414. var attrName = track.propName;
  34415. toCssAttrName && (attrName = toCssAttrName(attrName));
  34416. if (attrName) {
  34417. for (var i = 0; i < kfs.length; i++) {
  34418. var kf = kfs[i];
  34419. var percent = Math.round(kf.time / maxTime * 100) + '%';
  34420. var kfEasing = getEasingFunc(kf.easing);
  34421. var rawValue = kf.rawValue;
  34422. if (isString(rawValue) || isNumber(rawValue)) {
  34423. cssKfs[percent] = cssKfs[percent] || {};
  34424. cssKfs[percent][attrName] = kf.rawValue;
  34425. if (kfEasing) {
  34426. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  34427. }
  34428. }
  34429. }
  34430. }
  34431. }
  34432. }
  34433. }
  34434. for (var i = 0; i < len; i++) {
  34435. var animator = animators[i];
  34436. var targetProp = animator.targetName;
  34437. if (!targetProp) {
  34438. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  34439. }
  34440. else if (targetProp === 'shape') {
  34441. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  34442. }
  34443. }
  34444. for (var percent in transformKfs) {
  34445. var transform = {};
  34446. copyTransform(transform, el);
  34447. extend(transform, transformKfs[percent]);
  34448. var str = getSRTTransformString(transform);
  34449. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  34450. finalKfs[percent] = str ? {
  34451. transform: str
  34452. } : {};
  34453. setTransformOrigin(finalKfs[percent], transform);
  34454. if (timingFunction) {
  34455. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34456. }
  34457. }
  34458. var path;
  34459. var canAnimateShape = true;
  34460. for (var percent in shapeKfs) {
  34461. finalKfs[percent] = finalKfs[percent] || {};
  34462. var isFirst = !path;
  34463. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  34464. if (isFirst) {
  34465. path = new PathProxy();
  34466. }
  34467. var len_1 = path.len();
  34468. path.reset();
  34469. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  34470. var newLen = path.len();
  34471. if (!isFirst && len_1 !== newLen) {
  34472. canAnimateShape = false;
  34473. break;
  34474. }
  34475. if (timingFunction) {
  34476. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34477. }
  34478. }
  34479. if (!canAnimateShape) {
  34480. for (var percent in finalKfs) {
  34481. delete finalKfs[percent].d;
  34482. }
  34483. }
  34484. if (!onlyShape) {
  34485. for (var i = 0; i < len; i++) {
  34486. var animator = animators[i];
  34487. var targetProp = animator.targetName;
  34488. if (targetProp === 'style') {
  34489. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  34490. }
  34491. }
  34492. }
  34493. var percents = keys(finalKfs);
  34494. var allTransformOriginSame = true;
  34495. var transformOrigin;
  34496. for (var i = 1; i < percents.length; i++) {
  34497. var p0 = percents[i - 1];
  34498. var p1 = percents[i];
  34499. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  34500. allTransformOriginSame = false;
  34501. break;
  34502. }
  34503. transformOrigin = finalKfs[p0][transformOriginKey];
  34504. }
  34505. if (allTransformOriginSame && transformOrigin) {
  34506. for (var percent in finalKfs) {
  34507. if (finalKfs[percent][transformOriginKey]) {
  34508. delete finalKfs[percent][transformOriginKey];
  34509. }
  34510. }
  34511. attrs[transformOriginKey] = transformOrigin;
  34512. }
  34513. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  34514. var animationName = addAnimation(finalKfs, scope);
  34515. return animationName + " " + groupAnimator[0] + " both";
  34516. }
  34517. }
  34518. for (var key in groupAnimators) {
  34519. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  34520. if (animationCfg) {
  34521. cssAnimations.push(animationCfg);
  34522. }
  34523. }
  34524. if (cssAnimations.length) {
  34525. var className = scope.zrId + '-cls-' + scope.cssClassIdx++;
  34526. scope.cssNodes['.' + className] = {
  34527. animation: cssAnimations.join(',')
  34528. };
  34529. attrs["class"] = className;
  34530. }
  34531. }
  34532. var round$2 = Math.round;
  34533. function isImageLike$1(val) {
  34534. return val && isString(val.src);
  34535. }
  34536. function isCanvasLike(val) {
  34537. return val && isFunction(val.toDataURL);
  34538. }
  34539. function setStyleAttrs(attrs, style, el, scope) {
  34540. mapStyleToAttrs(function (key, val) {
  34541. var isFillStroke = key === 'fill' || key === 'stroke';
  34542. if (isFillStroke && isGradient(val)) {
  34543. setGradient(style, attrs, key, scope);
  34544. }
  34545. else if (isFillStroke && isPattern(val)) {
  34546. setPattern(el, attrs, key, scope);
  34547. }
  34548. else {
  34549. attrs[key] = val;
  34550. }
  34551. }, style, el, false);
  34552. setShadow(el, attrs, scope);
  34553. }
  34554. function noRotateScale(m) {
  34555. return isAroundZero$1(m[0] - 1)
  34556. && isAroundZero$1(m[1])
  34557. && isAroundZero$1(m[2])
  34558. && isAroundZero$1(m[3] - 1);
  34559. }
  34560. function noTranslate(m) {
  34561. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  34562. }
  34563. function setTransform(attrs, m, compress) {
  34564. if (m && !(noTranslate(m) && noRotateScale(m))) {
  34565. var mul = compress ? 10 : 1e4;
  34566. attrs.transform = noRotateScale(m)
  34567. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  34568. }
  34569. }
  34570. function convertPolyShape(shape, attrs, mul) {
  34571. var points = shape.points;
  34572. var strArr = [];
  34573. for (var i = 0; i < points.length; i++) {
  34574. strArr.push(round$2(points[i][0] * mul) / mul);
  34575. strArr.push(round$2(points[i][1] * mul) / mul);
  34576. }
  34577. attrs.points = strArr.join(' ');
  34578. }
  34579. function validatePolyShape(shape) {
  34580. return !shape.smooth;
  34581. }
  34582. function createAttrsConvert(desc) {
  34583. var normalizedDesc = map(desc, function (item) {
  34584. return (typeof item === 'string' ? [item, item] : item);
  34585. });
  34586. return function (shape, attrs, mul) {
  34587. for (var i = 0; i < normalizedDesc.length; i++) {
  34588. var item = normalizedDesc[i];
  34589. var val = shape[item[0]];
  34590. if (val != null) {
  34591. attrs[item[1]] = round$2(val * mul) / mul;
  34592. }
  34593. }
  34594. };
  34595. }
  34596. var builtinShapesDef = {
  34597. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  34598. polyline: [convertPolyShape, validatePolyShape],
  34599. polygon: [convertPolyShape, validatePolyShape]
  34600. };
  34601. function hasShapeAnimation(el) {
  34602. var animators = el.animators;
  34603. for (var i = 0; i < animators.length; i++) {
  34604. if (animators[i].targetName === 'shape') {
  34605. return true;
  34606. }
  34607. }
  34608. return false;
  34609. }
  34610. function brushSVGPath(el, scope) {
  34611. var style = el.style;
  34612. var shape = el.shape;
  34613. var builtinShpDef = builtinShapesDef[el.type];
  34614. var attrs = {};
  34615. var needsAnimate = scope.animation;
  34616. var svgElType = 'path';
  34617. var strokePercent = el.style.strokePercent;
  34618. var precision = (scope.compress && getPathPrecision(el)) || 4;
  34619. if (builtinShpDef
  34620. && !scope.willUpdate
  34621. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  34622. && !(needsAnimate && hasShapeAnimation(el))
  34623. && !(strokePercent < 1)) {
  34624. svgElType = el.type;
  34625. var mul = Math.pow(10, precision);
  34626. builtinShpDef[0](shape, attrs, mul);
  34627. }
  34628. else {
  34629. var needBuildPath = !el.path || el.shapeChanged();
  34630. if (!el.path) {
  34631. el.createPathProxy();
  34632. }
  34633. var path = el.path;
  34634. if (needBuildPath) {
  34635. path.beginPath();
  34636. el.buildPath(path, el.shape);
  34637. el.pathUpdated();
  34638. }
  34639. var pathVersion = path.getVersion();
  34640. var elExt = el;
  34641. var svgPathBuilder = elExt.__svgPathBuilder;
  34642. if (elExt.__svgPathVersion !== pathVersion
  34643. || !svgPathBuilder
  34644. || strokePercent !== elExt.__svgPathStrokePercent) {
  34645. if (!svgPathBuilder) {
  34646. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  34647. }
  34648. svgPathBuilder.reset(precision);
  34649. path.rebuildPath(svgPathBuilder, strokePercent);
  34650. svgPathBuilder.generateStr();
  34651. elExt.__svgPathVersion = pathVersion;
  34652. elExt.__svgPathStrokePercent = strokePercent;
  34653. }
  34654. attrs.d = svgPathBuilder.getStr();
  34655. }
  34656. setTransform(attrs, el.transform);
  34657. setStyleAttrs(attrs, style, el, scope);
  34658. scope.animation && createCSSAnimation(el, attrs, scope);
  34659. return createVNode(svgElType, el.id + '', attrs);
  34660. }
  34661. function brushSVGImage(el, scope) {
  34662. var style = el.style;
  34663. var image = style.image;
  34664. if (image && !isString(image)) {
  34665. if (isImageLike$1(image)) {
  34666. image = image.src;
  34667. }
  34668. else if (isCanvasLike(image)) {
  34669. image = image.toDataURL();
  34670. }
  34671. }
  34672. if (!image) {
  34673. return;
  34674. }
  34675. var x = style.x || 0;
  34676. var y = style.y || 0;
  34677. var dw = style.width;
  34678. var dh = style.height;
  34679. var attrs = {
  34680. href: image,
  34681. width: dw,
  34682. height: dh
  34683. };
  34684. if (x) {
  34685. attrs.x = x;
  34686. }
  34687. if (y) {
  34688. attrs.y = y;
  34689. }
  34690. setTransform(attrs, el.transform);
  34691. setStyleAttrs(attrs, style, el, scope);
  34692. scope.animation && createCSSAnimation(el, attrs, scope);
  34693. return createVNode('image', el.id + '', attrs);
  34694. }
  34695. function brushSVGTSpan(el, scope) {
  34696. var style = el.style;
  34697. var text = style.text;
  34698. text != null && (text += '');
  34699. if (!text || isNaN(style.x) || isNaN(style.y)) {
  34700. return;
  34701. }
  34702. var font = style.font || DEFAULT_FONT;
  34703. var x = style.x || 0;
  34704. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  34705. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  34706. || style.textAlign;
  34707. var attrs = {
  34708. 'dominant-baseline': 'central',
  34709. 'text-anchor': textAlign
  34710. };
  34711. if (hasSeparateFont(style)) {
  34712. var separatedFontStr = '';
  34713. var fontStyle = style.fontStyle;
  34714. var fontSize = parseFontSize(style.fontSize);
  34715. if (!parseFloat(fontSize)) {
  34716. return;
  34717. }
  34718. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  34719. var fontWeight = style.fontWeight;
  34720. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  34721. if (fontStyle && fontStyle !== 'normal') {
  34722. separatedFontStr += "font-style:" + fontStyle + ";";
  34723. }
  34724. if (fontWeight && fontWeight !== 'normal') {
  34725. separatedFontStr += "font-weight:" + fontWeight + ";";
  34726. }
  34727. attrs.style = separatedFontStr;
  34728. }
  34729. else {
  34730. attrs.style = "font: " + font;
  34731. }
  34732. if (text.match(/\s/)) {
  34733. attrs['xml:space'] = 'preserve';
  34734. }
  34735. if (x) {
  34736. attrs.x = x;
  34737. }
  34738. if (y) {
  34739. attrs.y = y;
  34740. }
  34741. setTransform(attrs, el.transform);
  34742. setStyleAttrs(attrs, style, el, scope);
  34743. scope.animation && createCSSAnimation(el, attrs, scope);
  34744. return createVNode('text', el.id + '', attrs, undefined, text);
  34745. }
  34746. function brush$1(el, scope) {
  34747. if (el instanceof Path) {
  34748. return brushSVGPath(el, scope);
  34749. }
  34750. else if (el instanceof ZRImage) {
  34751. return brushSVGImage(el, scope);
  34752. }
  34753. else if (el instanceof TSpan) {
  34754. return brushSVGTSpan(el, scope);
  34755. }
  34756. }
  34757. function setShadow(el, attrs, scope) {
  34758. var style = el.style;
  34759. if (hasShadow(style)) {
  34760. var shadowKey = getShadowKey(el);
  34761. var shadowCache = scope.shadowCache;
  34762. var shadowId = shadowCache[shadowKey];
  34763. if (!shadowId) {
  34764. var globalScale = el.getGlobalScale();
  34765. var scaleX = globalScale[0];
  34766. var scaleY = globalScale[1];
  34767. if (!scaleX || !scaleY) {
  34768. return;
  34769. }
  34770. var offsetX = style.shadowOffsetX || 0;
  34771. var offsetY = style.shadowOffsetY || 0;
  34772. var blur_1 = style.shadowBlur;
  34773. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  34774. var stdDx = blur_1 / 2 / scaleX;
  34775. var stdDy = blur_1 / 2 / scaleY;
  34776. var stdDeviation = stdDx + ' ' + stdDy;
  34777. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  34778. scope.defs[shadowId] = createVNode('filter', shadowId, {
  34779. 'id': shadowId,
  34780. 'x': '-100%',
  34781. 'y': '-100%',
  34782. 'width': '300%',
  34783. 'height': '300%'
  34784. }, [
  34785. createVNode('feDropShadow', '', {
  34786. 'dx': offsetX / scaleX,
  34787. 'dy': offsetY / scaleY,
  34788. 'stdDeviation': stdDeviation,
  34789. 'flood-color': color,
  34790. 'flood-opacity': opacity
  34791. })
  34792. ]);
  34793. shadowCache[shadowKey] = shadowId;
  34794. }
  34795. attrs.filter = getIdURL(shadowId);
  34796. }
  34797. }
  34798. function setGradient(style, attrs, target, scope) {
  34799. var val = style[target];
  34800. var gradientTag;
  34801. var gradientAttrs = {
  34802. 'gradientUnits': val.global
  34803. ? 'userSpaceOnUse'
  34804. : 'objectBoundingBox'
  34805. };
  34806. if (isLinearGradient(val)) {
  34807. gradientTag = 'linearGradient';
  34808. gradientAttrs.x1 = val.x;
  34809. gradientAttrs.y1 = val.y;
  34810. gradientAttrs.x2 = val.x2;
  34811. gradientAttrs.y2 = val.y2;
  34812. }
  34813. else if (isRadialGradient(val)) {
  34814. gradientTag = 'radialGradient';
  34815. gradientAttrs.cx = retrieve2(val.x, 0.5);
  34816. gradientAttrs.cy = retrieve2(val.y, 0.5);
  34817. gradientAttrs.r = retrieve2(val.r, 0.5);
  34818. }
  34819. else {
  34820. if ("development" !== 'production') {
  34821. logError('Illegal gradient type.');
  34822. }
  34823. return;
  34824. }
  34825. var colors = val.colorStops;
  34826. var colorStops = [];
  34827. for (var i = 0, len = colors.length; i < len; ++i) {
  34828. var offset = round4(colors[i].offset) * 100 + '%';
  34829. var stopColor = colors[i].color;
  34830. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  34831. var stopsAttrs = {
  34832. 'offset': offset
  34833. };
  34834. stopsAttrs['stop-color'] = color;
  34835. if (opacity < 1) {
  34836. stopsAttrs['stop-opacity'] = opacity;
  34837. }
  34838. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  34839. }
  34840. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  34841. var gradientKey = vNodeToString(gradientVNode);
  34842. var gradientCache = scope.gradientCache;
  34843. var gradientId = gradientCache[gradientKey];
  34844. if (!gradientId) {
  34845. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  34846. gradientCache[gradientKey] = gradientId;
  34847. gradientAttrs.id = gradientId;
  34848. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  34849. }
  34850. attrs[target] = getIdURL(gradientId);
  34851. }
  34852. function setPattern(el, attrs, target, scope) {
  34853. var val = el.style[target];
  34854. var boundingRect = el.getBoundingRect();
  34855. var patternAttrs = {};
  34856. var repeat = val.repeat;
  34857. var noRepeat = repeat === 'no-repeat';
  34858. var repeatX = repeat === 'repeat-x';
  34859. var repeatY = repeat === 'repeat-y';
  34860. var child;
  34861. if (isImagePattern(val)) {
  34862. var imageWidth_1 = val.imageWidth;
  34863. var imageHeight_1 = val.imageHeight;
  34864. var imageSrc = void 0;
  34865. var patternImage = val.image;
  34866. if (isString(patternImage)) {
  34867. imageSrc = patternImage;
  34868. }
  34869. else if (isImageLike$1(patternImage)) {
  34870. imageSrc = patternImage.src;
  34871. }
  34872. else if (isCanvasLike(patternImage)) {
  34873. imageSrc = patternImage.toDataURL();
  34874. }
  34875. if (typeof Image === 'undefined') {
  34876. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  34877. assert(imageWidth_1, errMsg);
  34878. assert(imageHeight_1, errMsg);
  34879. }
  34880. else if (imageWidth_1 == null || imageHeight_1 == null) {
  34881. var setSizeToVNode_1 = function (vNode, img) {
  34882. if (vNode) {
  34883. var svgEl = vNode.elm;
  34884. var width = imageWidth_1 || img.width;
  34885. var height = imageHeight_1 || img.height;
  34886. if (vNode.tag === 'pattern') {
  34887. if (repeatX) {
  34888. height = 1;
  34889. width /= boundingRect.width;
  34890. }
  34891. else if (repeatY) {
  34892. width = 1;
  34893. height /= boundingRect.height;
  34894. }
  34895. }
  34896. vNode.attrs.width = width;
  34897. vNode.attrs.height = height;
  34898. if (svgEl) {
  34899. svgEl.setAttribute('width', width);
  34900. svgEl.setAttribute('height', height);
  34901. }
  34902. }
  34903. };
  34904. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  34905. noRepeat || setSizeToVNode_1(patternVNode, img);
  34906. setSizeToVNode_1(child, img);
  34907. });
  34908. if (createdImage && createdImage.width && createdImage.height) {
  34909. imageWidth_1 = imageWidth_1 || createdImage.width;
  34910. imageHeight_1 = imageHeight_1 || createdImage.height;
  34911. }
  34912. }
  34913. child = createVNode('image', 'img', {
  34914. href: imageSrc,
  34915. width: imageWidth_1,
  34916. height: imageHeight_1
  34917. });
  34918. patternAttrs.width = imageWidth_1;
  34919. patternAttrs.height = imageHeight_1;
  34920. }
  34921. else if (val.svgElement) {
  34922. child = clone(val.svgElement);
  34923. patternAttrs.width = val.svgWidth;
  34924. patternAttrs.height = val.svgHeight;
  34925. }
  34926. if (!child) {
  34927. return;
  34928. }
  34929. var patternWidth;
  34930. var patternHeight;
  34931. if (noRepeat) {
  34932. patternWidth = patternHeight = 1;
  34933. }
  34934. else if (repeatX) {
  34935. patternHeight = 1;
  34936. patternWidth = patternAttrs.width / boundingRect.width;
  34937. }
  34938. else if (repeatY) {
  34939. patternWidth = 1;
  34940. patternHeight = patternAttrs.height / boundingRect.height;
  34941. }
  34942. else {
  34943. patternAttrs.patternUnits = 'userSpaceOnUse';
  34944. }
  34945. if (patternWidth != null && !isNaN(patternWidth)) {
  34946. patternAttrs.width = patternWidth;
  34947. }
  34948. if (patternHeight != null && !isNaN(patternHeight)) {
  34949. patternAttrs.height = patternHeight;
  34950. }
  34951. var patternTransform = getSRTTransformString(val);
  34952. patternTransform && (patternAttrs.patternTransform = patternTransform);
  34953. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  34954. var patternKey = vNodeToString(patternVNode);
  34955. var patternCache = scope.patternCache;
  34956. var patternId = patternCache[patternKey];
  34957. if (!patternId) {
  34958. patternId = scope.zrId + '-p' + scope.patternIdx++;
  34959. patternCache[patternKey] = patternId;
  34960. patternAttrs.id = patternId;
  34961. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  34962. }
  34963. attrs[target] = getIdURL(patternId);
  34964. }
  34965. function setClipPath(clipPath, attrs, scope) {
  34966. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  34967. var clipPathId = clipPathCache[clipPath.id];
  34968. if (!clipPathId) {
  34969. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  34970. var clipPathAttrs = {
  34971. id: clipPathId
  34972. };
  34973. clipPathCache[clipPath.id] = clipPathId;
  34974. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  34975. }
  34976. attrs['clip-path'] = getIdURL(clipPathId);
  34977. }
  34978. function createTextNode(text) {
  34979. return document.createTextNode(text);
  34980. }
  34981. function insertBefore(parentNode, newNode, referenceNode) {
  34982. parentNode.insertBefore(newNode, referenceNode);
  34983. }
  34984. function removeChild(node, child) {
  34985. node.removeChild(child);
  34986. }
  34987. function appendChild(node, child) {
  34988. node.appendChild(child);
  34989. }
  34990. function parentNode(node) {
  34991. return node.parentNode;
  34992. }
  34993. function nextSibling(node) {
  34994. return node.nextSibling;
  34995. }
  34996. function setTextContent(node, text) {
  34997. node.textContent = text;
  34998. }
  34999. var colonChar = 58;
  35000. var xChar = 120;
  35001. var emptyNode = createVNode('', '');
  35002. function isUndef(s) {
  35003. return s === undefined;
  35004. }
  35005. function isDef(s) {
  35006. return s !== undefined;
  35007. }
  35008. function createKeyToOldIdx(children, beginIdx, endIdx) {
  35009. var map = {};
  35010. for (var i = beginIdx; i <= endIdx; ++i) {
  35011. var key = children[i].key;
  35012. if (key !== undefined) {
  35013. if ("development" !== 'production') {
  35014. if (map[key] != null) {
  35015. console.error("Duplicate key " + key);
  35016. }
  35017. }
  35018. map[key] = i;
  35019. }
  35020. }
  35021. return map;
  35022. }
  35023. function sameVnode(vnode1, vnode2) {
  35024. var isSameKey = vnode1.key === vnode2.key;
  35025. var isSameTag = vnode1.tag === vnode2.tag;
  35026. return isSameTag && isSameKey;
  35027. }
  35028. function createElm(vnode) {
  35029. var i;
  35030. var children = vnode.children;
  35031. var tag = vnode.tag;
  35032. if (isDef(tag)) {
  35033. var elm = (vnode.elm = createElement(tag));
  35034. updateAttrs(emptyNode, vnode);
  35035. if (isArray(children)) {
  35036. for (i = 0; i < children.length; ++i) {
  35037. var ch = children[i];
  35038. if (ch != null) {
  35039. appendChild(elm, createElm(ch));
  35040. }
  35041. }
  35042. }
  35043. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  35044. appendChild(elm, createTextNode(vnode.text));
  35045. }
  35046. }
  35047. else {
  35048. vnode.elm = createTextNode(vnode.text);
  35049. }
  35050. return vnode.elm;
  35051. }
  35052. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  35053. for (; startIdx <= endIdx; ++startIdx) {
  35054. var ch = vnodes[startIdx];
  35055. if (ch != null) {
  35056. insertBefore(parentElm, createElm(ch), before);
  35057. }
  35058. }
  35059. }
  35060. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  35061. for (; startIdx <= endIdx; ++startIdx) {
  35062. var ch = vnodes[startIdx];
  35063. if (ch != null) {
  35064. if (isDef(ch.tag)) {
  35065. var parent_1 = parentNode(ch.elm);
  35066. removeChild(parent_1, ch.elm);
  35067. }
  35068. else {
  35069. removeChild(parentElm, ch.elm);
  35070. }
  35071. }
  35072. }
  35073. }
  35074. function updateAttrs(oldVnode, vnode) {
  35075. var key;
  35076. var elm = vnode.elm;
  35077. var oldAttrs = oldVnode && oldVnode.attrs || {};
  35078. var attrs = vnode.attrs || {};
  35079. if (oldAttrs === attrs) {
  35080. return;
  35081. }
  35082. for (key in attrs) {
  35083. var cur = attrs[key];
  35084. var old = oldAttrs[key];
  35085. if (old !== cur) {
  35086. if (cur === true) {
  35087. elm.setAttribute(key, '');
  35088. }
  35089. else if (cur === false) {
  35090. elm.removeAttribute(key);
  35091. }
  35092. else {
  35093. if (key.charCodeAt(0) !== xChar) {
  35094. elm.setAttribute(key, cur);
  35095. }
  35096. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  35097. elm.setAttributeNS(XMLNS, key, cur);
  35098. }
  35099. else if (key.charCodeAt(3) === colonChar) {
  35100. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  35101. }
  35102. else if (key.charCodeAt(5) === colonChar) {
  35103. elm.setAttributeNS(XLINKNS, key, cur);
  35104. }
  35105. else {
  35106. elm.setAttribute(key, cur);
  35107. }
  35108. }
  35109. }
  35110. }
  35111. for (key in oldAttrs) {
  35112. if (!(key in attrs)) {
  35113. elm.removeAttribute(key);
  35114. }
  35115. }
  35116. }
  35117. function updateChildren(parentElm, oldCh, newCh) {
  35118. var oldStartIdx = 0;
  35119. var newStartIdx = 0;
  35120. var oldEndIdx = oldCh.length - 1;
  35121. var oldStartVnode = oldCh[0];
  35122. var oldEndVnode = oldCh[oldEndIdx];
  35123. var newEndIdx = newCh.length - 1;
  35124. var newStartVnode = newCh[0];
  35125. var newEndVnode = newCh[newEndIdx];
  35126. var oldKeyToIdx;
  35127. var idxInOld;
  35128. var elmToMove;
  35129. var before;
  35130. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  35131. if (oldStartVnode == null) {
  35132. oldStartVnode = oldCh[++oldStartIdx];
  35133. }
  35134. else if (oldEndVnode == null) {
  35135. oldEndVnode = oldCh[--oldEndIdx];
  35136. }
  35137. else if (newStartVnode == null) {
  35138. newStartVnode = newCh[++newStartIdx];
  35139. }
  35140. else if (newEndVnode == null) {
  35141. newEndVnode = newCh[--newEndIdx];
  35142. }
  35143. else if (sameVnode(oldStartVnode, newStartVnode)) {
  35144. patchVnode(oldStartVnode, newStartVnode);
  35145. oldStartVnode = oldCh[++oldStartIdx];
  35146. newStartVnode = newCh[++newStartIdx];
  35147. }
  35148. else if (sameVnode(oldEndVnode, newEndVnode)) {
  35149. patchVnode(oldEndVnode, newEndVnode);
  35150. oldEndVnode = oldCh[--oldEndIdx];
  35151. newEndVnode = newCh[--newEndIdx];
  35152. }
  35153. else if (sameVnode(oldStartVnode, newEndVnode)) {
  35154. patchVnode(oldStartVnode, newEndVnode);
  35155. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  35156. oldStartVnode = oldCh[++oldStartIdx];
  35157. newEndVnode = newCh[--newEndIdx];
  35158. }
  35159. else if (sameVnode(oldEndVnode, newStartVnode)) {
  35160. patchVnode(oldEndVnode, newStartVnode);
  35161. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  35162. oldEndVnode = oldCh[--oldEndIdx];
  35163. newStartVnode = newCh[++newStartIdx];
  35164. }
  35165. else {
  35166. if (isUndef(oldKeyToIdx)) {
  35167. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  35168. }
  35169. idxInOld = oldKeyToIdx[newStartVnode.key];
  35170. if (isUndef(idxInOld)) {
  35171. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35172. }
  35173. else {
  35174. elmToMove = oldCh[idxInOld];
  35175. if (elmToMove.tag !== newStartVnode.tag) {
  35176. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35177. }
  35178. else {
  35179. patchVnode(elmToMove, newStartVnode);
  35180. oldCh[idxInOld] = undefined;
  35181. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  35182. }
  35183. }
  35184. newStartVnode = newCh[++newStartIdx];
  35185. }
  35186. }
  35187. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  35188. if (oldStartIdx > oldEndIdx) {
  35189. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  35190. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  35191. }
  35192. else {
  35193. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  35194. }
  35195. }
  35196. }
  35197. function patchVnode(oldVnode, vnode) {
  35198. var elm = (vnode.elm = oldVnode.elm);
  35199. var oldCh = oldVnode.children;
  35200. var ch = vnode.children;
  35201. if (oldVnode === vnode) {
  35202. return;
  35203. }
  35204. updateAttrs(oldVnode, vnode);
  35205. if (isUndef(vnode.text)) {
  35206. if (isDef(oldCh) && isDef(ch)) {
  35207. if (oldCh !== ch) {
  35208. updateChildren(elm, oldCh, ch);
  35209. }
  35210. }
  35211. else if (isDef(ch)) {
  35212. if (isDef(oldVnode.text)) {
  35213. setTextContent(elm, '');
  35214. }
  35215. addVnodes(elm, null, ch, 0, ch.length - 1);
  35216. }
  35217. else if (isDef(oldCh)) {
  35218. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35219. }
  35220. else if (isDef(oldVnode.text)) {
  35221. setTextContent(elm, '');
  35222. }
  35223. }
  35224. else if (oldVnode.text !== vnode.text) {
  35225. if (isDef(oldCh)) {
  35226. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35227. }
  35228. setTextContent(elm, vnode.text);
  35229. }
  35230. }
  35231. function patch(oldVnode, vnode) {
  35232. if (sameVnode(oldVnode, vnode)) {
  35233. patchVnode(oldVnode, vnode);
  35234. }
  35235. else {
  35236. var elm = oldVnode.elm;
  35237. var parent_2 = parentNode(elm);
  35238. createElm(vnode);
  35239. if (parent_2 !== null) {
  35240. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  35241. removeVnodes(parent_2, [oldVnode], 0, 0);
  35242. }
  35243. }
  35244. return vnode;
  35245. }
  35246. var svgId = 0;
  35247. var SVGPainter = (function () {
  35248. function SVGPainter(root, storage, opts) {
  35249. this.type = 'svg';
  35250. this.refreshHover = createMethodNotSupport('refreshHover');
  35251. this.configLayer = createMethodNotSupport('configLayer');
  35252. this.storage = storage;
  35253. this._opts = opts = extend({}, opts);
  35254. this.root = root;
  35255. this._id = 'zr' + svgId++;
  35256. this._oldVNode = createSVGVNode(opts.width, opts.height);
  35257. if (root && !opts.ssr) {
  35258. var viewport = this._viewport = document.createElement('div');
  35259. viewport.style.cssText = 'position:relative;overflow:hidden';
  35260. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  35261. updateAttrs(null, this._oldVNode);
  35262. viewport.appendChild(svgDom);
  35263. root.appendChild(viewport);
  35264. }
  35265. this.resize(opts.width, opts.height);
  35266. }
  35267. SVGPainter.prototype.getType = function () {
  35268. return this.type;
  35269. };
  35270. SVGPainter.prototype.getViewportRoot = function () {
  35271. return this._viewport;
  35272. };
  35273. SVGPainter.prototype.getViewportRootOffset = function () {
  35274. var viewportRoot = this.getViewportRoot();
  35275. if (viewportRoot) {
  35276. return {
  35277. offsetLeft: viewportRoot.offsetLeft || 0,
  35278. offsetTop: viewportRoot.offsetTop || 0
  35279. };
  35280. }
  35281. };
  35282. SVGPainter.prototype.getSvgDom = function () {
  35283. return this._svgDom;
  35284. };
  35285. SVGPainter.prototype.refresh = function () {
  35286. if (this.root) {
  35287. var vnode = this.renderToVNode({
  35288. willUpdate: true
  35289. });
  35290. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  35291. patch(this._oldVNode, vnode);
  35292. this._oldVNode = vnode;
  35293. }
  35294. };
  35295. SVGPainter.prototype.renderOneToVNode = function (el) {
  35296. return brush$1(el, createBrushScope(this._id));
  35297. };
  35298. SVGPainter.prototype.renderToVNode = function (opts) {
  35299. opts = opts || {};
  35300. var list = this.storage.getDisplayList(true);
  35301. var width = this._width;
  35302. var height = this._height;
  35303. var scope = createBrushScope(this._id);
  35304. scope.animation = opts.animation;
  35305. scope.willUpdate = opts.willUpdate;
  35306. scope.compress = opts.compress;
  35307. var children = [];
  35308. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  35309. bgVNode && children.push(bgVNode);
  35310. var mainVNode = !opts.compress
  35311. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  35312. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  35313. mainVNode && children.push(mainVNode);
  35314. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  35315. if (defs.length) {
  35316. children.push(createVNode('defs', 'defs', {}, defs));
  35317. }
  35318. if (opts.animation) {
  35319. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  35320. if (animationCssStr) {
  35321. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  35322. children.push(styleNode);
  35323. }
  35324. }
  35325. return createSVGVNode(width, height, children, opts.useViewBox);
  35326. };
  35327. SVGPainter.prototype.renderToString = function (opts) {
  35328. opts = opts || {};
  35329. return vNodeToString(this.renderToVNode({
  35330. animation: retrieve2(opts.cssAnimation, true),
  35331. willUpdate: false,
  35332. compress: true,
  35333. useViewBox: retrieve2(opts.useViewBox, true)
  35334. }), { newline: true });
  35335. };
  35336. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35337. this._backgroundColor = backgroundColor;
  35338. };
  35339. SVGPainter.prototype.getSvgRoot = function () {
  35340. return this._mainVNode && this._mainVNode.elm;
  35341. };
  35342. SVGPainter.prototype._paintList = function (list, scope, out) {
  35343. var listLen = list.length;
  35344. var clipPathsGroupsStack = [];
  35345. var clipPathsGroupsStackDepth = 0;
  35346. var currentClipPathGroup;
  35347. var prevClipPaths;
  35348. var clipGroupNodeIdx = 0;
  35349. for (var i = 0; i < listLen; i++) {
  35350. var displayable = list[i];
  35351. if (!displayable.invisible) {
  35352. var clipPaths = displayable.__clipPaths;
  35353. var len = clipPaths && clipPaths.length || 0;
  35354. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  35355. var lca = void 0;
  35356. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  35357. if (clipPaths && prevClipPaths
  35358. && clipPaths[lca] === prevClipPaths[lca]) {
  35359. break;
  35360. }
  35361. }
  35362. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  35363. clipPathsGroupsStackDepth--;
  35364. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  35365. }
  35366. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  35367. var groupAttrs = {};
  35368. setClipPath(clipPaths[i_2], groupAttrs, scope);
  35369. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  35370. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  35371. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  35372. currentClipPathGroup = g;
  35373. }
  35374. prevClipPaths = clipPaths;
  35375. var ret = brush$1(displayable, scope);
  35376. if (ret) {
  35377. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  35378. }
  35379. }
  35380. }
  35381. };
  35382. SVGPainter.prototype.resize = function (width, height) {
  35383. var opts = this._opts;
  35384. var root = this.root;
  35385. var viewport = this._viewport;
  35386. width != null && (opts.width = width);
  35387. height != null && (opts.height = height);
  35388. if (root && viewport) {
  35389. viewport.style.display = 'none';
  35390. width = getSize(root, 0, opts);
  35391. height = getSize(root, 1, opts);
  35392. viewport.style.display = '';
  35393. }
  35394. if (this._width !== width || this._height !== height) {
  35395. this._width = width;
  35396. this._height = height;
  35397. if (viewport) {
  35398. var viewportStyle = viewport.style;
  35399. viewportStyle.width = width + 'px';
  35400. viewportStyle.height = height + 'px';
  35401. }
  35402. if (!isPattern(this._backgroundColor)) {
  35403. var svgDom = this._svgDom;
  35404. if (svgDom) {
  35405. svgDom.setAttribute('width', width);
  35406. svgDom.setAttribute('height', height);
  35407. }
  35408. var bgEl = this._bgVNode && this._bgVNode.elm;
  35409. if (bgEl) {
  35410. bgEl.setAttribute('width', width);
  35411. bgEl.setAttribute('height', height);
  35412. }
  35413. }
  35414. else {
  35415. this.refresh();
  35416. }
  35417. }
  35418. };
  35419. SVGPainter.prototype.getWidth = function () {
  35420. return this._width;
  35421. };
  35422. SVGPainter.prototype.getHeight = function () {
  35423. return this._height;
  35424. };
  35425. SVGPainter.prototype.dispose = function () {
  35426. if (this.root) {
  35427. this.root.innerHTML = '';
  35428. }
  35429. this._svgDom =
  35430. this._viewport =
  35431. this.storage =
  35432. this._oldVNode =
  35433. this._bgVNode =
  35434. this._mainVNode = null;
  35435. };
  35436. SVGPainter.prototype.clear = function () {
  35437. if (this._svgDom) {
  35438. this._svgDom.innerHTML = null;
  35439. }
  35440. this._oldVNode = null;
  35441. };
  35442. SVGPainter.prototype.toDataURL = function (base64) {
  35443. var str = this.renderToString();
  35444. var prefix = 'data:image/svg+xml;';
  35445. if (base64) {
  35446. str = encodeBase64(str);
  35447. return str && prefix + 'base64,' + str;
  35448. }
  35449. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  35450. };
  35451. return SVGPainter;
  35452. }());
  35453. function createMethodNotSupport(method) {
  35454. return function () {
  35455. if ("development" !== 'production') {
  35456. logError('In SVG mode painter not support method "' + method + '"');
  35457. }
  35458. };
  35459. }
  35460. function createBackgroundVNode(width, height, backgroundColor, scope) {
  35461. var bgVNode;
  35462. if (backgroundColor && backgroundColor !== 'none') {
  35463. bgVNode = createVNode('rect', 'bg', {
  35464. width: width,
  35465. height: height,
  35466. x: '0',
  35467. y: '0',
  35468. id: '0'
  35469. });
  35470. if (isGradient(backgroundColor)) {
  35471. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  35472. }
  35473. else if (isPattern(backgroundColor)) {
  35474. setPattern({
  35475. style: {
  35476. fill: backgroundColor
  35477. },
  35478. dirty: noop,
  35479. getBoundingRect: function () { return ({ width: width, height: height }); }
  35480. }, bgVNode.attrs, 'fill', scope);
  35481. }
  35482. else {
  35483. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  35484. bgVNode.attrs.fill = color;
  35485. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  35486. }
  35487. }
  35488. return bgVNode;
  35489. }
  35490. function install(registers) {
  35491. registers.registerPainter('svg', SVGPainter);
  35492. }
  35493. function createDom(id, painter, dpr) {
  35494. var newDom = platformApi.createCanvas();
  35495. var width = painter.getWidth();
  35496. var height = painter.getHeight();
  35497. var newDomStyle = newDom.style;
  35498. if (newDomStyle) {
  35499. newDomStyle.position = 'absolute';
  35500. newDomStyle.left = '0';
  35501. newDomStyle.top = '0';
  35502. newDomStyle.width = width + 'px';
  35503. newDomStyle.height = height + 'px';
  35504. newDom.setAttribute('data-zr-dom-id', id);
  35505. }
  35506. newDom.width = width * dpr;
  35507. newDom.height = height * dpr;
  35508. return newDom;
  35509. }
  35510. var Layer = (function (_super) {
  35511. __extends(Layer, _super);
  35512. function Layer(id, painter, dpr) {
  35513. var _this = _super.call(this) || this;
  35514. _this.motionBlur = false;
  35515. _this.lastFrameAlpha = 0.7;
  35516. _this.dpr = 1;
  35517. _this.virtual = false;
  35518. _this.config = {};
  35519. _this.incremental = false;
  35520. _this.zlevel = 0;
  35521. _this.maxRepaintRectCount = 5;
  35522. _this.__dirty = true;
  35523. _this.__firstTimePaint = true;
  35524. _this.__used = false;
  35525. _this.__drawIndex = 0;
  35526. _this.__startIndex = 0;
  35527. _this.__endIndex = 0;
  35528. _this.__prevStartIndex = null;
  35529. _this.__prevEndIndex = null;
  35530. var dom;
  35531. dpr = dpr || devicePixelRatio;
  35532. if (typeof id === 'string') {
  35533. dom = createDom(id, painter, dpr);
  35534. }
  35535. else if (isObject(id)) {
  35536. dom = id;
  35537. id = dom.id;
  35538. }
  35539. _this.id = id;
  35540. _this.dom = dom;
  35541. var domStyle = dom.style;
  35542. if (domStyle) {
  35543. disableUserSelect(dom);
  35544. dom.onselectstart = function () { return false; };
  35545. domStyle.padding = '0';
  35546. domStyle.margin = '0';
  35547. domStyle.borderWidth = '0';
  35548. }
  35549. _this.painter = painter;
  35550. _this.dpr = dpr;
  35551. return _this;
  35552. }
  35553. Layer.prototype.getElementCount = function () {
  35554. return this.__endIndex - this.__startIndex;
  35555. };
  35556. Layer.prototype.afterBrush = function () {
  35557. this.__prevStartIndex = this.__startIndex;
  35558. this.__prevEndIndex = this.__endIndex;
  35559. };
  35560. Layer.prototype.initContext = function () {
  35561. this.ctx = this.dom.getContext('2d');
  35562. this.ctx.dpr = this.dpr;
  35563. };
  35564. Layer.prototype.setUnpainted = function () {
  35565. this.__firstTimePaint = true;
  35566. };
  35567. Layer.prototype.createBackBuffer = function () {
  35568. var dpr = this.dpr;
  35569. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  35570. this.ctxBack = this.domBack.getContext('2d');
  35571. if (dpr !== 1) {
  35572. this.ctxBack.scale(dpr, dpr);
  35573. }
  35574. };
  35575. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  35576. if (this.__firstTimePaint) {
  35577. this.__firstTimePaint = false;
  35578. return null;
  35579. }
  35580. var mergedRepaintRects = [];
  35581. var maxRepaintRectCount = this.maxRepaintRectCount;
  35582. var full = false;
  35583. var pendingRect = new BoundingRect(0, 0, 0, 0);
  35584. function addRectToMergePool(rect) {
  35585. if (!rect.isFinite() || rect.isZero()) {
  35586. return;
  35587. }
  35588. if (mergedRepaintRects.length === 0) {
  35589. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35590. boundingRect.copy(rect);
  35591. mergedRepaintRects.push(boundingRect);
  35592. }
  35593. else {
  35594. var isMerged = false;
  35595. var minDeltaArea = Infinity;
  35596. var bestRectToMergeIdx = 0;
  35597. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  35598. var mergedRect = mergedRepaintRects[i];
  35599. if (mergedRect.intersect(rect)) {
  35600. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  35601. pendingRect_1.copy(mergedRect);
  35602. pendingRect_1.union(rect);
  35603. mergedRepaintRects[i] = pendingRect_1;
  35604. isMerged = true;
  35605. break;
  35606. }
  35607. else if (full) {
  35608. pendingRect.copy(rect);
  35609. pendingRect.union(mergedRect);
  35610. var aArea = rect.width * rect.height;
  35611. var bArea = mergedRect.width * mergedRect.height;
  35612. var pendingArea = pendingRect.width * pendingRect.height;
  35613. var deltaArea = pendingArea - aArea - bArea;
  35614. if (deltaArea < minDeltaArea) {
  35615. minDeltaArea = deltaArea;
  35616. bestRectToMergeIdx = i;
  35617. }
  35618. }
  35619. }
  35620. if (full) {
  35621. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  35622. isMerged = true;
  35623. }
  35624. if (!isMerged) {
  35625. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35626. boundingRect.copy(rect);
  35627. mergedRepaintRects.push(boundingRect);
  35628. }
  35629. if (!full) {
  35630. full = mergedRepaintRects.length >= maxRepaintRectCount;
  35631. }
  35632. }
  35633. }
  35634. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  35635. var el = displayList[i];
  35636. if (el) {
  35637. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35638. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  35639. ? el.getPrevPaintRect()
  35640. : null;
  35641. if (prevRect) {
  35642. addRectToMergePool(prevRect);
  35643. }
  35644. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  35645. ? el.getPaintRect()
  35646. : null;
  35647. if (curRect) {
  35648. addRectToMergePool(curRect);
  35649. }
  35650. }
  35651. }
  35652. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  35653. var el = prevList[i];
  35654. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35655. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  35656. var prevRect = el.getPrevPaintRect();
  35657. if (prevRect) {
  35658. addRectToMergePool(prevRect);
  35659. }
  35660. }
  35661. }
  35662. var hasIntersections;
  35663. do {
  35664. hasIntersections = false;
  35665. for (var i = 0; i < mergedRepaintRects.length;) {
  35666. if (mergedRepaintRects[i].isZero()) {
  35667. mergedRepaintRects.splice(i, 1);
  35668. continue;
  35669. }
  35670. for (var j = i + 1; j < mergedRepaintRects.length;) {
  35671. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  35672. hasIntersections = true;
  35673. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  35674. mergedRepaintRects.splice(j, 1);
  35675. }
  35676. else {
  35677. j++;
  35678. }
  35679. }
  35680. i++;
  35681. }
  35682. } while (hasIntersections);
  35683. this._paintRects = mergedRepaintRects;
  35684. return mergedRepaintRects;
  35685. };
  35686. Layer.prototype.debugGetPaintRects = function () {
  35687. return (this._paintRects || []).slice();
  35688. };
  35689. Layer.prototype.resize = function (width, height) {
  35690. var dpr = this.dpr;
  35691. var dom = this.dom;
  35692. var domStyle = dom.style;
  35693. var domBack = this.domBack;
  35694. if (domStyle) {
  35695. domStyle.width = width + 'px';
  35696. domStyle.height = height + 'px';
  35697. }
  35698. dom.width = width * dpr;
  35699. dom.height = height * dpr;
  35700. if (domBack) {
  35701. domBack.width = width * dpr;
  35702. domBack.height = height * dpr;
  35703. if (dpr !== 1) {
  35704. this.ctxBack.scale(dpr, dpr);
  35705. }
  35706. }
  35707. };
  35708. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  35709. var dom = this.dom;
  35710. var ctx = this.ctx;
  35711. var width = dom.width;
  35712. var height = dom.height;
  35713. clearColor = clearColor || this.clearColor;
  35714. var haveMotionBLur = this.motionBlur && !clearAll;
  35715. var lastFrameAlpha = this.lastFrameAlpha;
  35716. var dpr = this.dpr;
  35717. var self = this;
  35718. if (haveMotionBLur) {
  35719. if (!this.domBack) {
  35720. this.createBackBuffer();
  35721. }
  35722. this.ctxBack.globalCompositeOperation = 'copy';
  35723. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  35724. }
  35725. var domBack = this.domBack;
  35726. function doClear(x, y, width, height) {
  35727. ctx.clearRect(x, y, width, height);
  35728. if (clearColor && clearColor !== 'transparent') {
  35729. var clearColorGradientOrPattern = void 0;
  35730. if (isGradientObject(clearColor)) {
  35731. var shouldCache = clearColor.global || (clearColor.__width === width
  35732. && clearColor.__height === height);
  35733. clearColorGradientOrPattern = shouldCache
  35734. && clearColor.__canvasGradient
  35735. || getCanvasGradient(ctx, clearColor, {
  35736. x: 0,
  35737. y: 0,
  35738. width: width,
  35739. height: height
  35740. });
  35741. clearColor.__canvasGradient = clearColorGradientOrPattern;
  35742. clearColor.__width = width;
  35743. clearColor.__height = height;
  35744. }
  35745. else if (isImagePatternObject(clearColor)) {
  35746. clearColor.scaleX = clearColor.scaleX || dpr;
  35747. clearColor.scaleY = clearColor.scaleY || dpr;
  35748. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  35749. dirty: function () {
  35750. self.setUnpainted();
  35751. self.__painter.refresh();
  35752. }
  35753. });
  35754. }
  35755. ctx.save();
  35756. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  35757. ctx.fillRect(x, y, width, height);
  35758. ctx.restore();
  35759. }
  35760. if (haveMotionBLur) {
  35761. ctx.save();
  35762. ctx.globalAlpha = lastFrameAlpha;
  35763. ctx.drawImage(domBack, x, y, width, height);
  35764. ctx.restore();
  35765. }
  35766. }
  35767. if (!repaintRects || haveMotionBLur) {
  35768. doClear(0, 0, width, height);
  35769. }
  35770. else if (repaintRects.length) {
  35771. each(repaintRects, function (rect) {
  35772. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35773. });
  35774. }
  35775. };
  35776. return Layer;
  35777. }(Eventful));
  35778. var HOVER_LAYER_ZLEVEL = 1e5;
  35779. var CANVAS_ZLEVEL = 314159;
  35780. var EL_AFTER_INCREMENTAL_INC = 0.01;
  35781. var INCREMENTAL_INC = 0.001;
  35782. function isLayerValid(layer) {
  35783. if (!layer) {
  35784. return false;
  35785. }
  35786. if (layer.__builtin__) {
  35787. return true;
  35788. }
  35789. if (typeof (layer.resize) !== 'function'
  35790. || typeof (layer.refresh) !== 'function') {
  35791. return false;
  35792. }
  35793. return true;
  35794. }
  35795. function createRoot(width, height) {
  35796. var domRoot = document.createElement('div');
  35797. domRoot.style.cssText = [
  35798. 'position:relative',
  35799. 'width:' + width + 'px',
  35800. 'height:' + height + 'px',
  35801. 'padding:0',
  35802. 'margin:0',
  35803. 'border-width:0'
  35804. ].join(';') + ';';
  35805. return domRoot;
  35806. }
  35807. var CanvasPainter = (function () {
  35808. function CanvasPainter(root, storage, opts, id) {
  35809. this.type = 'canvas';
  35810. this._zlevelList = [];
  35811. this._prevDisplayList = [];
  35812. this._layers = {};
  35813. this._layerConfig = {};
  35814. this._needsManuallyCompositing = false;
  35815. this.type = 'canvas';
  35816. var singleCanvas = !root.nodeName
  35817. || root.nodeName.toUpperCase() === 'CANVAS';
  35818. this._opts = opts = extend({}, opts || {});
  35819. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  35820. this._singleCanvas = singleCanvas;
  35821. this.root = root;
  35822. var rootStyle = root.style;
  35823. if (rootStyle) {
  35824. disableUserSelect(root);
  35825. root.innerHTML = '';
  35826. }
  35827. this.storage = storage;
  35828. var zlevelList = this._zlevelList;
  35829. this._prevDisplayList = [];
  35830. var layers = this._layers;
  35831. if (!singleCanvas) {
  35832. this._width = getSize(root, 0, opts);
  35833. this._height = getSize(root, 1, opts);
  35834. var domRoot = this._domRoot = createRoot(this._width, this._height);
  35835. root.appendChild(domRoot);
  35836. }
  35837. else {
  35838. var rootCanvas = root;
  35839. var width = rootCanvas.width;
  35840. var height = rootCanvas.height;
  35841. if (opts.width != null) {
  35842. width = opts.width;
  35843. }
  35844. if (opts.height != null) {
  35845. height = opts.height;
  35846. }
  35847. this.dpr = opts.devicePixelRatio || 1;
  35848. rootCanvas.width = width * this.dpr;
  35849. rootCanvas.height = height * this.dpr;
  35850. this._width = width;
  35851. this._height = height;
  35852. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  35853. mainLayer.__builtin__ = true;
  35854. mainLayer.initContext();
  35855. layers[CANVAS_ZLEVEL] = mainLayer;
  35856. mainLayer.zlevel = CANVAS_ZLEVEL;
  35857. zlevelList.push(CANVAS_ZLEVEL);
  35858. this._domRoot = root;
  35859. }
  35860. }
  35861. CanvasPainter.prototype.getType = function () {
  35862. return 'canvas';
  35863. };
  35864. CanvasPainter.prototype.isSingleCanvas = function () {
  35865. return this._singleCanvas;
  35866. };
  35867. CanvasPainter.prototype.getViewportRoot = function () {
  35868. return this._domRoot;
  35869. };
  35870. CanvasPainter.prototype.getViewportRootOffset = function () {
  35871. var viewportRoot = this.getViewportRoot();
  35872. if (viewportRoot) {
  35873. return {
  35874. offsetLeft: viewportRoot.offsetLeft || 0,
  35875. offsetTop: viewportRoot.offsetTop || 0
  35876. };
  35877. }
  35878. };
  35879. CanvasPainter.prototype.refresh = function (paintAll) {
  35880. var list = this.storage.getDisplayList(true);
  35881. var prevList = this._prevDisplayList;
  35882. var zlevelList = this._zlevelList;
  35883. this._redrawId = Math.random();
  35884. this._paintList(list, prevList, paintAll, this._redrawId);
  35885. for (var i = 0; i < zlevelList.length; i++) {
  35886. var z = zlevelList[i];
  35887. var layer = this._layers[z];
  35888. if (!layer.__builtin__ && layer.refresh) {
  35889. var clearColor = i === 0 ? this._backgroundColor : null;
  35890. layer.refresh(clearColor);
  35891. }
  35892. }
  35893. if (this._opts.useDirtyRect) {
  35894. this._prevDisplayList = list.slice();
  35895. }
  35896. return this;
  35897. };
  35898. CanvasPainter.prototype.refreshHover = function () {
  35899. this._paintHoverList(this.storage.getDisplayList(false));
  35900. };
  35901. CanvasPainter.prototype._paintHoverList = function (list) {
  35902. var len = list.length;
  35903. var hoverLayer = this._hoverlayer;
  35904. hoverLayer && hoverLayer.clear();
  35905. if (!len) {
  35906. return;
  35907. }
  35908. var scope = {
  35909. inHover: true,
  35910. viewWidth: this._width,
  35911. viewHeight: this._height
  35912. };
  35913. var ctx;
  35914. for (var i = 0; i < len; i++) {
  35915. var el = list[i];
  35916. if (el.__inHover) {
  35917. if (!hoverLayer) {
  35918. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  35919. }
  35920. if (!ctx) {
  35921. ctx = hoverLayer.ctx;
  35922. ctx.save();
  35923. }
  35924. brush(ctx, el, scope, i === len - 1);
  35925. }
  35926. }
  35927. if (ctx) {
  35928. ctx.restore();
  35929. }
  35930. };
  35931. CanvasPainter.prototype.getHoverLayer = function () {
  35932. return this.getLayer(HOVER_LAYER_ZLEVEL);
  35933. };
  35934. CanvasPainter.prototype.paintOne = function (ctx, el) {
  35935. brushSingle(ctx, el);
  35936. };
  35937. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  35938. if (this._redrawId !== redrawId) {
  35939. return;
  35940. }
  35941. paintAll = paintAll || false;
  35942. this._updateLayerStatus(list);
  35943. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  35944. if (this._needsManuallyCompositing) {
  35945. this._compositeManually();
  35946. }
  35947. if (needsRefreshHover) {
  35948. this._paintHoverList(list);
  35949. }
  35950. if (!finished) {
  35951. var self_1 = this;
  35952. requestAnimationFrame$1(function () {
  35953. self_1._paintList(list, prevList, paintAll, redrawId);
  35954. });
  35955. }
  35956. else {
  35957. this.eachLayer(function (layer) {
  35958. layer.afterBrush && layer.afterBrush();
  35959. });
  35960. }
  35961. };
  35962. CanvasPainter.prototype._compositeManually = function () {
  35963. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  35964. var width = this._domRoot.width;
  35965. var height = this._domRoot.height;
  35966. ctx.clearRect(0, 0, width, height);
  35967. this.eachBuiltinLayer(function (layer) {
  35968. if (layer.virtual) {
  35969. ctx.drawImage(layer.dom, 0, 0, width, height);
  35970. }
  35971. });
  35972. };
  35973. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  35974. var _this = this;
  35975. var layerList = [];
  35976. var useDirtyRect = this._opts.useDirtyRect;
  35977. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  35978. var zlevel = this._zlevelList[zi];
  35979. var layer = this._layers[zlevel];
  35980. if (layer.__builtin__
  35981. && layer !== this._hoverlayer
  35982. && (layer.__dirty || paintAll)) {
  35983. layerList.push(layer);
  35984. }
  35985. }
  35986. var finished = true;
  35987. var needsRefreshHover = false;
  35988. var _loop_1 = function (k) {
  35989. var layer = layerList[k];
  35990. var ctx = layer.ctx;
  35991. var repaintRects = useDirtyRect
  35992. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  35993. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  35994. var useTimer = !paintAll && layer.incremental && Date.now;
  35995. var startTime = useTimer && Date.now();
  35996. var clearColor = layer.zlevel === this_1._zlevelList[0]
  35997. ? this_1._backgroundColor : null;
  35998. if (layer.__startIndex === layer.__endIndex) {
  35999. layer.clear(false, clearColor, repaintRects);
  36000. }
  36001. else if (start === layer.__startIndex) {
  36002. var firstEl = list[start];
  36003. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  36004. layer.clear(false, clearColor, repaintRects);
  36005. }
  36006. }
  36007. if (start === -1) {
  36008. console.error('For some unknown reason. drawIndex is -1');
  36009. start = layer.__startIndex;
  36010. }
  36011. var i;
  36012. var repaint = function (repaintRect) {
  36013. var scope = {
  36014. inHover: false,
  36015. allClipped: false,
  36016. prevEl: null,
  36017. viewWidth: _this._width,
  36018. viewHeight: _this._height
  36019. };
  36020. for (i = start; i < layer.__endIndex; i++) {
  36021. var el = list[i];
  36022. if (el.__inHover) {
  36023. needsRefreshHover = true;
  36024. }
  36025. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  36026. if (useTimer) {
  36027. var dTime = Date.now() - startTime;
  36028. if (dTime > 15) {
  36029. break;
  36030. }
  36031. }
  36032. }
  36033. if (scope.prevElClipPaths) {
  36034. ctx.restore();
  36035. }
  36036. };
  36037. if (repaintRects) {
  36038. if (repaintRects.length === 0) {
  36039. i = layer.__endIndex;
  36040. }
  36041. else {
  36042. var dpr = this_1.dpr;
  36043. for (var r = 0; r < repaintRects.length; ++r) {
  36044. var rect = repaintRects[r];
  36045. ctx.save();
  36046. ctx.beginPath();
  36047. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  36048. ctx.clip();
  36049. repaint(rect);
  36050. ctx.restore();
  36051. }
  36052. }
  36053. }
  36054. else {
  36055. ctx.save();
  36056. repaint();
  36057. ctx.restore();
  36058. }
  36059. layer.__drawIndex = i;
  36060. if (layer.__drawIndex < layer.__endIndex) {
  36061. finished = false;
  36062. }
  36063. };
  36064. var this_1 = this;
  36065. for (var k = 0; k < layerList.length; k++) {
  36066. _loop_1(k);
  36067. }
  36068. if (env.wxa) {
  36069. each(this._layers, function (layer) {
  36070. if (layer && layer.ctx && layer.ctx.draw) {
  36071. layer.ctx.draw();
  36072. }
  36073. });
  36074. }
  36075. return {
  36076. finished: finished,
  36077. needsRefreshHover: needsRefreshHover
  36078. };
  36079. };
  36080. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  36081. var ctx = currentLayer.ctx;
  36082. if (useDirtyRect) {
  36083. var paintRect = el.getPaintRect();
  36084. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  36085. brush(ctx, el, scope, isLast);
  36086. el.setPrevPaintRect(paintRect);
  36087. }
  36088. }
  36089. else {
  36090. brush(ctx, el, scope, isLast);
  36091. }
  36092. };
  36093. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  36094. if (this._singleCanvas && !this._needsManuallyCompositing) {
  36095. zlevel = CANVAS_ZLEVEL;
  36096. }
  36097. var layer = this._layers[zlevel];
  36098. if (!layer) {
  36099. layer = new Layer('zr_' + zlevel, this, this.dpr);
  36100. layer.zlevel = zlevel;
  36101. layer.__builtin__ = true;
  36102. if (this._layerConfig[zlevel]) {
  36103. merge(layer, this._layerConfig[zlevel], true);
  36104. }
  36105. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  36106. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  36107. }
  36108. if (virtual) {
  36109. layer.virtual = virtual;
  36110. }
  36111. this.insertLayer(zlevel, layer);
  36112. layer.initContext();
  36113. }
  36114. return layer;
  36115. };
  36116. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  36117. var layersMap = this._layers;
  36118. var zlevelList = this._zlevelList;
  36119. var len = zlevelList.length;
  36120. var domRoot = this._domRoot;
  36121. var prevLayer = null;
  36122. var i = -1;
  36123. if (layersMap[zlevel]) {
  36124. if ("development" !== 'production') {
  36125. logError('ZLevel ' + zlevel + ' has been used already');
  36126. }
  36127. return;
  36128. }
  36129. if (!isLayerValid(layer)) {
  36130. if ("development" !== 'production') {
  36131. logError('Layer of zlevel ' + zlevel + ' is not valid');
  36132. }
  36133. return;
  36134. }
  36135. if (len > 0 && zlevel > zlevelList[0]) {
  36136. for (i = 0; i < len - 1; i++) {
  36137. if (zlevelList[i] < zlevel
  36138. && zlevelList[i + 1] > zlevel) {
  36139. break;
  36140. }
  36141. }
  36142. prevLayer = layersMap[zlevelList[i]];
  36143. }
  36144. zlevelList.splice(i + 1, 0, zlevel);
  36145. layersMap[zlevel] = layer;
  36146. if (!layer.virtual) {
  36147. if (prevLayer) {
  36148. var prevDom = prevLayer.dom;
  36149. if (prevDom.nextSibling) {
  36150. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  36151. }
  36152. else {
  36153. domRoot.appendChild(layer.dom);
  36154. }
  36155. }
  36156. else {
  36157. if (domRoot.firstChild) {
  36158. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  36159. }
  36160. else {
  36161. domRoot.appendChild(layer.dom);
  36162. }
  36163. }
  36164. }
  36165. layer.__painter = this;
  36166. };
  36167. CanvasPainter.prototype.eachLayer = function (cb, context) {
  36168. var zlevelList = this._zlevelList;
  36169. for (var i = 0; i < zlevelList.length; i++) {
  36170. var z = zlevelList[i];
  36171. cb.call(context, this._layers[z], z);
  36172. }
  36173. };
  36174. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  36175. var zlevelList = this._zlevelList;
  36176. for (var i = 0; i < zlevelList.length; i++) {
  36177. var z = zlevelList[i];
  36178. var layer = this._layers[z];
  36179. if (layer.__builtin__) {
  36180. cb.call(context, layer, z);
  36181. }
  36182. }
  36183. };
  36184. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  36185. var zlevelList = this._zlevelList;
  36186. for (var i = 0; i < zlevelList.length; i++) {
  36187. var z = zlevelList[i];
  36188. var layer = this._layers[z];
  36189. if (!layer.__builtin__) {
  36190. cb.call(context, layer, z);
  36191. }
  36192. }
  36193. };
  36194. CanvasPainter.prototype.getLayers = function () {
  36195. return this._layers;
  36196. };
  36197. CanvasPainter.prototype._updateLayerStatus = function (list) {
  36198. this.eachBuiltinLayer(function (layer, z) {
  36199. layer.__dirty = layer.__used = false;
  36200. });
  36201. function updatePrevLayer(idx) {
  36202. if (prevLayer) {
  36203. if (prevLayer.__endIndex !== idx) {
  36204. prevLayer.__dirty = true;
  36205. }
  36206. prevLayer.__endIndex = idx;
  36207. }
  36208. }
  36209. if (this._singleCanvas) {
  36210. for (var i_1 = 1; i_1 < list.length; i_1++) {
  36211. var el = list[i_1];
  36212. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  36213. this._needsManuallyCompositing = true;
  36214. break;
  36215. }
  36216. }
  36217. }
  36218. var prevLayer = null;
  36219. var incrementalLayerCount = 0;
  36220. var prevZlevel;
  36221. var i;
  36222. for (i = 0; i < list.length; i++) {
  36223. var el = list[i];
  36224. var zlevel = el.zlevel;
  36225. var layer = void 0;
  36226. if (prevZlevel !== zlevel) {
  36227. prevZlevel = zlevel;
  36228. incrementalLayerCount = 0;
  36229. }
  36230. if (el.incremental) {
  36231. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  36232. layer.incremental = true;
  36233. incrementalLayerCount = 1;
  36234. }
  36235. else {
  36236. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  36237. }
  36238. if (!layer.__builtin__) {
  36239. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  36240. }
  36241. if (layer !== prevLayer) {
  36242. layer.__used = true;
  36243. if (layer.__startIndex !== i) {
  36244. layer.__dirty = true;
  36245. }
  36246. layer.__startIndex = i;
  36247. if (!layer.incremental) {
  36248. layer.__drawIndex = i;
  36249. }
  36250. else {
  36251. layer.__drawIndex = -1;
  36252. }
  36253. updatePrevLayer(i);
  36254. prevLayer = layer;
  36255. }
  36256. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  36257. layer.__dirty = true;
  36258. if (layer.incremental && layer.__drawIndex < 0) {
  36259. layer.__drawIndex = i;
  36260. }
  36261. }
  36262. }
  36263. updatePrevLayer(i);
  36264. this.eachBuiltinLayer(function (layer, z) {
  36265. if (!layer.__used && layer.getElementCount() > 0) {
  36266. layer.__dirty = true;
  36267. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  36268. }
  36269. if (layer.__dirty && layer.__drawIndex < 0) {
  36270. layer.__drawIndex = layer.__startIndex;
  36271. }
  36272. });
  36273. };
  36274. CanvasPainter.prototype.clear = function () {
  36275. this.eachBuiltinLayer(this._clearLayer);
  36276. return this;
  36277. };
  36278. CanvasPainter.prototype._clearLayer = function (layer) {
  36279. layer.clear();
  36280. };
  36281. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  36282. this._backgroundColor = backgroundColor;
  36283. each(this._layers, function (layer) {
  36284. layer.setUnpainted();
  36285. });
  36286. };
  36287. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  36288. if (config) {
  36289. var layerConfig = this._layerConfig;
  36290. if (!layerConfig[zlevel]) {
  36291. layerConfig[zlevel] = config;
  36292. }
  36293. else {
  36294. merge(layerConfig[zlevel], config, true);
  36295. }
  36296. for (var i = 0; i < this._zlevelList.length; i++) {
  36297. var _zlevel = this._zlevelList[i];
  36298. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  36299. var layer = this._layers[_zlevel];
  36300. merge(layer, layerConfig[zlevel], true);
  36301. }
  36302. }
  36303. }
  36304. };
  36305. CanvasPainter.prototype.delLayer = function (zlevel) {
  36306. var layers = this._layers;
  36307. var zlevelList = this._zlevelList;
  36308. var layer = layers[zlevel];
  36309. if (!layer) {
  36310. return;
  36311. }
  36312. layer.dom.parentNode.removeChild(layer.dom);
  36313. delete layers[zlevel];
  36314. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  36315. };
  36316. CanvasPainter.prototype.resize = function (width, height) {
  36317. if (!this._domRoot.style) {
  36318. if (width == null || height == null) {
  36319. return;
  36320. }
  36321. this._width = width;
  36322. this._height = height;
  36323. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  36324. }
  36325. else {
  36326. var domRoot = this._domRoot;
  36327. domRoot.style.display = 'none';
  36328. var opts = this._opts;
  36329. var root = this.root;
  36330. width != null && (opts.width = width);
  36331. height != null && (opts.height = height);
  36332. width = getSize(root, 0, opts);
  36333. height = getSize(root, 1, opts);
  36334. domRoot.style.display = '';
  36335. if (this._width !== width || height !== this._height) {
  36336. domRoot.style.width = width + 'px';
  36337. domRoot.style.height = height + 'px';
  36338. for (var id in this._layers) {
  36339. if (this._layers.hasOwnProperty(id)) {
  36340. this._layers[id].resize(width, height);
  36341. }
  36342. }
  36343. this.refresh(true);
  36344. }
  36345. this._width = width;
  36346. this._height = height;
  36347. }
  36348. return this;
  36349. };
  36350. CanvasPainter.prototype.clearLayer = function (zlevel) {
  36351. var layer = this._layers[zlevel];
  36352. if (layer) {
  36353. layer.clear();
  36354. }
  36355. };
  36356. CanvasPainter.prototype.dispose = function () {
  36357. this.root.innerHTML = '';
  36358. this.root =
  36359. this.storage =
  36360. this._domRoot =
  36361. this._layers = null;
  36362. };
  36363. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  36364. opts = opts || {};
  36365. if (this._singleCanvas && !this._compositeManually) {
  36366. return this._layers[CANVAS_ZLEVEL].dom;
  36367. }
  36368. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  36369. imageLayer.initContext();
  36370. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  36371. var ctx = imageLayer.ctx;
  36372. if (opts.pixelRatio <= this.dpr) {
  36373. this.refresh();
  36374. var width_1 = imageLayer.dom.width;
  36375. var height_1 = imageLayer.dom.height;
  36376. this.eachLayer(function (layer) {
  36377. if (layer.__builtin__) {
  36378. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  36379. }
  36380. else if (layer.renderToCanvas) {
  36381. ctx.save();
  36382. layer.renderToCanvas(ctx);
  36383. ctx.restore();
  36384. }
  36385. });
  36386. }
  36387. else {
  36388. var scope = {
  36389. inHover: false,
  36390. viewWidth: this._width,
  36391. viewHeight: this._height
  36392. };
  36393. var displayList = this.storage.getDisplayList(true);
  36394. for (var i = 0, len = displayList.length; i < len; i++) {
  36395. var el = displayList[i];
  36396. brush(ctx, el, scope, i === len - 1);
  36397. }
  36398. }
  36399. return imageLayer.dom;
  36400. };
  36401. CanvasPainter.prototype.getWidth = function () {
  36402. return this._width;
  36403. };
  36404. CanvasPainter.prototype.getHeight = function () {
  36405. return this._height;
  36406. };
  36407. return CanvasPainter;
  36408. }());
  36409. function install$1(registers) {
  36410. registers.registerPainter('canvas', CanvasPainter);
  36411. }
  36412. var LineSeriesModel =
  36413. /** @class */
  36414. function (_super) {
  36415. __extends(LineSeriesModel, _super);
  36416. function LineSeriesModel() {
  36417. var _this = _super !== null && _super.apply(this, arguments) || this;
  36418. _this.type = LineSeriesModel.type;
  36419. _this.hasSymbolVisual = true;
  36420. return _this;
  36421. }
  36422. LineSeriesModel.prototype.getInitialData = function (option) {
  36423. if ("development" !== 'production') {
  36424. var coordSys = option.coordinateSystem;
  36425. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  36426. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  36427. }
  36428. }
  36429. return createSeriesData(null, this, {
  36430. useEncodeDefaulter: true
  36431. });
  36432. };
  36433. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  36434. var group = new Group();
  36435. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  36436. group.add(line);
  36437. line.setStyle(opt.lineStyle);
  36438. var visualType = this.getData().getVisual('symbol');
  36439. var visualRotate = this.getData().getVisual('symbolRotate');
  36440. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  36441. var size = opt.itemHeight * 0.8;
  36442. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  36443. group.add(symbol);
  36444. symbol.setStyle(opt.itemStyle);
  36445. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  36446. symbol.rotation = symbolRotate * Math.PI / 180;
  36447. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  36448. if (symbolType.indexOf('empty') > -1) {
  36449. symbol.style.stroke = symbol.style.fill;
  36450. symbol.style.fill = '#fff';
  36451. symbol.style.lineWidth = 2;
  36452. }
  36453. return group;
  36454. };
  36455. LineSeriesModel.type = 'series.line';
  36456. LineSeriesModel.dependencies = ['grid', 'polar'];
  36457. LineSeriesModel.defaultOption = {
  36458. // zlevel: 0,
  36459. z: 3,
  36460. coordinateSystem: 'cartesian2d',
  36461. legendHoverLink: true,
  36462. clip: true,
  36463. label: {
  36464. position: 'top'
  36465. },
  36466. // itemStyle: {
  36467. // },
  36468. endLabel: {
  36469. show: false,
  36470. valueAnimation: true,
  36471. distance: 8
  36472. },
  36473. lineStyle: {
  36474. width: 2,
  36475. type: 'solid'
  36476. },
  36477. emphasis: {
  36478. scale: true
  36479. },
  36480. // areaStyle: {
  36481. // origin of areaStyle. Valid values:
  36482. // `'auto'/null/undefined`: from axisLine to data
  36483. // `'start'`: from min to data
  36484. // `'end'`: from data to max
  36485. // origin: 'auto'
  36486. // },
  36487. // false, 'start', 'end', 'middle'
  36488. step: false,
  36489. // Disabled if step is true
  36490. smooth: false,
  36491. smoothMonotone: null,
  36492. symbol: 'emptyCircle',
  36493. symbolSize: 4,
  36494. symbolRotate: null,
  36495. showSymbol: true,
  36496. // `false`: follow the label interval strategy.
  36497. // `true`: show all symbols.
  36498. // `'auto'`: If possible, show all symbols, otherwise
  36499. // follow the label interval strategy.
  36500. showAllSymbol: 'auto',
  36501. // Whether to connect break point.
  36502. connectNulls: false,
  36503. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  36504. sampling: 'none',
  36505. animationEasing: 'linear',
  36506. // Disable progressive
  36507. progressive: 0,
  36508. hoverLayerThreshold: Infinity,
  36509. universalTransition: {
  36510. divideShape: 'clone'
  36511. },
  36512. triggerLineEvent: false
  36513. };
  36514. return LineSeriesModel;
  36515. }(SeriesModel);
  36516. /**
  36517. * @return label string. Not null/undefined
  36518. */
  36519. function getDefaultLabel(data, dataIndex) {
  36520. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36521. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  36522. if (len === 1) {
  36523. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  36524. return rawVal != null ? rawVal + '' : null;
  36525. } else if (len) {
  36526. var vals = [];
  36527. for (var i = 0; i < labelDims.length; i++) {
  36528. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  36529. }
  36530. return vals.join(' ');
  36531. }
  36532. }
  36533. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  36534. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36535. if (!isArray(interpolatedValue)) {
  36536. return interpolatedValue + '';
  36537. }
  36538. var vals = [];
  36539. for (var i = 0; i < labelDims.length; i++) {
  36540. var dimIndex = data.getDimensionIndex(labelDims[i]);
  36541. if (dimIndex >= 0) {
  36542. vals.push(interpolatedValue[dimIndex]);
  36543. }
  36544. }
  36545. return vals.join(' ');
  36546. }
  36547. var Symbol =
  36548. /** @class */
  36549. function (_super) {
  36550. __extends(Symbol, _super);
  36551. function Symbol(data, idx, seriesScope, opts) {
  36552. var _this = _super.call(this) || this;
  36553. _this.updateData(data, idx, seriesScope, opts);
  36554. return _this;
  36555. }
  36556. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  36557. // Remove paths created before
  36558. this.removeAll(); // let symbolPath = createSymbol(
  36559. // symbolType, -0.5, -0.5, 1, 1, color
  36560. // );
  36561. // If width/height are set too small (e.g., set to 1) on ios10
  36562. // and macOS Sierra, a circle stroke become a rect, no matter what
  36563. // the scale is set. So we set width/height as 2. See #4150.
  36564. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  36565. symbolPath.attr({
  36566. z2: 100,
  36567. culling: true,
  36568. scaleX: symbolSize[0] / 2,
  36569. scaleY: symbolSize[1] / 2
  36570. }); // Rewrite drift method
  36571. symbolPath.drift = driftSymbol;
  36572. this._symbolType = symbolType;
  36573. this.add(symbolPath);
  36574. };
  36575. /**
  36576. * Stop animation
  36577. * @param {boolean} toLastFrame
  36578. */
  36579. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  36580. this.childAt(0).stopAnimation(null, toLastFrame);
  36581. };
  36582. Symbol.prototype.getSymbolType = function () {
  36583. return this._symbolType;
  36584. };
  36585. /**
  36586. * FIXME:
  36587. * Caution: This method breaks the encapsulation of this module,
  36588. * but it indeed brings convenience. So do not use the method
  36589. * unless you detailedly know all the implements of `Symbol`,
  36590. * especially animation.
  36591. *
  36592. * Get symbol path element.
  36593. */
  36594. Symbol.prototype.getSymbolPath = function () {
  36595. return this.childAt(0);
  36596. };
  36597. /**
  36598. * Highlight symbol
  36599. */
  36600. Symbol.prototype.highlight = function () {
  36601. enterEmphasis(this.childAt(0));
  36602. };
  36603. /**
  36604. * Downplay symbol
  36605. */
  36606. Symbol.prototype.downplay = function () {
  36607. leaveEmphasis(this.childAt(0));
  36608. };
  36609. /**
  36610. * @param {number} zlevel
  36611. * @param {number} z
  36612. */
  36613. Symbol.prototype.setZ = function (zlevel, z) {
  36614. var symbolPath = this.childAt(0);
  36615. symbolPath.zlevel = zlevel;
  36616. symbolPath.z = z;
  36617. };
  36618. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  36619. var symbolPath = this.childAt(0);
  36620. symbolPath.draggable = draggable;
  36621. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  36622. };
  36623. /**
  36624. * Update symbol properties
  36625. */
  36626. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  36627. this.silent = false;
  36628. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36629. var seriesModel = data.hostModel;
  36630. var symbolSize = Symbol.getSymbolSize(data, idx);
  36631. var isInit = symbolType !== this._symbolType;
  36632. var disableAnimation = opts && opts.disableAnimation;
  36633. if (isInit) {
  36634. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  36635. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  36636. } else {
  36637. var symbolPath = this.childAt(0);
  36638. symbolPath.silent = false;
  36639. var target = {
  36640. scaleX: symbolSize[0] / 2,
  36641. scaleY: symbolSize[1] / 2
  36642. };
  36643. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  36644. saveOldStyle(symbolPath);
  36645. }
  36646. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  36647. if (isInit) {
  36648. var symbolPath = this.childAt(0);
  36649. if (!disableAnimation) {
  36650. var target = {
  36651. scaleX: this._sizeX,
  36652. scaleY: this._sizeY,
  36653. style: {
  36654. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  36655. opacity: symbolPath.style.opacity
  36656. }
  36657. };
  36658. symbolPath.scaleX = symbolPath.scaleY = 0;
  36659. symbolPath.style.opacity = 0;
  36660. initProps(symbolPath, target, seriesModel, idx);
  36661. }
  36662. }
  36663. if (disableAnimation) {
  36664. // Must stop leave transition manually if don't call initProps or updateProps.
  36665. this.childAt(0).stopAnimation('leave');
  36666. }
  36667. };
  36668. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  36669. var symbolPath = this.childAt(0);
  36670. var seriesModel = data.hostModel;
  36671. var emphasisItemStyle;
  36672. var blurItemStyle;
  36673. var selectItemStyle;
  36674. var focus;
  36675. var blurScope;
  36676. var emphasisDisabled;
  36677. var labelStatesModels;
  36678. var hoverScale;
  36679. var cursorStyle;
  36680. if (seriesScope) {
  36681. emphasisItemStyle = seriesScope.emphasisItemStyle;
  36682. blurItemStyle = seriesScope.blurItemStyle;
  36683. selectItemStyle = seriesScope.selectItemStyle;
  36684. focus = seriesScope.focus;
  36685. blurScope = seriesScope.blurScope;
  36686. labelStatesModels = seriesScope.labelStatesModels;
  36687. hoverScale = seriesScope.hoverScale;
  36688. cursorStyle = seriesScope.cursorStyle;
  36689. emphasisDisabled = seriesScope.emphasisDisabled;
  36690. }
  36691. if (!seriesScope || data.hasItemOption) {
  36692. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  36693. var emphasisModel = itemModel.getModel('emphasis');
  36694. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  36695. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  36696. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  36697. focus = emphasisModel.get('focus');
  36698. blurScope = emphasisModel.get('blurScope');
  36699. emphasisDisabled = emphasisModel.get('disabled');
  36700. labelStatesModels = getLabelStatesModels(itemModel);
  36701. hoverScale = emphasisModel.getShallow('scale');
  36702. cursorStyle = itemModel.getShallow('cursor');
  36703. }
  36704. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  36705. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  36706. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  36707. if (symbolOffset) {
  36708. symbolPath.x = symbolOffset[0];
  36709. symbolPath.y = symbolOffset[1];
  36710. }
  36711. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  36712. var symbolStyle = data.getItemVisual(idx, 'style');
  36713. var visualColor = symbolStyle.fill;
  36714. if (symbolPath instanceof ZRImage) {
  36715. var pathStyle = symbolPath.style;
  36716. symbolPath.useStyle(extend({
  36717. // TODO other properties like x, y ?
  36718. image: pathStyle.image,
  36719. x: pathStyle.x,
  36720. y: pathStyle.y,
  36721. width: pathStyle.width,
  36722. height: pathStyle.height
  36723. }, symbolStyle));
  36724. } else {
  36725. if (symbolPath.__isEmptyBrush) {
  36726. // fill and stroke will be swapped if it's empty.
  36727. // So we cloned a new style to avoid it affecting the original style in visual storage.
  36728. // TODO Better implementation. No empty logic!
  36729. symbolPath.useStyle(extend({}, symbolStyle));
  36730. } else {
  36731. symbolPath.useStyle(symbolStyle);
  36732. } // Disable decal because symbol scale will been applied on the decal.
  36733. symbolPath.style.decal = null;
  36734. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  36735. symbolPath.style.strokeNoScale = true;
  36736. }
  36737. var liftZ = data.getItemVisual(idx, 'liftZ');
  36738. var z2Origin = this._z2;
  36739. if (liftZ != null) {
  36740. if (z2Origin == null) {
  36741. this._z2 = symbolPath.z2;
  36742. symbolPath.z2 += liftZ;
  36743. }
  36744. } else if (z2Origin != null) {
  36745. symbolPath.z2 = z2Origin;
  36746. this._z2 = null;
  36747. }
  36748. var useNameLabel = opts && opts.useNameLabel;
  36749. setLabelStyle(symbolPath, labelStatesModels, {
  36750. labelFetcher: seriesModel,
  36751. labelDataIndex: idx,
  36752. defaultText: getLabelDefaultText,
  36753. inheritColor: visualColor,
  36754. defaultOpacity: symbolStyle.opacity
  36755. }); // Do not execute util needed.
  36756. function getLabelDefaultText(idx) {
  36757. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  36758. }
  36759. this._sizeX = symbolSize[0] / 2;
  36760. this._sizeY = symbolSize[1] / 2;
  36761. var emphasisState = symbolPath.ensureState('emphasis');
  36762. emphasisState.style = emphasisItemStyle;
  36763. symbolPath.ensureState('select').style = selectItemStyle;
  36764. symbolPath.ensureState('blur').style = blurItemStyle; // null / undefined / true means to use default strategy.
  36765. // 0 / false / negative number / NaN / Infinity means no scale.
  36766. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY) // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  36767. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1; // always set scale to allow resetting
  36768. emphasisState.scaleX = this._sizeX * scaleRatio;
  36769. emphasisState.scaleY = this._sizeY * scaleRatio;
  36770. this.setSymbolScale(1);
  36771. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  36772. };
  36773. Symbol.prototype.setSymbolScale = function (scale) {
  36774. this.scaleX = this.scaleY = scale;
  36775. };
  36776. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  36777. var symbolPath = this.childAt(0);
  36778. var dataIndex = getECData(this).dataIndex;
  36779. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  36780. this.silent = symbolPath.silent = true; // Not show text when animating
  36781. if (opt && opt.fadeLabel) {
  36782. var textContent = symbolPath.getTextContent();
  36783. if (textContent) {
  36784. removeElement(textContent, {
  36785. style: {
  36786. opacity: 0
  36787. }
  36788. }, seriesModel, {
  36789. dataIndex: dataIndex,
  36790. removeOpt: animationOpt,
  36791. cb: function () {
  36792. symbolPath.removeTextContent();
  36793. }
  36794. });
  36795. }
  36796. } else {
  36797. symbolPath.removeTextContent();
  36798. }
  36799. removeElement(symbolPath, {
  36800. style: {
  36801. opacity: 0
  36802. },
  36803. scaleX: 0,
  36804. scaleY: 0
  36805. }, seriesModel, {
  36806. dataIndex: dataIndex,
  36807. cb: cb,
  36808. removeOpt: animationOpt
  36809. });
  36810. };
  36811. Symbol.getSymbolSize = function (data, idx) {
  36812. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  36813. };
  36814. return Symbol;
  36815. }(Group);
  36816. function driftSymbol(dx, dy) {
  36817. this.parent.drift(dx, dy);
  36818. }
  36819. function symbolNeedsDraw(data, point, idx, opt) {
  36820. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) // We do not set clipShape on group, because it will cut part of
  36821. // the symbol element shape. We use the same clip shape here as
  36822. // the line clip.
  36823. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  36824. }
  36825. function normalizeUpdateOpt(opt) {
  36826. if (opt != null && !isObject(opt)) {
  36827. opt = {
  36828. isIgnore: opt
  36829. };
  36830. }
  36831. return opt || {};
  36832. }
  36833. function makeSeriesScope(data) {
  36834. var seriesModel = data.hostModel;
  36835. var emphasisModel = seriesModel.getModel('emphasis');
  36836. return {
  36837. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  36838. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  36839. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  36840. focus: emphasisModel.get('focus'),
  36841. blurScope: emphasisModel.get('blurScope'),
  36842. emphasisDisabled: emphasisModel.get('disabled'),
  36843. hoverScale: emphasisModel.get('scale'),
  36844. labelStatesModels: getLabelStatesModels(seriesModel),
  36845. cursorStyle: seriesModel.get('cursor')
  36846. };
  36847. }
  36848. var SymbolDraw =
  36849. /** @class */
  36850. function () {
  36851. function SymbolDraw(SymbolCtor) {
  36852. this.group = new Group();
  36853. this._SymbolCtor = SymbolCtor || Symbol;
  36854. }
  36855. /**
  36856. * Update symbols draw by new data
  36857. */
  36858. SymbolDraw.prototype.updateData = function (data, opt) {
  36859. // Remove progressive els.
  36860. this._progressiveEls = null;
  36861. opt = normalizeUpdateOpt(opt);
  36862. var group = this.group;
  36863. var seriesModel = data.hostModel;
  36864. var oldData = this._data;
  36865. var SymbolCtor = this._SymbolCtor;
  36866. var disableAnimation = opt.disableAnimation;
  36867. var seriesScope = makeSeriesScope(data);
  36868. var symbolUpdateOpt = {
  36869. disableAnimation: disableAnimation
  36870. };
  36871. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  36872. return data.getItemLayout(idx);
  36873. }; // There is no oldLineData only when first rendering or switching from
  36874. // stream mode to normal mode, where previous elements should be removed.
  36875. if (!oldData) {
  36876. group.removeAll();
  36877. }
  36878. data.diff(oldData).add(function (newIdx) {
  36879. var point = getSymbolPoint(newIdx);
  36880. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  36881. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36882. symbolEl.setPosition(point);
  36883. data.setItemGraphicEl(newIdx, symbolEl);
  36884. group.add(symbolEl);
  36885. }
  36886. }).update(function (newIdx, oldIdx) {
  36887. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36888. var point = getSymbolPoint(newIdx);
  36889. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  36890. group.remove(symbolEl);
  36891. return;
  36892. }
  36893. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  36894. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  36895. if (!symbolEl // Create a new if symbol type changed.
  36896. || oldSymbolType && oldSymbolType !== newSymbolType) {
  36897. group.remove(symbolEl);
  36898. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36899. symbolEl.setPosition(point);
  36900. } else {
  36901. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  36902. var target = {
  36903. x: point[0],
  36904. y: point[1]
  36905. };
  36906. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  36907. } // Add back
  36908. group.add(symbolEl);
  36909. data.setItemGraphicEl(newIdx, symbolEl);
  36910. }).remove(function (oldIdx) {
  36911. var el = oldData.getItemGraphicEl(oldIdx);
  36912. el && el.fadeOut(function () {
  36913. group.remove(el);
  36914. }, seriesModel);
  36915. }).execute();
  36916. this._getSymbolPoint = getSymbolPoint;
  36917. this._data = data;
  36918. };
  36919. SymbolDraw.prototype.updateLayout = function () {
  36920. var _this = this;
  36921. var data = this._data;
  36922. if (data) {
  36923. // Not use animation
  36924. data.eachItemGraphicEl(function (el, idx) {
  36925. var point = _this._getSymbolPoint(idx);
  36926. el.setPosition(point);
  36927. el.markRedraw();
  36928. });
  36929. }
  36930. };
  36931. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  36932. this._seriesScope = makeSeriesScope(data);
  36933. this._data = null;
  36934. this.group.removeAll();
  36935. };
  36936. /**
  36937. * Update symbols draw by new data
  36938. */
  36939. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  36940. // Clear
  36941. this._progressiveEls = [];
  36942. opt = normalizeUpdateOpt(opt);
  36943. function updateIncrementalAndHover(el) {
  36944. if (!el.isGroup) {
  36945. el.incremental = true;
  36946. el.ensureState('emphasis').hoverLayer = true;
  36947. }
  36948. }
  36949. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  36950. var point = data.getItemLayout(idx);
  36951. if (symbolNeedsDraw(data, point, idx, opt)) {
  36952. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  36953. el.traverse(updateIncrementalAndHover);
  36954. el.setPosition(point);
  36955. this.group.add(el);
  36956. data.setItemGraphicEl(idx, el);
  36957. this._progressiveEls.push(el);
  36958. }
  36959. }
  36960. };
  36961. SymbolDraw.prototype.eachRendered = function (cb) {
  36962. traverseElements(this._progressiveEls || this.group, cb);
  36963. };
  36964. SymbolDraw.prototype.remove = function (enableAnimation) {
  36965. var group = this.group;
  36966. var data = this._data; // Incremental model do not have this._data.
  36967. if (data && enableAnimation) {
  36968. data.eachItemGraphicEl(function (el) {
  36969. el.fadeOut(function () {
  36970. group.remove(el);
  36971. }, data.hostModel);
  36972. });
  36973. } else {
  36974. group.removeAll();
  36975. }
  36976. };
  36977. return SymbolDraw;
  36978. }();
  36979. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  36980. var baseAxis = coordSys.getBaseAxis();
  36981. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36982. var valueStart = getValueStart(valueAxis, valueOrigin);
  36983. var baseAxisDim = baseAxis.dim;
  36984. var valueAxisDim = valueAxis.dim;
  36985. var valueDim = data.mapDimension(valueAxisDim);
  36986. var baseDim = data.mapDimension(baseAxisDim);
  36987. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  36988. var dims = map(coordSys.dimensions, function (coordDim) {
  36989. return data.mapDimension(coordDim);
  36990. });
  36991. var stacked = false;
  36992. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36993. if (isDimensionStacked(data, dims[0]
  36994. /* , dims[1] */
  36995. )) {
  36996. // jshint ignore:line
  36997. stacked = true;
  36998. dims[0] = stackResultDim;
  36999. }
  37000. if (isDimensionStacked(data, dims[1]
  37001. /* , dims[0] */
  37002. )) {
  37003. // jshint ignore:line
  37004. stacked = true;
  37005. dims[1] = stackResultDim;
  37006. }
  37007. return {
  37008. dataDimsForPoint: dims,
  37009. valueStart: valueStart,
  37010. valueAxisDim: valueAxisDim,
  37011. baseAxisDim: baseAxisDim,
  37012. stacked: !!stacked,
  37013. valueDim: valueDim,
  37014. baseDim: baseDim,
  37015. baseDataOffset: baseDataOffset,
  37016. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  37017. };
  37018. }
  37019. function getValueStart(valueAxis, valueOrigin) {
  37020. var valueStart = 0;
  37021. var extent = valueAxis.scale.getExtent();
  37022. if (valueOrigin === 'start') {
  37023. valueStart = extent[0];
  37024. } else if (valueOrigin === 'end') {
  37025. valueStart = extent[1];
  37026. } // If origin is specified as a number, use it as
  37027. // valueStart directly
  37028. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  37029. valueStart = valueOrigin;
  37030. } // auto
  37031. else {
  37032. // Both positive
  37033. if (extent[0] > 0) {
  37034. valueStart = extent[0];
  37035. } // Both negative
  37036. else if (extent[1] < 0) {
  37037. valueStart = extent[1];
  37038. } // If is one positive, and one negative, onZero shall be true
  37039. }
  37040. return valueStart;
  37041. }
  37042. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  37043. var value = NaN;
  37044. if (dataCoordInfo.stacked) {
  37045. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  37046. }
  37047. if (isNaN(value)) {
  37048. value = dataCoordInfo.valueStart;
  37049. }
  37050. var baseDataOffset = dataCoordInfo.baseDataOffset;
  37051. var stackedData = [];
  37052. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  37053. stackedData[1 - baseDataOffset] = value;
  37054. return coordSys.dataToPoint(stackedData);
  37055. }
  37056. function diffData(oldData, newData) {
  37057. var diffResult = [];
  37058. newData.diff(oldData).add(function (idx) {
  37059. diffResult.push({
  37060. cmd: '+',
  37061. idx: idx
  37062. });
  37063. }).update(function (newIdx, oldIdx) {
  37064. diffResult.push({
  37065. cmd: '=',
  37066. idx: oldIdx,
  37067. idx1: newIdx
  37068. });
  37069. }).remove(function (idx) {
  37070. diffResult.push({
  37071. cmd: '-',
  37072. idx: idx
  37073. });
  37074. }).execute();
  37075. return diffResult;
  37076. }
  37077. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  37078. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  37079. // let oldIdList = oldData.mapArray(oldData.getId);
  37080. // convertToIntId(newIdList, oldIdList);
  37081. // // FIXME One data ?
  37082. // diff = arrayDiff(oldIdList, newIdList);
  37083. var currPoints = [];
  37084. var nextPoints = []; // Points for stacking base line
  37085. var currStackedPoints = [];
  37086. var nextStackedPoints = [];
  37087. var status = [];
  37088. var sortedIndices = [];
  37089. var rawIndices = [];
  37090. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  37091. var oldPoints = oldData.getLayout('points') || [];
  37092. var newPoints = newData.getLayout('points') || [];
  37093. for (var i = 0; i < diff.length; i++) {
  37094. var diffItem = diff[i];
  37095. var pointAdded = true;
  37096. var oldIdx2 = void 0;
  37097. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  37098. // Which is in case remvoing or add more than one data in the tail or head
  37099. switch (diffItem.cmd) {
  37100. case '=':
  37101. oldIdx2 = diffItem.idx * 2;
  37102. newIdx2 = diffItem.idx1 * 2;
  37103. var currentX = oldPoints[oldIdx2];
  37104. var currentY = oldPoints[oldIdx2 + 1];
  37105. var nextX = newPoints[newIdx2];
  37106. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  37107. if (isNaN(currentX) || isNaN(currentY)) {
  37108. currentX = nextX;
  37109. currentY = nextY;
  37110. }
  37111. currPoints.push(currentX, currentY);
  37112. nextPoints.push(nextX, nextY);
  37113. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  37114. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37115. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  37116. break;
  37117. case '+':
  37118. var newIdx = diffItem.idx;
  37119. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  37120. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  37121. newIdx2 = newIdx * 2;
  37122. currPoints.push(oldPt[0], oldPt[1]);
  37123. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  37124. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  37125. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  37126. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37127. rawIndices.push(newData.getRawIndex(newIdx));
  37128. break;
  37129. case '-':
  37130. pointAdded = false;
  37131. } // Original indices
  37132. if (pointAdded) {
  37133. status.push(diffItem);
  37134. sortedIndices.push(sortedIndices.length);
  37135. }
  37136. } // Diff result may be crossed if all items are changed
  37137. // Sort by data index
  37138. sortedIndices.sort(function (a, b) {
  37139. return rawIndices[a] - rawIndices[b];
  37140. });
  37141. var len = currPoints.length;
  37142. var sortedCurrPoints = createFloat32Array(len);
  37143. var sortedNextPoints = createFloat32Array(len);
  37144. var sortedCurrStackedPoints = createFloat32Array(len);
  37145. var sortedNextStackedPoints = createFloat32Array(len);
  37146. var sortedStatus = [];
  37147. for (var i = 0; i < sortedIndices.length; i++) {
  37148. var idx = sortedIndices[i];
  37149. var i2 = i * 2;
  37150. var idx2 = idx * 2;
  37151. sortedCurrPoints[i2] = currPoints[idx2];
  37152. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  37153. sortedNextPoints[i2] = nextPoints[idx2];
  37154. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  37155. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  37156. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  37157. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  37158. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  37159. sortedStatus[i] = status[idx];
  37160. }
  37161. return {
  37162. current: sortedCurrPoints,
  37163. next: sortedNextPoints,
  37164. stackedOnCurrent: sortedCurrStackedPoints,
  37165. stackedOnNext: sortedNextStackedPoints,
  37166. status: sortedStatus
  37167. };
  37168. }
  37169. var mathMin$5 = Math.min;
  37170. var mathMax$5 = Math.max;
  37171. function isPointNull(x, y) {
  37172. return isNaN(x) || isNaN(y);
  37173. }
  37174. /**
  37175. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  37176. * situations. This should be used when points are non-monotone neither in x or
  37177. * y dimension.
  37178. */
  37179. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  37180. var prevX;
  37181. var prevY;
  37182. var cpx0;
  37183. var cpy0;
  37184. var cpx1;
  37185. var cpy1;
  37186. var idx = start;
  37187. var k = 0;
  37188. for (; k < segLen; k++) {
  37189. var x = points[idx * 2];
  37190. var y = points[idx * 2 + 1];
  37191. if (idx >= allLen || idx < 0) {
  37192. break;
  37193. }
  37194. if (isPointNull(x, y)) {
  37195. if (connectNulls) {
  37196. idx += dir;
  37197. continue;
  37198. }
  37199. break;
  37200. }
  37201. if (idx === start) {
  37202. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  37203. cpx0 = x;
  37204. cpy0 = y;
  37205. } else {
  37206. var dx = x - prevX;
  37207. var dy = y - prevY; // Ignore tiny segment.
  37208. if (dx * dx + dy * dy < 0.5) {
  37209. idx += dir;
  37210. continue;
  37211. }
  37212. if (smooth > 0) {
  37213. var nextIdx = idx + dir;
  37214. var nextX = points[nextIdx * 2];
  37215. var nextY = points[nextIdx * 2 + 1]; // Ignore duplicate point
  37216. while (nextX === x && nextY === y && k < segLen) {
  37217. k++;
  37218. nextIdx += dir;
  37219. idx += dir;
  37220. nextX = points[nextIdx * 2];
  37221. nextY = points[nextIdx * 2 + 1];
  37222. x = points[idx * 2];
  37223. y = points[idx * 2 + 1];
  37224. dx = x - prevX;
  37225. dy = y - prevY;
  37226. }
  37227. var tmpK = k + 1;
  37228. if (connectNulls) {
  37229. // Find next point not null
  37230. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  37231. tmpK++;
  37232. nextIdx += dir;
  37233. nextX = points[nextIdx * 2];
  37234. nextY = points[nextIdx * 2 + 1];
  37235. }
  37236. }
  37237. var ratioNextSeg = 0.5;
  37238. var vx = 0;
  37239. var vy = 0;
  37240. var nextCpx0 = void 0;
  37241. var nextCpy0 = void 0; // Is last point
  37242. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  37243. cpx1 = x;
  37244. cpy1 = y;
  37245. } else {
  37246. vx = nextX - prevX;
  37247. vy = nextY - prevY;
  37248. var dx0 = x - prevX;
  37249. var dx1 = nextX - x;
  37250. var dy0 = y - prevY;
  37251. var dy1 = nextY - y;
  37252. var lenPrevSeg = void 0;
  37253. var lenNextSeg = void 0;
  37254. if (smoothMonotone === 'x') {
  37255. lenPrevSeg = Math.abs(dx0);
  37256. lenNextSeg = Math.abs(dx1);
  37257. var dir_1 = vx > 0 ? 1 : -1;
  37258. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  37259. cpy1 = y;
  37260. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  37261. nextCpy0 = y;
  37262. } else if (smoothMonotone === 'y') {
  37263. lenPrevSeg = Math.abs(dy0);
  37264. lenNextSeg = Math.abs(dy1);
  37265. var dir_2 = vy > 0 ? 1 : -1;
  37266. cpx1 = x;
  37267. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  37268. nextCpx0 = x;
  37269. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  37270. } else {
  37271. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  37272. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  37273. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  37274. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  37275. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  37276. nextCpx0 = x + vx * smooth * ratioNextSeg;
  37277. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  37278. // Avoid exceeding extreme after smoothing.
  37279. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  37280. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  37281. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  37282. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  37283. vx = nextCpx0 - x;
  37284. vy = nextCpy0 - y;
  37285. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  37286. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  37287. // Avoid exceeding extreme after smoothing.
  37288. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  37289. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  37290. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  37291. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  37292. vx = x - cpx1;
  37293. vy = y - cpy1;
  37294. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  37295. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  37296. }
  37297. }
  37298. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  37299. cpx0 = nextCpx0;
  37300. cpy0 = nextCpy0;
  37301. } else {
  37302. ctx.lineTo(x, y);
  37303. }
  37304. }
  37305. prevX = x;
  37306. prevY = y;
  37307. idx += dir;
  37308. }
  37309. return k;
  37310. }
  37311. var ECPolylineShape =
  37312. /** @class */
  37313. function () {
  37314. function ECPolylineShape() {
  37315. this.smooth = 0;
  37316. this.smoothConstraint = true;
  37317. }
  37318. return ECPolylineShape;
  37319. }();
  37320. var ECPolyline =
  37321. /** @class */
  37322. function (_super) {
  37323. __extends(ECPolyline, _super);
  37324. function ECPolyline(opts) {
  37325. var _this = _super.call(this, opts) || this;
  37326. _this.type = 'ec-polyline';
  37327. return _this;
  37328. }
  37329. ECPolyline.prototype.getDefaultStyle = function () {
  37330. return {
  37331. stroke: '#000',
  37332. fill: null
  37333. };
  37334. };
  37335. ECPolyline.prototype.getDefaultShape = function () {
  37336. return new ECPolylineShape();
  37337. };
  37338. ECPolyline.prototype.buildPath = function (ctx, shape) {
  37339. var points = shape.points;
  37340. var i = 0;
  37341. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  37342. if (shape.connectNulls) {
  37343. // Must remove first and last null values avoid draw error in polygon
  37344. for (; len > 0; len--) {
  37345. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37346. break;
  37347. }
  37348. }
  37349. for (; i < len; i++) {
  37350. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37351. break;
  37352. }
  37353. }
  37354. }
  37355. while (i < len) {
  37356. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  37357. }
  37358. };
  37359. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  37360. if (!this.path) {
  37361. this.createPathProxy();
  37362. this.buildPath(this.path, this.shape);
  37363. }
  37364. var path = this.path;
  37365. var data = path.data;
  37366. var CMD = PathProxy.CMD;
  37367. var x0;
  37368. var y0;
  37369. var isDimX = dim === 'x';
  37370. var roots = [];
  37371. for (var i = 0; i < data.length;) {
  37372. var cmd = data[i++];
  37373. var x = void 0;
  37374. var y = void 0;
  37375. var x2 = void 0;
  37376. var y2 = void 0;
  37377. var x3 = void 0;
  37378. var y3 = void 0;
  37379. var t = void 0;
  37380. switch (cmd) {
  37381. case CMD.M:
  37382. x0 = data[i++];
  37383. y0 = data[i++];
  37384. break;
  37385. case CMD.L:
  37386. x = data[i++];
  37387. y = data[i++];
  37388. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  37389. if (t <= 1 && t >= 0) {
  37390. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  37391. return isDimX ? [xOrY, val] : [val, xOrY];
  37392. }
  37393. x0 = x;
  37394. y0 = y;
  37395. break;
  37396. case CMD.C:
  37397. x = data[i++];
  37398. y = data[i++];
  37399. x2 = data[i++];
  37400. y2 = data[i++];
  37401. x3 = data[i++];
  37402. y3 = data[i++];
  37403. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  37404. if (nRoot > 0) {
  37405. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  37406. var t_1 = roots[i_1];
  37407. if (t_1 <= 1 && t_1 >= 0) {
  37408. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  37409. return isDimX ? [xOrY, val] : [val, xOrY];
  37410. }
  37411. }
  37412. }
  37413. x0 = x3;
  37414. y0 = y3;
  37415. break;
  37416. }
  37417. }
  37418. };
  37419. return ECPolyline;
  37420. }(Path);
  37421. var ECPolygonShape =
  37422. /** @class */
  37423. function (_super) {
  37424. __extends(ECPolygonShape, _super);
  37425. function ECPolygonShape() {
  37426. return _super !== null && _super.apply(this, arguments) || this;
  37427. }
  37428. return ECPolygonShape;
  37429. }(ECPolylineShape);
  37430. var ECPolygon =
  37431. /** @class */
  37432. function (_super) {
  37433. __extends(ECPolygon, _super);
  37434. function ECPolygon(opts) {
  37435. var _this = _super.call(this, opts) || this;
  37436. _this.type = 'ec-polygon';
  37437. return _this;
  37438. }
  37439. ECPolygon.prototype.getDefaultShape = function () {
  37440. return new ECPolygonShape();
  37441. };
  37442. ECPolygon.prototype.buildPath = function (ctx, shape) {
  37443. var points = shape.points;
  37444. var stackedOnPoints = shape.stackedOnPoints;
  37445. var i = 0;
  37446. var len = points.length / 2;
  37447. var smoothMonotone = shape.smoothMonotone;
  37448. if (shape.connectNulls) {
  37449. // Must remove first and last null values avoid draw error in polygon
  37450. for (; len > 0; len--) {
  37451. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37452. break;
  37453. }
  37454. }
  37455. for (; i < len; i++) {
  37456. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37457. break;
  37458. }
  37459. }
  37460. }
  37461. while (i < len) {
  37462. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  37463. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  37464. i += k + 1;
  37465. ctx.closePath();
  37466. }
  37467. };
  37468. return ECPolygon;
  37469. }(Path);
  37470. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  37471. var rect = cartesian.getArea();
  37472. var x = rect.x;
  37473. var y = rect.y;
  37474. var width = rect.width;
  37475. var height = rect.height;
  37476. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  37477. x -= lineWidth / 2;
  37478. y -= lineWidth / 2;
  37479. width += lineWidth;
  37480. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  37481. x = Math.floor(x);
  37482. width = Math.round(width);
  37483. var clipPath = new Rect({
  37484. shape: {
  37485. x: x,
  37486. y: y,
  37487. width: width,
  37488. height: height
  37489. }
  37490. });
  37491. if (hasAnimation) {
  37492. var baseAxis = cartesian.getBaseAxis();
  37493. var isHorizontal = baseAxis.isHorizontal();
  37494. var isAxisInversed = baseAxis.inverse;
  37495. if (isHorizontal) {
  37496. if (isAxisInversed) {
  37497. clipPath.shape.x += width;
  37498. }
  37499. clipPath.shape.width = 0;
  37500. } else {
  37501. if (!isAxisInversed) {
  37502. clipPath.shape.y += height;
  37503. }
  37504. clipPath.shape.height = 0;
  37505. }
  37506. var duringCb = isFunction(during) ? function (percent) {
  37507. during(percent, clipPath);
  37508. } : null;
  37509. initProps(clipPath, {
  37510. shape: {
  37511. width: width,
  37512. height: height,
  37513. x: x,
  37514. y: y
  37515. }
  37516. }, seriesModel, null, done, duringCb);
  37517. }
  37518. return clipPath;
  37519. }
  37520. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  37521. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  37522. var r0 = round(sectorArea.r0, 1);
  37523. var r = round(sectorArea.r, 1);
  37524. var clipPath = new Sector({
  37525. shape: {
  37526. cx: round(polar.cx, 1),
  37527. cy: round(polar.cy, 1),
  37528. r0: r0,
  37529. r: r,
  37530. startAngle: sectorArea.startAngle,
  37531. endAngle: sectorArea.endAngle,
  37532. clockwise: sectorArea.clockwise
  37533. }
  37534. });
  37535. if (hasAnimation) {
  37536. var isRadial = polar.getBaseAxis().dim === 'angle';
  37537. if (isRadial) {
  37538. clipPath.shape.endAngle = sectorArea.startAngle;
  37539. } else {
  37540. clipPath.shape.r = r0;
  37541. }
  37542. initProps(clipPath, {
  37543. shape: {
  37544. endAngle: sectorArea.endAngle,
  37545. r: r
  37546. }
  37547. }, seriesModel);
  37548. }
  37549. return clipPath;
  37550. }
  37551. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  37552. if (!coordSys) {
  37553. return null;
  37554. } else if (coordSys.type === 'polar') {
  37555. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37556. } else if (coordSys.type === 'cartesian2d') {
  37557. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  37558. }
  37559. return null;
  37560. }
  37561. /*
  37562. * Licensed to the Apache Software Foundation (ASF) under one
  37563. * or more contributor license agreements. See the NOTICE file
  37564. * distributed with this work for additional information
  37565. * regarding copyright ownership. The ASF licenses this file
  37566. * to you under the Apache License, Version 2.0 (the
  37567. * "License"); you may not use this file except in compliance
  37568. * with the License. You may obtain a copy of the License at
  37569. *
  37570. * http://www.apache.org/licenses/LICENSE-2.0
  37571. *
  37572. * Unless required by applicable law or agreed to in writing,
  37573. * software distributed under the License is distributed on an
  37574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37575. * KIND, either express or implied. See the License for the
  37576. * specific language governing permissions and limitations
  37577. * under the License.
  37578. */
  37579. /**
  37580. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37581. */
  37582. /*
  37583. * Licensed to the Apache Software Foundation (ASF) under one
  37584. * or more contributor license agreements. See the NOTICE file
  37585. * distributed with this work for additional information
  37586. * regarding copyright ownership. The ASF licenses this file
  37587. * to you under the Apache License, Version 2.0 (the
  37588. * "License"); you may not use this file except in compliance
  37589. * with the License. You may obtain a copy of the License at
  37590. *
  37591. * http://www.apache.org/licenses/LICENSE-2.0
  37592. *
  37593. * Unless required by applicable law or agreed to in writing,
  37594. * software distributed under the License is distributed on an
  37595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37596. * KIND, either express or implied. See the License for the
  37597. * specific language governing permissions and limitations
  37598. * under the License.
  37599. */
  37600. function isCoordinateSystemType(coordSys, type) {
  37601. return coordSys.type === type;
  37602. }
  37603. function isPointsSame(points1, points2) {
  37604. if (points1.length !== points2.length) {
  37605. return;
  37606. }
  37607. for (var i = 0; i < points1.length; i++) {
  37608. if (points1[i] !== points2[i]) {
  37609. return;
  37610. }
  37611. }
  37612. return true;
  37613. }
  37614. function bboxFromPoints(points) {
  37615. var minX = Infinity;
  37616. var minY = Infinity;
  37617. var maxX = -Infinity;
  37618. var maxY = -Infinity;
  37619. for (var i = 0; i < points.length;) {
  37620. var x = points[i++];
  37621. var y = points[i++];
  37622. if (!isNaN(x)) {
  37623. minX = Math.min(x, minX);
  37624. maxX = Math.max(x, maxX);
  37625. }
  37626. if (!isNaN(y)) {
  37627. minY = Math.min(y, minY);
  37628. maxY = Math.max(y, maxY);
  37629. }
  37630. }
  37631. return [[minX, minY], [maxX, maxY]];
  37632. }
  37633. function getBoundingDiff(points1, points2) {
  37634. var _a = bboxFromPoints(points1),
  37635. min1 = _a[0],
  37636. max1 = _a[1];
  37637. var _b = bboxFromPoints(points2),
  37638. min2 = _b[0],
  37639. max2 = _b[1]; // Get a max value from each corner of two boundings.
  37640. 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]));
  37641. }
  37642. function getSmooth(smooth) {
  37643. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  37644. }
  37645. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  37646. if (!dataCoordInfo.valueDim) {
  37647. return [];
  37648. }
  37649. var len = data.count();
  37650. var points = createFloat32Array(len * 2);
  37651. for (var idx = 0; idx < len; idx++) {
  37652. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  37653. points[idx * 2] = pt[0];
  37654. points[idx * 2 + 1] = pt[1];
  37655. }
  37656. return points;
  37657. }
  37658. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  37659. var baseAxis = coordSys.getBaseAxis();
  37660. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  37661. var stepPoints = [];
  37662. var i = 0;
  37663. var stepPt = [];
  37664. var pt = [];
  37665. var nextPt = [];
  37666. var filteredPoints = [];
  37667. if (connectNulls) {
  37668. for (i = 0; i < points.length; i += 2) {
  37669. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  37670. filteredPoints.push(points[i], points[i + 1]);
  37671. }
  37672. }
  37673. points = filteredPoints;
  37674. }
  37675. for (i = 0; i < points.length - 2; i += 2) {
  37676. nextPt[0] = points[i + 2];
  37677. nextPt[1] = points[i + 3];
  37678. pt[0] = points[i];
  37679. pt[1] = points[i + 1];
  37680. stepPoints.push(pt[0], pt[1]);
  37681. switch (stepTurnAt) {
  37682. case 'end':
  37683. stepPt[baseIndex] = nextPt[baseIndex];
  37684. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37685. stepPoints.push(stepPt[0], stepPt[1]);
  37686. break;
  37687. case 'middle':
  37688. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  37689. var stepPt2 = [];
  37690. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  37691. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37692. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  37693. stepPoints.push(stepPt[0], stepPt[1]);
  37694. stepPoints.push(stepPt2[0], stepPt2[1]);
  37695. break;
  37696. default:
  37697. // default is start
  37698. stepPt[baseIndex] = pt[baseIndex];
  37699. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  37700. stepPoints.push(stepPt[0], stepPt[1]);
  37701. }
  37702. } // Last points
  37703. stepPoints.push(points[i++], points[i++]);
  37704. return stepPoints;
  37705. }
  37706. /**
  37707. * Clip color stops to edge. Avoid creating too large gradients.
  37708. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  37709. *
  37710. * The stops has been sorted from small to large.
  37711. */
  37712. function clipColorStops(colorStops, maxSize) {
  37713. var newColorStops = [];
  37714. var len = colorStops.length; // coord will always < 0 in prevOutOfRangeColorStop.
  37715. var prevOutOfRangeColorStop;
  37716. var prevInRangeColorStop;
  37717. function lerpStop(stop0, stop1, clippedCoord) {
  37718. var coord0 = stop0.coord;
  37719. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  37720. var color = lerp$1(p, [stop0.color, stop1.color]);
  37721. return {
  37722. coord: clippedCoord,
  37723. color: color
  37724. };
  37725. }
  37726. for (var i = 0; i < len; i++) {
  37727. var stop_1 = colorStops[i];
  37728. var coord = stop_1.coord;
  37729. if (coord < 0) {
  37730. prevOutOfRangeColorStop = stop_1;
  37731. } else if (coord > maxSize) {
  37732. if (prevInRangeColorStop) {
  37733. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  37734. } else if (prevOutOfRangeColorStop) {
  37735. // If there are two stops and coord range is between these two stops
  37736. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  37737. } // All following stop will be out of range. So just ignore them.
  37738. break;
  37739. } else {
  37740. if (prevOutOfRangeColorStop) {
  37741. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0)); // Reset
  37742. prevOutOfRangeColorStop = null;
  37743. }
  37744. newColorStops.push(stop_1);
  37745. prevInRangeColorStop = stop_1;
  37746. }
  37747. }
  37748. return newColorStops;
  37749. }
  37750. function getVisualGradient(data, coordSys, api) {
  37751. var visualMetaList = data.getVisual('visualMeta');
  37752. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  37753. // When data.count() is 0, gradient range can not be calculated.
  37754. return;
  37755. }
  37756. if (coordSys.type !== 'cartesian2d') {
  37757. if ("development" !== 'production') {
  37758. console.warn('Visual map on line style is only supported on cartesian2d.');
  37759. }
  37760. return;
  37761. }
  37762. var coordDim;
  37763. var visualMeta;
  37764. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  37765. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  37766. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  37767. if (coordDim === 'x' || coordDim === 'y') {
  37768. visualMeta = visualMetaList[i];
  37769. break;
  37770. }
  37771. }
  37772. if (!visualMeta) {
  37773. if ("development" !== 'production') {
  37774. console.warn('Visual map on line style only support x or y dimension.');
  37775. }
  37776. return;
  37777. } // If the area to be rendered is bigger than area defined by LinearGradient,
  37778. // the canvas spec prescribes that the color of the first stop and the last
  37779. // stop should be used. But if two stops are added at offset 0, in effect
  37780. // browsers use the color of the second stop to render area outside
  37781. // LinearGradient. So we can only infinitesimally extend area defined in
  37782. // LinearGradient to render `outerColors`.
  37783. var axis = coordSys.getAxis(coordDim); // dataToCoord mapping may not be linear, but must be monotonic.
  37784. var colorStops = map(visualMeta.stops, function (stop) {
  37785. // offset will be calculated later.
  37786. return {
  37787. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  37788. color: stop.color
  37789. };
  37790. });
  37791. var stopLen = colorStops.length;
  37792. var outerColors = visualMeta.outerColors.slice();
  37793. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  37794. colorStops.reverse();
  37795. outerColors.reverse();
  37796. }
  37797. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  37798. var inRangeStopLen = colorStopsInRange.length;
  37799. if (!inRangeStopLen && stopLen) {
  37800. // All stops are out of range. All will be the same color.
  37801. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  37802. }
  37803. var tinyExtent = 10; // Arbitrary value: 10px
  37804. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  37805. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  37806. var coordSpan = maxCoord - minCoord;
  37807. if (coordSpan < 1e-3) {
  37808. return 'transparent';
  37809. }
  37810. each(colorStopsInRange, function (stop) {
  37811. stop.offset = (stop.coord - minCoord) / coordSpan;
  37812. });
  37813. colorStopsInRange.push({
  37814. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  37815. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  37816. color: outerColors[1] || 'transparent'
  37817. });
  37818. colorStopsInRange.unshift({
  37819. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  37820. color: outerColors[0] || 'transparent'
  37821. });
  37822. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  37823. gradient[coordDim] = minCoord;
  37824. gradient[coordDim + '2'] = maxCoord;
  37825. return gradient;
  37826. }
  37827. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  37828. var showAllSymbol = seriesModel.get('showAllSymbol');
  37829. var isAuto = showAllSymbol === 'auto';
  37830. if (showAllSymbol && !isAuto) {
  37831. return;
  37832. }
  37833. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  37834. if (!categoryAxis) {
  37835. return;
  37836. } // Note that category label interval strategy might bring some weird effect
  37837. // in some scenario: users may wonder why some of the symbols are not
  37838. // displayed. So we show all symbols as possible as we can.
  37839. if (isAuto // Simplify the logic, do not determine label overlap here.
  37840. && canShowAllSymbolForCategory(categoryAxis, data)) {
  37841. return;
  37842. } // Otherwise follow the label interval strategy on category axis.
  37843. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  37844. var labelMap = {};
  37845. each(categoryAxis.getViewLabels(), function (labelItem) {
  37846. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  37847. labelMap[ordinalNumber] = 1;
  37848. });
  37849. return function (dataIndex) {
  37850. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  37851. };
  37852. }
  37853. function canShowAllSymbolForCategory(categoryAxis, data) {
  37854. // In most cases, line is monotonous on category axis, and the label size
  37855. // is close with each other. So we check the symbol size and some of the
  37856. // label size alone with the category axis to estimate whether all symbol
  37857. // can be shown without overlap.
  37858. var axisExtent = categoryAxis.getExtent();
  37859. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  37860. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  37861. // Sampling some points, max 5.
  37862. var dataLen = data.count();
  37863. var step = Math.max(1, Math.round(dataLen / 5));
  37864. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  37865. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  37866. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  37867. * 1.5 > availSize) {
  37868. return false;
  37869. }
  37870. }
  37871. return true;
  37872. }
  37873. function isPointNull$1(x, y) {
  37874. return isNaN(x) || isNaN(y);
  37875. }
  37876. function getLastIndexNotNull(points) {
  37877. var len = points.length / 2;
  37878. for (; len > 0; len--) {
  37879. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  37880. break;
  37881. }
  37882. }
  37883. return len - 1;
  37884. }
  37885. function getPointAtIndex(points, idx) {
  37886. return [points[idx * 2], points[idx * 2 + 1]];
  37887. }
  37888. function getIndexRange(points, xOrY, dim) {
  37889. var len = points.length / 2;
  37890. var dimIdx = dim === 'x' ? 0 : 1;
  37891. var a;
  37892. var b;
  37893. var prevIndex = 0;
  37894. var nextIndex = -1;
  37895. for (var i = 0; i < len; i++) {
  37896. b = points[i * 2 + dimIdx];
  37897. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  37898. continue;
  37899. }
  37900. if (i === 0) {
  37901. a = b;
  37902. continue;
  37903. }
  37904. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  37905. nextIndex = i;
  37906. break;
  37907. }
  37908. prevIndex = i;
  37909. a = b;
  37910. }
  37911. return {
  37912. range: [prevIndex, nextIndex],
  37913. t: (xOrY - a) / (b - a)
  37914. };
  37915. }
  37916. function anyStateShowEndLabel(seriesModel) {
  37917. if (seriesModel.get(['endLabel', 'show'])) {
  37918. return true;
  37919. }
  37920. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  37921. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  37922. return true;
  37923. }
  37924. }
  37925. return false;
  37926. }
  37927. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  37928. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  37929. var endLabelModel_1 = seriesModel.getModel('endLabel');
  37930. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  37931. var data_1 = seriesModel.getData();
  37932. var labelAnimationRecord_1 = {
  37933. lastFrameIndex: 0
  37934. };
  37935. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  37936. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  37937. } : null;
  37938. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  37939. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  37940. var endLabel = lineView._endLabel;
  37941. if (endLabel && hasAnimation) {
  37942. if (labelAnimationRecord_1.originalX != null) {
  37943. endLabel.attr({
  37944. x: labelAnimationRecord_1.originalX,
  37945. y: labelAnimationRecord_1.originalY
  37946. });
  37947. }
  37948. }
  37949. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  37950. if (!seriesModel.get('clip', true)) {
  37951. var rectShape = clipPath.shape;
  37952. var expandSize = Math.max(rectShape.width, rectShape.height);
  37953. if (isHorizontal) {
  37954. rectShape.y -= expandSize;
  37955. rectShape.height += expandSize * 2;
  37956. } else {
  37957. rectShape.x -= expandSize;
  37958. rectShape.width += expandSize * 2;
  37959. }
  37960. } // Set to the final frame. To make sure label layout is right.
  37961. if (during) {
  37962. during(1, clipPath);
  37963. }
  37964. return clipPath;
  37965. } else {
  37966. if ("development" !== 'production') {
  37967. if (seriesModel.get(['endLabel', 'show'])) {
  37968. console.warn('endLabel is not supported for lines in polar systems.');
  37969. }
  37970. }
  37971. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37972. }
  37973. }
  37974. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  37975. var baseAxis = coordSys.getBaseAxis();
  37976. var isHorizontal = baseAxis.isHorizontal();
  37977. var isBaseInversed = baseAxis.inverse;
  37978. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  37979. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  37980. return {
  37981. normal: {
  37982. align: endLabelModel.get('align') || align,
  37983. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  37984. }
  37985. };
  37986. }
  37987. var LineView =
  37988. /** @class */
  37989. function (_super) {
  37990. __extends(LineView, _super);
  37991. function LineView() {
  37992. return _super !== null && _super.apply(this, arguments) || this;
  37993. }
  37994. LineView.prototype.init = function () {
  37995. var lineGroup = new Group();
  37996. var symbolDraw = new SymbolDraw();
  37997. this.group.add(symbolDraw.group);
  37998. this._symbolDraw = symbolDraw;
  37999. this._lineGroup = lineGroup;
  38000. };
  38001. LineView.prototype.render = function (seriesModel, ecModel, api) {
  38002. var _this = this;
  38003. var coordSys = seriesModel.coordinateSystem;
  38004. var group = this.group;
  38005. var data = seriesModel.getData();
  38006. var lineStyleModel = seriesModel.getModel('lineStyle');
  38007. var areaStyleModel = seriesModel.getModel('areaStyle');
  38008. var points = data.getLayout('points') || [];
  38009. var isCoordSysPolar = coordSys.type === 'polar';
  38010. var prevCoordSys = this._coordSys;
  38011. var symbolDraw = this._symbolDraw;
  38012. var polyline = this._polyline;
  38013. var polygon = this._polygon;
  38014. var lineGroup = this._lineGroup;
  38015. var hasAnimation = !ecModel.ssr && seriesModel.isAnimationEnabled();
  38016. var isAreaChart = !areaStyleModel.isEmpty();
  38017. var valueOrigin = areaStyleModel.get('origin');
  38018. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  38019. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  38020. var showSymbol = seriesModel.get('showSymbol');
  38021. var connectNulls = seriesModel.get('connectNulls');
  38022. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  38023. var oldData = this._data;
  38024. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38025. if (el.__temp) {
  38026. group.remove(el);
  38027. oldData.setItemGraphicEl(idx, null);
  38028. }
  38029. }); // Remove previous created symbols if showSymbol changed to false
  38030. if (!showSymbol) {
  38031. symbolDraw.remove();
  38032. }
  38033. group.add(lineGroup); // FIXME step not support polar
  38034. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  38035. var clipShapeForSymbol;
  38036. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  38037. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  38038. // See #7913 and `test/dataZoom-clip.html`.
  38039. if (clipShapeForSymbol.width != null) {
  38040. clipShapeForSymbol.x -= 0.1;
  38041. clipShapeForSymbol.y -= 0.1;
  38042. clipShapeForSymbol.width += 0.2;
  38043. clipShapeForSymbol.height += 0.2;
  38044. } else if (clipShapeForSymbol.r0) {
  38045. clipShapeForSymbol.r0 -= 0.5;
  38046. clipShapeForSymbol.r += 0.5;
  38047. }
  38048. }
  38049. this._clipShapeForSymbol = clipShapeForSymbol;
  38050. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  38051. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  38052. showSymbol && symbolDraw.updateData(data, {
  38053. isIgnore: isIgnoreFunc,
  38054. clipShape: clipShapeForSymbol,
  38055. disableAnimation: true,
  38056. getSymbolPoint: function (idx) {
  38057. return [points[idx * 2], points[idx * 2 + 1]];
  38058. }
  38059. });
  38060. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  38061. if (step) {
  38062. // TODO If stacked series is not step
  38063. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38064. if (stackedOnPoints) {
  38065. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38066. }
  38067. }
  38068. polyline = this._newPolyline(points);
  38069. if (isAreaChart) {
  38070. polygon = this._newPolygon(points, stackedOnPoints);
  38071. } // If areaStyle is removed
  38072. else if (polygon) {
  38073. lineGroup.remove(polygon);
  38074. polygon = this._polygon = null;
  38075. } // NOTE: Must update _endLabel before setClipPath.
  38076. if (!isCoordSysPolar) {
  38077. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38078. }
  38079. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38080. } else {
  38081. if (isAreaChart && !polygon) {
  38082. // If areaStyle is added
  38083. polygon = this._newPolygon(points, stackedOnPoints);
  38084. } else if (polygon && !isAreaChart) {
  38085. // If areaStyle is removed
  38086. lineGroup.remove(polygon);
  38087. polygon = this._polygon = null;
  38088. } // NOTE: Must update _endLabel before setClipPath.
  38089. if (!isCoordSysPolar) {
  38090. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38091. } // Update clipPath
  38092. var oldClipPath = lineGroup.getClipPath();
  38093. if (oldClipPath) {
  38094. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  38095. initProps(oldClipPath, {
  38096. shape: newClipPath.shape
  38097. }, seriesModel);
  38098. } else {
  38099. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38100. } // Always update, or it is wrong in the case turning on legend
  38101. // because points are not changed.
  38102. showSymbol && symbolDraw.updateData(data, {
  38103. isIgnore: isIgnoreFunc,
  38104. clipShape: clipShapeForSymbol,
  38105. disableAnimation: true,
  38106. getSymbolPoint: function (idx) {
  38107. return [points[idx * 2], points[idx * 2 + 1]];
  38108. }
  38109. }); // In the case data zoom triggered refreshing frequently
  38110. // Data may not change if line has a category axis. So it should animate nothing.
  38111. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  38112. if (hasAnimation) {
  38113. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  38114. } else {
  38115. // Not do it in update with animation
  38116. if (step) {
  38117. // TODO If stacked series is not step
  38118. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38119. if (stackedOnPoints) {
  38120. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38121. }
  38122. }
  38123. polyline.setShape({
  38124. points: points
  38125. });
  38126. polygon && polygon.setShape({
  38127. points: points,
  38128. stackedOnPoints: stackedOnPoints
  38129. });
  38130. }
  38131. }
  38132. }
  38133. var emphasisModel = seriesModel.getModel('emphasis');
  38134. var focus = emphasisModel.get('focus');
  38135. var blurScope = emphasisModel.get('blurScope');
  38136. var emphasisDisabled = emphasisModel.get('disabled');
  38137. polyline.useStyle(defaults( // Use color in lineStyle first
  38138. lineStyleModel.getLineStyle(), {
  38139. fill: 'none',
  38140. stroke: visualColor,
  38141. lineJoin: 'bevel'
  38142. }));
  38143. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  38144. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  38145. var emphasisLineStyle = polyline.getState('emphasis').style;
  38146. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  38147. } // Needs seriesIndex for focus
  38148. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  38149. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  38150. var smooth = getSmooth(seriesModel.get('smooth'));
  38151. var smoothMonotone = seriesModel.get('smoothMonotone');
  38152. polyline.setShape({
  38153. smooth: smooth,
  38154. smoothMonotone: smoothMonotone,
  38155. connectNulls: connectNulls
  38156. });
  38157. if (polygon) {
  38158. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  38159. var stackedOnSmooth = 0;
  38160. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38161. fill: visualColor,
  38162. opacity: 0.7,
  38163. lineJoin: 'bevel',
  38164. decal: data.getVisual('style').decal
  38165. }));
  38166. if (stackedOnSeries) {
  38167. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  38168. }
  38169. polygon.setShape({
  38170. smooth: smooth,
  38171. stackedOnSmooth: stackedOnSmooth,
  38172. smoothMonotone: smoothMonotone,
  38173. connectNulls: connectNulls
  38174. });
  38175. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  38176. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  38177. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  38178. }
  38179. var changePolyState = function (toState) {
  38180. _this._changePolyState(toState);
  38181. };
  38182. data.eachItemGraphicEl(function (el) {
  38183. // Switch polyline / polygon state if element changed its state.
  38184. el && (el.onHoverStateChange = changePolyState);
  38185. });
  38186. this._polyline.onHoverStateChange = changePolyState;
  38187. this._data = data; // Save the coordinate system for transition animation when data changed
  38188. this._coordSys = coordSys;
  38189. this._stackedOnPoints = stackedOnPoints;
  38190. this._points = points;
  38191. this._step = step;
  38192. this._valueOrigin = valueOrigin;
  38193. if (seriesModel.get('triggerLineEvent')) {
  38194. this.packEventData(seriesModel, polyline);
  38195. polygon && this.packEventData(seriesModel, polygon);
  38196. }
  38197. };
  38198. LineView.prototype.packEventData = function (seriesModel, el) {
  38199. getECData(el).eventData = {
  38200. componentType: 'series',
  38201. componentSubType: 'line',
  38202. componentIndex: seriesModel.componentIndex,
  38203. seriesIndex: seriesModel.seriesIndex,
  38204. seriesName: seriesModel.name,
  38205. seriesType: 'line'
  38206. };
  38207. };
  38208. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  38209. var data = seriesModel.getData();
  38210. var dataIndex = queryDataIndex(data, payload);
  38211. this._changePolyState('emphasis');
  38212. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  38213. var points = data.getLayout('points');
  38214. var symbol = data.getItemGraphicEl(dataIndex);
  38215. if (!symbol) {
  38216. // Create a temporary symbol if it is not exists
  38217. var x = points[dataIndex * 2];
  38218. var y = points[dataIndex * 2 + 1];
  38219. if (isNaN(x) || isNaN(y)) {
  38220. // Null data
  38221. return;
  38222. } // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  38223. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  38224. return;
  38225. }
  38226. var zlevel = seriesModel.get('zlevel') || 0;
  38227. var z = seriesModel.get('z') || 0;
  38228. symbol = new Symbol(data, dataIndex);
  38229. symbol.x = x;
  38230. symbol.y = y;
  38231. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  38232. var symbolLabel = symbol.getSymbolPath().getTextContent();
  38233. if (symbolLabel) {
  38234. symbolLabel.zlevel = zlevel;
  38235. symbolLabel.z = z;
  38236. symbolLabel.z2 = this._polyline.z2 + 1;
  38237. }
  38238. symbol.__temp = true;
  38239. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  38240. symbol.stopSymbolAnimation(true);
  38241. this.group.add(symbol);
  38242. }
  38243. symbol.highlight();
  38244. } else {
  38245. // Highlight whole series
  38246. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  38247. }
  38248. };
  38249. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  38250. var data = seriesModel.getData();
  38251. var dataIndex = queryDataIndex(data, payload);
  38252. this._changePolyState('normal');
  38253. if (dataIndex != null && dataIndex >= 0) {
  38254. var symbol = data.getItemGraphicEl(dataIndex);
  38255. if (symbol) {
  38256. if (symbol.__temp) {
  38257. data.setItemGraphicEl(dataIndex, null);
  38258. this.group.remove(symbol);
  38259. } else {
  38260. symbol.downplay();
  38261. }
  38262. }
  38263. } else {
  38264. // FIXME
  38265. // can not downplay completely.
  38266. // Downplay whole series
  38267. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  38268. }
  38269. };
  38270. LineView.prototype._changePolyState = function (toState) {
  38271. var polygon = this._polygon;
  38272. setStatesFlag(this._polyline, toState);
  38273. polygon && setStatesFlag(polygon, toState);
  38274. };
  38275. LineView.prototype._newPolyline = function (points) {
  38276. var polyline = this._polyline; // Remove previous created polyline
  38277. if (polyline) {
  38278. this._lineGroup.remove(polyline);
  38279. }
  38280. polyline = new ECPolyline({
  38281. shape: {
  38282. points: points
  38283. },
  38284. segmentIgnoreThreshold: 2,
  38285. z2: 10
  38286. });
  38287. this._lineGroup.add(polyline);
  38288. this._polyline = polyline;
  38289. return polyline;
  38290. };
  38291. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  38292. var polygon = this._polygon; // Remove previous created polygon
  38293. if (polygon) {
  38294. this._lineGroup.remove(polygon);
  38295. }
  38296. polygon = new ECPolygon({
  38297. shape: {
  38298. points: points,
  38299. stackedOnPoints: stackedOnPoints
  38300. },
  38301. segmentIgnoreThreshold: 2
  38302. });
  38303. this._lineGroup.add(polygon);
  38304. this._polygon = polygon;
  38305. return polygon;
  38306. };
  38307. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  38308. var isHorizontalOrRadial;
  38309. var isCoordSysPolar;
  38310. var baseAxis = coordSys.getBaseAxis();
  38311. var isAxisInverse = baseAxis.inverse;
  38312. if (coordSys.type === 'cartesian2d') {
  38313. isHorizontalOrRadial = baseAxis.isHorizontal();
  38314. isCoordSysPolar = false;
  38315. } else if (coordSys.type === 'polar') {
  38316. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38317. isCoordSysPolar = true;
  38318. }
  38319. var seriesModel = data.hostModel;
  38320. var seriesDuration = seriesModel.get('animationDuration');
  38321. if (isFunction(seriesDuration)) {
  38322. seriesDuration = seriesDuration(null);
  38323. }
  38324. var seriesDelay = seriesModel.get('animationDelay') || 0;
  38325. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  38326. data.eachItemGraphicEl(function (symbol, idx) {
  38327. var el = symbol;
  38328. if (el) {
  38329. var point = [symbol.x, symbol.y];
  38330. var start = void 0;
  38331. var end = void 0;
  38332. var current = void 0;
  38333. if (clipShape) {
  38334. if (isCoordSysPolar) {
  38335. var polarClip = clipShape;
  38336. var coord = coordSys.pointToCoord(point);
  38337. if (isHorizontalOrRadial) {
  38338. start = polarClip.startAngle;
  38339. end = polarClip.endAngle;
  38340. current = -coord[1] / 180 * Math.PI;
  38341. } else {
  38342. start = polarClip.r0;
  38343. end = polarClip.r;
  38344. current = coord[0];
  38345. }
  38346. } else {
  38347. var gridClip = clipShape;
  38348. if (isHorizontalOrRadial) {
  38349. start = gridClip.x;
  38350. end = gridClip.x + gridClip.width;
  38351. current = symbol.x;
  38352. } else {
  38353. start = gridClip.y + gridClip.height;
  38354. end = gridClip.y;
  38355. current = symbol.y;
  38356. }
  38357. }
  38358. }
  38359. var ratio = end === start ? 0 : (current - start) / (end - start);
  38360. if (isAxisInverse) {
  38361. ratio = 1 - ratio;
  38362. }
  38363. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  38364. var symbolPath = el.getSymbolPath();
  38365. var text = symbolPath.getTextContent();
  38366. el.attr({
  38367. scaleX: 0,
  38368. scaleY: 0
  38369. });
  38370. el.animateTo({
  38371. scaleX: 1,
  38372. scaleY: 1
  38373. }, {
  38374. duration: 200,
  38375. setToFinal: true,
  38376. delay: delay
  38377. });
  38378. if (text) {
  38379. text.animateFrom({
  38380. style: {
  38381. opacity: 0
  38382. }
  38383. }, {
  38384. duration: 300,
  38385. delay: delay
  38386. });
  38387. }
  38388. symbolPath.disableLabelAnimation = true;
  38389. }
  38390. });
  38391. };
  38392. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  38393. var endLabelModel = seriesModel.getModel('endLabel');
  38394. if (anyStateShowEndLabel(seriesModel)) {
  38395. var data_2 = seriesModel.getData();
  38396. var polyline = this._polyline; // series may be filtered.
  38397. var points = data_2.getLayout('points');
  38398. if (!points) {
  38399. polyline.removeTextContent();
  38400. this._endLabel = null;
  38401. return;
  38402. }
  38403. var endLabel = this._endLabel;
  38404. if (!endLabel) {
  38405. endLabel = this._endLabel = new ZRText({
  38406. z2: 200 // should be higher than item symbol
  38407. });
  38408. endLabel.ignoreClip = true;
  38409. polyline.setTextContent(this._endLabel);
  38410. polyline.disableLabelAnimation = true;
  38411. } // Find last non-NaN data to display data
  38412. var dataIndex = getLastIndexNotNull(points);
  38413. if (dataIndex >= 0) {
  38414. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  38415. inheritColor: inheritColor,
  38416. labelFetcher: seriesModel,
  38417. labelDataIndex: dataIndex,
  38418. defaultText: function (dataIndex, opt, interpolatedValue) {
  38419. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  38420. },
  38421. enableTextSetter: true
  38422. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  38423. polyline.textConfig.position = null;
  38424. }
  38425. } else if (this._endLabel) {
  38426. this._polyline.removeTextContent();
  38427. this._endLabel = null;
  38428. }
  38429. };
  38430. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  38431. var endLabel = this._endLabel;
  38432. var polyline = this._polyline;
  38433. if (endLabel) {
  38434. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  38435. // The label is not prepared at this time.
  38436. if (percent < 1 && animationRecord.originalX == null) {
  38437. animationRecord.originalX = endLabel.x;
  38438. animationRecord.originalY = endLabel.y;
  38439. }
  38440. var points = data.getLayout('points');
  38441. var seriesModel = data.hostModel;
  38442. var connectNulls = seriesModel.get('connectNulls');
  38443. var precision = endLabelModel.get('precision');
  38444. var distance = endLabelModel.get('distance') || 0;
  38445. var baseAxis = coordSys.getBaseAxis();
  38446. var isHorizontal = baseAxis.isHorizontal();
  38447. var isBaseInversed = baseAxis.inverse;
  38448. var clipShape = clipRect.shape;
  38449. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  38450. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  38451. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  38452. var dim = isHorizontal ? 'x' : 'y';
  38453. var dataIndexRange = getIndexRange(points, xOrY, dim);
  38454. var indices = dataIndexRange.range;
  38455. var diff = indices[1] - indices[0];
  38456. var value = void 0;
  38457. if (diff >= 1) {
  38458. // diff > 1 && connectNulls, which is on the null data.
  38459. if (diff > 1 && !connectNulls) {
  38460. var pt = getPointAtIndex(points, indices[0]);
  38461. endLabel.attr({
  38462. x: pt[0] + distanceX,
  38463. y: pt[1] + distanceY
  38464. });
  38465. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  38466. } else {
  38467. var pt = polyline.getPointOn(xOrY, dim);
  38468. pt && endLabel.attr({
  38469. x: pt[0] + distanceX,
  38470. y: pt[1] + distanceY
  38471. });
  38472. var startValue = seriesModel.getRawValue(indices[0]);
  38473. var endValue = seriesModel.getRawValue(indices[1]);
  38474. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  38475. }
  38476. animationRecord.lastFrameIndex = indices[0];
  38477. } else {
  38478. // If diff <= 0, which is the range is not found(Include NaN)
  38479. // Choose the first point or last point.
  38480. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  38481. var pt = getPointAtIndex(points, idx);
  38482. valueAnimation && (value = seriesModel.getRawValue(idx));
  38483. endLabel.attr({
  38484. x: pt[0] + distanceX,
  38485. y: pt[1] + distanceY
  38486. });
  38487. }
  38488. if (valueAnimation) {
  38489. labelInner(endLabel).setLabelText(value);
  38490. }
  38491. }
  38492. };
  38493. /**
  38494. * @private
  38495. */
  38496. // FIXME Two value axis
  38497. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  38498. var polyline = this._polyline;
  38499. var polygon = this._polygon;
  38500. var seriesModel = data.hostModel;
  38501. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  38502. var current = diff.current;
  38503. var stackedOnCurrent = diff.stackedOnCurrent;
  38504. var next = diff.next;
  38505. var stackedOnNext = diff.stackedOnNext;
  38506. if (step) {
  38507. // TODO If stacked series is not step
  38508. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  38509. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  38510. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  38511. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  38512. } // Don't apply animation if diff is large.
  38513. // For better result and avoid memory explosion problems like
  38514. // https://github.com/apache/incubator-echarts/issues/12229
  38515. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  38516. polyline.stopAnimation();
  38517. polyline.setShape({
  38518. points: next
  38519. });
  38520. if (polygon) {
  38521. polygon.stopAnimation();
  38522. polygon.setShape({
  38523. points: next,
  38524. stackedOnPoints: stackedOnNext
  38525. });
  38526. }
  38527. return;
  38528. }
  38529. polyline.shape.__points = diff.current;
  38530. polyline.shape.points = current;
  38531. var target = {
  38532. shape: {
  38533. points: next
  38534. }
  38535. }; // Also animate the original points.
  38536. // If points reference is changed when turning into step line.
  38537. if (diff.current !== current) {
  38538. target.shape.__points = diff.next;
  38539. } // Stop previous animation.
  38540. polyline.stopAnimation();
  38541. updateProps(polyline, target, seriesModel);
  38542. if (polygon) {
  38543. polygon.setShape({
  38544. // Reuse the points with polyline.
  38545. points: current,
  38546. stackedOnPoints: stackedOnCurrent
  38547. });
  38548. polygon.stopAnimation();
  38549. updateProps(polygon, {
  38550. shape: {
  38551. stackedOnPoints: stackedOnNext
  38552. }
  38553. }, seriesModel); // If use attr directly in updateProps.
  38554. if (polyline.shape.points !== polygon.shape.points) {
  38555. polygon.shape.points = polyline.shape.points;
  38556. }
  38557. }
  38558. var updatedDataInfo = [];
  38559. var diffStatus = diff.status;
  38560. for (var i = 0; i < diffStatus.length; i++) {
  38561. var cmd = diffStatus[i].cmd;
  38562. if (cmd === '=') {
  38563. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  38564. if (el) {
  38565. updatedDataInfo.push({
  38566. el: el,
  38567. ptIdx: i // Index of points
  38568. });
  38569. }
  38570. }
  38571. }
  38572. if (polyline.animators && polyline.animators.length) {
  38573. polyline.animators[0].during(function () {
  38574. polygon && polygon.dirtyShape();
  38575. var points = polyline.shape.__points;
  38576. for (var i = 0; i < updatedDataInfo.length; i++) {
  38577. var el = updatedDataInfo[i].el;
  38578. var offset = updatedDataInfo[i].ptIdx * 2;
  38579. el.x = points[offset];
  38580. el.y = points[offset + 1];
  38581. el.markRedraw();
  38582. }
  38583. });
  38584. }
  38585. };
  38586. LineView.prototype.remove = function (ecModel) {
  38587. var group = this.group;
  38588. var oldData = this._data;
  38589. this._lineGroup.removeAll();
  38590. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  38591. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38592. if (el.__temp) {
  38593. group.remove(el);
  38594. oldData.setItemGraphicEl(idx, null);
  38595. }
  38596. });
  38597. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  38598. };
  38599. LineView.type = 'line';
  38600. return LineView;
  38601. }(ChartView);
  38602. function pointsLayout(seriesType, forceStoreInTypedArray) {
  38603. return {
  38604. seriesType: seriesType,
  38605. plan: createRenderPlanner(),
  38606. reset: function (seriesModel) {
  38607. var data = seriesModel.getData();
  38608. var coordSys = seriesModel.coordinateSystem;
  38609. var pipelineContext = seriesModel.pipelineContext;
  38610. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  38611. if (!coordSys) {
  38612. return;
  38613. }
  38614. var dims = map(coordSys.dimensions, function (dim) {
  38615. return data.mapDimension(dim);
  38616. }).slice(0, 2);
  38617. var dimLen = dims.length;
  38618. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  38619. if (isDimensionStacked(data, dims[0])) {
  38620. dims[0] = stackResultDim;
  38621. }
  38622. if (isDimensionStacked(data, dims[1])) {
  38623. dims[1] = stackResultDim;
  38624. }
  38625. var store = data.getStore();
  38626. var dimIdx0 = data.getDimensionIndex(dims[0]);
  38627. var dimIdx1 = data.getDimensionIndex(dims[1]);
  38628. return dimLen && {
  38629. progress: function (params, data) {
  38630. var segCount = params.end - params.start;
  38631. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  38632. var tmpIn = [];
  38633. var tmpOut = [];
  38634. for (var i = params.start, offset = 0; i < params.end; i++) {
  38635. var point = void 0;
  38636. if (dimLen === 1) {
  38637. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  38638. point = coordSys.dataToPoint(x, null, tmpOut);
  38639. } else {
  38640. tmpIn[0] = store.get(dimIdx0, i);
  38641. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  38642. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  38643. }
  38644. if (useTypedArray) {
  38645. points[offset++] = point[0];
  38646. points[offset++] = point[1];
  38647. } else {
  38648. data.setItemLayout(i, point.slice());
  38649. }
  38650. }
  38651. useTypedArray && data.setLayout('points', points);
  38652. }
  38653. };
  38654. }
  38655. };
  38656. }
  38657. var samplers = {
  38658. average: function (frame) {
  38659. var sum = 0;
  38660. var count = 0;
  38661. for (var i = 0; i < frame.length; i++) {
  38662. if (!isNaN(frame[i])) {
  38663. sum += frame[i];
  38664. count++;
  38665. }
  38666. } // Return NaN if count is 0
  38667. return count === 0 ? NaN : sum / count;
  38668. },
  38669. sum: function (frame) {
  38670. var sum = 0;
  38671. for (var i = 0; i < frame.length; i++) {
  38672. // Ignore NaN
  38673. sum += frame[i] || 0;
  38674. }
  38675. return sum;
  38676. },
  38677. max: function (frame) {
  38678. var max = -Infinity;
  38679. for (var i = 0; i < frame.length; i++) {
  38680. frame[i] > max && (max = frame[i]);
  38681. } // NaN will cause illegal axis extent.
  38682. return isFinite(max) ? max : NaN;
  38683. },
  38684. min: function (frame) {
  38685. var min = Infinity;
  38686. for (var i = 0; i < frame.length; i++) {
  38687. frame[i] < min && (min = frame[i]);
  38688. } // NaN will cause illegal axis extent.
  38689. return isFinite(min) ? min : NaN;
  38690. },
  38691. // TODO
  38692. // Median
  38693. nearest: function (frame) {
  38694. return frame[0];
  38695. }
  38696. };
  38697. var indexSampler = function (frame) {
  38698. return Math.round(frame.length / 2);
  38699. };
  38700. function dataSample(seriesType) {
  38701. return {
  38702. seriesType: seriesType,
  38703. // FIXME:TS never used, so comment it
  38704. // modifyOutputEnd: true,
  38705. reset: function (seriesModel, ecModel, api) {
  38706. var data = seriesModel.getData();
  38707. var sampling = seriesModel.get('sampling');
  38708. var coordSys = seriesModel.coordinateSystem;
  38709. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  38710. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  38711. var baseAxis = coordSys.getBaseAxis();
  38712. var valueAxis = coordSys.getOtherAxis(baseAxis);
  38713. var extent = baseAxis.getExtent();
  38714. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  38715. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  38716. var rate = Math.round(count / size);
  38717. if (isFinite(rate) && rate > 1) {
  38718. if (sampling === 'lttb') {
  38719. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  38720. }
  38721. var sampler = void 0;
  38722. if (isString(sampling)) {
  38723. sampler = samplers[sampling];
  38724. } else if (isFunction(sampling)) {
  38725. sampler = sampling;
  38726. }
  38727. if (sampler) {
  38728. // Only support sample the first dim mapped from value axis.
  38729. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  38730. }
  38731. }
  38732. }
  38733. }
  38734. };
  38735. }
  38736. function install$2(registers) {
  38737. registers.registerChartView(LineView);
  38738. registers.registerSeriesModel(LineSeriesModel);
  38739. registers.registerLayout(pointsLayout('line', true));
  38740. registers.registerVisual({
  38741. seriesType: 'line',
  38742. reset: function (seriesModel) {
  38743. var data = seriesModel.getData(); // Visual coding for legend
  38744. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  38745. if (lineStyle && !lineStyle.stroke) {
  38746. // Fill in visual should be palette color if
  38747. // has color callback
  38748. lineStyle.stroke = data.getVisual('style').fill;
  38749. }
  38750. data.setVisual('legendLineStyle', lineStyle);
  38751. }
  38752. }); // Down sample after filter
  38753. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  38754. }
  38755. var BaseBarSeriesModel =
  38756. /** @class */
  38757. function (_super) {
  38758. __extends(BaseBarSeriesModel, _super);
  38759. function BaseBarSeriesModel() {
  38760. var _this = _super !== null && _super.apply(this, arguments) || this;
  38761. _this.type = BaseBarSeriesModel.type;
  38762. return _this;
  38763. }
  38764. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38765. return createSeriesData(null, this, {
  38766. useEncodeDefaulter: true
  38767. });
  38768. };
  38769. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  38770. var coordSys = this.coordinateSystem;
  38771. if (coordSys && coordSys.clampData) {
  38772. // PENDING if clamp ?
  38773. var clampData_1 = coordSys.clampData(value);
  38774. var pt_1 = coordSys.dataToPoint(clampData_1);
  38775. if (startingAtTick) {
  38776. each(coordSys.getAxes(), function (axis, idx) {
  38777. // If axis type is category, use tick coords instead
  38778. if (axis.type === 'category' && dims != null) {
  38779. var tickCoords = axis.getTicksCoords();
  38780. var targetTickId = clampData_1[idx]; // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  38781. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  38782. if (isEnd) {
  38783. targetTickId += 1;
  38784. } // The only contains one tick, tickCoords is
  38785. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  38786. // to the length should always be larger than 1
  38787. if (tickCoords.length < 2) {
  38788. return;
  38789. } else if (tickCoords.length === 2) {
  38790. // The left value and right value of the axis are
  38791. // the same. coord is 0 in both items. Use the max
  38792. // value of the axis as the coord
  38793. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  38794. return;
  38795. }
  38796. var leftCoord = void 0;
  38797. var coord = void 0;
  38798. var stepTickValue = 1;
  38799. for (var i = 0; i < tickCoords.length; i++) {
  38800. var tickCoord = tickCoords[i].coord; // The last item of tickCoords doesn't contain
  38801. // tickValue
  38802. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  38803. if (tickValue === targetTickId) {
  38804. coord = tickCoord;
  38805. break;
  38806. } else if (tickValue < targetTickId) {
  38807. leftCoord = tickCoord;
  38808. } else if (leftCoord != null && tickValue > targetTickId) {
  38809. coord = (tickCoord + leftCoord) / 2;
  38810. break;
  38811. }
  38812. if (i === 1) {
  38813. // Here we assume the step of category axes is
  38814. // the same
  38815. stepTickValue = tickValue - tickCoords[0].tickValue;
  38816. }
  38817. }
  38818. if (coord == null) {
  38819. if (!leftCoord) {
  38820. // targetTickId is smaller than all tick ids in the
  38821. // visible area, use the leftmost tick coord
  38822. coord = tickCoords[0].coord;
  38823. } else if (leftCoord) {
  38824. // targetTickId is larger than all tick ids in the
  38825. // visible area, use the rightmost tick coord
  38826. coord = tickCoords[tickCoords.length - 1].coord;
  38827. }
  38828. }
  38829. pt_1[idx] = axis.toGlobalCoord(coord);
  38830. }
  38831. });
  38832. } else {
  38833. var data = this.getData();
  38834. var offset = data.getLayout('offset');
  38835. var size = data.getLayout('size');
  38836. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  38837. pt_1[offsetIndex] += offset + size / 2;
  38838. }
  38839. return pt_1;
  38840. }
  38841. return [NaN, NaN];
  38842. };
  38843. BaseBarSeriesModel.type = 'series.__base_bar__';
  38844. BaseBarSeriesModel.defaultOption = {
  38845. // zlevel: 0,
  38846. z: 2,
  38847. coordinateSystem: 'cartesian2d',
  38848. legendHoverLink: true,
  38849. // stack: null
  38850. // Cartesian coordinate system
  38851. // xAxisIndex: 0,
  38852. // yAxisIndex: 0,
  38853. barMinHeight: 0,
  38854. barMinAngle: 0,
  38855. // cursor: null,
  38856. large: false,
  38857. largeThreshold: 400,
  38858. progressive: 3e3,
  38859. progressiveChunkMode: 'mod'
  38860. };
  38861. return BaseBarSeriesModel;
  38862. }(SeriesModel);
  38863. SeriesModel.registerClass(BaseBarSeriesModel);
  38864. var BarSeriesModel =
  38865. /** @class */
  38866. function (_super) {
  38867. __extends(BarSeriesModel, _super);
  38868. function BarSeriesModel() {
  38869. var _this = _super !== null && _super.apply(this, arguments) || this;
  38870. _this.type = BarSeriesModel.type;
  38871. return _this;
  38872. }
  38873. BarSeriesModel.prototype.getInitialData = function () {
  38874. return createSeriesData(null, this, {
  38875. useEncodeDefaulter: true,
  38876. createInvertedIndices: !!this.get('realtimeSort', true) || null
  38877. });
  38878. };
  38879. /**
  38880. * @override
  38881. */
  38882. BarSeriesModel.prototype.getProgressive = function () {
  38883. // Do not support progressive in normal mode.
  38884. return this.get('large') ? this.get('progressive') : false;
  38885. };
  38886. /**
  38887. * @override
  38888. */
  38889. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  38890. // Do not support progressive in normal mode.
  38891. var progressiveThreshold = this.get('progressiveThreshold');
  38892. var largeThreshold = this.get('largeThreshold');
  38893. if (largeThreshold > progressiveThreshold) {
  38894. progressiveThreshold = largeThreshold;
  38895. }
  38896. return progressiveThreshold;
  38897. };
  38898. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  38899. return selectors.rect(data.getItemLayout(dataIndex));
  38900. };
  38901. BarSeriesModel.type = 'series.bar';
  38902. BarSeriesModel.dependencies = ['grid', 'polar'];
  38903. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  38904. // If clipped
  38905. // Only available on cartesian2d
  38906. clip: true,
  38907. roundCap: false,
  38908. showBackground: false,
  38909. backgroundStyle: {
  38910. color: 'rgba(180, 180, 180, 0.2)',
  38911. borderColor: null,
  38912. borderWidth: 0,
  38913. borderType: 'solid',
  38914. borderRadius: 0,
  38915. shadowBlur: 0,
  38916. shadowColor: null,
  38917. shadowOffsetX: 0,
  38918. shadowOffsetY: 0,
  38919. opacity: 1
  38920. },
  38921. select: {
  38922. itemStyle: {
  38923. borderColor: '#212121'
  38924. }
  38925. },
  38926. realtimeSort: false
  38927. });
  38928. return BarSeriesModel;
  38929. }(BaseBarSeriesModel);
  38930. /**
  38931. * Sausage: similar to sector, but have half circle on both sides
  38932. */
  38933. var SausageShape =
  38934. /** @class */
  38935. function () {
  38936. function SausageShape() {
  38937. this.cx = 0;
  38938. this.cy = 0;
  38939. this.r0 = 0;
  38940. this.r = 0;
  38941. this.startAngle = 0;
  38942. this.endAngle = Math.PI * 2;
  38943. this.clockwise = true;
  38944. }
  38945. return SausageShape;
  38946. }();
  38947. var SausagePath =
  38948. /** @class */
  38949. function (_super) {
  38950. __extends(SausagePath, _super);
  38951. function SausagePath(opts) {
  38952. var _this = _super.call(this, opts) || this;
  38953. _this.type = 'sausage';
  38954. return _this;
  38955. }
  38956. SausagePath.prototype.getDefaultShape = function () {
  38957. return new SausageShape();
  38958. };
  38959. SausagePath.prototype.buildPath = function (ctx, shape) {
  38960. var cx = shape.cx;
  38961. var cy = shape.cy;
  38962. var r0 = Math.max(shape.r0 || 0, 0);
  38963. var r = Math.max(shape.r, 0);
  38964. var dr = (r - r0) * 0.5;
  38965. var rCenter = r0 + dr;
  38966. var startAngle = shape.startAngle;
  38967. var endAngle = shape.endAngle;
  38968. var clockwise = shape.clockwise;
  38969. var PI2 = Math.PI * 2;
  38970. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  38971. if (!lessThanCircle) {
  38972. // Normalize angles
  38973. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  38974. }
  38975. var unitStartX = Math.cos(startAngle);
  38976. var unitStartY = Math.sin(startAngle);
  38977. var unitEndX = Math.cos(endAngle);
  38978. var unitEndY = Math.sin(endAngle);
  38979. if (lessThanCircle) {
  38980. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  38981. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  38982. } else {
  38983. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  38984. }
  38985. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  38986. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  38987. if (r0 !== 0) {
  38988. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  38989. } // ctx.closePath();
  38990. };
  38991. return SausagePath;
  38992. }(Path);
  38993. function createSectorCalculateTextPosition(positionMapping, opts) {
  38994. opts = opts || {};
  38995. var isRoundCap = opts.isRoundCap;
  38996. return function (out, opts, boundingRect) {
  38997. var textPosition = opts.position;
  38998. if (!textPosition || textPosition instanceof Array) {
  38999. return calculateTextPosition(out, opts, boundingRect);
  39000. }
  39001. var mappedSectorPosition = positionMapping(textPosition);
  39002. var distance = opts.distance != null ? opts.distance : 5;
  39003. var sector = this.shape;
  39004. var cx = sector.cx;
  39005. var cy = sector.cy;
  39006. var r = sector.r;
  39007. var r0 = sector.r0;
  39008. var middleR = (r + r0) / 2;
  39009. var startAngle = sector.startAngle;
  39010. var endAngle = sector.endAngle;
  39011. var middleAngle = (startAngle + endAngle) / 2;
  39012. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  39013. var mathCos = Math.cos;
  39014. var mathSin = Math.sin; // base position: top-left
  39015. var x = cx + r * mathCos(startAngle);
  39016. var y = cy + r * mathSin(startAngle);
  39017. var textAlign = 'left';
  39018. var textVerticalAlign = 'top';
  39019. switch (mappedSectorPosition) {
  39020. case 'startArc':
  39021. x = cx + (r0 - distance) * mathCos(middleAngle);
  39022. y = cy + (r0 - distance) * mathSin(middleAngle);
  39023. textAlign = 'center';
  39024. textVerticalAlign = 'top';
  39025. break;
  39026. case 'insideStartArc':
  39027. x = cx + (r0 + distance) * mathCos(middleAngle);
  39028. y = cy + (r0 + distance) * mathSin(middleAngle);
  39029. textAlign = 'center';
  39030. textVerticalAlign = 'bottom';
  39031. break;
  39032. case 'startAngle':
  39033. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  39034. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  39035. textAlign = 'right';
  39036. textVerticalAlign = 'middle';
  39037. break;
  39038. case 'insideStartAngle':
  39039. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  39040. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  39041. textAlign = 'left';
  39042. textVerticalAlign = 'middle';
  39043. break;
  39044. case 'middle':
  39045. x = cx + middleR * mathCos(middleAngle);
  39046. y = cy + middleR * mathSin(middleAngle);
  39047. textAlign = 'center';
  39048. textVerticalAlign = 'middle';
  39049. break;
  39050. case 'endArc':
  39051. x = cx + (r + distance) * mathCos(middleAngle);
  39052. y = cy + (r + distance) * mathSin(middleAngle);
  39053. textAlign = 'center';
  39054. textVerticalAlign = 'bottom';
  39055. break;
  39056. case 'insideEndArc':
  39057. x = cx + (r - distance) * mathCos(middleAngle);
  39058. y = cy + (r - distance) * mathSin(middleAngle);
  39059. textAlign = 'center';
  39060. textVerticalAlign = 'top';
  39061. break;
  39062. case 'endAngle':
  39063. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  39064. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  39065. textAlign = 'left';
  39066. textVerticalAlign = 'middle';
  39067. break;
  39068. case 'insideEndAngle':
  39069. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  39070. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  39071. textAlign = 'right';
  39072. textVerticalAlign = 'middle';
  39073. break;
  39074. default:
  39075. return calculateTextPosition(out, opts, boundingRect);
  39076. }
  39077. out = out || {};
  39078. out.x = x;
  39079. out.y = y;
  39080. out.align = textAlign;
  39081. out.verticalAlign = textVerticalAlign;
  39082. return out;
  39083. };
  39084. }
  39085. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  39086. if (isNumber(rotateType)) {
  39087. // user-set rotation
  39088. sector.setTextConfig({
  39089. rotation: rotateType
  39090. });
  39091. return;
  39092. } else if (isArray(textPosition)) {
  39093. // user-set position, use 0 as auto rotation
  39094. sector.setTextConfig({
  39095. rotation: 0
  39096. });
  39097. return;
  39098. }
  39099. var shape = sector.shape;
  39100. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  39101. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  39102. var middleAngle = (startAngle + endAngle) / 2;
  39103. var anchorAngle;
  39104. var mappedSectorPosition = positionMapping(textPosition);
  39105. switch (mappedSectorPosition) {
  39106. case 'startArc':
  39107. case 'insideStartArc':
  39108. case 'middle':
  39109. case 'insideEndArc':
  39110. case 'endArc':
  39111. anchorAngle = middleAngle;
  39112. break;
  39113. case 'startAngle':
  39114. case 'insideStartAngle':
  39115. anchorAngle = startAngle;
  39116. break;
  39117. case 'endAngle':
  39118. case 'insideEndAngle':
  39119. anchorAngle = endAngle;
  39120. break;
  39121. default:
  39122. sector.setTextConfig({
  39123. rotation: 0
  39124. });
  39125. return;
  39126. }
  39127. var rotate = Math.PI * 1.5 - anchorAngle;
  39128. /**
  39129. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  39130. * half round flipped to increase readability. However, only middle
  39131. * position supports this for now, because in other positions, the
  39132. * anchor point is not at the center of the text, so the positions
  39133. * after rotating is not as expected.
  39134. */
  39135. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  39136. rotate -= Math.PI;
  39137. }
  39138. sector.setTextConfig({
  39139. rotation: rotate
  39140. });
  39141. }
  39142. function adjustAngleDistanceX(angle, distance, isEnd) {
  39143. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  39144. }
  39145. function adjustAngleDistanceY(angle, distance, isEnd) {
  39146. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  39147. }
  39148. function getSectorCornerRadius(model, shape, zeroIfNull) {
  39149. var cornerRadius = model.get('borderRadius');
  39150. if (cornerRadius == null) {
  39151. return zeroIfNull ? {
  39152. cornerRadius: 0
  39153. } : null;
  39154. }
  39155. if (!isArray(cornerRadius)) {
  39156. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  39157. }
  39158. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  39159. return {
  39160. cornerRadius: map(cornerRadius, function (cr) {
  39161. return parsePercent(cr, dr);
  39162. })
  39163. };
  39164. }
  39165. var mathMax$6 = Math.max;
  39166. var mathMin$6 = Math.min;
  39167. function getClipArea(coord, data) {
  39168. var coordSysClipArea = coord.getArea && coord.getArea();
  39169. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39170. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  39171. // We should not clip this part.
  39172. // See test/bar2.html
  39173. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  39174. var expandWidth = data.getLayout('bandWidth');
  39175. if (baseAxis.isHorizontal()) {
  39176. coordSysClipArea.x -= expandWidth;
  39177. coordSysClipArea.width += expandWidth * 2;
  39178. } else {
  39179. coordSysClipArea.y -= expandWidth;
  39180. coordSysClipArea.height += expandWidth * 2;
  39181. }
  39182. }
  39183. }
  39184. return coordSysClipArea;
  39185. }
  39186. var BarView =
  39187. /** @class */
  39188. function (_super) {
  39189. __extends(BarView, _super);
  39190. function BarView() {
  39191. var _this = _super.call(this) || this;
  39192. _this.type = BarView.type;
  39193. _this._isFirstFrame = true;
  39194. return _this;
  39195. }
  39196. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39197. this._model = seriesModel;
  39198. this._removeOnRenderedListener(api);
  39199. this._updateDrawMode(seriesModel);
  39200. var coordinateSystemType = seriesModel.get('coordinateSystem');
  39201. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  39202. // Clear previously rendered progressive elements.
  39203. this._progressiveEls = null;
  39204. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  39205. } else if ("development" !== 'production') {
  39206. warn('Only cartesian2d and polar supported for bar.');
  39207. }
  39208. };
  39209. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  39210. this._clear();
  39211. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  39212. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  39213. this._updateLargeClip(seriesModel);
  39214. };
  39215. BarView.prototype.incrementalRender = function (params, seriesModel) {
  39216. // Reset
  39217. this._progressiveEls = []; // Do not support progressive in normal mode.
  39218. this._incrementalRenderLarge(params, seriesModel);
  39219. };
  39220. BarView.prototype.eachRendered = function (cb) {
  39221. traverseElements(this._progressiveEls || this.group, cb);
  39222. };
  39223. BarView.prototype._updateDrawMode = function (seriesModel) {
  39224. var isLargeDraw = seriesModel.pipelineContext.large;
  39225. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  39226. this._isLargeDraw = isLargeDraw;
  39227. this._clear();
  39228. }
  39229. };
  39230. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  39231. var group = this.group;
  39232. var data = seriesModel.getData();
  39233. var oldData = this._data;
  39234. var coord = seriesModel.coordinateSystem;
  39235. var baseAxis = coord.getBaseAxis();
  39236. var isHorizontalOrRadial;
  39237. if (coord.type === 'cartesian2d') {
  39238. isHorizontalOrRadial = baseAxis.isHorizontal();
  39239. } else if (coord.type === 'polar') {
  39240. isHorizontalOrRadial = baseAxis.dim === 'angle';
  39241. }
  39242. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  39243. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  39244. if (realtimeSortCfg) {
  39245. this._enableRealtimeSort(realtimeSortCfg, data, api);
  39246. }
  39247. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  39248. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  39249. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  39250. // And don't want the label are clipped.
  39251. var roundCap = seriesModel.get('roundCap', true);
  39252. var drawBackground = seriesModel.get('showBackground', true);
  39253. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39254. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  39255. var bgEls = [];
  39256. var oldBgEls = this._backgroundEls;
  39257. var isInitSort = payload && payload.isInitSort;
  39258. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  39259. function createBackground(dataIndex) {
  39260. var bgLayout = getLayout[coord.type](data, dataIndex);
  39261. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  39262. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39263. if (coord.type === 'cartesian2d') {
  39264. bgEl.setShape('r', barBorderRadius);
  39265. } else {
  39266. bgEl.setShape('cornerRadius', barBorderRadius);
  39267. }
  39268. bgEls[dataIndex] = bgEl;
  39269. return bgEl;
  39270. }
  39271. data.diff(oldData).add(function (dataIndex) {
  39272. var itemModel = data.getItemModel(dataIndex);
  39273. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  39274. if (drawBackground) {
  39275. createBackground(dataIndex);
  39276. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  39277. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  39278. return;
  39279. }
  39280. var isClipped = false;
  39281. if (needsClip) {
  39282. // Clip will modify the layout params.
  39283. // And return a boolean to determine if the shape are fully clipped.
  39284. isClipped = clip[coord.type](coordSysClipArea, layout);
  39285. }
  39286. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  39287. if (realtimeSortCfg) {
  39288. /**
  39289. * Force label animation because even if the element is
  39290. * ignored because it's clipped, it may not be clipped after
  39291. * changing order. Then, if not using forceLabelAnimation,
  39292. * the label animation was never started, in which case,
  39293. * the label will be the final value and doesn't have label
  39294. * animation.
  39295. */
  39296. el.forceLabelAnimation = true;
  39297. }
  39298. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39299. if (isInitSort) {
  39300. el.attr({
  39301. shape: layout
  39302. });
  39303. } else if (realtimeSortCfg) {
  39304. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  39305. } else {
  39306. initProps(el, {
  39307. shape: layout
  39308. }, seriesModel, dataIndex);
  39309. }
  39310. data.setItemGraphicEl(dataIndex, el);
  39311. group.add(el);
  39312. el.ignore = isClipped;
  39313. }).update(function (newIndex, oldIndex) {
  39314. var itemModel = data.getItemModel(newIndex);
  39315. var layout = getLayout[coord.type](data, newIndex, itemModel);
  39316. if (drawBackground) {
  39317. var bgEl = void 0;
  39318. if (oldBgEls.length === 0) {
  39319. bgEl = createBackground(oldIndex);
  39320. } else {
  39321. bgEl = oldBgEls[oldIndex];
  39322. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39323. if (coord.type === 'cartesian2d') {
  39324. bgEl.setShape('r', barBorderRadius);
  39325. } else {
  39326. bgEl.setShape('cornerRadius', barBorderRadius);
  39327. }
  39328. bgEls[newIndex] = bgEl;
  39329. }
  39330. var bgLayout = getLayout[coord.type](data, newIndex);
  39331. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  39332. updateProps(bgEl, {
  39333. shape: shape
  39334. }, animationModel, newIndex);
  39335. }
  39336. var el = oldData.getItemGraphicEl(oldIndex);
  39337. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  39338. group.remove(el);
  39339. return;
  39340. }
  39341. var isClipped = false;
  39342. if (needsClip) {
  39343. isClipped = clip[coord.type](coordSysClipArea, layout);
  39344. if (isClipped) {
  39345. group.remove(el);
  39346. }
  39347. }
  39348. if (!el) {
  39349. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  39350. } else {
  39351. saveOldStyle(el);
  39352. }
  39353. if (realtimeSortCfg) {
  39354. el.forceLabelAnimation = true;
  39355. }
  39356. if (isChangeOrder) {
  39357. var textEl = el.getTextContent();
  39358. if (textEl) {
  39359. var labelInnerStore = labelInner(textEl);
  39360. if (labelInnerStore.prevValue != null) {
  39361. /**
  39362. * Set preValue to be value so that no new label
  39363. * should be started, otherwise, it will take a full
  39364. * `animationDurationUpdate` time to finish the
  39365. * animation, which is not expected.
  39366. */
  39367. labelInnerStore.prevValue = labelInnerStore.value;
  39368. }
  39369. }
  39370. } // Not change anything if only order changed.
  39371. // Especially not change label.
  39372. else {
  39373. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39374. }
  39375. if (isInitSort) {
  39376. el.attr({
  39377. shape: layout
  39378. });
  39379. } else if (realtimeSortCfg) {
  39380. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  39381. } else {
  39382. updateProps(el, {
  39383. shape: layout
  39384. }, seriesModel, newIndex, null);
  39385. }
  39386. data.setItemGraphicEl(newIndex, el);
  39387. el.ignore = isClipped;
  39388. group.add(el);
  39389. }).remove(function (dataIndex) {
  39390. var el = oldData.getItemGraphicEl(dataIndex);
  39391. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  39392. }).execute();
  39393. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  39394. bgGroup.removeAll();
  39395. for (var i = 0; i < bgEls.length; ++i) {
  39396. bgGroup.add(bgEls[i]);
  39397. }
  39398. group.add(bgGroup);
  39399. this._backgroundEls = bgEls;
  39400. this._data = data;
  39401. };
  39402. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  39403. this._clear();
  39404. createLarge(seriesModel, this.group);
  39405. this._updateLargeClip(seriesModel);
  39406. };
  39407. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  39408. this._removeBackground();
  39409. createLarge(seriesModel, this.group, this._progressiveEls, true);
  39410. };
  39411. BarView.prototype._updateLargeClip = function (seriesModel) {
  39412. // Use clipPath in large mode.
  39413. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  39414. var group = this.group;
  39415. if (clipPath) {
  39416. group.setClipPath(clipPath);
  39417. } else {
  39418. group.removeClipPath();
  39419. }
  39420. };
  39421. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  39422. var _this = this; // If no data in the first frame, wait for data to initSort
  39423. if (!data.count()) {
  39424. return;
  39425. }
  39426. var baseAxis = realtimeSortCfg.baseAxis;
  39427. if (this._isFirstFrame) {
  39428. this._dispatchInitSort(data, realtimeSortCfg, api);
  39429. this._isFirstFrame = false;
  39430. } else {
  39431. var orderMapping_1 = function (idx) {
  39432. var el = data.getItemGraphicEl(idx);
  39433. var shape = el && el.shape;
  39434. return shape && // The result should be consistent with the initial sort by data value.
  39435. // Do not support the case that both positive and negative exist.
  39436. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width) // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  39437. || 0;
  39438. };
  39439. this._onRendered = function () {
  39440. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  39441. };
  39442. api.getZr().on('rendered', this._onRendered);
  39443. }
  39444. };
  39445. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  39446. var info = [];
  39447. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  39448. var mappedValue = orderMapping(dataIdx);
  39449. mappedValue = mappedValue == null ? NaN : mappedValue;
  39450. info.push({
  39451. dataIndex: dataIdx,
  39452. mappedValue: mappedValue,
  39453. ordinalNumber: ordinalNumber
  39454. });
  39455. });
  39456. info.sort(function (a, b) {
  39457. // If NaN, it will be treated as min val.
  39458. return b.mappedValue - a.mappedValue;
  39459. });
  39460. return {
  39461. ordinalNumbers: map(info, function (item) {
  39462. return item.ordinalNumber;
  39463. })
  39464. };
  39465. };
  39466. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  39467. var scale = baseAxis.scale;
  39468. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  39469. var lastValue = Number.MAX_VALUE;
  39470. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  39471. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  39472. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  39473. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  39474. : orderMapping(data.indexOfRawIndex(rawIdx));
  39475. if (value > lastValue) {
  39476. return true;
  39477. }
  39478. lastValue = value;
  39479. }
  39480. return false;
  39481. };
  39482. /*
  39483. * Consider the case when A and B changed order, whose representing
  39484. * bars are both out of sight, we don't wish to trigger reorder action
  39485. * as long as the order in the view doesn't change.
  39486. */
  39487. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  39488. var scale = baseAxis.scale;
  39489. var extent = scale.getExtent();
  39490. var tickNum = Math.max(0, extent[0]);
  39491. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  39492. for (; tickNum <= tickMax; ++tickNum) {
  39493. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  39494. return true;
  39495. }
  39496. }
  39497. };
  39498. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  39499. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  39500. return;
  39501. }
  39502. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  39503. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  39504. this._removeOnRenderedListener(api);
  39505. api.dispatchAction({
  39506. type: 'changeAxisOrder',
  39507. componentType: baseAxis.dim + 'Axis',
  39508. axisId: baseAxis.index,
  39509. sortInfo: sortInfo
  39510. });
  39511. }
  39512. };
  39513. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  39514. var baseAxis = realtimeSortCfg.baseAxis;
  39515. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  39516. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  39517. });
  39518. api.dispatchAction({
  39519. type: 'changeAxisOrder',
  39520. componentType: baseAxis.dim + 'Axis',
  39521. isInitSort: true,
  39522. axisId: baseAxis.index,
  39523. sortInfo: sortResult
  39524. });
  39525. };
  39526. BarView.prototype.remove = function (ecModel, api) {
  39527. this._clear(this._model);
  39528. this._removeOnRenderedListener(api);
  39529. };
  39530. BarView.prototype.dispose = function (ecModel, api) {
  39531. this._removeOnRenderedListener(api);
  39532. };
  39533. BarView.prototype._removeOnRenderedListener = function (api) {
  39534. if (this._onRendered) {
  39535. api.getZr().off('rendered', this._onRendered);
  39536. this._onRendered = null;
  39537. }
  39538. };
  39539. BarView.prototype._clear = function (model) {
  39540. var group = this.group;
  39541. var data = this._data;
  39542. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  39543. this._removeBackground();
  39544. this._backgroundEls = [];
  39545. data.eachItemGraphicEl(function (el) {
  39546. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  39547. });
  39548. } else {
  39549. group.removeAll();
  39550. }
  39551. this._data = null;
  39552. this._isFirstFrame = true;
  39553. };
  39554. BarView.prototype._removeBackground = function () {
  39555. this.group.remove(this._backgroundGroup);
  39556. this._backgroundGroup = null;
  39557. };
  39558. BarView.type = 'bar';
  39559. return BarView;
  39560. }(ChartView);
  39561. var clip = {
  39562. cartesian2d: function (coordSysBoundingRect, layout) {
  39563. var signWidth = layout.width < 0 ? -1 : 1;
  39564. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  39565. if (signWidth < 0) {
  39566. layout.x += layout.width;
  39567. layout.width = -layout.width;
  39568. }
  39569. if (signHeight < 0) {
  39570. layout.y += layout.height;
  39571. layout.height = -layout.height;
  39572. }
  39573. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  39574. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  39575. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  39576. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  39577. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  39578. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  39579. var xClipped = x2 < x;
  39580. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  39581. // But we should also place the element at the edge of the coord sys bounding rect.
  39582. // Because if data changed and the bar shows again, its transition animation
  39583. // will begin at this place.
  39584. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  39585. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  39586. layout.width = xClipped ? 0 : x2 - x;
  39587. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  39588. if (signWidth < 0) {
  39589. layout.x += layout.width;
  39590. layout.width = -layout.width;
  39591. }
  39592. if (signHeight < 0) {
  39593. layout.y += layout.height;
  39594. layout.height = -layout.height;
  39595. }
  39596. return xClipped || yClipped;
  39597. },
  39598. polar: function (coordSysClipArea, layout) {
  39599. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  39600. if (signR < 0) {
  39601. var tmp = layout.r;
  39602. layout.r = layout.r0;
  39603. layout.r0 = tmp;
  39604. }
  39605. var r = mathMin$6(layout.r, coordSysClipArea.r);
  39606. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  39607. layout.r = r;
  39608. layout.r0 = r0;
  39609. var clipped = r - r0 < 0; // Reverse back
  39610. if (signR < 0) {
  39611. var tmp = layout.r;
  39612. layout.r = layout.r0;
  39613. layout.r0 = tmp;
  39614. }
  39615. return clipped;
  39616. }
  39617. };
  39618. var elementCreator = {
  39619. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  39620. var rect = new Rect({
  39621. shape: extend({}, layout),
  39622. z2: 1
  39623. });
  39624. rect.__dataIndex = newIndex;
  39625. rect.name = 'item';
  39626. if (animationModel) {
  39627. var rectShape = rect.shape;
  39628. var animateProperty = isHorizontal ? 'height' : 'width';
  39629. rectShape[animateProperty] = 0;
  39630. }
  39631. return rect;
  39632. },
  39633. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  39634. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  39635. var sector = new ShapeClass({
  39636. shape: layout,
  39637. z2: 1
  39638. });
  39639. sector.name = 'item';
  39640. var positionMap = createPolarPositionMapping(isRadial);
  39641. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  39642. isRoundCap: ShapeClass === SausagePath
  39643. }); // Animation
  39644. if (animationModel) {
  39645. var sectorShape = sector.shape;
  39646. var animateProperty = isRadial ? 'r' : 'endAngle';
  39647. var animateTarget = {};
  39648. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  39649. animateTarget[animateProperty] = layout[animateProperty];
  39650. (isUpdate ? updateProps : initProps)(sector, {
  39651. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  39652. }, animationModel);
  39653. }
  39654. return sector;
  39655. }
  39656. };
  39657. function shouldRealtimeSort(seriesModel, coordSys) {
  39658. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  39659. var baseAxis = coordSys.getBaseAxis();
  39660. if ("development" !== 'production') {
  39661. if (realtimeSortOption) {
  39662. if (baseAxis.type !== 'category') {
  39663. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  39664. }
  39665. if (coordSys.type !== 'cartesian2d') {
  39666. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  39667. }
  39668. }
  39669. }
  39670. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  39671. return {
  39672. baseAxis: baseAxis,
  39673. otherAxis: coordSys.getOtherAxis(baseAxis)
  39674. };
  39675. }
  39676. }
  39677. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  39678. var seriesTarget;
  39679. var axisTarget;
  39680. if (isHorizontal) {
  39681. axisTarget = {
  39682. x: layout.x,
  39683. width: layout.width
  39684. };
  39685. seriesTarget = {
  39686. y: layout.y,
  39687. height: layout.height
  39688. };
  39689. } else {
  39690. axisTarget = {
  39691. y: layout.y,
  39692. height: layout.height
  39693. };
  39694. seriesTarget = {
  39695. x: layout.x,
  39696. width: layout.width
  39697. };
  39698. }
  39699. if (!isChangeOrder) {
  39700. // Keep the original growth animation if only axis order changed.
  39701. // Not start a new animation.
  39702. (isUpdate ? updateProps : initProps)(el, {
  39703. shape: seriesTarget
  39704. }, seriesAnimationModel, newIndex, null);
  39705. }
  39706. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  39707. (isUpdate ? updateProps : initProps)(el, {
  39708. shape: axisTarget
  39709. }, axisAnimationModel, newIndex);
  39710. }
  39711. function checkPropertiesNotValid(obj, props) {
  39712. for (var i = 0; i < props.length; i++) {
  39713. if (!isFinite(obj[props[i]])) {
  39714. return true;
  39715. }
  39716. }
  39717. return false;
  39718. }
  39719. var rectPropties = ['x', 'y', 'width', 'height'];
  39720. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  39721. var isValidLayout = {
  39722. cartesian2d: function (layout) {
  39723. return !checkPropertiesNotValid(layout, rectPropties);
  39724. },
  39725. polar: function (layout) {
  39726. return !checkPropertiesNotValid(layout, polarPropties);
  39727. }
  39728. };
  39729. var getLayout = {
  39730. // itemModel is only used to get borderWidth, which is not needed
  39731. // when calculating bar background layout.
  39732. cartesian2d: function (data, dataIndex, itemModel) {
  39733. var layout = data.getItemLayout(dataIndex);
  39734. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  39735. var signX = layout.width > 0 ? 1 : -1;
  39736. var signY = layout.height > 0 ? 1 : -1;
  39737. return {
  39738. x: layout.x + signX * fixedLineWidth / 2,
  39739. y: layout.y + signY * fixedLineWidth / 2,
  39740. width: layout.width - signX * fixedLineWidth,
  39741. height: layout.height - signY * fixedLineWidth
  39742. };
  39743. },
  39744. polar: function (data, dataIndex, itemModel) {
  39745. var layout = data.getItemLayout(dataIndex);
  39746. return {
  39747. cx: layout.cx,
  39748. cy: layout.cy,
  39749. r0: layout.r0,
  39750. r: layout.r,
  39751. startAngle: layout.startAngle,
  39752. endAngle: layout.endAngle,
  39753. clockwise: layout.clockwise
  39754. };
  39755. }
  39756. };
  39757. function isZeroOnPolar(layout) {
  39758. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  39759. }
  39760. function createPolarPositionMapping(isRadial) {
  39761. return function (isRadial) {
  39762. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  39763. return function (position) {
  39764. switch (position) {
  39765. case 'start':
  39766. case 'insideStart':
  39767. case 'end':
  39768. case 'insideEnd':
  39769. return position + arcOrAngle;
  39770. default:
  39771. return position;
  39772. }
  39773. };
  39774. }(isRadial);
  39775. }
  39776. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  39777. var style = data.getItemVisual(dataIndex, 'style');
  39778. if (!isPolar) {
  39779. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  39780. el.setShape('r', borderRadius);
  39781. } else if (!seriesModel.get('roundCap')) {
  39782. var sectorShape = el.shape;
  39783. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  39784. extend(sectorShape, cornerRadius);
  39785. el.setShape(sectorShape);
  39786. }
  39787. el.useStyle(style);
  39788. var cursorStyle = itemModel.getShallow('cursor');
  39789. cursorStyle && el.attr('cursor', cursorStyle);
  39790. 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';
  39791. var labelStatesModels = getLabelStatesModels(itemModel);
  39792. setLabelStyle(el, labelStatesModels, {
  39793. labelFetcher: seriesModel,
  39794. labelDataIndex: dataIndex,
  39795. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  39796. inheritColor: style.fill,
  39797. defaultOpacity: style.opacity,
  39798. defaultOutsidePosition: labelPositionOutside
  39799. });
  39800. var label = el.getTextContent();
  39801. if (isPolar && label) {
  39802. var position = itemModel.get(['label', 'position']);
  39803. el.textConfig.inside = position === 'middle' ? true : null;
  39804. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  39805. }
  39806. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  39807. return getDefaultInterpolatedLabel(data, value);
  39808. });
  39809. var emphasisModel = itemModel.getModel(['emphasis']);
  39810. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39811. setStatesStylesFromModel(el, itemModel);
  39812. if (isZeroOnPolar(layout)) {
  39813. el.style.fill = 'none';
  39814. el.style.stroke = 'none';
  39815. each(el.states, function (state) {
  39816. if (state.style) {
  39817. state.style.fill = state.style.stroke = 'none';
  39818. }
  39819. });
  39820. }
  39821. } // In case width or height are too small.
  39822. function getLineWidth(itemModel, rawLayout) {
  39823. // Has no border.
  39824. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  39825. if (!borderColor || borderColor === 'none') {
  39826. return 0;
  39827. }
  39828. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  39829. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  39830. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  39831. return Math.min(lineWidth, width, height);
  39832. }
  39833. var LagePathShape =
  39834. /** @class */
  39835. function () {
  39836. function LagePathShape() {}
  39837. return LagePathShape;
  39838. }();
  39839. var LargePath =
  39840. /** @class */
  39841. function (_super) {
  39842. __extends(LargePath, _super);
  39843. function LargePath(opts) {
  39844. var _this = _super.call(this, opts) || this;
  39845. _this.type = 'largeBar';
  39846. return _this;
  39847. }
  39848. LargePath.prototype.getDefaultShape = function () {
  39849. return new LagePathShape();
  39850. };
  39851. LargePath.prototype.buildPath = function (ctx, shape) {
  39852. // Drawing lines is more efficient than drawing
  39853. // a whole line or drawing rects.
  39854. var points = shape.points;
  39855. var baseDimIdx = this.baseDimIdx;
  39856. var valueDimIdx = 1 - this.baseDimIdx;
  39857. var startPoint = [];
  39858. var size = [];
  39859. var barWidth = this.barWidth;
  39860. for (var i = 0; i < points.length; i += 3) {
  39861. size[baseDimIdx] = barWidth;
  39862. size[valueDimIdx] = points[i + 2];
  39863. startPoint[baseDimIdx] = points[i + baseDimIdx];
  39864. startPoint[valueDimIdx] = points[i + valueDimIdx];
  39865. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  39866. }
  39867. };
  39868. return LargePath;
  39869. }(Path);
  39870. function createLarge(seriesModel, group, progressiveEls, incremental) {
  39871. // TODO support polar
  39872. var data = seriesModel.getData();
  39873. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  39874. var largeDataIndices = data.getLayout('largeDataIndices');
  39875. var barWidth = data.getLayout('size');
  39876. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39877. var bgPoints = data.getLayout('largeBackgroundPoints');
  39878. if (bgPoints) {
  39879. var bgEl = new LargePath({
  39880. shape: {
  39881. points: bgPoints
  39882. },
  39883. incremental: !!incremental,
  39884. silent: true,
  39885. z2: 0
  39886. });
  39887. bgEl.baseDimIdx = baseDimIdx;
  39888. bgEl.largeDataIndices = largeDataIndices;
  39889. bgEl.barWidth = barWidth;
  39890. bgEl.useStyle(backgroundModel.getItemStyle());
  39891. group.add(bgEl);
  39892. progressiveEls && progressiveEls.push(bgEl);
  39893. }
  39894. var el = new LargePath({
  39895. shape: {
  39896. points: data.getLayout('largePoints')
  39897. },
  39898. incremental: !!incremental,
  39899. ignoreCoarsePointer: true,
  39900. z2: 1
  39901. });
  39902. el.baseDimIdx = baseDimIdx;
  39903. el.largeDataIndices = largeDataIndices;
  39904. el.barWidth = barWidth;
  39905. group.add(el);
  39906. el.useStyle(data.getVisual('style')); // Enable tooltip and user mouse/touch event handlers.
  39907. getECData(el).seriesIndex = seriesModel.seriesIndex;
  39908. if (!seriesModel.get('silent')) {
  39909. el.on('mousedown', largePathUpdateDataIndex);
  39910. el.on('mousemove', largePathUpdateDataIndex);
  39911. }
  39912. progressiveEls && progressiveEls.push(el);
  39913. } // Use throttle to avoid frequently traverse to find dataIndex.
  39914. var largePathUpdateDataIndex = throttle(function (event) {
  39915. var largePath = this;
  39916. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  39917. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  39918. }, 30, false);
  39919. function largePathFindDataIndex(largePath, x, y) {
  39920. var baseDimIdx = largePath.baseDimIdx;
  39921. var valueDimIdx = 1 - baseDimIdx;
  39922. var points = largePath.shape.points;
  39923. var largeDataIndices = largePath.largeDataIndices;
  39924. var startPoint = [];
  39925. var size = [];
  39926. var barWidth = largePath.barWidth;
  39927. for (var i = 0, len = points.length / 3; i < len; i++) {
  39928. var ii = i * 3;
  39929. size[baseDimIdx] = barWidth;
  39930. size[valueDimIdx] = points[ii + 2];
  39931. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  39932. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  39933. if (size[valueDimIdx] < 0) {
  39934. startPoint[valueDimIdx] += size[valueDimIdx];
  39935. size[valueDimIdx] = -size[valueDimIdx];
  39936. }
  39937. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  39938. return largeDataIndices[i];
  39939. }
  39940. }
  39941. return -1;
  39942. }
  39943. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  39944. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39945. var rectShape = layout;
  39946. var coordLayout = coord.getArea();
  39947. return {
  39948. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  39949. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  39950. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  39951. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  39952. };
  39953. } else {
  39954. var coordLayout = coord.getArea();
  39955. var sectorShape = layout;
  39956. return {
  39957. cx: coordLayout.cx,
  39958. cy: coordLayout.cy,
  39959. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  39960. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  39961. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  39962. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  39963. };
  39964. }
  39965. }
  39966. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  39967. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  39968. return new ElementClz({
  39969. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  39970. silent: true,
  39971. z2: 0
  39972. });
  39973. }
  39974. function install$3(registers) {
  39975. registers.registerChartView(BarView);
  39976. registers.registerSeriesModel(BarSeriesModel);
  39977. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Do layout after other overall layout, which can prepare some information.
  39978. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar')); // Down sample after filter
  39979. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  39980. /**
  39981. * @payload
  39982. * @property {string} [componentType=series]
  39983. * @property {number} [dx]
  39984. * @property {number} [dy]
  39985. * @property {number} [zoom]
  39986. * @property {number} [originX]
  39987. * @property {number} [originY]
  39988. */
  39989. registers.registerAction({
  39990. type: 'changeAxisOrder',
  39991. event: 'changeAxisOrder',
  39992. update: 'update'
  39993. }, function (payload, ecModel) {
  39994. var componentType = payload.componentType || 'series';
  39995. ecModel.eachComponent({
  39996. mainType: componentType,
  39997. query: payload
  39998. }, function (componentModel) {
  39999. if (payload.sortInfo) {
  40000. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  40001. }
  40002. });
  40003. });
  40004. }
  40005. var PI2$8 = Math.PI * 2;
  40006. var RADIAN = Math.PI / 180;
  40007. function getViewRect(seriesModel, api) {
  40008. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40009. width: api.getWidth(),
  40010. height: api.getHeight()
  40011. });
  40012. }
  40013. function getBasicPieLayout(seriesModel, api) {
  40014. var viewRect = getViewRect(seriesModel, api); // center can be string or number when coordinateSystem is specified
  40015. var center = seriesModel.get('center');
  40016. var radius = seriesModel.get('radius');
  40017. if (!isArray(radius)) {
  40018. radius = [0, radius];
  40019. }
  40020. var width = parsePercent$1(viewRect.width, api.getWidth());
  40021. var height = parsePercent$1(viewRect.height, api.getHeight());
  40022. var size = Math.min(width, height);
  40023. var r0 = parsePercent$1(radius[0], size / 2);
  40024. var r = parsePercent$1(radius[1], size / 2);
  40025. var cx;
  40026. var cy;
  40027. var coordSys = seriesModel.coordinateSystem;
  40028. if (coordSys) {
  40029. // percentage is not allowed when coordinate system is specified
  40030. var point = coordSys.dataToPoint(center);
  40031. cx = point[0] || 0;
  40032. cy = point[1] || 0;
  40033. } else {
  40034. if (!isArray(center)) {
  40035. center = [center, center];
  40036. }
  40037. cx = parsePercent$1(center[0], width) + viewRect.x;
  40038. cy = parsePercent$1(center[1], height) + viewRect.y;
  40039. }
  40040. return {
  40041. cx: cx,
  40042. cy: cy,
  40043. r0: r0,
  40044. r: r
  40045. };
  40046. }
  40047. function pieLayout(seriesType, ecModel, api) {
  40048. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  40049. var data = seriesModel.getData();
  40050. var valueDim = data.mapDimension('value');
  40051. var viewRect = getViewRect(seriesModel, api);
  40052. var _a = getBasicPieLayout(seriesModel, api),
  40053. cx = _a.cx,
  40054. cy = _a.cy,
  40055. r = _a.r,
  40056. r0 = _a.r0;
  40057. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  40058. var minAngle = seriesModel.get('minAngle') * RADIAN;
  40059. var validDataCount = 0;
  40060. data.each(valueDim, function (value) {
  40061. !isNaN(value) && validDataCount++;
  40062. });
  40063. var sum = data.getSum(valueDim); // Sum may be 0
  40064. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  40065. var clockwise = seriesModel.get('clockwise');
  40066. var roseType = seriesModel.get('roseType');
  40067. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  40068. var extent = data.getDataExtent(valueDim);
  40069. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  40070. var restAngle = PI2$8;
  40071. var valueSumLargerThanMinAngle = 0;
  40072. var currentAngle = startAngle;
  40073. var dir = clockwise ? 1 : -1;
  40074. data.setLayout({
  40075. viewRect: viewRect,
  40076. r: r
  40077. });
  40078. data.each(valueDim, function (value, idx) {
  40079. var angle;
  40080. if (isNaN(value)) {
  40081. data.setItemLayout(idx, {
  40082. angle: NaN,
  40083. startAngle: NaN,
  40084. endAngle: NaN,
  40085. clockwise: clockwise,
  40086. cx: cx,
  40087. cy: cy,
  40088. r0: r0,
  40089. r: roseType ? NaN : r
  40090. });
  40091. return;
  40092. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  40093. if (roseType !== 'area') {
  40094. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  40095. } else {
  40096. angle = PI2$8 / validDataCount;
  40097. }
  40098. if (angle < minAngle) {
  40099. angle = minAngle;
  40100. restAngle -= minAngle;
  40101. } else {
  40102. valueSumLargerThanMinAngle += value;
  40103. }
  40104. var endAngle = currentAngle + dir * angle;
  40105. data.setItemLayout(idx, {
  40106. angle: angle,
  40107. startAngle: currentAngle,
  40108. endAngle: endAngle,
  40109. clockwise: clockwise,
  40110. cx: cx,
  40111. cy: cy,
  40112. r0: r0,
  40113. r: roseType ? linearMap(value, extent, [r0, r]) : r
  40114. });
  40115. currentAngle = endAngle;
  40116. }); // Some sector is constrained by minAngle
  40117. // Rest sectors needs recalculate angle
  40118. if (restAngle < PI2$8 && validDataCount) {
  40119. // Average the angle if rest angle is not enough after all angles is
  40120. // Constrained by minAngle
  40121. if (restAngle <= 1e-3) {
  40122. var angle_1 = PI2$8 / validDataCount;
  40123. data.each(valueDim, function (value, idx) {
  40124. if (!isNaN(value)) {
  40125. var layout_1 = data.getItemLayout(idx);
  40126. layout_1.angle = angle_1;
  40127. layout_1.startAngle = startAngle + dir * idx * angle_1;
  40128. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  40129. }
  40130. });
  40131. } else {
  40132. unitRadian = restAngle / valueSumLargerThanMinAngle;
  40133. currentAngle = startAngle;
  40134. data.each(valueDim, function (value, idx) {
  40135. if (!isNaN(value)) {
  40136. var layout_2 = data.getItemLayout(idx);
  40137. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  40138. layout_2.startAngle = currentAngle;
  40139. layout_2.endAngle = currentAngle + dir * angle;
  40140. currentAngle += dir * angle;
  40141. }
  40142. });
  40143. }
  40144. }
  40145. });
  40146. }
  40147. /*
  40148. * Licensed to the Apache Software Foundation (ASF) under one
  40149. * or more contributor license agreements. See the NOTICE file
  40150. * distributed with this work for additional information
  40151. * regarding copyright ownership. The ASF licenses this file
  40152. * to you under the Apache License, Version 2.0 (the
  40153. * "License"); you may not use this file except in compliance
  40154. * with the License. You may obtain a copy of the License at
  40155. *
  40156. * http://www.apache.org/licenses/LICENSE-2.0
  40157. *
  40158. * Unless required by applicable law or agreed to in writing,
  40159. * software distributed under the License is distributed on an
  40160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40161. * KIND, either express or implied. See the License for the
  40162. * specific language governing permissions and limitations
  40163. * under the License.
  40164. */
  40165. /**
  40166. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40167. */
  40168. /*
  40169. * Licensed to the Apache Software Foundation (ASF) under one
  40170. * or more contributor license agreements. See the NOTICE file
  40171. * distributed with this work for additional information
  40172. * regarding copyright ownership. The ASF licenses this file
  40173. * to you under the Apache License, Version 2.0 (the
  40174. * "License"); you may not use this file except in compliance
  40175. * with the License. You may obtain a copy of the License at
  40176. *
  40177. * http://www.apache.org/licenses/LICENSE-2.0
  40178. *
  40179. * Unless required by applicable law or agreed to in writing,
  40180. * software distributed under the License is distributed on an
  40181. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40182. * KIND, either express or implied. See the License for the
  40183. * specific language governing permissions and limitations
  40184. * under the License.
  40185. */
  40186. function dataFilter(seriesType) {
  40187. return {
  40188. seriesType: seriesType,
  40189. reset: function (seriesModel, ecModel) {
  40190. var legendModels = ecModel.findComponents({
  40191. mainType: 'legend'
  40192. });
  40193. if (!legendModels || !legendModels.length) {
  40194. return;
  40195. }
  40196. var data = seriesModel.getData();
  40197. data.filterSelf(function (idx) {
  40198. var name = data.getName(idx); // If in any legend component the status is not selected.
  40199. for (var i = 0; i < legendModels.length; i++) {
  40200. // @ts-ignore FIXME: LegendModel
  40201. if (!legendModels[i].isSelected(name)) {
  40202. return false;
  40203. }
  40204. }
  40205. return true;
  40206. });
  40207. }
  40208. };
  40209. }
  40210. var RADIAN$1 = Math.PI / 180;
  40211. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  40212. if (list.length < 2) {
  40213. return;
  40214. }
  40215. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  40216. var rB = semi.rB;
  40217. var rB2 = rB * rB;
  40218. for (var i = 0; i < semi.list.length; i++) {
  40219. var item = semi.list[i];
  40220. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  40221. var rA = r + item.len;
  40222. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  40223. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  40224. var newX = cx + (dx + item.len2) * dir;
  40225. var deltaX = newX - item.label.x;
  40226. var newTargetWidth = item.targetTextWidth - deltaX * dir; // text x is changed, so need to recalculate width.
  40227. constrainTextWidth(item, newTargetWidth, true);
  40228. item.label.x = newX;
  40229. }
  40230. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  40231. function recalculateX(items) {
  40232. // Extremes of
  40233. var topSemi = {
  40234. list: [],
  40235. maxY: 0
  40236. };
  40237. var bottomSemi = {
  40238. list: [],
  40239. maxY: 0
  40240. };
  40241. for (var i = 0; i < items.length; i++) {
  40242. if (items[i].labelAlignTo !== 'none') {
  40243. continue;
  40244. }
  40245. var item = items[i];
  40246. var semi = item.label.y > cy ? bottomSemi : topSemi;
  40247. var dy = Math.abs(item.label.y - cy);
  40248. if (dy >= semi.maxY) {
  40249. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  40250. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  40251. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  40252. semi.rB = rB;
  40253. semi.maxY = dy;
  40254. }
  40255. semi.list.push(item);
  40256. }
  40257. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  40258. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  40259. }
  40260. var len = list.length;
  40261. for (var i = 0; i < len; i++) {
  40262. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  40263. var dx = list[i].label.x - farthestX;
  40264. list[i].linePoints[1][0] += dx;
  40265. list[i].label.x = farthestX;
  40266. }
  40267. }
  40268. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  40269. recalculateX(list);
  40270. }
  40271. }
  40272. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  40273. var leftList = [];
  40274. var rightList = [];
  40275. var leftmostX = Number.MAX_VALUE;
  40276. var rightmostX = -Number.MAX_VALUE;
  40277. for (var i = 0; i < labelLayoutList.length; i++) {
  40278. var label = labelLayoutList[i].label;
  40279. if (isPositionCenter(labelLayoutList[i])) {
  40280. continue;
  40281. }
  40282. if (label.x < cx) {
  40283. leftmostX = Math.min(leftmostX, label.x);
  40284. leftList.push(labelLayoutList[i]);
  40285. } else {
  40286. rightmostX = Math.max(rightmostX, label.x);
  40287. rightList.push(labelLayoutList[i]);
  40288. }
  40289. }
  40290. for (var i = 0; i < labelLayoutList.length; i++) {
  40291. var layout = labelLayoutList[i];
  40292. if (!isPositionCenter(layout) && layout.linePoints) {
  40293. if (layout.labelStyleWidth != null) {
  40294. continue;
  40295. }
  40296. var label = layout.label;
  40297. var linePoints = layout.linePoints;
  40298. var targetTextWidth = void 0;
  40299. if (layout.labelAlignTo === 'edge') {
  40300. if (label.x < cx) {
  40301. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  40302. } else {
  40303. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  40304. }
  40305. } else if (layout.labelAlignTo === 'labelLine') {
  40306. if (label.x < cx) {
  40307. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  40308. } else {
  40309. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  40310. }
  40311. } else {
  40312. if (label.x < cx) {
  40313. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  40314. } else {
  40315. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  40316. }
  40317. }
  40318. layout.targetTextWidth = targetTextWidth;
  40319. constrainTextWidth(layout, targetTextWidth);
  40320. }
  40321. }
  40322. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  40323. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  40324. for (var i = 0; i < labelLayoutList.length; i++) {
  40325. var layout = labelLayoutList[i];
  40326. if (!isPositionCenter(layout) && layout.linePoints) {
  40327. var label = layout.label;
  40328. var linePoints = layout.linePoints;
  40329. var isAlignToEdge = layout.labelAlignTo === 'edge';
  40330. var padding = label.style.padding;
  40331. var paddingH = padding ? padding[1] + padding[3] : 0; // textRect.width already contains paddingH if bgColor is set
  40332. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  40333. var realTextWidth = layout.rect.width + extraPaddingH;
  40334. var dist = linePoints[1][0] - linePoints[2][0];
  40335. if (isAlignToEdge) {
  40336. if (label.x < cx) {
  40337. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  40338. } else {
  40339. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  40340. }
  40341. } else {
  40342. if (label.x < cx) {
  40343. linePoints[2][0] = label.x + layout.labelDistance;
  40344. } else {
  40345. linePoints[2][0] = label.x - layout.labelDistance;
  40346. }
  40347. linePoints[1][0] = linePoints[2][0] + dist;
  40348. }
  40349. linePoints[1][1] = linePoints[2][1] = label.y;
  40350. }
  40351. }
  40352. }
  40353. /**
  40354. * Set max width of each label, and then wrap each label to the max width.
  40355. *
  40356. * @param layout label layout
  40357. * @param availableWidth max width for the label to display
  40358. * @param forceRecalculate recaculate the text layout even if the current width
  40359. * is smaller than `availableWidth`. This is useful when the text was previously
  40360. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  40361. * which case, previous wrapping should be redo.
  40362. */
  40363. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  40364. if (forceRecalculate === void 0) {
  40365. forceRecalculate = false;
  40366. }
  40367. if (layout.labelStyleWidth != null) {
  40368. // User-defined style.width has the highest priority.
  40369. return;
  40370. }
  40371. var label = layout.label;
  40372. var style = label.style;
  40373. var textRect = layout.rect;
  40374. var bgColor = style.backgroundColor;
  40375. var padding = style.padding;
  40376. var paddingH = padding ? padding[1] + padding[3] : 0;
  40377. var overflow = style.overflow; // textRect.width already contains paddingH if bgColor is set
  40378. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  40379. if (availableWidth < oldOuterWidth || forceRecalculate) {
  40380. var oldHeight = textRect.height;
  40381. if (overflow && overflow.match('break')) {
  40382. // Temporarily set background to be null to calculate
  40383. // the bounding box without background.
  40384. label.setStyle('backgroundColor', null); // Set constraining width
  40385. label.setStyle('width', availableWidth - paddingH); // This is the real bounding box of the text without padding.
  40386. var innerRect = label.getBoundingRect();
  40387. label.setStyle('width', Math.ceil(innerRect.width));
  40388. label.setStyle('backgroundColor', bgColor);
  40389. } else {
  40390. var availableInnerWidth = availableWidth - paddingH;
  40391. var newWidth = availableWidth < oldOuterWidth // Current text is too wide, use `availableWidth` as max width.
  40392. ? availableInnerWidth : // Current available width is enough, but the text may have
  40393. // already been wrapped with a smaller available width.
  40394. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth // Current available is larger than text width,
  40395. // so don't constrain width (otherwise it may have
  40396. // empty space in the background).
  40397. ? null // Current available is smaller than text width, so
  40398. // use the current available width as constraining
  40399. // width.
  40400. : availableInnerWidth : // Current available width is enough, so no need to
  40401. // constrain.
  40402. null;
  40403. label.setStyle('width', newWidth);
  40404. }
  40405. var newRect = label.getBoundingRect();
  40406. textRect.width = newRect.width;
  40407. var margin = (label.style.margin || 0) + 2.1;
  40408. textRect.height = newRect.height + margin;
  40409. textRect.y -= (textRect.height - oldHeight) / 2;
  40410. }
  40411. }
  40412. function isPositionCenter(sectorShape) {
  40413. // Not change x for center label
  40414. return sectorShape.position === 'center';
  40415. }
  40416. function pieLabelLayout(seriesModel) {
  40417. var data = seriesModel.getData();
  40418. var labelLayoutList = [];
  40419. var cx;
  40420. var cy;
  40421. var hasLabelRotate = false;
  40422. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  40423. var viewRect = data.getLayout('viewRect');
  40424. var r = data.getLayout('r');
  40425. var viewWidth = viewRect.width;
  40426. var viewLeft = viewRect.x;
  40427. var viewTop = viewRect.y;
  40428. var viewHeight = viewRect.height;
  40429. function setNotShow(el) {
  40430. el.ignore = true;
  40431. }
  40432. function isLabelShown(label) {
  40433. if (!label.ignore) {
  40434. return true;
  40435. }
  40436. for (var key in label.states) {
  40437. if (label.states[key].ignore === false) {
  40438. return true;
  40439. }
  40440. }
  40441. return false;
  40442. }
  40443. data.each(function (idx) {
  40444. var sector = data.getItemGraphicEl(idx);
  40445. var sectorShape = sector.shape;
  40446. var label = sector.getTextContent();
  40447. var labelLine = sector.getTextGuideLine();
  40448. var itemModel = data.getItemModel(idx);
  40449. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  40450. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  40451. var labelDistance = labelModel.get('distanceToLabelLine');
  40452. var labelAlignTo = labelModel.get('alignTo');
  40453. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  40454. var bleedMargin = labelModel.get('bleedMargin');
  40455. var labelLineModel = itemModel.getModel('labelLine');
  40456. var labelLineLen = labelLineModel.get('length');
  40457. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  40458. var labelLineLen2 = labelLineModel.get('length2');
  40459. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  40460. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  40461. each(label.states, setNotShow);
  40462. label.ignore = true;
  40463. if (labelLine) {
  40464. each(labelLine.states, setNotShow);
  40465. labelLine.ignore = true;
  40466. }
  40467. return;
  40468. }
  40469. if (!isLabelShown(label)) {
  40470. return;
  40471. }
  40472. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  40473. var nx = Math.cos(midAngle);
  40474. var ny = Math.sin(midAngle);
  40475. var textX;
  40476. var textY;
  40477. var linePoints;
  40478. var textAlign;
  40479. cx = sectorShape.cx;
  40480. cy = sectorShape.cy;
  40481. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  40482. if (labelPosition === 'center') {
  40483. textX = sectorShape.cx;
  40484. textY = sectorShape.cy;
  40485. textAlign = 'center';
  40486. } else {
  40487. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  40488. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  40489. textX = x1 + nx * 3;
  40490. textY = y1 + ny * 3;
  40491. if (!isLabelInside) {
  40492. // For roseType
  40493. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  40494. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  40495. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  40496. var y3 = y2;
  40497. if (labelAlignTo === 'edge') {
  40498. // Adjust textX because text align of edge is opposite
  40499. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  40500. } else {
  40501. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  40502. }
  40503. textY = y3;
  40504. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  40505. }
  40506. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  40507. }
  40508. var PI = Math.PI;
  40509. var labelRotate = 0;
  40510. var rotate = labelModel.get('rotate');
  40511. if (isNumber(rotate)) {
  40512. labelRotate = rotate * (PI / 180);
  40513. } else if (labelPosition === 'center') {
  40514. labelRotate = 0;
  40515. } else if (rotate === 'radial' || rotate === true) {
  40516. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  40517. labelRotate = radialAngle;
  40518. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  40519. var rad = Math.atan2(nx, ny);
  40520. if (rad < 0) {
  40521. rad = PI * 2 + rad;
  40522. }
  40523. var isDown = ny > 0;
  40524. if (isDown) {
  40525. rad = PI + rad;
  40526. }
  40527. labelRotate = rad - PI;
  40528. }
  40529. hasLabelRotate = !!labelRotate;
  40530. label.x = textX;
  40531. label.y = textY;
  40532. label.rotation = labelRotate;
  40533. label.setStyle({
  40534. verticalAlign: 'middle'
  40535. }); // Not sectorShape the inside label
  40536. if (!isLabelInside) {
  40537. var textRect = label.getBoundingRect().clone();
  40538. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  40539. var margin = (label.style.margin || 0) + 2.1;
  40540. textRect.y -= margin / 2;
  40541. textRect.height += margin;
  40542. labelLayoutList.push({
  40543. label: label,
  40544. labelLine: labelLine,
  40545. position: labelPosition,
  40546. len: labelLineLen,
  40547. len2: labelLineLen2,
  40548. minTurnAngle: labelLineModel.get('minTurnAngle'),
  40549. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  40550. surfaceNormal: new Point(nx, ny),
  40551. linePoints: linePoints,
  40552. textAlign: textAlign,
  40553. labelDistance: labelDistance,
  40554. labelAlignTo: labelAlignTo,
  40555. edgeDistance: edgeDistance,
  40556. bleedMargin: bleedMargin,
  40557. rect: textRect,
  40558. unconstrainedWidth: textRect.width,
  40559. labelStyleWidth: label.style.width
  40560. });
  40561. } else {
  40562. label.setStyle({
  40563. align: textAlign
  40564. });
  40565. var selectState = label.states.select;
  40566. if (selectState) {
  40567. selectState.x += label.x;
  40568. selectState.y += label.y;
  40569. }
  40570. }
  40571. sector.setTextConfig({
  40572. inside: isLabelInside
  40573. });
  40574. });
  40575. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  40576. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  40577. }
  40578. for (var i = 0; i < labelLayoutList.length; i++) {
  40579. var layout = labelLayoutList[i];
  40580. var label = layout.label;
  40581. var labelLine = layout.labelLine;
  40582. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  40583. if (label) {
  40584. label.setStyle({
  40585. align: layout.textAlign
  40586. });
  40587. if (notShowLabel) {
  40588. each(label.states, setNotShow);
  40589. label.ignore = true;
  40590. }
  40591. var selectState = label.states.select;
  40592. if (selectState) {
  40593. selectState.x += label.x;
  40594. selectState.y += label.y;
  40595. }
  40596. }
  40597. if (labelLine) {
  40598. var linePoints = layout.linePoints;
  40599. if (notShowLabel || !linePoints) {
  40600. each(labelLine.states, setNotShow);
  40601. labelLine.ignore = true;
  40602. } else {
  40603. limitTurnAngle(linePoints, layout.minTurnAngle);
  40604. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  40605. labelLine.setShape({
  40606. points: linePoints
  40607. }); // Set the anchor to the midpoint of sector
  40608. label.__hostTarget.textGuideLineConfig = {
  40609. anchor: new Point(linePoints[0][0], linePoints[0][1])
  40610. };
  40611. }
  40612. }
  40613. }
  40614. }
  40615. /**
  40616. * Piece of pie including Sector, Label, LabelLine
  40617. */
  40618. var PiePiece =
  40619. /** @class */
  40620. function (_super) {
  40621. __extends(PiePiece, _super);
  40622. function PiePiece(data, idx, startAngle) {
  40623. var _this = _super.call(this) || this;
  40624. _this.z2 = 2;
  40625. var text = new ZRText();
  40626. _this.setTextContent(text);
  40627. _this.updateData(data, idx, startAngle, true);
  40628. return _this;
  40629. }
  40630. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  40631. var sector = this;
  40632. var seriesModel = data.hostModel;
  40633. var itemModel = data.getItemModel(idx);
  40634. var emphasisModel = itemModel.getModel('emphasis');
  40635. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  40636. // see `setItemLayout` in `pieLayout.ts`.
  40637. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  40638. if (isNaN(sectorShape.startAngle)) {
  40639. // Use NaN shape to avoid drawing shape.
  40640. sector.setShape(sectorShape);
  40641. return;
  40642. }
  40643. if (firstCreate) {
  40644. sector.setShape(sectorShape);
  40645. var animationType = seriesModel.getShallow('animationType');
  40646. if (seriesModel.ecModel.ssr) {
  40647. // Use scale animation in SSR mode(opacity?)
  40648. // Because CSS SVG animation doesn't support very customized shape animation.
  40649. initProps(sector, {
  40650. scaleX: 0,
  40651. scaleY: 0
  40652. }, seriesModel, {
  40653. dataIndex: idx,
  40654. isFrom: true
  40655. });
  40656. sector.originX = sectorShape.cx;
  40657. sector.originY = sectorShape.cy;
  40658. } else if (animationType === 'scale') {
  40659. sector.shape.r = layout.r0;
  40660. initProps(sector, {
  40661. shape: {
  40662. r: layout.r
  40663. }
  40664. }, seriesModel, idx);
  40665. } // Expansion
  40666. else {
  40667. if (startAngle != null) {
  40668. sector.setShape({
  40669. startAngle: startAngle,
  40670. endAngle: startAngle
  40671. });
  40672. initProps(sector, {
  40673. shape: {
  40674. startAngle: layout.startAngle,
  40675. endAngle: layout.endAngle
  40676. }
  40677. }, seriesModel, idx);
  40678. } else {
  40679. sector.shape.endAngle = layout.startAngle;
  40680. updateProps(sector, {
  40681. shape: {
  40682. endAngle: layout.endAngle
  40683. }
  40684. }, seriesModel, idx);
  40685. }
  40686. }
  40687. } else {
  40688. saveOldStyle(sector); // Transition animation from the old shape
  40689. updateProps(sector, {
  40690. shape: sectorShape
  40691. }, seriesModel, idx);
  40692. }
  40693. sector.useStyle(data.getItemVisual(idx, 'style'));
  40694. setStatesStylesFromModel(sector, itemModel);
  40695. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  40696. var offset = seriesModel.get('selectedOffset');
  40697. var dx = Math.cos(midAngle) * offset;
  40698. var dy = Math.sin(midAngle) * offset;
  40699. var cursorStyle = itemModel.getShallow('cursor');
  40700. cursorStyle && sector.attr('cursor', cursorStyle);
  40701. this._updateLabel(seriesModel, data, idx);
  40702. sector.ensureState('emphasis').shape = extend({
  40703. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  40704. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  40705. extend(sector.ensureState('select'), {
  40706. x: dx,
  40707. y: dy,
  40708. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  40709. });
  40710. extend(sector.ensureState('blur'), {
  40711. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  40712. });
  40713. var labelLine = sector.getTextGuideLine();
  40714. var labelText = sector.getTextContent();
  40715. labelLine && extend(labelLine.ensureState('select'), {
  40716. x: dx,
  40717. y: dy
  40718. }); // TODO: needs dx, dy in zrender?
  40719. extend(labelText.ensureState('select'), {
  40720. x: dx,
  40721. y: dy
  40722. });
  40723. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  40724. };
  40725. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  40726. var sector = this;
  40727. var itemModel = data.getItemModel(idx);
  40728. var labelLineModel = itemModel.getModel('labelLine');
  40729. var style = data.getItemVisual(idx, 'style');
  40730. var visualColor = style && style.fill;
  40731. var visualOpacity = style && style.opacity;
  40732. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  40733. labelFetcher: data.hostModel,
  40734. labelDataIndex: idx,
  40735. inheritColor: visualColor,
  40736. defaultOpacity: visualOpacity,
  40737. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  40738. });
  40739. var labelText = sector.getTextContent(); // Set textConfig on sector.
  40740. sector.setTextConfig({
  40741. // reset position, rotation
  40742. position: null,
  40743. rotation: null
  40744. }); // Make sure update style on labelText after setLabelStyle.
  40745. // Because setLabelStyle will replace a new style on it.
  40746. labelText.attr({
  40747. z2: 10
  40748. });
  40749. var labelPosition = seriesModel.get(['label', 'position']);
  40750. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  40751. sector.removeTextGuideLine();
  40752. } else {
  40753. var polyline = this.getTextGuideLine();
  40754. if (!polyline) {
  40755. polyline = new Polyline();
  40756. this.setTextGuideLine(polyline);
  40757. } // Default use item visual color
  40758. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  40759. stroke: visualColor,
  40760. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  40761. });
  40762. }
  40763. };
  40764. return PiePiece;
  40765. }(Sector); // Pie view
  40766. var PieView =
  40767. /** @class */
  40768. function (_super) {
  40769. __extends(PieView, _super);
  40770. function PieView() {
  40771. var _this = _super !== null && _super.apply(this, arguments) || this;
  40772. _this.ignoreLabelLineUpdate = true;
  40773. return _this;
  40774. }
  40775. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  40776. var data = seriesModel.getData();
  40777. var oldData = this._data;
  40778. var group = this.group;
  40779. var startAngle; // First render
  40780. if (!oldData && data.count() > 0) {
  40781. var shape = data.getItemLayout(0);
  40782. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  40783. shape = data.getItemLayout(s);
  40784. }
  40785. if (shape) {
  40786. startAngle = shape.startAngle;
  40787. }
  40788. } // remove empty-circle if it exists
  40789. if (this._emptyCircleSector) {
  40790. group.remove(this._emptyCircleSector);
  40791. } // when all data are filtered, show lightgray empty circle
  40792. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  40793. var sector = new Sector({
  40794. shape: getBasicPieLayout(seriesModel, api)
  40795. });
  40796. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  40797. this._emptyCircleSector = sector;
  40798. group.add(sector);
  40799. }
  40800. data.diff(oldData).add(function (idx) {
  40801. var piePiece = new PiePiece(data, idx, startAngle);
  40802. data.setItemGraphicEl(idx, piePiece);
  40803. group.add(piePiece);
  40804. }).update(function (newIdx, oldIdx) {
  40805. var piePiece = oldData.getItemGraphicEl(oldIdx);
  40806. piePiece.updateData(data, newIdx, startAngle);
  40807. piePiece.off('click');
  40808. group.add(piePiece);
  40809. data.setItemGraphicEl(newIdx, piePiece);
  40810. }).remove(function (idx) {
  40811. var piePiece = oldData.getItemGraphicEl(idx);
  40812. removeElementWithFadeOut(piePiece, seriesModel, idx);
  40813. }).execute();
  40814. pieLabelLayout(seriesModel); // Always use initial animation.
  40815. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  40816. this._data = data;
  40817. }
  40818. };
  40819. PieView.prototype.dispose = function () {};
  40820. PieView.prototype.containPoint = function (point, seriesModel) {
  40821. var data = seriesModel.getData();
  40822. var itemLayout = data.getItemLayout(0);
  40823. if (itemLayout) {
  40824. var dx = point[0] - itemLayout.cx;
  40825. var dy = point[1] - itemLayout.cy;
  40826. var radius = Math.sqrt(dx * dx + dy * dy);
  40827. return radius <= itemLayout.r && radius >= itemLayout.r0;
  40828. }
  40829. };
  40830. PieView.type = 'pie';
  40831. return PieView;
  40832. }(ChartView);
  40833. /**
  40834. * [Usage]:
  40835. * (1)
  40836. * createListSimply(seriesModel, ['value']);
  40837. * (2)
  40838. * createListSimply(seriesModel, {
  40839. * coordDimensions: ['value'],
  40840. * dimensionsCount: 5
  40841. * });
  40842. */
  40843. function createSeriesDataSimply(seriesModel, opt, nameList) {
  40844. opt = isArray(opt) && {
  40845. coordDimensions: opt
  40846. } || extend({
  40847. encodeDefine: seriesModel.getEncode()
  40848. }, opt);
  40849. var source = seriesModel.getSource();
  40850. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  40851. var list = new SeriesData(dimensions, seriesModel);
  40852. list.initData(source, nameList);
  40853. return list;
  40854. }
  40855. /*
  40856. * Licensed to the Apache Software Foundation (ASF) under one
  40857. * or more contributor license agreements. See the NOTICE file
  40858. * distributed with this work for additional information
  40859. * regarding copyright ownership. The ASF licenses this file
  40860. * to you under the Apache License, Version 2.0 (the
  40861. * "License"); you may not use this file except in compliance
  40862. * with the License. You may obtain a copy of the License at
  40863. *
  40864. * http://www.apache.org/licenses/LICENSE-2.0
  40865. *
  40866. * Unless required by applicable law or agreed to in writing,
  40867. * software distributed under the License is distributed on an
  40868. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40869. * KIND, either express or implied. See the License for the
  40870. * specific language governing permissions and limitations
  40871. * under the License.
  40872. */
  40873. /**
  40874. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40875. */
  40876. /*
  40877. * Licensed to the Apache Software Foundation (ASF) under one
  40878. * or more contributor license agreements. See the NOTICE file
  40879. * distributed with this work for additional information
  40880. * regarding copyright ownership. The ASF licenses this file
  40881. * to you under the Apache License, Version 2.0 (the
  40882. * "License"); you may not use this file except in compliance
  40883. * with the License. You may obtain a copy of the License at
  40884. *
  40885. * http://www.apache.org/licenses/LICENSE-2.0
  40886. *
  40887. * Unless required by applicable law or agreed to in writing,
  40888. * software distributed under the License is distributed on an
  40889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40890. * KIND, either express or implied. See the License for the
  40891. * specific language governing permissions and limitations
  40892. * under the License.
  40893. */
  40894. /**
  40895. * LegendVisualProvider is an bridge that pick encoded color from data and
  40896. * provide to the legend component.
  40897. */
  40898. var LegendVisualProvider =
  40899. /** @class */
  40900. function () {
  40901. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  40902. getDataWithEncodedVisual, // Function to get raw data before filtered.
  40903. getRawData) {
  40904. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  40905. this._getRawData = getRawData;
  40906. }
  40907. LegendVisualProvider.prototype.getAllNames = function () {
  40908. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  40909. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  40910. return rawData.mapArray(rawData.getName);
  40911. };
  40912. LegendVisualProvider.prototype.containName = function (name) {
  40913. var rawData = this._getRawData();
  40914. return rawData.indexOfName(name) >= 0;
  40915. };
  40916. LegendVisualProvider.prototype.indexOfName = function (name) {
  40917. // Only get data when necessary.
  40918. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  40919. // Invoking Series#getData immediately will throw an error.
  40920. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  40921. return dataWithEncodedVisual.indexOfName(name);
  40922. };
  40923. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  40924. // Get encoded visual properties from final filtered data.
  40925. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  40926. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  40927. };
  40928. return LegendVisualProvider;
  40929. }();
  40930. var innerData = makeInner();
  40931. var PieSeriesModel =
  40932. /** @class */
  40933. function (_super) {
  40934. __extends(PieSeriesModel, _super);
  40935. function PieSeriesModel() {
  40936. return _super !== null && _super.apply(this, arguments) || this;
  40937. }
  40938. /**
  40939. * @overwrite
  40940. */
  40941. PieSeriesModel.prototype.init = function (option) {
  40942. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  40943. // Use a function instead of direct access because data reference may changed
  40944. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  40945. this._defaultLabelLine(option);
  40946. };
  40947. /**
  40948. * @overwrite
  40949. */
  40950. PieSeriesModel.prototype.mergeOption = function () {
  40951. _super.prototype.mergeOption.apply(this, arguments);
  40952. };
  40953. /**
  40954. * @overwrite
  40955. */
  40956. PieSeriesModel.prototype.getInitialData = function () {
  40957. return createSeriesDataSimply(this, {
  40958. coordDimensions: ['value'],
  40959. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  40960. });
  40961. };
  40962. /**
  40963. * @overwrite
  40964. */
  40965. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  40966. var data = this.getData(); // update seats when data is changed
  40967. var dataInner = innerData(data);
  40968. var seats = dataInner.seats;
  40969. if (!seats) {
  40970. var valueList_1 = [];
  40971. data.each(data.mapDimension('value'), function (value) {
  40972. valueList_1.push(value);
  40973. });
  40974. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  40975. }
  40976. var params = _super.prototype.getDataParams.call(this, dataIndex); // seats may be empty when sum is 0
  40977. params.percent = seats[dataIndex] || 0;
  40978. params.$vars.push('percent');
  40979. return params;
  40980. };
  40981. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  40982. // Extend labelLine emphasis
  40983. defaultEmphasis(option, 'labelLine', ['show']);
  40984. var labelLineNormalOpt = option.labelLine;
  40985. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  40986. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  40987. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  40988. };
  40989. PieSeriesModel.type = 'series.pie';
  40990. PieSeriesModel.defaultOption = {
  40991. // zlevel: 0,
  40992. z: 2,
  40993. legendHoverLink: true,
  40994. colorBy: 'data',
  40995. // 默认全局居中
  40996. center: ['50%', '50%'],
  40997. radius: [0, '75%'],
  40998. // 默认顺时针
  40999. clockwise: true,
  41000. startAngle: 90,
  41001. // 最小角度改为0
  41002. minAngle: 0,
  41003. // If the angle of a sector less than `minShowLabelAngle`,
  41004. // the label will not be displayed.
  41005. minShowLabelAngle: 0,
  41006. // 选中时扇区偏移量
  41007. selectedOffset: 10,
  41008. // 选择模式,默认关闭,可选single,multiple
  41009. // selectedMode: false,
  41010. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  41011. // roseType: null,
  41012. percentPrecision: 2,
  41013. // If still show when all data zero.
  41014. stillShowZeroSum: true,
  41015. // cursor: null,
  41016. left: 0,
  41017. top: 0,
  41018. right: 0,
  41019. bottom: 0,
  41020. width: null,
  41021. height: null,
  41022. label: {
  41023. // color: 'inherit',
  41024. // If rotate around circle
  41025. rotate: 0,
  41026. show: true,
  41027. overflow: 'truncate',
  41028. // 'outer', 'inside', 'center'
  41029. position: 'outer',
  41030. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  41031. alignTo: 'none',
  41032. // Closest distance between label and chart edge.
  41033. // Works only position is 'outer' and alignTo is 'edge'.
  41034. edgeDistance: '25%',
  41035. // Works only position is 'outer' and alignTo is not 'edge'.
  41036. bleedMargin: 10,
  41037. // Distance between text and label line.
  41038. distanceToLabelLine: 5 // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  41039. // 默认使用全局文本样式,详见 textStyle
  41040. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  41041. },
  41042. // Enabled when label.normal.position is 'outer'
  41043. labelLine: {
  41044. show: true,
  41045. // 引导线两段中的第一段长度
  41046. length: 15,
  41047. // 引导线两段中的第二段长度
  41048. length2: 15,
  41049. smooth: false,
  41050. minTurnAngle: 90,
  41051. maxSurfaceAngle: 90,
  41052. lineStyle: {
  41053. // color: 各异,
  41054. width: 1,
  41055. type: 'solid'
  41056. }
  41057. },
  41058. itemStyle: {
  41059. borderWidth: 1,
  41060. borderJoin: 'round'
  41061. },
  41062. showEmptyCircle: true,
  41063. emptyCircleStyle: {
  41064. color: 'lightgray',
  41065. opacity: 1
  41066. },
  41067. labelLayout: {
  41068. // Hide the overlapped label.
  41069. hideOverlap: true
  41070. },
  41071. emphasis: {
  41072. scale: true,
  41073. scaleSize: 5
  41074. },
  41075. // If use strategy to avoid label overlapping
  41076. avoidLabelOverlap: true,
  41077. // Animation type. Valid values: expansion, scale
  41078. animationType: 'expansion',
  41079. animationDuration: 1000,
  41080. // Animation type when update. Valid values: transition, expansion
  41081. animationTypeUpdate: 'transition',
  41082. animationEasingUpdate: 'cubicInOut',
  41083. animationDurationUpdate: 500,
  41084. animationEasing: 'cubicInOut'
  41085. };
  41086. return PieSeriesModel;
  41087. }(SeriesModel);
  41088. function negativeDataFilter(seriesType) {
  41089. return {
  41090. seriesType: seriesType,
  41091. reset: function (seriesModel, ecModel) {
  41092. var data = seriesModel.getData();
  41093. data.filterSelf(function (idx) {
  41094. // handle negative value condition
  41095. var valueDim = data.mapDimension('value');
  41096. var curValue = data.get(valueDim, idx);
  41097. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  41098. return false;
  41099. }
  41100. return true;
  41101. });
  41102. }
  41103. };
  41104. }
  41105. function install$4(registers) {
  41106. registers.registerChartView(PieView);
  41107. registers.registerSeriesModel(PieSeriesModel);
  41108. createLegacyDataSelectAction('pie', registers.registerAction);
  41109. registers.registerLayout(curry(pieLayout, 'pie'));
  41110. registers.registerProcessor(dataFilter('pie'));
  41111. registers.registerProcessor(negativeDataFilter('pie'));
  41112. }
  41113. var ScatterSeriesModel =
  41114. /** @class */
  41115. function (_super) {
  41116. __extends(ScatterSeriesModel, _super);
  41117. function ScatterSeriesModel() {
  41118. var _this = _super !== null && _super.apply(this, arguments) || this;
  41119. _this.type = ScatterSeriesModel.type;
  41120. _this.hasSymbolVisual = true;
  41121. return _this;
  41122. }
  41123. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41124. return createSeriesData(null, this, {
  41125. useEncodeDefaulter: true
  41126. });
  41127. };
  41128. ScatterSeriesModel.prototype.getProgressive = function () {
  41129. var progressive = this.option.progressive;
  41130. if (progressive == null) {
  41131. // PENDING
  41132. return this.option.large ? 5e3 : this.get('progressive');
  41133. }
  41134. return progressive;
  41135. };
  41136. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  41137. var progressiveThreshold = this.option.progressiveThreshold;
  41138. if (progressiveThreshold == null) {
  41139. // PENDING
  41140. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  41141. }
  41142. return progressiveThreshold;
  41143. };
  41144. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  41145. return selectors.point(data.getItemLayout(dataIndex));
  41146. };
  41147. ScatterSeriesModel.prototype.getZLevelKey = function () {
  41148. // Each progressive series has individual key.
  41149. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  41150. };
  41151. ScatterSeriesModel.type = 'series.scatter';
  41152. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  41153. ScatterSeriesModel.defaultOption = {
  41154. coordinateSystem: 'cartesian2d',
  41155. // zlevel: 0,
  41156. z: 2,
  41157. legendHoverLink: true,
  41158. symbolSize: 10,
  41159. // symbolRotate: null, // 图形旋转控制
  41160. large: false,
  41161. // Available when large is true
  41162. largeThreshold: 2000,
  41163. // cursor: null,
  41164. itemStyle: {
  41165. opacity: 0.8 // color: 各异
  41166. },
  41167. emphasis: {
  41168. scale: true
  41169. },
  41170. // If clip the overflow graphics
  41171. // Works on cartesian / polar series
  41172. clip: true,
  41173. select: {
  41174. itemStyle: {
  41175. borderColor: '#212121'
  41176. }
  41177. },
  41178. universalTransition: {
  41179. divideShape: 'clone'
  41180. } // progressive: null
  41181. };
  41182. return ScatterSeriesModel;
  41183. }(SeriesModel);
  41184. var BOOST_SIZE_THRESHOLD = 4;
  41185. var LargeSymbolPathShape =
  41186. /** @class */
  41187. function () {
  41188. function LargeSymbolPathShape() {}
  41189. return LargeSymbolPathShape;
  41190. }();
  41191. var LargeSymbolPath =
  41192. /** @class */
  41193. function (_super) {
  41194. __extends(LargeSymbolPath, _super);
  41195. function LargeSymbolPath(opts) {
  41196. var _this = _super.call(this, opts) || this;
  41197. _this._off = 0;
  41198. _this.hoverDataIdx = -1;
  41199. return _this;
  41200. }
  41201. LargeSymbolPath.prototype.getDefaultShape = function () {
  41202. return new LargeSymbolPathShape();
  41203. };
  41204. LargeSymbolPath.prototype.reset = function () {
  41205. this.notClear = false;
  41206. this._off = 0;
  41207. };
  41208. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  41209. var points = shape.points;
  41210. var size = shape.size;
  41211. var symbolProxy = this.symbolProxy;
  41212. var symbolProxyShape = symbolProxy.shape;
  41213. var ctx = path.getContext ? path.getContext() : path;
  41214. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  41215. var softClipShape = this.softClipShape;
  41216. var i; // Do draw in afterBrush.
  41217. if (canBoost) {
  41218. this._ctx = ctx;
  41219. return;
  41220. }
  41221. this._ctx = null;
  41222. for (i = this._off; i < points.length;) {
  41223. var x = points[i++];
  41224. var y = points[i++];
  41225. if (isNaN(x) || isNaN(y)) {
  41226. continue;
  41227. }
  41228. if (softClipShape && !softClipShape.contain(x, y)) {
  41229. continue;
  41230. }
  41231. symbolProxyShape.x = x - size[0] / 2;
  41232. symbolProxyShape.y = y - size[1] / 2;
  41233. symbolProxyShape.width = size[0];
  41234. symbolProxyShape.height = size[1];
  41235. symbolProxy.buildPath(path, symbolProxyShape, true);
  41236. }
  41237. if (this.incremental) {
  41238. this._off = i;
  41239. this.notClear = true;
  41240. }
  41241. };
  41242. LargeSymbolPath.prototype.afterBrush = function () {
  41243. var shape = this.shape;
  41244. var points = shape.points;
  41245. var size = shape.size;
  41246. var ctx = this._ctx;
  41247. var softClipShape = this.softClipShape;
  41248. var i;
  41249. if (!ctx) {
  41250. return;
  41251. } // PENDING If style or other canvas status changed?
  41252. for (i = this._off; i < points.length;) {
  41253. var x = points[i++];
  41254. var y = points[i++];
  41255. if (isNaN(x) || isNaN(y)) {
  41256. continue;
  41257. }
  41258. if (softClipShape && !softClipShape.contain(x, y)) {
  41259. continue;
  41260. } // fillRect is faster than building a rect path and draw.
  41261. // And it support light globalCompositeOperation.
  41262. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  41263. }
  41264. if (this.incremental) {
  41265. this._off = i;
  41266. this.notClear = true;
  41267. }
  41268. };
  41269. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  41270. // TODO ???
  41271. // Consider transform
  41272. var shape = this.shape;
  41273. var points = shape.points;
  41274. var size = shape.size;
  41275. var w = Math.max(size[0], 4);
  41276. var h = Math.max(size[1], 4); // Not consider transform
  41277. // Treat each element as a rect
  41278. // top down traverse
  41279. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  41280. var i = idx * 2;
  41281. var x0 = points[i] - w / 2;
  41282. var y0 = points[i + 1] - h / 2;
  41283. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  41284. return idx;
  41285. }
  41286. }
  41287. return -1;
  41288. };
  41289. LargeSymbolPath.prototype.contain = function (x, y) {
  41290. var localPos = this.transformCoordToLocal(x, y);
  41291. var rect = this.getBoundingRect();
  41292. x = localPos[0];
  41293. y = localPos[1];
  41294. if (rect.contain(x, y)) {
  41295. // Cache found data index.
  41296. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  41297. return dataIdx >= 0;
  41298. }
  41299. this.hoverDataIdx = -1;
  41300. return false;
  41301. };
  41302. LargeSymbolPath.prototype.getBoundingRect = function () {
  41303. // Ignore stroke for large symbol draw.
  41304. var rect = this._rect;
  41305. if (!rect) {
  41306. var shape = this.shape;
  41307. var points = shape.points;
  41308. var size = shape.size;
  41309. var w = size[0];
  41310. var h = size[1];
  41311. var minX = Infinity;
  41312. var minY = Infinity;
  41313. var maxX = -Infinity;
  41314. var maxY = -Infinity;
  41315. for (var i = 0; i < points.length;) {
  41316. var x = points[i++];
  41317. var y = points[i++];
  41318. minX = Math.min(x, minX);
  41319. maxX = Math.max(x, maxX);
  41320. minY = Math.min(y, minY);
  41321. maxY = Math.max(y, maxY);
  41322. }
  41323. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  41324. }
  41325. return rect;
  41326. };
  41327. return LargeSymbolPath;
  41328. }(Path);
  41329. var LargeSymbolDraw =
  41330. /** @class */
  41331. function () {
  41332. function LargeSymbolDraw() {
  41333. this.group = new Group();
  41334. }
  41335. /**
  41336. * Update symbols draw by new data
  41337. */
  41338. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  41339. this._clear();
  41340. var symbolEl = this._create();
  41341. symbolEl.setShape({
  41342. points: data.getLayout('points')
  41343. });
  41344. this._setCommon(symbolEl, data, opt);
  41345. };
  41346. LargeSymbolDraw.prototype.updateLayout = function (data) {
  41347. var points = data.getLayout('points');
  41348. this.group.eachChild(function (child) {
  41349. if (child.startIndex != null) {
  41350. var len = (child.endIndex - child.startIndex) * 2;
  41351. var byteOffset = child.startIndex * 4 * 2;
  41352. points = new Float32Array(points.buffer, byteOffset, len);
  41353. }
  41354. child.setShape('points', points); // Reset draw cursor.
  41355. child.reset();
  41356. });
  41357. };
  41358. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  41359. this._clear();
  41360. };
  41361. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  41362. var lastAdded = this._newAdded[0];
  41363. var points = data.getLayout('points');
  41364. var oldPoints = lastAdded && lastAdded.shape.points; // Merging the exists. Each element has 1e4 points.
  41365. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  41366. if (oldPoints && oldPoints.length < 2e4) {
  41367. var oldLen = oldPoints.length;
  41368. var newPoints = new Float32Array(oldLen + points.length); // Concat two array
  41369. newPoints.set(oldPoints);
  41370. newPoints.set(points, oldLen); // Update endIndex
  41371. lastAdded.endIndex = taskParams.end;
  41372. lastAdded.setShape({
  41373. points: newPoints
  41374. });
  41375. } else {
  41376. // Clear
  41377. this._newAdded = [];
  41378. var symbolEl = this._create();
  41379. symbolEl.startIndex = taskParams.start;
  41380. symbolEl.endIndex = taskParams.end;
  41381. symbolEl.incremental = true;
  41382. symbolEl.setShape({
  41383. points: points
  41384. });
  41385. this._setCommon(symbolEl, data, opt);
  41386. }
  41387. };
  41388. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  41389. this._newAdded[0] && cb(this._newAdded[0]);
  41390. };
  41391. LargeSymbolDraw.prototype._create = function () {
  41392. var symbolEl = new LargeSymbolPath({
  41393. cursor: 'default'
  41394. });
  41395. symbolEl.ignoreCoarsePointer = true;
  41396. this.group.add(symbolEl);
  41397. this._newAdded.push(symbolEl);
  41398. return symbolEl;
  41399. };
  41400. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  41401. var hostModel = data.hostModel;
  41402. opt = opt || {};
  41403. var size = data.getVisual('symbolSize');
  41404. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  41405. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  41406. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  41407. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  41408. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  41409. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  41410. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  41411. var globalStyle = data.getVisual('style');
  41412. var visualColor = globalStyle && globalStyle.fill;
  41413. if (visualColor) {
  41414. symbolEl.setColor(visualColor);
  41415. }
  41416. var ecData = getECData(symbolEl); // Enable tooltip
  41417. // PENDING May have performance issue when path is extremely large
  41418. ecData.seriesIndex = hostModel.seriesIndex;
  41419. symbolEl.on('mousemove', function (e) {
  41420. ecData.dataIndex = null;
  41421. var dataIndex = symbolEl.hoverDataIdx;
  41422. if (dataIndex >= 0) {
  41423. // Provide dataIndex for tooltip
  41424. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  41425. }
  41426. });
  41427. };
  41428. LargeSymbolDraw.prototype.remove = function () {
  41429. this._clear();
  41430. };
  41431. LargeSymbolDraw.prototype._clear = function () {
  41432. this._newAdded = [];
  41433. this.group.removeAll();
  41434. };
  41435. return LargeSymbolDraw;
  41436. }();
  41437. var ScatterView =
  41438. /** @class */
  41439. function (_super) {
  41440. __extends(ScatterView, _super);
  41441. function ScatterView() {
  41442. var _this = _super !== null && _super.apply(this, arguments) || this;
  41443. _this.type = ScatterView.type;
  41444. return _this;
  41445. }
  41446. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  41447. var data = seriesModel.getData();
  41448. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41449. symbolDraw.updateData(data, {
  41450. // TODO
  41451. // If this parameter should be a shape or a bounding volume
  41452. // shape will be more general.
  41453. // But bounding volume like bounding rect will be much faster in the contain calculation
  41454. clipShape: this._getClipShape(seriesModel)
  41455. });
  41456. this._finished = true;
  41457. };
  41458. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  41459. var data = seriesModel.getData();
  41460. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41461. symbolDraw.incrementalPrepareUpdate(data);
  41462. this._finished = false;
  41463. };
  41464. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  41465. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  41466. clipShape: this._getClipShape(seriesModel)
  41467. });
  41468. this._finished = taskParams.end === seriesModel.getData().count();
  41469. };
  41470. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  41471. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  41472. // PENDING
  41473. this.group.dirty();
  41474. if (!this._finished || data.count() > 1e4) {
  41475. return {
  41476. update: true
  41477. };
  41478. } else {
  41479. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  41480. if (res.progress) {
  41481. res.progress({
  41482. start: 0,
  41483. end: data.count(),
  41484. count: data.count()
  41485. }, data);
  41486. }
  41487. this._symbolDraw.updateLayout(data);
  41488. }
  41489. };
  41490. ScatterView.prototype.eachRendered = function (cb) {
  41491. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  41492. };
  41493. ScatterView.prototype._getClipShape = function (seriesModel) {
  41494. var coordSys = seriesModel.coordinateSystem;
  41495. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  41496. return seriesModel.get('clip', true) ? clipArea : null;
  41497. };
  41498. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  41499. var symbolDraw = this._symbolDraw;
  41500. var pipelineContext = seriesModel.pipelineContext;
  41501. var isLargeDraw = pipelineContext.large;
  41502. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  41503. symbolDraw && symbolDraw.remove();
  41504. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  41505. this._isLargeDraw = isLargeDraw;
  41506. this.group.removeAll();
  41507. }
  41508. this.group.add(symbolDraw.group);
  41509. return symbolDraw;
  41510. };
  41511. ScatterView.prototype.remove = function (ecModel, api) {
  41512. this._symbolDraw && this._symbolDraw.remove(true);
  41513. this._symbolDraw = null;
  41514. };
  41515. ScatterView.prototype.dispose = function () {};
  41516. ScatterView.type = 'scatter';
  41517. return ScatterView;
  41518. }(ChartView);
  41519. var GridModel =
  41520. /** @class */
  41521. function (_super) {
  41522. __extends(GridModel, _super);
  41523. function GridModel() {
  41524. return _super !== null && _super.apply(this, arguments) || this;
  41525. }
  41526. GridModel.type = 'grid';
  41527. GridModel.dependencies = ['xAxis', 'yAxis'];
  41528. GridModel.layoutMode = 'box';
  41529. GridModel.defaultOption = {
  41530. show: false,
  41531. // zlevel: 0,
  41532. z: 0,
  41533. left: '10%',
  41534. top: 60,
  41535. right: '10%',
  41536. bottom: 70,
  41537. // If grid size contain label
  41538. containLabel: false,
  41539. // width: {totalWidth} - left - right,
  41540. // height: {totalHeight} - top - bottom,
  41541. backgroundColor: 'rgba(0,0,0,0)',
  41542. borderWidth: 1,
  41543. borderColor: '#ccc'
  41544. };
  41545. return GridModel;
  41546. }(ComponentModel);
  41547. var CartesianAxisModel =
  41548. /** @class */
  41549. function (_super) {
  41550. __extends(CartesianAxisModel, _super);
  41551. function CartesianAxisModel() {
  41552. return _super !== null && _super.apply(this, arguments) || this;
  41553. }
  41554. CartesianAxisModel.prototype.getCoordSysModel = function () {
  41555. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  41556. };
  41557. CartesianAxisModel.type = 'cartesian2dAxis';
  41558. return CartesianAxisModel;
  41559. }(ComponentModel);
  41560. mixin(CartesianAxisModel, AxisModelCommonMixin);
  41561. var defaultOption = {
  41562. show: true,
  41563. // zlevel: 0,
  41564. z: 0,
  41565. // Inverse the axis.
  41566. inverse: false,
  41567. // Axis name displayed.
  41568. name: '',
  41569. // 'start' | 'middle' | 'end'
  41570. nameLocation: 'end',
  41571. // By degree. By default auto rotate by nameLocation.
  41572. nameRotate: null,
  41573. nameTruncate: {
  41574. maxWidth: null,
  41575. ellipsis: '...',
  41576. placeholder: '.'
  41577. },
  41578. // Use global text style by default.
  41579. nameTextStyle: {},
  41580. // The gap between axisName and axisLine.
  41581. nameGap: 15,
  41582. // Default `false` to support tooltip.
  41583. silent: false,
  41584. // Default `false` to avoid legacy user event listener fail.
  41585. triggerEvent: false,
  41586. tooltip: {
  41587. show: false
  41588. },
  41589. axisPointer: {},
  41590. axisLine: {
  41591. show: true,
  41592. onZero: true,
  41593. onZeroAxisIndex: null,
  41594. lineStyle: {
  41595. color: '#6E7079',
  41596. width: 1,
  41597. type: 'solid'
  41598. },
  41599. // The arrow at both ends the the axis.
  41600. symbol: ['none', 'none'],
  41601. symbolSize: [10, 15]
  41602. },
  41603. axisTick: {
  41604. show: true,
  41605. // Whether axisTick is inside the grid or outside the grid.
  41606. inside: false,
  41607. // The length of axisTick.
  41608. length: 5,
  41609. lineStyle: {
  41610. width: 1
  41611. }
  41612. },
  41613. axisLabel: {
  41614. show: true,
  41615. // Whether axisLabel is inside the grid or outside the grid.
  41616. inside: false,
  41617. rotate: 0,
  41618. // true | false | null/undefined (auto)
  41619. showMinLabel: null,
  41620. // true | false | null/undefined (auto)
  41621. showMaxLabel: null,
  41622. margin: 8,
  41623. // formatter: null,
  41624. fontSize: 12
  41625. },
  41626. splitLine: {
  41627. show: true,
  41628. lineStyle: {
  41629. color: ['#E0E6F1'],
  41630. width: 1,
  41631. type: 'solid'
  41632. }
  41633. },
  41634. splitArea: {
  41635. show: false,
  41636. areaStyle: {
  41637. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  41638. }
  41639. }
  41640. };
  41641. var categoryAxis = merge({
  41642. // The gap at both ends of the axis. For categoryAxis, boolean.
  41643. boundaryGap: true,
  41644. // Set false to faster category collection.
  41645. deduplication: null,
  41646. // splitArea: {
  41647. // show: false
  41648. // },
  41649. splitLine: {
  41650. show: false
  41651. },
  41652. axisTick: {
  41653. // If tick is align with label when boundaryGap is true
  41654. alignWithLabel: false,
  41655. interval: 'auto'
  41656. },
  41657. axisLabel: {
  41658. interval: 'auto'
  41659. }
  41660. }, defaultOption);
  41661. var valueAxis = merge({
  41662. boundaryGap: [0, 0],
  41663. axisLine: {
  41664. // Not shown when other axis is categoryAxis in cartesian
  41665. show: 'auto'
  41666. },
  41667. axisTick: {
  41668. // Not shown when other axis is categoryAxis in cartesian
  41669. show: 'auto'
  41670. },
  41671. // TODO
  41672. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  41673. splitNumber: 5,
  41674. minorTick: {
  41675. // Minor tick, not available for cateogry axis.
  41676. show: false,
  41677. // Split number of minor ticks. The value should be in range of (0, 100)
  41678. splitNumber: 5,
  41679. // Length of minor tick
  41680. length: 3,
  41681. // Line style
  41682. lineStyle: {// Default to be same with axisTick
  41683. }
  41684. },
  41685. minorSplitLine: {
  41686. show: false,
  41687. lineStyle: {
  41688. color: '#F4F7FD',
  41689. width: 1
  41690. }
  41691. }
  41692. }, defaultOption);
  41693. var timeAxis = merge({
  41694. splitNumber: 6,
  41695. axisLabel: {
  41696. // To eliminate labels that are not nice
  41697. showMinLabel: false,
  41698. showMaxLabel: false,
  41699. rich: {
  41700. primary: {
  41701. fontWeight: 'bold'
  41702. }
  41703. }
  41704. },
  41705. splitLine: {
  41706. show: false
  41707. }
  41708. }, valueAxis);
  41709. var logAxis = defaults({
  41710. logBase: 10
  41711. }, valueAxis);
  41712. var axisDefault = {
  41713. category: categoryAxis,
  41714. value: valueAxis,
  41715. time: timeAxis,
  41716. log: logAxis
  41717. };
  41718. /*
  41719. * Licensed to the Apache Software Foundation (ASF) under one
  41720. * or more contributor license agreements. See the NOTICE file
  41721. * distributed with this work for additional information
  41722. * regarding copyright ownership. The ASF licenses this file
  41723. * to you under the Apache License, Version 2.0 (the
  41724. * "License"); you may not use this file except in compliance
  41725. * with the License. You may obtain a copy of the License at
  41726. *
  41727. * http://www.apache.org/licenses/LICENSE-2.0
  41728. *
  41729. * Unless required by applicable law or agreed to in writing,
  41730. * software distributed under the License is distributed on an
  41731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41732. * KIND, either express or implied. See the License for the
  41733. * specific language governing permissions and limitations
  41734. * under the License.
  41735. */
  41736. /**
  41737. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41738. */
  41739. /*
  41740. * Licensed to the Apache Software Foundation (ASF) under one
  41741. * or more contributor license agreements. See the NOTICE file
  41742. * distributed with this work for additional information
  41743. * regarding copyright ownership. The ASF licenses this file
  41744. * to you under the Apache License, Version 2.0 (the
  41745. * "License"); you may not use this file except in compliance
  41746. * with the License. You may obtain a copy of the License at
  41747. *
  41748. * http://www.apache.org/licenses/LICENSE-2.0
  41749. *
  41750. * Unless required by applicable law or agreed to in writing,
  41751. * software distributed under the License is distributed on an
  41752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41753. * KIND, either express or implied. See the License for the
  41754. * specific language governing permissions and limitations
  41755. * under the License.
  41756. */
  41757. var AXIS_TYPES = {
  41758. value: 1,
  41759. category: 1,
  41760. time: 1,
  41761. log: 1
  41762. };
  41763. /**
  41764. * Generate sub axis model class
  41765. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  41766. */
  41767. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  41768. each(AXIS_TYPES, function (v, axisType) {
  41769. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  41770. var AxisModel =
  41771. /** @class */
  41772. function (_super) {
  41773. __extends(AxisModel, _super);
  41774. function AxisModel() {
  41775. var _this = _super !== null && _super.apply(this, arguments) || this;
  41776. _this.type = axisName + 'Axis.' + axisType;
  41777. return _this;
  41778. }
  41779. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  41780. var layoutMode = fetchLayoutMode(this);
  41781. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  41782. var themeModel = ecModel.getTheme();
  41783. merge(option, themeModel.get(axisType + 'Axis'));
  41784. merge(option, this.getDefaultOption());
  41785. option.type = getAxisType(option);
  41786. if (layoutMode) {
  41787. mergeLayoutParam(option, inputPositionParams, layoutMode);
  41788. }
  41789. };
  41790. AxisModel.prototype.optionUpdated = function () {
  41791. var thisOption = this.option;
  41792. if (thisOption.type === 'category') {
  41793. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  41794. }
  41795. };
  41796. /**
  41797. * Should not be called before all of 'getInitailData' finished.
  41798. * Because categories are collected during initializing data.
  41799. */
  41800. AxisModel.prototype.getCategories = function (rawData) {
  41801. var option = this.option; // FIXME
  41802. // warning if called before all of 'getInitailData' finished.
  41803. if (option.type === 'category') {
  41804. if (rawData) {
  41805. return option.data;
  41806. }
  41807. return this.__ordinalMeta.categories;
  41808. }
  41809. };
  41810. AxisModel.prototype.getOrdinalMeta = function () {
  41811. return this.__ordinalMeta;
  41812. };
  41813. AxisModel.type = axisName + 'Axis.' + axisType;
  41814. AxisModel.defaultOption = defaultOption;
  41815. return AxisModel;
  41816. }(BaseAxisModelClass);
  41817. registers.registerComponentModel(AxisModel);
  41818. });
  41819. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  41820. }
  41821. function getAxisType(option) {
  41822. // Default axis with data is category axis
  41823. return option.type || (option.data ? 'category' : 'value');
  41824. }
  41825. var Cartesian =
  41826. /** @class */
  41827. function () {
  41828. function Cartesian(name) {
  41829. this.type = 'cartesian';
  41830. this._dimList = [];
  41831. this._axes = {};
  41832. this.name = name || '';
  41833. }
  41834. Cartesian.prototype.getAxis = function (dim) {
  41835. return this._axes[dim];
  41836. };
  41837. Cartesian.prototype.getAxes = function () {
  41838. return map(this._dimList, function (dim) {
  41839. return this._axes[dim];
  41840. }, this);
  41841. };
  41842. Cartesian.prototype.getAxesByScale = function (scaleType) {
  41843. scaleType = scaleType.toLowerCase();
  41844. return filter(this.getAxes(), function (axis) {
  41845. return axis.scale.type === scaleType;
  41846. });
  41847. };
  41848. Cartesian.prototype.addAxis = function (axis) {
  41849. var dim = axis.dim;
  41850. this._axes[dim] = axis;
  41851. this._dimList.push(dim);
  41852. };
  41853. return Cartesian;
  41854. }();
  41855. var cartesian2DDimensions = ['x', 'y'];
  41856. function canCalculateAffineTransform(scale) {
  41857. return scale.type === 'interval' || scale.type === 'time';
  41858. }
  41859. var Cartesian2D =
  41860. /** @class */
  41861. function (_super) {
  41862. __extends(Cartesian2D, _super);
  41863. function Cartesian2D() {
  41864. var _this = _super !== null && _super.apply(this, arguments) || this;
  41865. _this.type = 'cartesian2d';
  41866. _this.dimensions = cartesian2DDimensions;
  41867. return _this;
  41868. }
  41869. /**
  41870. * Calculate an affine transform matrix if two axes are time or value.
  41871. * It's mainly for accelartion on the large time series data.
  41872. */
  41873. Cartesian2D.prototype.calcAffineTransform = function () {
  41874. this._transform = this._invTransform = null;
  41875. var xAxisScale = this.getAxis('x').scale;
  41876. var yAxisScale = this.getAxis('y').scale;
  41877. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  41878. return;
  41879. }
  41880. var xScaleExtent = xAxisScale.getExtent();
  41881. var yScaleExtent = yAxisScale.getExtent();
  41882. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  41883. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  41884. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  41885. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  41886. if (!xScaleSpan || !yScaleSpan) {
  41887. return;
  41888. } // Accelerate data to point calculation on the special large time series data.
  41889. var scaleX = (end[0] - start[0]) / xScaleSpan;
  41890. var scaleY = (end[1] - start[1]) / yScaleSpan;
  41891. var translateX = start[0] - xScaleExtent[0] * scaleX;
  41892. var translateY = start[1] - yScaleExtent[0] * scaleY;
  41893. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  41894. this._invTransform = invert([], m);
  41895. };
  41896. /**
  41897. * Base axis will be used on stacking.
  41898. */
  41899. Cartesian2D.prototype.getBaseAxis = function () {
  41900. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  41901. };
  41902. Cartesian2D.prototype.containPoint = function (point) {
  41903. var axisX = this.getAxis('x');
  41904. var axisY = this.getAxis('y');
  41905. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  41906. };
  41907. Cartesian2D.prototype.containData = function (data) {
  41908. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  41909. };
  41910. Cartesian2D.prototype.containZone = function (data1, data2) {
  41911. var zoneDiag1 = this.dataToPoint(data1);
  41912. var zoneDiag2 = this.dataToPoint(data2);
  41913. var area = this.getArea();
  41914. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  41915. return area.intersect(zone);
  41916. };
  41917. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  41918. out = out || [];
  41919. var xVal = data[0];
  41920. var yVal = data[1]; // Fast path
  41921. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  41922. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  41923. return applyTransform(out, data, this._transform);
  41924. }
  41925. var xAxis = this.getAxis('x');
  41926. var yAxis = this.getAxis('y');
  41927. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  41928. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  41929. return out;
  41930. };
  41931. Cartesian2D.prototype.clampData = function (data, out) {
  41932. var xScale = this.getAxis('x').scale;
  41933. var yScale = this.getAxis('y').scale;
  41934. var xAxisExtent = xScale.getExtent();
  41935. var yAxisExtent = yScale.getExtent();
  41936. var x = xScale.parse(data[0]);
  41937. var y = yScale.parse(data[1]);
  41938. out = out || [];
  41939. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  41940. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  41941. return out;
  41942. };
  41943. Cartesian2D.prototype.pointToData = function (point, clamp) {
  41944. var out = [];
  41945. if (this._invTransform) {
  41946. return applyTransform(out, point, this._invTransform);
  41947. }
  41948. var xAxis = this.getAxis('x');
  41949. var yAxis = this.getAxis('y');
  41950. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  41951. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  41952. return out;
  41953. };
  41954. Cartesian2D.prototype.getOtherAxis = function (axis) {
  41955. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  41956. };
  41957. /**
  41958. * Get rect area of cartesian.
  41959. * Area will have a contain function to determine if a point is in the coordinate system.
  41960. */
  41961. Cartesian2D.prototype.getArea = function () {
  41962. var xExtent = this.getAxis('x').getGlobalExtent();
  41963. var yExtent = this.getAxis('y').getGlobalExtent();
  41964. var x = Math.min(xExtent[0], xExtent[1]);
  41965. var y = Math.min(yExtent[0], yExtent[1]);
  41966. var width = Math.max(xExtent[0], xExtent[1]) - x;
  41967. var height = Math.max(yExtent[0], yExtent[1]) - y;
  41968. return new BoundingRect(x, y, width, height);
  41969. };
  41970. return Cartesian2D;
  41971. }(Cartesian);
  41972. var Axis2D =
  41973. /** @class */
  41974. function (_super) {
  41975. __extends(Axis2D, _super);
  41976. function Axis2D(dim, scale, coordExtent, axisType, position) {
  41977. var _this = _super.call(this, dim, scale, coordExtent) || this;
  41978. /**
  41979. * Index of axis, can be used as key
  41980. * Injected outside.
  41981. */
  41982. _this.index = 0;
  41983. _this.type = axisType || 'value';
  41984. _this.position = position || 'bottom';
  41985. return _this;
  41986. }
  41987. Axis2D.prototype.isHorizontal = function () {
  41988. var position = this.position;
  41989. return position === 'top' || position === 'bottom';
  41990. };
  41991. /**
  41992. * Each item cooresponds to this.getExtent(), which
  41993. * means globalExtent[0] may greater than globalExtent[1],
  41994. * unless `asc` is input.
  41995. *
  41996. * @param {boolean} [asc]
  41997. * @return {Array.<number>}
  41998. */
  41999. Axis2D.prototype.getGlobalExtent = function (asc) {
  42000. var ret = this.getExtent();
  42001. ret[0] = this.toGlobalCoord(ret[0]);
  42002. ret[1] = this.toGlobalCoord(ret[1]);
  42003. asc && ret[0] > ret[1] && ret.reverse();
  42004. return ret;
  42005. };
  42006. Axis2D.prototype.pointToData = function (point, clamp) {
  42007. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  42008. };
  42009. /**
  42010. * Set ordinalSortInfo
  42011. * @param info new OrdinalSortInfo
  42012. */
  42013. Axis2D.prototype.setCategorySortInfo = function (info) {
  42014. if (this.type !== 'category') {
  42015. return false;
  42016. }
  42017. this.model.option.categorySortInfo = info;
  42018. this.scale.setSortInfo(info);
  42019. };
  42020. return Axis2D;
  42021. }(Axis);
  42022. /**
  42023. * Can only be called after coordinate system creation stage.
  42024. * (Can be called before coordinate system update stage).
  42025. */
  42026. function layout$1(gridModel, axisModel, opt) {
  42027. opt = opt || {};
  42028. var grid = gridModel.coordinateSystem;
  42029. var axis = axisModel.axis;
  42030. var layout = {};
  42031. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  42032. var rawAxisPosition = axis.position;
  42033. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  42034. var axisDim = axis.dim;
  42035. var rect = grid.getRect();
  42036. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  42037. var idx = {
  42038. left: 0,
  42039. right: 1,
  42040. top: 0,
  42041. bottom: 1,
  42042. onZero: 2
  42043. };
  42044. var axisOffset = axisModel.get('offset') || 0;
  42045. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  42046. if (otherAxisOnZeroOf) {
  42047. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  42048. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  42049. } // Axis position
  42050. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  42051. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  42052. var dirMap = {
  42053. top: -1,
  42054. bottom: 1,
  42055. left: -1,
  42056. right: 1
  42057. };
  42058. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  42059. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  42060. if (axisModel.get(['axisTick', 'inside'])) {
  42061. layout.tickDirection = -layout.tickDirection;
  42062. }
  42063. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  42064. layout.labelDirection = -layout.labelDirection;
  42065. } // Special label rotation
  42066. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  42067. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  42068. layout.z2 = 1;
  42069. return layout;
  42070. }
  42071. function isCartesian2DSeries(seriesModel) {
  42072. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  42073. }
  42074. function findAxisModels(seriesModel) {
  42075. var axisModelMap = {
  42076. xAxisModel: null,
  42077. yAxisModel: null
  42078. };
  42079. each(axisModelMap, function (v, key) {
  42080. var axisType = key.replace(/Model$/, '');
  42081. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  42082. if ("development" !== 'production') {
  42083. if (!axisModel) {
  42084. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  42085. }
  42086. }
  42087. axisModelMap[key] = axisModel;
  42088. });
  42089. return axisModelMap;
  42090. }
  42091. var mathLog$1 = Math.log;
  42092. function alignScaleTicks(scale, axisModel, alignToScale) {
  42093. var intervalScaleProto = IntervalScale.prototype; // NOTE: There is a precondition for log scale here:
  42094. // In log scale we store _interval and _extent of exponent value.
  42095. // So if we use the method of InternalScale to set/get these data.
  42096. // It process the exponent value, which is linear and what we want here.
  42097. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  42098. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  42099. var alignToSplitNumber = alignToTicks.length - 1;
  42100. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  42101. var scaleExtent = getScaleExtent(scale, axisModel);
  42102. var rawExtent = scaleExtent.extent;
  42103. var isMinFixed = scaleExtent.fixMin;
  42104. var isMaxFixed = scaleExtent.fixMax;
  42105. if (scale.type === 'log') {
  42106. var logBase = mathLog$1(scale.base);
  42107. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  42108. }
  42109. scale.setExtent(rawExtent[0], rawExtent[1]);
  42110. scale.calcNiceExtent({
  42111. splitNumber: alignToSplitNumber,
  42112. fixMin: isMinFixed,
  42113. fixMax: isMaxFixed
  42114. });
  42115. var extent = intervalScaleProto.getExtent.call(scale); // Need to update the rawExtent.
  42116. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  42117. if (isMinFixed) {
  42118. rawExtent[0] = extent[0];
  42119. }
  42120. if (isMaxFixed) {
  42121. rawExtent[1] = extent[1];
  42122. }
  42123. var interval = intervalScaleProto.getInterval.call(scale);
  42124. var min = rawExtent[0];
  42125. var max = rawExtent[1];
  42126. if (isMinFixed && isMaxFixed) {
  42127. // User set min, max, divide to get new interval
  42128. interval = (max - min) / alignToSplitNumber;
  42129. } else if (isMinFixed) {
  42130. max = rawExtent[0] + interval * alignToSplitNumber; // User set min, expand extent on the other side
  42131. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  42132. interval = increaseInterval(interval);
  42133. max = rawExtent[0] + interval * alignToSplitNumber;
  42134. }
  42135. } else if (isMaxFixed) {
  42136. // User set max, expand extent on the other side
  42137. min = rawExtent[1] - interval * alignToSplitNumber;
  42138. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  42139. interval = increaseInterval(interval);
  42140. min = rawExtent[1] - interval * alignToSplitNumber;
  42141. }
  42142. } else {
  42143. var nicedSplitNumber = scale.getTicks().length - 1;
  42144. if (nicedSplitNumber > alignToSplitNumber) {
  42145. interval = increaseInterval(interval);
  42146. }
  42147. var range = interval * alignToSplitNumber;
  42148. max = Math.ceil(rawExtent[1] / interval) * interval;
  42149. min = round(max - range); // Not change the result that crossing zero.
  42150. if (min < 0 && rawExtent[0] >= 0) {
  42151. min = 0;
  42152. max = round(range);
  42153. } else if (max > 0 && rawExtent[1] <= 0) {
  42154. max = 0;
  42155. min = -round(range);
  42156. }
  42157. } // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  42158. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  42159. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval; // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  42160. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  42161. intervalScaleProto.setInterval.call(scale, interval);
  42162. if (t0 || t1) {
  42163. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  42164. }
  42165. if ("development" !== 'production') {
  42166. var ticks = intervalScaleProto.getTicks.call(scale);
  42167. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  42168. warn( // eslint-disable-next-line
  42169. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  42170. }
  42171. }
  42172. }
  42173. var Grid =
  42174. /** @class */
  42175. function () {
  42176. function Grid(gridModel, ecModel, api) {
  42177. // FIXME:TS where used (different from registered type 'cartesian2d')?
  42178. this.type = 'grid';
  42179. this._coordsMap = {};
  42180. this._coordsList = [];
  42181. this._axesMap = {};
  42182. this._axesList = [];
  42183. this.axisPointerEnabled = true;
  42184. this.dimensions = cartesian2DDimensions;
  42185. this._initCartesian(gridModel, ecModel, api);
  42186. this.model = gridModel;
  42187. }
  42188. Grid.prototype.getRect = function () {
  42189. return this._rect;
  42190. };
  42191. Grid.prototype.update = function (ecModel, api) {
  42192. var axesMap = this._axesMap;
  42193. this._updateScale(ecModel, this.model);
  42194. function updateAxisTicks(axes) {
  42195. var alignTo; // Axis is added in order of axisIndex.
  42196. var axesIndices = keys(axes);
  42197. var len = axesIndices.length;
  42198. if (!len) {
  42199. return;
  42200. }
  42201. var axisNeedsAlign = []; // Process once and calculate the ticks for those don't use alignTicks.
  42202. for (var i = len - 1; i >= 0; i--) {
  42203. var idx = +axesIndices[i]; // Convert to number.
  42204. var axis = axes[idx];
  42205. var model = axis.model;
  42206. var scale = axis.scale;
  42207. if ( // Only value and log axis without interval support alignTicks.
  42208. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  42209. axisNeedsAlign.push(axis);
  42210. } else {
  42211. niceScaleExtent(scale, model);
  42212. if (isIntervalOrLogScale(scale)) {
  42213. // Can only align to interval or log axis.
  42214. alignTo = axis;
  42215. }
  42216. }
  42217. }
  42218. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  42219. if (axisNeedsAlign.length) {
  42220. if (!alignTo) {
  42221. alignTo = axisNeedsAlign.pop();
  42222. niceScaleExtent(alignTo.scale, alignTo.model);
  42223. }
  42224. each(axisNeedsAlign, function (axis) {
  42225. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  42226. });
  42227. }
  42228. }
  42229. updateAxisTicks(axesMap.x);
  42230. updateAxisTicks(axesMap.y); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  42231. var onZeroRecords = {};
  42232. each(axesMap.x, function (xAxis) {
  42233. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  42234. });
  42235. each(axesMap.y, function (yAxis) {
  42236. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  42237. }); // Resize again if containLabel is enabled
  42238. // FIXME It may cause getting wrong grid size in data processing stage
  42239. this.resize(this.model, api);
  42240. };
  42241. /**
  42242. * Resize the grid
  42243. */
  42244. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  42245. var boxLayoutParams = gridModel.getBoxLayoutParams();
  42246. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  42247. var gridRect = getLayoutRect(boxLayoutParams, {
  42248. width: api.getWidth(),
  42249. height: api.getHeight()
  42250. });
  42251. this._rect = gridRect;
  42252. var axesList = this._axesList;
  42253. adjustAxes(); // Minus label size
  42254. if (isContainLabel) {
  42255. each(axesList, function (axis) {
  42256. if (!axis.model.get(['axisLabel', 'inside'])) {
  42257. var labelUnionRect = estimateLabelUnionRect(axis);
  42258. if (labelUnionRect) {
  42259. var dim = axis.isHorizontal() ? 'height' : 'width';
  42260. var margin = axis.model.get(['axisLabel', 'margin']);
  42261. gridRect[dim] -= labelUnionRect[dim] + margin;
  42262. if (axis.position === 'top') {
  42263. gridRect.y += labelUnionRect.height + margin;
  42264. } else if (axis.position === 'left') {
  42265. gridRect.x += labelUnionRect.width + margin;
  42266. }
  42267. }
  42268. }
  42269. });
  42270. adjustAxes();
  42271. }
  42272. each(this._coordsList, function (coord) {
  42273. // Calculate affine matrix to accelerate the data to point transform.
  42274. // If all the axes scales are time or value.
  42275. coord.calcAffineTransform();
  42276. });
  42277. function adjustAxes() {
  42278. each(axesList, function (axis) {
  42279. var isHorizontal = axis.isHorizontal();
  42280. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  42281. var idx = axis.inverse ? 1 : 0;
  42282. axis.setExtent(extent[idx], extent[1 - idx]);
  42283. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  42284. });
  42285. }
  42286. };
  42287. Grid.prototype.getAxis = function (dim, axisIndex) {
  42288. var axesMapOnDim = this._axesMap[dim];
  42289. if (axesMapOnDim != null) {
  42290. return axesMapOnDim[axisIndex || 0];
  42291. }
  42292. };
  42293. Grid.prototype.getAxes = function () {
  42294. return this._axesList.slice();
  42295. };
  42296. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  42297. if (xAxisIndex != null && yAxisIndex != null) {
  42298. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42299. return this._coordsMap[key];
  42300. }
  42301. if (isObject(xAxisIndex)) {
  42302. yAxisIndex = xAxisIndex.yAxisIndex;
  42303. xAxisIndex = xAxisIndex.xAxisIndex;
  42304. }
  42305. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  42306. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  42307. return coordList[i];
  42308. }
  42309. }
  42310. };
  42311. Grid.prototype.getCartesians = function () {
  42312. return this._coordsList.slice();
  42313. };
  42314. /**
  42315. * @implements
  42316. */
  42317. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  42318. var target = this._findConvertTarget(finder);
  42319. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  42320. };
  42321. /**
  42322. * @implements
  42323. */
  42324. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  42325. var target = this._findConvertTarget(finder);
  42326. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  42327. };
  42328. Grid.prototype._findConvertTarget = function (finder) {
  42329. var seriesModel = finder.seriesModel;
  42330. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  42331. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  42332. var gridModel = finder.gridModel;
  42333. var coordsList = this._coordsList;
  42334. var cartesian;
  42335. var axis;
  42336. if (seriesModel) {
  42337. cartesian = seriesModel.coordinateSystem;
  42338. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  42339. } else if (xAxisModel && yAxisModel) {
  42340. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42341. } else if (xAxisModel) {
  42342. axis = this.getAxis('x', xAxisModel.componentIndex);
  42343. } else if (yAxisModel) {
  42344. axis = this.getAxis('y', yAxisModel.componentIndex);
  42345. } // Lowest priority.
  42346. else if (gridModel) {
  42347. var grid = gridModel.coordinateSystem;
  42348. if (grid === this) {
  42349. cartesian = this._coordsList[0];
  42350. }
  42351. }
  42352. return {
  42353. cartesian: cartesian,
  42354. axis: axis
  42355. };
  42356. };
  42357. /**
  42358. * @implements
  42359. */
  42360. Grid.prototype.containPoint = function (point) {
  42361. var coord = this._coordsList[0];
  42362. if (coord) {
  42363. return coord.containPoint(point);
  42364. }
  42365. };
  42366. /**
  42367. * Initialize cartesian coordinate systems
  42368. */
  42369. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  42370. var _this = this;
  42371. var grid = this;
  42372. var axisPositionUsed = {
  42373. left: false,
  42374. right: false,
  42375. top: false,
  42376. bottom: false
  42377. };
  42378. var axesMap = {
  42379. x: {},
  42380. y: {}
  42381. };
  42382. var axesCount = {
  42383. x: 0,
  42384. y: 0
  42385. }; // Create axis
  42386. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  42387. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  42388. if (!axesCount.x || !axesCount.y) {
  42389. // Roll back when there no either x or y axis
  42390. this._axesMap = {};
  42391. this._axesList = [];
  42392. return;
  42393. }
  42394. this._axesMap = axesMap; // Create cartesian2d
  42395. each(axesMap.x, function (xAxis, xAxisIndex) {
  42396. each(axesMap.y, function (yAxis, yAxisIndex) {
  42397. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42398. var cartesian = new Cartesian2D(key);
  42399. cartesian.master = _this;
  42400. cartesian.model = gridModel;
  42401. _this._coordsMap[key] = cartesian;
  42402. _this._coordsList.push(cartesian);
  42403. cartesian.addAxis(xAxis);
  42404. cartesian.addAxis(yAxis);
  42405. });
  42406. });
  42407. function createAxisCreator(dimName) {
  42408. return function (axisModel, idx) {
  42409. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  42410. return;
  42411. }
  42412. var axisPosition = axisModel.get('position');
  42413. if (dimName === 'x') {
  42414. // Fix position
  42415. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  42416. // Default bottom of X
  42417. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  42418. }
  42419. } else {
  42420. // Fix position
  42421. if (axisPosition !== 'left' && axisPosition !== 'right') {
  42422. // Default left of Y
  42423. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  42424. }
  42425. }
  42426. axisPositionUsed[axisPosition] = true;
  42427. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  42428. var isCategory = axis.type === 'category';
  42429. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42430. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  42431. axisModel.axis = axis; // Inject axisModel into axis
  42432. axis.model = axisModel; // Inject grid info axis
  42433. axis.grid = grid; // Index of axis, can be used as key
  42434. axis.index = idx;
  42435. grid._axesList.push(axis);
  42436. axesMap[dimName][idx] = axis;
  42437. axesCount[dimName]++;
  42438. };
  42439. }
  42440. };
  42441. /**
  42442. * Update cartesian properties from series.
  42443. */
  42444. Grid.prototype._updateScale = function (ecModel, gridModel) {
  42445. // Reset scale
  42446. each(this._axesList, function (axis) {
  42447. axis.scale.setExtent(Infinity, -Infinity);
  42448. if (axis.type === 'category') {
  42449. var categorySortInfo = axis.model.get('categorySortInfo');
  42450. axis.scale.setSortInfo(categorySortInfo);
  42451. }
  42452. });
  42453. ecModel.eachSeries(function (seriesModel) {
  42454. if (isCartesian2DSeries(seriesModel)) {
  42455. var axesModelMap = findAxisModels(seriesModel);
  42456. var xAxisModel = axesModelMap.xAxisModel;
  42457. var yAxisModel = axesModelMap.yAxisModel;
  42458. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  42459. return;
  42460. }
  42461. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42462. var data = seriesModel.getData();
  42463. var xAxis = cartesian.getAxis('x');
  42464. var yAxis = cartesian.getAxis('y');
  42465. unionExtent(data, xAxis);
  42466. unionExtent(data, yAxis);
  42467. }
  42468. }, this);
  42469. function unionExtent(data, axis) {
  42470. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  42471. axis.scale.unionExtentFromData(data, dim);
  42472. });
  42473. }
  42474. };
  42475. /**
  42476. * @param dim 'x' or 'y' or 'auto' or null/undefined
  42477. */
  42478. Grid.prototype.getTooltipAxes = function (dim) {
  42479. var baseAxes = [];
  42480. var otherAxes = [];
  42481. each(this.getCartesians(), function (cartesian) {
  42482. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  42483. var otherAxis = cartesian.getOtherAxis(baseAxis);
  42484. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  42485. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  42486. });
  42487. return {
  42488. baseAxes: baseAxes,
  42489. otherAxes: otherAxes
  42490. };
  42491. };
  42492. Grid.create = function (ecModel, api) {
  42493. var grids = [];
  42494. ecModel.eachComponent('grid', function (gridModel, idx) {
  42495. var grid = new Grid(gridModel, ecModel, api);
  42496. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  42497. // should be performed in create stage.
  42498. grid.resize(gridModel, api, true);
  42499. gridModel.coordinateSystem = grid;
  42500. grids.push(grid);
  42501. }); // Inject the coordinateSystems into seriesModel
  42502. ecModel.eachSeries(function (seriesModel) {
  42503. if (!isCartesian2DSeries(seriesModel)) {
  42504. return;
  42505. }
  42506. var axesModelMap = findAxisModels(seriesModel);
  42507. var xAxisModel = axesModelMap.xAxisModel;
  42508. var yAxisModel = axesModelMap.yAxisModel;
  42509. var gridModel = xAxisModel.getCoordSysModel();
  42510. if ("development" !== 'production') {
  42511. if (!gridModel) {
  42512. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  42513. }
  42514. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  42515. throw new Error('xAxis and yAxis must use the same grid');
  42516. }
  42517. }
  42518. var grid = gridModel.coordinateSystem;
  42519. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42520. });
  42521. return grids;
  42522. }; // For deciding which dimensions to use when creating list data
  42523. Grid.dimensions = cartesian2DDimensions;
  42524. return Grid;
  42525. }();
  42526. /**
  42527. * Check if the axis is used in the specified grid.
  42528. */
  42529. function isAxisUsedInTheGrid(axisModel, gridModel) {
  42530. return axisModel.getCoordSysModel() === gridModel;
  42531. }
  42532. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  42533. onZeroRecords) {
  42534. axis.getAxesOnZeroOf = function () {
  42535. // TODO: onZero of multiple axes.
  42536. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  42537. }; // onZero can not be enabled in these two situations:
  42538. // 1. When any other axis is a category axis.
  42539. // 2. When no axis is cross 0 point.
  42540. var otherAxes = axesMap[otherAxisDim];
  42541. var otherAxisOnZeroOf;
  42542. var axisModel = axis.model;
  42543. var onZero = axisModel.get(['axisLine', 'onZero']);
  42544. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  42545. if (!onZero) {
  42546. return;
  42547. } // If target axis is specified.
  42548. if (onZeroAxisIndex != null) {
  42549. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  42550. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  42551. }
  42552. } else {
  42553. // Find the first available other axis.
  42554. for (var idx in otherAxes) {
  42555. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  42556. // if both onZero, the two Y axes overlap.
  42557. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  42558. otherAxisOnZeroOf = otherAxes[idx];
  42559. break;
  42560. }
  42561. }
  42562. }
  42563. if (otherAxisOnZeroOf) {
  42564. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  42565. }
  42566. function getOnZeroRecordKey(axis) {
  42567. return axis.dim + '_' + axis.index;
  42568. }
  42569. }
  42570. function canOnZeroToAxis(axis) {
  42571. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  42572. }
  42573. function updateAxisTransform(axis, coordBase) {
  42574. var axisExtent = axis.getExtent();
  42575. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  42576. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  42577. return coord + coordBase;
  42578. } : function (coord) {
  42579. return axisExtentSum - coord + coordBase;
  42580. };
  42581. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  42582. return coord - coordBase;
  42583. } : function (coord) {
  42584. return axisExtentSum - coord + coordBase;
  42585. };
  42586. }
  42587. var PI$5 = Math.PI;
  42588. /**
  42589. * A final axis is translated and rotated from a "standard axis".
  42590. * So opt.position and opt.rotation is required.
  42591. *
  42592. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  42593. * for example: (0, 0) ------------> (0, 50)
  42594. *
  42595. * nameDirection or tickDirection or labelDirection is 1 means tick
  42596. * or label is below the standard axis, whereas is -1 means above
  42597. * the standard axis. labelOffset means offset between label and axis,
  42598. * which is useful when 'onZero', where axisLabel is in the grid and
  42599. * label in outside grid.
  42600. *
  42601. * Tips: like always,
  42602. * positive rotation represents anticlockwise, and negative rotation
  42603. * represents clockwise.
  42604. * The direction of position coordinate is the same as the direction
  42605. * of screen coordinate.
  42606. *
  42607. * Do not need to consider axis 'inverse', which is auto processed by
  42608. * axis extent.
  42609. */
  42610. var AxisBuilder =
  42611. /** @class */
  42612. function () {
  42613. function AxisBuilder(axisModel, opt) {
  42614. this.group = new Group();
  42615. this.opt = opt;
  42616. this.axisModel = axisModel; // Default value
  42617. defaults(opt, {
  42618. labelOffset: 0,
  42619. nameDirection: 1,
  42620. tickDirection: 1,
  42621. labelDirection: 1,
  42622. silent: true,
  42623. handleAutoShown: function () {
  42624. return true;
  42625. }
  42626. }); // FIXME Not use a separate text group?
  42627. var transformGroup = new Group({
  42628. x: opt.position[0],
  42629. y: opt.position[1],
  42630. rotation: opt.rotation
  42631. }); // this.group.add(transformGroup);
  42632. // this._transformGroup = transformGroup;
  42633. transformGroup.updateTransform();
  42634. this._transformGroup = transformGroup;
  42635. }
  42636. AxisBuilder.prototype.hasBuilder = function (name) {
  42637. return !!builders[name];
  42638. };
  42639. AxisBuilder.prototype.add = function (name) {
  42640. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  42641. };
  42642. AxisBuilder.prototype.getGroup = function () {
  42643. return this.group;
  42644. };
  42645. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  42646. var rotationDiff = remRadian(textRotation - axisRotation);
  42647. var textAlign;
  42648. var textVerticalAlign;
  42649. if (isRadianAroundZero(rotationDiff)) {
  42650. // Label is parallel with axis line.
  42651. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  42652. textAlign = 'center';
  42653. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  42654. // Label is inverse parallel with axis line.
  42655. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  42656. textAlign = 'center';
  42657. } else {
  42658. textVerticalAlign = 'middle';
  42659. if (rotationDiff > 0 && rotationDiff < PI$5) {
  42660. textAlign = direction > 0 ? 'right' : 'left';
  42661. } else {
  42662. textAlign = direction > 0 ? 'left' : 'right';
  42663. }
  42664. }
  42665. return {
  42666. rotation: rotationDiff,
  42667. textAlign: textAlign,
  42668. textVerticalAlign: textVerticalAlign
  42669. };
  42670. };
  42671. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  42672. var eventData = {
  42673. componentType: axisModel.mainType,
  42674. componentIndex: axisModel.componentIndex
  42675. };
  42676. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  42677. return eventData;
  42678. };
  42679. AxisBuilder.isLabelSilent = function (axisModel) {
  42680. var tooltipOpt = axisModel.get('tooltip');
  42681. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  42682. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  42683. };
  42684. return AxisBuilder;
  42685. }();
  42686. var builders = {
  42687. axisLine: function (opt, axisModel, group, transformGroup) {
  42688. var shown = axisModel.get(['axisLine', 'show']);
  42689. if (shown === 'auto' && opt.handleAutoShown) {
  42690. shown = opt.handleAutoShown('axisLine');
  42691. }
  42692. if (!shown) {
  42693. return;
  42694. }
  42695. var extent = axisModel.axis.getExtent();
  42696. var matrix = transformGroup.transform;
  42697. var pt1 = [extent[0], 0];
  42698. var pt2 = [extent[1], 0];
  42699. var inverse = pt1[0] > pt2[0];
  42700. if (matrix) {
  42701. applyTransform(pt1, pt1, matrix);
  42702. applyTransform(pt2, pt2, matrix);
  42703. }
  42704. var lineStyle = extend({
  42705. lineCap: 'round'
  42706. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  42707. var line = new Line({
  42708. shape: {
  42709. x1: pt1[0],
  42710. y1: pt1[1],
  42711. x2: pt2[0],
  42712. y2: pt2[1]
  42713. },
  42714. style: lineStyle,
  42715. strokeContainThreshold: opt.strokeContainThreshold || 5,
  42716. silent: true,
  42717. z2: 1
  42718. });
  42719. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  42720. line.anid = 'line';
  42721. group.add(line);
  42722. var arrows = axisModel.get(['axisLine', 'symbol']);
  42723. if (arrows != null) {
  42724. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  42725. if (isString(arrows)) {
  42726. // Use the same arrow for start and end point
  42727. arrows = [arrows, arrows];
  42728. }
  42729. if (isString(arrowSize) || isNumber(arrowSize)) {
  42730. // Use the same size for width and height
  42731. arrowSize = [arrowSize, arrowSize];
  42732. }
  42733. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  42734. var symbolWidth_1 = arrowSize[0];
  42735. var symbolHeight_1 = arrowSize[1];
  42736. each([{
  42737. rotate: opt.rotation + Math.PI / 2,
  42738. offset: arrowOffset[0],
  42739. r: 0
  42740. }, {
  42741. rotate: opt.rotation - Math.PI / 2,
  42742. offset: arrowOffset[1],
  42743. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  42744. }], function (point, index) {
  42745. if (arrows[index] !== 'none' && arrows[index] != null) {
  42746. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  42747. var r = point.r + point.offset;
  42748. var pt = inverse ? pt2 : pt1;
  42749. symbol.attr({
  42750. rotation: point.rotate,
  42751. x: pt[0] + r * Math.cos(opt.rotation),
  42752. y: pt[1] - r * Math.sin(opt.rotation),
  42753. silent: true,
  42754. z2: 11
  42755. });
  42756. group.add(symbol);
  42757. }
  42758. });
  42759. }
  42760. },
  42761. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  42762. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  42763. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  42764. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  42765. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection); // This bit fixes the label overlap issue for the time chart.
  42766. // See https://github.com/apache/echarts/issues/14266 for more.
  42767. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  42768. var labelList = prepareLayoutList(map(labelEls, function (label) {
  42769. return {
  42770. label: label,
  42771. priority: label.z2,
  42772. defaultAttr: {
  42773. ignore: label.ignore
  42774. }
  42775. };
  42776. }));
  42777. hideOverlap(labelList);
  42778. }
  42779. },
  42780. axisName: function (opt, axisModel, group, transformGroup) {
  42781. var name = retrieve(opt.axisName, axisModel.get('name'));
  42782. if (!name) {
  42783. return;
  42784. }
  42785. var nameLocation = axisModel.get('nameLocation');
  42786. var nameDirection = opt.nameDirection;
  42787. var textStyleModel = axisModel.getModel('nameTextStyle');
  42788. var gap = axisModel.get('nameGap') || 0;
  42789. var extent = axisModel.axis.getExtent();
  42790. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  42791. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  42792. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  42793. var labelLayout;
  42794. var nameRotation = axisModel.get('nameRotate');
  42795. if (nameRotation != null) {
  42796. nameRotation = nameRotation * PI$5 / 180; // To radian.
  42797. }
  42798. var axisNameAvailableWidth;
  42799. if (isNameLocationCenter(nameLocation)) {
  42800. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  42801. nameDirection);
  42802. } else {
  42803. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  42804. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  42805. if (axisNameAvailableWidth != null) {
  42806. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  42807. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  42808. }
  42809. }
  42810. var textFont = textStyleModel.getFont();
  42811. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  42812. var ellipsis = truncateOpt.ellipsis;
  42813. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  42814. var textEl = new ZRText({
  42815. x: pos[0],
  42816. y: pos[1],
  42817. rotation: labelLayout.rotation,
  42818. silent: AxisBuilder.isLabelSilent(axisModel),
  42819. style: createTextStyle(textStyleModel, {
  42820. text: name,
  42821. font: textFont,
  42822. overflow: 'truncate',
  42823. width: maxWidth,
  42824. ellipsis: ellipsis,
  42825. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  42826. align: textStyleModel.get('align') || labelLayout.textAlign,
  42827. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  42828. }),
  42829. z2: 1
  42830. });
  42831. setTooltipConfig({
  42832. el: textEl,
  42833. componentModel: axisModel,
  42834. itemName: name
  42835. });
  42836. textEl.__fullText = name; // Id for animation
  42837. textEl.anid = 'name';
  42838. if (axisModel.get('triggerEvent')) {
  42839. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  42840. eventData.targetType = 'axisName';
  42841. eventData.name = name;
  42842. getECData(textEl).eventData = eventData;
  42843. } // FIXME
  42844. transformGroup.add(textEl);
  42845. textEl.updateTransform();
  42846. group.add(textEl);
  42847. textEl.decomposeTransform();
  42848. }
  42849. };
  42850. function endTextLayout(rotation, textPosition, textRotate, extent) {
  42851. var rotationDiff = remRadian(textRotate - rotation);
  42852. var textAlign;
  42853. var textVerticalAlign;
  42854. var inverse = extent[0] > extent[1];
  42855. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  42856. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  42857. textVerticalAlign = onLeft ? 'bottom' : 'top';
  42858. textAlign = 'center';
  42859. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  42860. textVerticalAlign = onLeft ? 'top' : 'bottom';
  42861. textAlign = 'center';
  42862. } else {
  42863. textVerticalAlign = 'middle';
  42864. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  42865. textAlign = onLeft ? 'left' : 'right';
  42866. } else {
  42867. textAlign = onLeft ? 'right' : 'left';
  42868. }
  42869. }
  42870. return {
  42871. rotation: rotationDiff,
  42872. textAlign: textAlign,
  42873. textVerticalAlign: textVerticalAlign
  42874. };
  42875. }
  42876. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  42877. if (shouldShowAllLabels(axisModel.axis)) {
  42878. return;
  42879. } // If min or max are user set, we need to check
  42880. // If the tick on min(max) are overlap on their neighbour tick
  42881. // If they are overlapped, we need to hide the min(max) tick label
  42882. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  42883. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  42884. // Have not consider onBand yet, where tick els is more than label els.
  42885. labelEls = labelEls || [];
  42886. tickEls = tickEls || [];
  42887. var firstLabel = labelEls[0];
  42888. var nextLabel = labelEls[1];
  42889. var lastLabel = labelEls[labelEls.length - 1];
  42890. var prevLabel = labelEls[labelEls.length - 2];
  42891. var firstTick = tickEls[0];
  42892. var nextTick = tickEls[1];
  42893. var lastTick = tickEls[tickEls.length - 1];
  42894. var prevTick = tickEls[tickEls.length - 2];
  42895. if (showMinLabel === false) {
  42896. ignoreEl(firstLabel);
  42897. ignoreEl(firstTick);
  42898. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  42899. if (showMinLabel) {
  42900. ignoreEl(nextLabel);
  42901. ignoreEl(nextTick);
  42902. } else {
  42903. ignoreEl(firstLabel);
  42904. ignoreEl(firstTick);
  42905. }
  42906. }
  42907. if (showMaxLabel === false) {
  42908. ignoreEl(lastLabel);
  42909. ignoreEl(lastTick);
  42910. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  42911. if (showMaxLabel) {
  42912. ignoreEl(prevLabel);
  42913. ignoreEl(prevTick);
  42914. } else {
  42915. ignoreEl(lastLabel);
  42916. ignoreEl(lastTick);
  42917. }
  42918. }
  42919. }
  42920. function ignoreEl(el) {
  42921. el && (el.ignore = true);
  42922. }
  42923. function isTwoLabelOverlapped(current, next) {
  42924. // current and next has the same rotation.
  42925. var firstRect = current && current.getBoundingRect().clone();
  42926. var nextRect = next && next.getBoundingRect().clone();
  42927. if (!firstRect || !nextRect) {
  42928. return;
  42929. } // When checking intersect of two rotated labels, we use mRotationBack
  42930. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  42931. var mRotationBack = identity([]);
  42932. rotate(mRotationBack, mRotationBack, -current.rotation);
  42933. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  42934. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  42935. return firstRect.intersect(nextRect);
  42936. }
  42937. function isNameLocationCenter(nameLocation) {
  42938. return nameLocation === 'middle' || nameLocation === 'center';
  42939. }
  42940. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  42941. var tickEls = [];
  42942. var pt1 = [];
  42943. var pt2 = [];
  42944. for (var i = 0; i < ticksCoords.length; i++) {
  42945. var tickCoord = ticksCoords[i].coord;
  42946. pt1[0] = tickCoord;
  42947. pt1[1] = 0;
  42948. pt2[0] = tickCoord;
  42949. pt2[1] = tickEndCoord;
  42950. if (tickTransform) {
  42951. applyTransform(pt1, pt1, tickTransform);
  42952. applyTransform(pt2, pt2, tickTransform);
  42953. } // Tick line, Not use group transform to have better line draw
  42954. var tickEl = new Line({
  42955. shape: {
  42956. x1: pt1[0],
  42957. y1: pt1[1],
  42958. x2: pt2[0],
  42959. y2: pt2[1]
  42960. },
  42961. style: tickLineStyle,
  42962. z2: 2,
  42963. autoBatch: true,
  42964. silent: true
  42965. });
  42966. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  42967. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  42968. tickEls.push(tickEl);
  42969. }
  42970. return tickEls;
  42971. }
  42972. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  42973. var axis = axisModel.axis;
  42974. var tickModel = axisModel.getModel('axisTick');
  42975. var shown = tickModel.get('show');
  42976. if (shown === 'auto' && opt.handleAutoShown) {
  42977. shown = opt.handleAutoShown('axisTick');
  42978. }
  42979. if (!shown || axis.scale.isBlank()) {
  42980. return;
  42981. }
  42982. var lineStyleModel = tickModel.getModel('lineStyle');
  42983. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  42984. var ticksCoords = axis.getTicksCoords();
  42985. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  42986. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  42987. }), 'ticks');
  42988. for (var i = 0; i < ticksEls.length; i++) {
  42989. group.add(ticksEls[i]);
  42990. }
  42991. return ticksEls;
  42992. }
  42993. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  42994. var axis = axisModel.axis;
  42995. var minorTickModel = axisModel.getModel('minorTick');
  42996. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  42997. return;
  42998. }
  42999. var minorTicksCoords = axis.getMinorTicksCoords();
  43000. if (!minorTicksCoords.length) {
  43001. return;
  43002. }
  43003. var lineStyleModel = minorTickModel.getModel('lineStyle');
  43004. var tickEndCoord = tickDirection * minorTickModel.get('length');
  43005. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  43006. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43007. }));
  43008. for (var i = 0; i < minorTicksCoords.length; i++) {
  43009. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  43010. for (var k = 0; k < minorTicksEls.length; k++) {
  43011. group.add(minorTicksEls[k]);
  43012. }
  43013. }
  43014. }
  43015. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  43016. var axis = axisModel.axis;
  43017. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  43018. if (!show || axis.scale.isBlank()) {
  43019. return;
  43020. }
  43021. var labelModel = axisModel.getModel('axisLabel');
  43022. var labelMargin = labelModel.get('margin');
  43023. var labels = axis.getViewLabels(); // Special label rotate.
  43024. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  43025. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  43026. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  43027. var labelEls = [];
  43028. var silent = AxisBuilder.isLabelSilent(axisModel);
  43029. var triggerEvent = axisModel.get('triggerEvent');
  43030. each(labels, function (labelItem, index) {
  43031. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  43032. var formattedLabel = labelItem.formattedLabel;
  43033. var rawLabel = labelItem.rawLabel;
  43034. var itemLabelModel = labelModel;
  43035. if (rawCategoryData && rawCategoryData[tickValue]) {
  43036. var rawCategoryItem = rawCategoryData[tickValue];
  43037. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  43038. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  43039. }
  43040. }
  43041. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  43042. var tickCoord = axis.dataToCoord(tickValue);
  43043. var textEl = new ZRText({
  43044. x: tickCoord,
  43045. y: opt.labelOffset + opt.labelDirection * labelMargin,
  43046. rotation: labelLayout.rotation,
  43047. silent: silent,
  43048. z2: 10 + (labelItem.level || 0),
  43049. style: createTextStyle(itemLabelModel, {
  43050. text: formattedLabel,
  43051. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  43052. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  43053. fill: isFunction(textColor) ? textColor( // (1) In category axis with data zoom, tick is not the original
  43054. // index of axis.data. So tick should not be exposed to user
  43055. // in category axis.
  43056. // (2) Compatible with previous version, which always use formatted label as
  43057. // input. But in interval scale the formatted label is like '223,445', which
  43058. // maked user replace ','. So we modify it to return original val but remain
  43059. // it as 'string' to avoid error in replacing.
  43060. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  43061. })
  43062. });
  43063. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  43064. if (triggerEvent) {
  43065. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43066. eventData.targetType = 'axisLabel';
  43067. eventData.value = rawLabel;
  43068. eventData.tickIndex = index;
  43069. if (axis.type === 'category') {
  43070. eventData.dataIndex = tickValue;
  43071. }
  43072. getECData(textEl).eventData = eventData;
  43073. } // FIXME
  43074. transformGroup.add(textEl);
  43075. textEl.updateTransform();
  43076. labelEls.push(textEl);
  43077. group.add(textEl);
  43078. textEl.decomposeTransform();
  43079. });
  43080. return labelEls;
  43081. }
  43082. // allAxesInfo should be updated when setOption performed.
  43083. function collect(ecModel, api) {
  43084. var result = {
  43085. /**
  43086. * key: makeKey(axis.model)
  43087. * value: {
  43088. * axis,
  43089. * coordSys,
  43090. * axisPointerModel,
  43091. * triggerTooltip,
  43092. * involveSeries,
  43093. * snap,
  43094. * seriesModels,
  43095. * seriesDataCount
  43096. * }
  43097. */
  43098. axesInfo: {},
  43099. seriesInvolved: false,
  43100. /**
  43101. * key: makeKey(coordSys.model)
  43102. * value: Object: key makeKey(axis.model), value: axisInfo
  43103. */
  43104. coordSysAxesInfo: {},
  43105. coordSysMap: {}
  43106. };
  43107. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  43108. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  43109. return result;
  43110. }
  43111. function collectAxesInfo(result, ecModel, api) {
  43112. var globalTooltipModel = ecModel.getComponent('tooltip');
  43113. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  43114. var linksOption = globalAxisPointerModel.get('link', true) || [];
  43115. var linkGroups = []; // Collect axes info.
  43116. each(api.getCoordinateSystems(), function (coordSys) {
  43117. // Some coordinate system do not support axes, like geo.
  43118. if (!coordSys.axisPointerEnabled) {
  43119. return;
  43120. }
  43121. var coordSysKey = makeKey(coordSys.model);
  43122. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  43123. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convenient way to show axisPointer
  43124. // for user. So we enable setting tooltip on coordSys model.
  43125. var coordSysModel = coordSys.model;
  43126. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  43127. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  43128. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  43129. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  43130. // show but axisPointer will show as normal.
  43131. && baseTooltipModel.get('show')) {
  43132. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  43133. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  43134. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  43135. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  43136. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  43137. if (triggerAxis || cross) {
  43138. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  43139. }
  43140. if (cross) {
  43141. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  43142. }
  43143. } // fromTooltip: true | false | 'cross'
  43144. // triggerTooltip: true | false | null
  43145. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  43146. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  43147. var axisPointerShow = axisPointerModel.get('show');
  43148. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  43149. return;
  43150. }
  43151. if (triggerTooltip == null) {
  43152. triggerTooltip = axisPointerModel.get('triggerTooltip');
  43153. }
  43154. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  43155. var snap = axisPointerModel.get('snap');
  43156. var axisKey = makeKey(axis.model);
  43157. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  43158. var axisInfo = result.axesInfo[axisKey] = {
  43159. key: axisKey,
  43160. axis: axis,
  43161. coordSys: coordSys,
  43162. axisPointerModel: axisPointerModel,
  43163. triggerTooltip: triggerTooltip,
  43164. involveSeries: involveSeries,
  43165. snap: snap,
  43166. useHandle: isHandleTrigger(axisPointerModel),
  43167. seriesModels: [],
  43168. linkGroup: null
  43169. };
  43170. axesInfoInCoordSys[axisKey] = axisInfo;
  43171. result.seriesInvolved = result.seriesInvolved || involveSeries;
  43172. var groupIndex = getLinkGroupIndex(linksOption, axis);
  43173. if (groupIndex != null) {
  43174. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  43175. axesInfo: {}
  43176. });
  43177. linkGroup.axesInfo[axisKey] = axisInfo;
  43178. linkGroup.mapper = linksOption[groupIndex].mapper;
  43179. axisInfo.linkGroup = linkGroup;
  43180. }
  43181. }
  43182. });
  43183. }
  43184. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  43185. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  43186. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  43187. var volatileOption = {};
  43188. each(fields, function (field) {
  43189. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  43190. }); // category axis do not auto snap, otherwise some tick that do not
  43191. // has value can not be hovered. value/time/log axis default snap if
  43192. // triggered from tooltip and trigger tooltip.
  43193. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatible with previous behavior, tooltip axis does not show label by default.
  43194. // Only these properties can be overridden from tooltip to axisPointer.
  43195. if (tooltipAxisPointerModel.get('type') === 'cross') {
  43196. volatileOption.type = 'line';
  43197. }
  43198. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  43199. labelOption.show == null && (labelOption.show = false);
  43200. if (fromTooltip === 'cross') {
  43201. // When 'cross', both axes show labels.
  43202. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  43203. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  43204. // (cross style is dashed by default)
  43205. if (!triggerTooltip) {
  43206. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  43207. crossStyle && defaults(labelOption, crossStyle.textStyle);
  43208. }
  43209. }
  43210. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  43211. }
  43212. function collectSeriesInfo(result, ecModel) {
  43213. // Prepare data for axis trigger
  43214. ecModel.eachSeries(function (seriesModel) {
  43215. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  43216. var coordSys = seriesModel.coordinateSystem;
  43217. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  43218. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  43219. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  43220. return;
  43221. }
  43222. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  43223. var axis = axisInfo.axis;
  43224. if (coordSys.getAxis(axis.dim) === axis) {
  43225. axisInfo.seriesModels.push(seriesModel);
  43226. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  43227. axisInfo.seriesDataCount += seriesModel.getData().count();
  43228. }
  43229. });
  43230. });
  43231. }
  43232. /**
  43233. * For example:
  43234. * {
  43235. * axisPointer: {
  43236. * links: [{
  43237. * xAxisIndex: [2, 4],
  43238. * yAxisIndex: 'all'
  43239. * }, {
  43240. * xAxisId: ['a5', 'a7'],
  43241. * xAxisName: 'xxx'
  43242. * }]
  43243. * }
  43244. * }
  43245. */
  43246. function getLinkGroupIndex(linksOption, axis) {
  43247. var axisModel = axis.model;
  43248. var dim = axis.dim;
  43249. for (var i = 0; i < linksOption.length; i++) {
  43250. var linkOption = linksOption[i] || {};
  43251. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  43252. return i;
  43253. }
  43254. }
  43255. }
  43256. function checkPropInLink(linkPropValue, axisPropValue) {
  43257. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  43258. }
  43259. function fixValue(axisModel) {
  43260. var axisInfo = getAxisInfo(axisModel);
  43261. if (!axisInfo) {
  43262. return;
  43263. }
  43264. var axisPointerModel = axisInfo.axisPointerModel;
  43265. var scale = axisInfo.axis.scale;
  43266. var option = axisPointerModel.option;
  43267. var status = axisPointerModel.get('status');
  43268. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  43269. if (value != null) {
  43270. value = scale.parse(value);
  43271. }
  43272. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  43273. // and status should be initialized.
  43274. if (status == null) {
  43275. option.status = useHandle ? 'show' : 'hide';
  43276. }
  43277. var extent = scale.getExtent().slice();
  43278. extent[0] > extent[1] && extent.reverse();
  43279. if ( // Pick a value on axis when initializing.
  43280. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  43281. // where we should re-pick a value to keep `handle` displaying normally.
  43282. || value > extent[1]) {
  43283. // Make handle displayed on the end of the axis when init, which looks better.
  43284. value = extent[1];
  43285. }
  43286. if (value < extent[0]) {
  43287. value = extent[0];
  43288. }
  43289. option.value = value;
  43290. if (useHandle) {
  43291. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  43292. }
  43293. }
  43294. function getAxisInfo(axisModel) {
  43295. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  43296. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  43297. }
  43298. function getAxisPointerModel(axisModel) {
  43299. var axisInfo = getAxisInfo(axisModel);
  43300. return axisInfo && axisInfo.axisPointerModel;
  43301. }
  43302. function isHandleTrigger(axisPointerModel) {
  43303. return !!axisPointerModel.get(['handle', 'show']);
  43304. }
  43305. /**
  43306. * @param {module:echarts/model/Model} model
  43307. * @return {string} unique key
  43308. */
  43309. function makeKey(model) {
  43310. return model.type + '||' + model.id;
  43311. }
  43312. var axisPointerClazz = {};
  43313. /**
  43314. * Base class of AxisView.
  43315. */
  43316. var AxisView =
  43317. /** @class */
  43318. function (_super) {
  43319. __extends(AxisView, _super);
  43320. function AxisView() {
  43321. var _this = _super !== null && _super.apply(this, arguments) || this;
  43322. _this.type = AxisView.type;
  43323. return _this;
  43324. }
  43325. /**
  43326. * @override
  43327. */
  43328. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43329. // FIXME
  43330. // This process should proformed after coordinate systems updated
  43331. // (axis scale updated), and should be performed each time update.
  43332. // So put it here temporarily, although it is not appropriate to
  43333. // put a model-writing procedure in `view`.
  43334. this.axisPointerClass && fixValue(axisModel);
  43335. _super.prototype.render.apply(this, arguments);
  43336. this._doUpdateAxisPointerClass(axisModel, api, true);
  43337. };
  43338. /**
  43339. * Action handler.
  43340. */
  43341. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  43342. this._doUpdateAxisPointerClass(axisModel, api, false);
  43343. };
  43344. /**
  43345. * @override
  43346. */
  43347. AxisView.prototype.remove = function (ecModel, api) {
  43348. var axisPointer = this._axisPointer;
  43349. axisPointer && axisPointer.remove(api);
  43350. };
  43351. /**
  43352. * @override
  43353. */
  43354. AxisView.prototype.dispose = function (ecModel, api) {
  43355. this._disposeAxisPointer(api);
  43356. _super.prototype.dispose.apply(this, arguments);
  43357. };
  43358. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  43359. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  43360. if (!Clazz) {
  43361. return;
  43362. }
  43363. var axisPointerModel = getAxisPointerModel(axisModel);
  43364. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  43365. };
  43366. AxisView.prototype._disposeAxisPointer = function (api) {
  43367. this._axisPointer && this._axisPointer.dispose(api);
  43368. this._axisPointer = null;
  43369. };
  43370. AxisView.registerAxisPointerClass = function (type, clazz) {
  43371. if ("development" !== 'production') {
  43372. if (axisPointerClazz[type]) {
  43373. throw new Error('axisPointer ' + type + ' exists');
  43374. }
  43375. }
  43376. axisPointerClazz[type] = clazz;
  43377. };
  43378. AxisView.getAxisPointerClass = function (type) {
  43379. return type && axisPointerClazz[type];
  43380. };
  43381. AxisView.type = 'axis';
  43382. return AxisView;
  43383. }(ComponentView);
  43384. var inner$6 = makeInner();
  43385. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  43386. var axis = axisModel.axis;
  43387. if (axis.scale.isBlank()) {
  43388. return;
  43389. } // TODO: TYPE
  43390. var splitAreaModel = axisModel.getModel('splitArea');
  43391. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  43392. var areaColors = areaStyleModel.get('color');
  43393. var gridRect = gridModel.coordinateSystem.getRect();
  43394. var ticksCoords = axis.getTicksCoords({
  43395. tickModel: splitAreaModel,
  43396. clamp: true
  43397. });
  43398. if (!ticksCoords.length) {
  43399. return;
  43400. } // For Making appropriate splitArea animation, the color and anid
  43401. // should be corresponding to previous one if possible.
  43402. var areaColorsLen = areaColors.length;
  43403. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  43404. var newSplitAreaColors = createHashMap();
  43405. var colorIndex = 0;
  43406. if (lastSplitAreaColors) {
  43407. for (var i = 0; i < ticksCoords.length; i++) {
  43408. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  43409. if (cIndex != null) {
  43410. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  43411. break;
  43412. }
  43413. }
  43414. }
  43415. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  43416. var areaStyle = areaStyleModel.getAreaStyle();
  43417. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  43418. for (var i = 1; i < ticksCoords.length; i++) {
  43419. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43420. var x = void 0;
  43421. var y = void 0;
  43422. var width = void 0;
  43423. var height = void 0;
  43424. if (axis.isHorizontal()) {
  43425. x = prev;
  43426. y = gridRect.y;
  43427. width = tickCoord - x;
  43428. height = gridRect.height;
  43429. prev = x + width;
  43430. } else {
  43431. x = gridRect.x;
  43432. y = prev;
  43433. width = gridRect.width;
  43434. height = tickCoord - y;
  43435. prev = y + height;
  43436. }
  43437. var tickValue = ticksCoords[i - 1].tickValue;
  43438. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  43439. axisGroup.add(new Rect({
  43440. anid: tickValue != null ? 'area_' + tickValue : null,
  43441. shape: {
  43442. x: x,
  43443. y: y,
  43444. width: width,
  43445. height: height
  43446. },
  43447. style: defaults({
  43448. fill: areaColors[colorIndex]
  43449. }, areaStyle),
  43450. autoBatch: true,
  43451. silent: true
  43452. }));
  43453. colorIndex = (colorIndex + 1) % areaColorsLen;
  43454. }
  43455. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  43456. }
  43457. function rectCoordAxisHandleRemove(axisView) {
  43458. inner$6(axisView).splitAreaColors = null;
  43459. }
  43460. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  43461. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  43462. var CartesianAxisView =
  43463. /** @class */
  43464. function (_super) {
  43465. __extends(CartesianAxisView, _super);
  43466. function CartesianAxisView() {
  43467. var _this = _super !== null && _super.apply(this, arguments) || this;
  43468. _this.type = CartesianAxisView.type;
  43469. _this.axisPointerClass = 'CartesianAxisPointer';
  43470. return _this;
  43471. }
  43472. /**
  43473. * @override
  43474. */
  43475. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43476. this.group.removeAll();
  43477. var oldAxisGroup = this._axisGroup;
  43478. this._axisGroup = new Group();
  43479. this.group.add(this._axisGroup);
  43480. if (!axisModel.get('show')) {
  43481. return;
  43482. }
  43483. var gridModel = axisModel.getCoordSysModel();
  43484. var layout = layout$1(gridModel, axisModel);
  43485. var axisBuilder = new AxisBuilder(axisModel, extend({
  43486. handleAutoShown: function (elementType) {
  43487. var cartesians = gridModel.coordinateSystem.getCartesians();
  43488. for (var i = 0; i < cartesians.length; i++) {
  43489. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  43490. // Still show axis tick or axisLine if other axis is value / log
  43491. return true;
  43492. }
  43493. } // Not show axisTick or axisLine if other axis is category / time
  43494. return false;
  43495. }
  43496. }, layout));
  43497. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  43498. this._axisGroup.add(axisBuilder.getGroup());
  43499. each(selfBuilderAttrs, function (name) {
  43500. if (axisModel.get([name, 'show'])) {
  43501. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  43502. }
  43503. }, this); // THIS is a special case for bar racing chart.
  43504. // Update the axis label from the natural initial layout to
  43505. // sorted layout should has no animation.
  43506. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  43507. if (!isInitialSortFromBarRacing) {
  43508. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  43509. }
  43510. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  43511. };
  43512. CartesianAxisView.prototype.remove = function () {
  43513. rectCoordAxisHandleRemove(this);
  43514. };
  43515. CartesianAxisView.type = 'cartesianAxis';
  43516. return CartesianAxisView;
  43517. }(AxisView);
  43518. var axisElementBuilders = {
  43519. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43520. var axis = axisModel.axis;
  43521. if (axis.scale.isBlank()) {
  43522. return;
  43523. }
  43524. var splitLineModel = axisModel.getModel('splitLine');
  43525. var lineStyleModel = splitLineModel.getModel('lineStyle');
  43526. var lineColors = lineStyleModel.get('color');
  43527. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  43528. var gridRect = gridModel.coordinateSystem.getRect();
  43529. var isHorizontal = axis.isHorizontal();
  43530. var lineCount = 0;
  43531. var ticksCoords = axis.getTicksCoords({
  43532. tickModel: splitLineModel
  43533. });
  43534. var p1 = [];
  43535. var p2 = [];
  43536. var lineStyle = lineStyleModel.getLineStyle();
  43537. for (var i = 0; i < ticksCoords.length; i++) {
  43538. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43539. if (isHorizontal) {
  43540. p1[0] = tickCoord;
  43541. p1[1] = gridRect.y;
  43542. p2[0] = tickCoord;
  43543. p2[1] = gridRect.y + gridRect.height;
  43544. } else {
  43545. p1[0] = gridRect.x;
  43546. p1[1] = tickCoord;
  43547. p2[0] = gridRect.x + gridRect.width;
  43548. p2[1] = tickCoord;
  43549. }
  43550. var colorIndex = lineCount++ % lineColors.length;
  43551. var tickValue = ticksCoords[i].tickValue;
  43552. var line = new Line({
  43553. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  43554. autoBatch: true,
  43555. shape: {
  43556. x1: p1[0],
  43557. y1: p1[1],
  43558. x2: p2[0],
  43559. y2: p2[1]
  43560. },
  43561. style: defaults({
  43562. stroke: lineColors[colorIndex]
  43563. }, lineStyle),
  43564. silent: true
  43565. });
  43566. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43567. axisGroup.add(line);
  43568. }
  43569. },
  43570. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43571. var axis = axisModel.axis;
  43572. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  43573. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  43574. var gridRect = gridModel.coordinateSystem.getRect();
  43575. var isHorizontal = axis.isHorizontal();
  43576. var minorTicksCoords = axis.getMinorTicksCoords();
  43577. if (!minorTicksCoords.length) {
  43578. return;
  43579. }
  43580. var p1 = [];
  43581. var p2 = [];
  43582. var lineStyle = lineStyleModel.getLineStyle();
  43583. for (var i = 0; i < minorTicksCoords.length; i++) {
  43584. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  43585. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  43586. if (isHorizontal) {
  43587. p1[0] = tickCoord;
  43588. p1[1] = gridRect.y;
  43589. p2[0] = tickCoord;
  43590. p2[1] = gridRect.y + gridRect.height;
  43591. } else {
  43592. p1[0] = gridRect.x;
  43593. p1[1] = tickCoord;
  43594. p2[0] = gridRect.x + gridRect.width;
  43595. p2[1] = tickCoord;
  43596. }
  43597. var line = new Line({
  43598. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  43599. autoBatch: true,
  43600. shape: {
  43601. x1: p1[0],
  43602. y1: p1[1],
  43603. x2: p2[0],
  43604. y2: p2[1]
  43605. },
  43606. style: lineStyle,
  43607. silent: true
  43608. });
  43609. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43610. axisGroup.add(line);
  43611. }
  43612. }
  43613. },
  43614. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  43615. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  43616. }
  43617. };
  43618. var CartesianXAxisView =
  43619. /** @class */
  43620. function (_super) {
  43621. __extends(CartesianXAxisView, _super);
  43622. function CartesianXAxisView() {
  43623. var _this = _super !== null && _super.apply(this, arguments) || this;
  43624. _this.type = CartesianXAxisView.type;
  43625. return _this;
  43626. }
  43627. CartesianXAxisView.type = 'xAxis';
  43628. return CartesianXAxisView;
  43629. }(CartesianAxisView);
  43630. var CartesianYAxisView =
  43631. /** @class */
  43632. function (_super) {
  43633. __extends(CartesianYAxisView, _super);
  43634. function CartesianYAxisView() {
  43635. var _this = _super !== null && _super.apply(this, arguments) || this;
  43636. _this.type = CartesianXAxisView.type;
  43637. return _this;
  43638. }
  43639. CartesianYAxisView.type = 'yAxis';
  43640. return CartesianYAxisView;
  43641. }(CartesianAxisView);
  43642. var GridView =
  43643. /** @class */
  43644. function (_super) {
  43645. __extends(GridView, _super);
  43646. function GridView() {
  43647. var _this = _super !== null && _super.apply(this, arguments) || this;
  43648. _this.type = 'grid';
  43649. return _this;
  43650. }
  43651. GridView.prototype.render = function (gridModel, ecModel) {
  43652. this.group.removeAll();
  43653. if (gridModel.get('show')) {
  43654. this.group.add(new Rect({
  43655. shape: gridModel.coordinateSystem.getRect(),
  43656. style: defaults({
  43657. fill: gridModel.get('backgroundColor')
  43658. }, gridModel.getItemStyle()),
  43659. silent: true,
  43660. z2: -1
  43661. }));
  43662. }
  43663. };
  43664. GridView.type = 'grid';
  43665. return GridView;
  43666. }(ComponentView);
  43667. var extraOption = {
  43668. // gridIndex: 0,
  43669. // gridId: '',
  43670. offset: 0
  43671. };
  43672. function install$5(registers) {
  43673. registers.registerComponentView(GridView);
  43674. registers.registerComponentModel(GridModel);
  43675. registers.registerCoordinateSystem('cartesian2d', Grid);
  43676. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  43677. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  43678. registers.registerComponentView(CartesianXAxisView);
  43679. registers.registerComponentView(CartesianYAxisView);
  43680. registers.registerPreprocessor(function (option) {
  43681. // Only create grid when need
  43682. if (option.xAxis && option.yAxis && !option.grid) {
  43683. option.grid = {};
  43684. }
  43685. });
  43686. }
  43687. function install$6(registers) {
  43688. // In case developer forget to include grid component
  43689. use(install$5);
  43690. registers.registerSeriesModel(ScatterSeriesModel);
  43691. registers.registerChartView(ScatterView);
  43692. registers.registerLayout(pointsLayout('scatter'));
  43693. }
  43694. function radarLayout(ecModel) {
  43695. ecModel.eachSeriesByType('radar', function (seriesModel) {
  43696. var data = seriesModel.getData();
  43697. var points = [];
  43698. var coordSys = seriesModel.coordinateSystem;
  43699. if (!coordSys) {
  43700. return;
  43701. }
  43702. var axes = coordSys.getIndicatorAxes();
  43703. each(axes, function (axis, axisIndex) {
  43704. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  43705. points[dataIndex] = points[dataIndex] || [];
  43706. var point = coordSys.dataToPoint(val, axisIndex);
  43707. points[dataIndex][axisIndex] = isValidPoint(point) ? point : getValueMissingPoint(coordSys);
  43708. });
  43709. }); // Close polygon
  43710. data.each(function (idx) {
  43711. // TODO
  43712. // Is it appropriate to connect to the next data when some data is missing?
  43713. // Or, should trade it like `connectNull` in line chart?
  43714. var firstPoint = find(points[idx], function (point) {
  43715. return isValidPoint(point);
  43716. }) || getValueMissingPoint(coordSys); // Copy the first actual point to the end of the array
  43717. points[idx].push(firstPoint.slice());
  43718. data.setItemLayout(idx, points[idx]);
  43719. });
  43720. });
  43721. }
  43722. function isValidPoint(point) {
  43723. return !isNaN(point[0]) && !isNaN(point[1]);
  43724. }
  43725. function getValueMissingPoint(coordSys) {
  43726. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  43727. // (probably cause problem when refreshing or animating)
  43728. return [coordSys.cx, coordSys.cy];
  43729. }
  43730. function radarBackwardCompat(option) {
  43731. var polarOptArr = option.polar;
  43732. if (polarOptArr) {
  43733. if (!isArray(polarOptArr)) {
  43734. polarOptArr = [polarOptArr];
  43735. }
  43736. var polarNotRadar_1 = [];
  43737. each(polarOptArr, function (polarOpt, idx) {
  43738. if (polarOpt.indicator) {
  43739. if (polarOpt.type && !polarOpt.shape) {
  43740. polarOpt.shape = polarOpt.type;
  43741. }
  43742. option.radar = option.radar || [];
  43743. if (!isArray(option.radar)) {
  43744. option.radar = [option.radar];
  43745. }
  43746. option.radar.push(polarOpt);
  43747. } else {
  43748. polarNotRadar_1.push(polarOpt);
  43749. }
  43750. });
  43751. option.polar = polarNotRadar_1;
  43752. }
  43753. each(option.series, function (seriesOpt) {
  43754. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  43755. seriesOpt.radarIndex = seriesOpt.polarIndex;
  43756. }
  43757. });
  43758. }
  43759. var RadarView =
  43760. /** @class */
  43761. function (_super) {
  43762. __extends(RadarView, _super);
  43763. function RadarView() {
  43764. var _this = _super !== null && _super.apply(this, arguments) || this;
  43765. _this.type = RadarView.type;
  43766. return _this;
  43767. }
  43768. RadarView.prototype.render = function (seriesModel, ecModel, api) {
  43769. var polar = seriesModel.coordinateSystem;
  43770. var group = this.group;
  43771. var data = seriesModel.getData();
  43772. var oldData = this._data;
  43773. function createSymbol$1(data, idx) {
  43774. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  43775. if (symbolType === 'none') {
  43776. return;
  43777. }
  43778. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  43779. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2);
  43780. var symbolRotate = data.getItemVisual(idx, 'symbolRotate') || 0;
  43781. symbolPath.attr({
  43782. style: {
  43783. strokeNoScale: true
  43784. },
  43785. z2: 100,
  43786. scaleX: symbolSize[0] / 2,
  43787. scaleY: symbolSize[1] / 2,
  43788. rotation: symbolRotate * Math.PI / 180 || 0
  43789. });
  43790. return symbolPath;
  43791. }
  43792. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  43793. // Simply rerender all
  43794. symbolGroup.removeAll();
  43795. for (var i = 0; i < newPoints.length - 1; i++) {
  43796. var symbolPath = createSymbol$1(data, idx);
  43797. if (symbolPath) {
  43798. symbolPath.__dimIdx = i;
  43799. if (oldPoints[i]) {
  43800. symbolPath.setPosition(oldPoints[i]);
  43801. graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, {
  43802. x: newPoints[i][0],
  43803. y: newPoints[i][1]
  43804. }, seriesModel, idx);
  43805. } else {
  43806. symbolPath.setPosition(newPoints[i]);
  43807. }
  43808. symbolGroup.add(symbolPath);
  43809. }
  43810. }
  43811. }
  43812. function getInitialPoints(points) {
  43813. return map(points, function (pt) {
  43814. return [polar.cx, polar.cy];
  43815. });
  43816. }
  43817. data.diff(oldData).add(function (idx) {
  43818. var points = data.getItemLayout(idx);
  43819. if (!points) {
  43820. return;
  43821. }
  43822. var polygon = new Polygon();
  43823. var polyline = new Polyline();
  43824. var target = {
  43825. shape: {
  43826. points: points
  43827. }
  43828. };
  43829. polygon.shape.points = getInitialPoints(points);
  43830. polyline.shape.points = getInitialPoints(points);
  43831. initProps(polygon, target, seriesModel, idx);
  43832. initProps(polyline, target, seriesModel, idx);
  43833. var itemGroup = new Group();
  43834. var symbolGroup = new Group();
  43835. itemGroup.add(polyline);
  43836. itemGroup.add(polygon);
  43837. itemGroup.add(symbolGroup);
  43838. updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, true);
  43839. data.setItemGraphicEl(idx, itemGroup);
  43840. }).update(function (newIdx, oldIdx) {
  43841. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  43842. var polyline = itemGroup.childAt(0);
  43843. var polygon = itemGroup.childAt(1);
  43844. var symbolGroup = itemGroup.childAt(2);
  43845. var target = {
  43846. shape: {
  43847. points: data.getItemLayout(newIdx)
  43848. }
  43849. };
  43850. if (!target.shape.points) {
  43851. return;
  43852. }
  43853. updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false);
  43854. saveOldStyle(polygon);
  43855. saveOldStyle(polyline);
  43856. updateProps(polyline, target, seriesModel);
  43857. updateProps(polygon, target, seriesModel);
  43858. data.setItemGraphicEl(newIdx, itemGroup);
  43859. }).remove(function (idx) {
  43860. group.remove(oldData.getItemGraphicEl(idx));
  43861. }).execute();
  43862. data.eachItemGraphicEl(function (itemGroup, idx) {
  43863. var itemModel = data.getItemModel(idx);
  43864. var polyline = itemGroup.childAt(0);
  43865. var polygon = itemGroup.childAt(1);
  43866. var symbolGroup = itemGroup.childAt(2); // Radar uses the visual encoded from itemStyle.
  43867. var itemStyle = data.getItemVisual(idx, 'style');
  43868. var color = itemStyle.fill;
  43869. group.add(itemGroup);
  43870. polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), {
  43871. fill: 'none',
  43872. stroke: color
  43873. }));
  43874. setStatesStylesFromModel(polyline, itemModel, 'lineStyle');
  43875. setStatesStylesFromModel(polygon, itemModel, 'areaStyle');
  43876. var areaStyleModel = itemModel.getModel('areaStyle');
  43877. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  43878. polygon.ignore = polygonIgnore;
  43879. each(['emphasis', 'select', 'blur'], function (stateName) {
  43880. var stateModel = itemModel.getModel([stateName, 'areaStyle']);
  43881. var stateIgnore = stateModel.isEmpty() && stateModel.parentModel.isEmpty(); // Won't be ignore if normal state is not ignore.
  43882. polygon.ensureState(stateName).ignore = stateIgnore && polygonIgnore;
  43883. });
  43884. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  43885. fill: color,
  43886. opacity: 0.7,
  43887. decal: itemStyle.decal
  43888. }));
  43889. var emphasisModel = itemModel.getModel('emphasis');
  43890. var itemHoverStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  43891. symbolGroup.eachChild(function (symbolPath) {
  43892. if (symbolPath instanceof ZRImage) {
  43893. var pathStyle = symbolPath.style;
  43894. symbolPath.useStyle(extend({
  43895. // TODO other properties like x, y ?
  43896. image: pathStyle.image,
  43897. x: pathStyle.x,
  43898. y: pathStyle.y,
  43899. width: pathStyle.width,
  43900. height: pathStyle.height
  43901. }, itemStyle));
  43902. } else {
  43903. symbolPath.useStyle(itemStyle);
  43904. symbolPath.setColor(color);
  43905. symbolPath.style.strokeNoScale = true;
  43906. }
  43907. var pathEmphasisState = symbolPath.ensureState('emphasis');
  43908. pathEmphasisState.style = clone(itemHoverStyle);
  43909. var defaultText = data.getStore().get(data.getDimensionIndex(symbolPath.__dimIdx), idx);
  43910. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  43911. setLabelStyle(symbolPath, getLabelStatesModels(itemModel), {
  43912. labelFetcher: data.hostModel,
  43913. labelDataIndex: idx,
  43914. labelDimIndex: symbolPath.__dimIdx,
  43915. defaultText: defaultText,
  43916. inheritColor: color,
  43917. defaultOpacity: itemStyle.opacity
  43918. });
  43919. });
  43920. toggleHoverEmphasis(itemGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  43921. });
  43922. this._data = data;
  43923. };
  43924. RadarView.prototype.remove = function () {
  43925. this.group.removeAll();
  43926. this._data = null;
  43927. };
  43928. RadarView.type = 'radar';
  43929. return RadarView;
  43930. }(ChartView);
  43931. var RadarSeriesModel =
  43932. /** @class */
  43933. function (_super) {
  43934. __extends(RadarSeriesModel, _super);
  43935. function RadarSeriesModel() {
  43936. var _this = _super !== null && _super.apply(this, arguments) || this;
  43937. _this.type = RadarSeriesModel.type;
  43938. _this.hasSymbolVisual = true;
  43939. return _this;
  43940. } // Overwrite
  43941. RadarSeriesModel.prototype.init = function (option) {
  43942. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  43943. // Use a function instead of direct access because data reference may changed
  43944. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  43945. };
  43946. RadarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  43947. return createSeriesDataSimply(this, {
  43948. generateCoord: 'indicator_',
  43949. generateCoordCount: Infinity
  43950. });
  43951. };
  43952. RadarSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  43953. var data = this.getData();
  43954. var coordSys = this.coordinateSystem;
  43955. var indicatorAxes = coordSys.getIndicatorAxes();
  43956. var name = this.getData().getName(dataIndex);
  43957. var nameToDisplay = name === '' ? this.name : name;
  43958. var markerColor = retrieveVisualColorForTooltipMarker(this, dataIndex);
  43959. return createTooltipMarkup('section', {
  43960. header: nameToDisplay,
  43961. sortBlocks: true,
  43962. blocks: map(indicatorAxes, function (axis) {
  43963. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  43964. return createTooltipMarkup('nameValue', {
  43965. markerType: 'subItem',
  43966. markerColor: markerColor,
  43967. name: axis.name,
  43968. value: val,
  43969. sortParam: val
  43970. });
  43971. })
  43972. });
  43973. };
  43974. RadarSeriesModel.prototype.getTooltipPosition = function (dataIndex) {
  43975. if (dataIndex != null) {
  43976. var data_1 = this.getData();
  43977. var coordSys = this.coordinateSystem;
  43978. var values = data_1.getValues(map(coordSys.dimensions, function (dim) {
  43979. return data_1.mapDimension(dim);
  43980. }), dataIndex);
  43981. for (var i = 0, len = values.length; i < len; i++) {
  43982. if (!isNaN(values[i])) {
  43983. var indicatorAxes = coordSys.getIndicatorAxes();
  43984. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  43985. }
  43986. }
  43987. }
  43988. };
  43989. RadarSeriesModel.type = 'series.radar';
  43990. RadarSeriesModel.dependencies = ['radar'];
  43991. RadarSeriesModel.defaultOption = {
  43992. // zlevel: 0,
  43993. z: 2,
  43994. colorBy: 'data',
  43995. coordinateSystem: 'radar',
  43996. legendHoverLink: true,
  43997. radarIndex: 0,
  43998. lineStyle: {
  43999. width: 2,
  44000. type: 'solid',
  44001. join: 'round'
  44002. },
  44003. label: {
  44004. position: 'top'
  44005. },
  44006. // areaStyle: {
  44007. // },
  44008. // itemStyle: {}
  44009. symbolSize: 8 // symbolRotate: null
  44010. };
  44011. return RadarSeriesModel;
  44012. }(SeriesModel);
  44013. var valueAxisDefault = axisDefault.value;
  44014. function defaultsShow(opt, show) {
  44015. return defaults({
  44016. show: show
  44017. }, opt);
  44018. }
  44019. var RadarModel =
  44020. /** @class */
  44021. function (_super) {
  44022. __extends(RadarModel, _super);
  44023. function RadarModel() {
  44024. var _this = _super !== null && _super.apply(this, arguments) || this;
  44025. _this.type = RadarModel.type;
  44026. return _this;
  44027. }
  44028. RadarModel.prototype.optionUpdated = function () {
  44029. var boundaryGap = this.get('boundaryGap');
  44030. var splitNumber = this.get('splitNumber');
  44031. var scale = this.get('scale');
  44032. var axisLine = this.get('axisLine');
  44033. var axisTick = this.get('axisTick'); // let axisType = this.get('axisType');
  44034. var axisLabel = this.get('axisLabel');
  44035. var nameTextStyle = this.get('axisName');
  44036. var showName = this.get(['axisName', 'show']);
  44037. var nameFormatter = this.get(['axisName', 'formatter']);
  44038. var nameGap = this.get('axisNameGap');
  44039. var triggerEvent = this.get('triggerEvent');
  44040. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  44041. // PENDING
  44042. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  44043. indicatorOpt.min = 0;
  44044. } else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  44045. indicatorOpt.max = 0;
  44046. }
  44047. var iNameTextStyle = nameTextStyle;
  44048. if (indicatorOpt.color != null) {
  44049. iNameTextStyle = defaults({
  44050. color: indicatorOpt.color
  44051. }, nameTextStyle);
  44052. } // Use same configuration
  44053. var innerIndicatorOpt = merge(clone(indicatorOpt), {
  44054. boundaryGap: boundaryGap,
  44055. splitNumber: splitNumber,
  44056. scale: scale,
  44057. axisLine: axisLine,
  44058. axisTick: axisTick,
  44059. // axisType: axisType,
  44060. axisLabel: axisLabel,
  44061. // Compatible with 2 and use text
  44062. name: indicatorOpt.text,
  44063. showName: showName,
  44064. nameLocation: 'end',
  44065. nameGap: nameGap,
  44066. // min: 0,
  44067. nameTextStyle: iNameTextStyle,
  44068. triggerEvent: triggerEvent
  44069. }, false);
  44070. if (isString(nameFormatter)) {
  44071. var indName = innerIndicatorOpt.name;
  44072. innerIndicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  44073. } else if (isFunction(nameFormatter)) {
  44074. innerIndicatorOpt.name = nameFormatter(innerIndicatorOpt.name, innerIndicatorOpt);
  44075. }
  44076. var model = new Model(innerIndicatorOpt, null, this.ecModel);
  44077. mixin(model, AxisModelCommonMixin.prototype); // For triggerEvent.
  44078. model.mainType = 'radar';
  44079. model.componentIndex = this.componentIndex;
  44080. return model;
  44081. }, this);
  44082. this._indicatorModels = indicatorModels;
  44083. };
  44084. RadarModel.prototype.getIndicatorModels = function () {
  44085. return this._indicatorModels;
  44086. };
  44087. RadarModel.type = 'radar';
  44088. RadarModel.defaultOption = {
  44089. // zlevel: 0,
  44090. z: 0,
  44091. center: ['50%', '50%'],
  44092. radius: '75%',
  44093. startAngle: 90,
  44094. axisName: {
  44095. show: true // formatter: null
  44096. // textStyle: {}
  44097. },
  44098. boundaryGap: [0, 0],
  44099. splitNumber: 5,
  44100. axisNameGap: 15,
  44101. scale: false,
  44102. // Polygon or circle
  44103. shape: 'polygon',
  44104. axisLine: merge({
  44105. lineStyle: {
  44106. color: '#bbb'
  44107. }
  44108. }, valueAxisDefault.axisLine),
  44109. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  44110. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  44111. // axisType: 'value',
  44112. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  44113. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  44114. // {text, min, max}
  44115. indicator: []
  44116. };
  44117. return RadarModel;
  44118. }(ComponentModel);
  44119. var axisBuilderAttrs$1 = ['axisLine', 'axisTickLabel', 'axisName'];
  44120. var RadarView$1 =
  44121. /** @class */
  44122. function (_super) {
  44123. __extends(RadarView, _super);
  44124. function RadarView() {
  44125. var _this = _super !== null && _super.apply(this, arguments) || this;
  44126. _this.type = RadarView.type;
  44127. return _this;
  44128. }
  44129. RadarView.prototype.render = function (radarModel, ecModel, api) {
  44130. var group = this.group;
  44131. group.removeAll();
  44132. this._buildAxes(radarModel);
  44133. this._buildSplitLineAndArea(radarModel);
  44134. };
  44135. RadarView.prototype._buildAxes = function (radarModel) {
  44136. var radar = radarModel.coordinateSystem;
  44137. var indicatorAxes = radar.getIndicatorAxes();
  44138. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  44139. var axisName = indicatorAxis.model.get('showName') ? indicatorAxis.name : ''; // hide name
  44140. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  44141. axisName: axisName,
  44142. position: [radar.cx, radar.cy],
  44143. rotation: indicatorAxis.angle,
  44144. labelDirection: -1,
  44145. tickDirection: -1,
  44146. nameDirection: 1
  44147. });
  44148. return axisBuilder;
  44149. });
  44150. each(axisBuilders, function (axisBuilder) {
  44151. each(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  44152. this.group.add(axisBuilder.getGroup());
  44153. }, this);
  44154. };
  44155. RadarView.prototype._buildSplitLineAndArea = function (radarModel) {
  44156. var radar = radarModel.coordinateSystem;
  44157. var indicatorAxes = radar.getIndicatorAxes();
  44158. if (!indicatorAxes.length) {
  44159. return;
  44160. }
  44161. var shape = radarModel.get('shape');
  44162. var splitLineModel = radarModel.getModel('splitLine');
  44163. var splitAreaModel = radarModel.getModel('splitArea');
  44164. var lineStyleModel = splitLineModel.getModel('lineStyle');
  44165. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  44166. var showSplitLine = splitLineModel.get('show');
  44167. var showSplitArea = splitAreaModel.get('show');
  44168. var splitLineColors = lineStyleModel.get('color');
  44169. var splitAreaColors = areaStyleModel.get('color');
  44170. var splitLineColorsArr = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  44171. var splitAreaColorsArr = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  44172. var splitLines = [];
  44173. var splitAreas = [];
  44174. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  44175. var colorIndex = idx % areaOrLineColorList.length;
  44176. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  44177. return colorIndex;
  44178. }
  44179. if (shape === 'circle') {
  44180. var ticksRadius = indicatorAxes[0].getTicksCoords();
  44181. var cx = radar.cx;
  44182. var cy = radar.cy;
  44183. for (var i = 0; i < ticksRadius.length; i++) {
  44184. if (showSplitLine) {
  44185. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44186. splitLines[colorIndex].push(new Circle({
  44187. shape: {
  44188. cx: cx,
  44189. cy: cy,
  44190. r: ticksRadius[i].coord
  44191. }
  44192. }));
  44193. }
  44194. if (showSplitArea && i < ticksRadius.length - 1) {
  44195. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i);
  44196. splitAreas[colorIndex].push(new Ring({
  44197. shape: {
  44198. cx: cx,
  44199. cy: cy,
  44200. r0: ticksRadius[i].coord,
  44201. r: ticksRadius[i + 1].coord
  44202. }
  44203. }));
  44204. }
  44205. }
  44206. } // Polyyon
  44207. else {
  44208. var realSplitNumber_1;
  44209. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  44210. var ticksCoords = indicatorAxis.getTicksCoords();
  44211. realSplitNumber_1 = realSplitNumber_1 == null ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber_1);
  44212. return map(ticksCoords, function (tickCoord) {
  44213. return radar.coordToPoint(tickCoord.coord, idx);
  44214. });
  44215. });
  44216. var prevPoints = [];
  44217. for (var i = 0; i <= realSplitNumber_1; i++) {
  44218. var points = [];
  44219. for (var j = 0; j < indicatorAxes.length; j++) {
  44220. points.push(axesTicksPoints[j][i]);
  44221. } // Close
  44222. if (points[0]) {
  44223. points.push(points[0].slice());
  44224. } else {
  44225. if ("development" !== 'production') {
  44226. console.error('Can\'t draw value axis ' + i);
  44227. }
  44228. }
  44229. if (showSplitLine) {
  44230. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44231. splitLines[colorIndex].push(new Polyline({
  44232. shape: {
  44233. points: points
  44234. }
  44235. }));
  44236. }
  44237. if (showSplitArea && prevPoints) {
  44238. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i - 1);
  44239. splitAreas[colorIndex].push(new Polygon({
  44240. shape: {
  44241. points: points.concat(prevPoints)
  44242. }
  44243. }));
  44244. }
  44245. prevPoints = points.slice().reverse();
  44246. }
  44247. }
  44248. var lineStyle = lineStyleModel.getLineStyle();
  44249. var areaStyle = areaStyleModel.getAreaStyle(); // Add splitArea before splitLine
  44250. each(splitAreas, function (splitAreas, idx) {
  44251. this.group.add(mergePath$1(splitAreas, {
  44252. style: defaults({
  44253. stroke: 'none',
  44254. fill: splitAreaColorsArr[idx % splitAreaColorsArr.length]
  44255. }, areaStyle),
  44256. silent: true
  44257. }));
  44258. }, this);
  44259. each(splitLines, function (splitLines, idx) {
  44260. this.group.add(mergePath$1(splitLines, {
  44261. style: defaults({
  44262. fill: 'none',
  44263. stroke: splitLineColorsArr[idx % splitLineColorsArr.length]
  44264. }, lineStyle),
  44265. silent: true
  44266. }));
  44267. }, this);
  44268. };
  44269. RadarView.type = 'radar';
  44270. return RadarView;
  44271. }(ComponentView);
  44272. var IndicatorAxis =
  44273. /** @class */
  44274. function (_super) {
  44275. __extends(IndicatorAxis, _super);
  44276. function IndicatorAxis(dim, scale, radiusExtent) {
  44277. var _this = _super.call(this, dim, scale, radiusExtent) || this;
  44278. _this.type = 'value';
  44279. _this.angle = 0;
  44280. _this.name = '';
  44281. return _this;
  44282. }
  44283. return IndicatorAxis;
  44284. }(Axis);
  44285. var Radar =
  44286. /** @class */
  44287. function () {
  44288. function Radar(radarModel, ecModel, api) {
  44289. /**
  44290. *
  44291. * Radar dimensions
  44292. */
  44293. this.dimensions = [];
  44294. this._model = radarModel;
  44295. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  44296. var dim = 'indicator_' + idx;
  44297. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale() // (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale()
  44298. );
  44299. indicatorAxis.name = indicatorModel.get('name'); // Inject model and axis
  44300. indicatorAxis.model = indicatorModel;
  44301. indicatorModel.axis = indicatorAxis;
  44302. this.dimensions.push(dim);
  44303. return indicatorAxis;
  44304. }, this);
  44305. this.resize(radarModel, api);
  44306. }
  44307. Radar.prototype.getIndicatorAxes = function () {
  44308. return this._indicatorAxes;
  44309. };
  44310. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  44311. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44312. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  44313. }; // TODO: API should be coordToPoint([coord, indicatorIndex])
  44314. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  44315. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44316. var angle = indicatorAxis.angle;
  44317. var x = this.cx + coord * Math.cos(angle);
  44318. var y = this.cy - coord * Math.sin(angle);
  44319. return [x, y];
  44320. };
  44321. Radar.prototype.pointToData = function (pt) {
  44322. var dx = pt[0] - this.cx;
  44323. var dy = pt[1] - this.cy;
  44324. var radius = Math.sqrt(dx * dx + dy * dy);
  44325. dx /= radius;
  44326. dy /= radius;
  44327. var radian = Math.atan2(-dy, dx); // Find the closest angle
  44328. // FIXME index can calculated directly
  44329. var minRadianDiff = Infinity;
  44330. var closestAxis;
  44331. var closestAxisIdx = -1;
  44332. for (var i = 0; i < this._indicatorAxes.length; i++) {
  44333. var indicatorAxis = this._indicatorAxes[i];
  44334. var diff = Math.abs(radian - indicatorAxis.angle);
  44335. if (diff < minRadianDiff) {
  44336. closestAxis = indicatorAxis;
  44337. closestAxisIdx = i;
  44338. minRadianDiff = diff;
  44339. }
  44340. }
  44341. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  44342. };
  44343. Radar.prototype.resize = function (radarModel, api) {
  44344. var center = radarModel.get('center');
  44345. var viewWidth = api.getWidth();
  44346. var viewHeight = api.getHeight();
  44347. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  44348. this.cx = parsePercent$1(center[0], viewWidth);
  44349. this.cy = parsePercent$1(center[1], viewHeight);
  44350. this.startAngle = radarModel.get('startAngle') * Math.PI / 180; // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  44351. var radius = radarModel.get('radius');
  44352. if (isString(radius) || isNumber(radius)) {
  44353. radius = [0, radius];
  44354. }
  44355. this.r0 = parsePercent$1(radius[0], viewSize);
  44356. this.r = parsePercent$1(radius[1], viewSize);
  44357. each(this._indicatorAxes, function (indicatorAxis, idx) {
  44358. indicatorAxis.setExtent(this.r0, this.r);
  44359. var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; // Normalize to [-PI, PI]
  44360. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  44361. indicatorAxis.angle = angle;
  44362. }, this);
  44363. };
  44364. Radar.prototype.update = function (ecModel, api) {
  44365. var indicatorAxes = this._indicatorAxes;
  44366. var radarModel = this._model;
  44367. each(indicatorAxes, function (indicatorAxis) {
  44368. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  44369. });
  44370. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  44371. if (radarSeries.get('coordinateSystem') !== 'radar' // @ts-ignore
  44372. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel) {
  44373. return;
  44374. }
  44375. var data = radarSeries.getData();
  44376. each(indicatorAxes, function (indicatorAxis) {
  44377. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  44378. });
  44379. }, this);
  44380. var splitNumber = radarModel.get('splitNumber');
  44381. var dummyScale = new IntervalScale();
  44382. dummyScale.setExtent(0, splitNumber);
  44383. dummyScale.setInterval(1); // Force all the axis fixing the maxSplitNumber.
  44384. each(indicatorAxes, function (indicatorAxis, idx) {
  44385. alignScaleTicks(indicatorAxis.scale, indicatorAxis.model, dummyScale);
  44386. });
  44387. };
  44388. Radar.prototype.convertToPixel = function (ecModel, finder, value) {
  44389. console.warn('Not implemented.');
  44390. return null;
  44391. };
  44392. Radar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  44393. console.warn('Not implemented.');
  44394. return null;
  44395. };
  44396. Radar.prototype.containPoint = function (point) {
  44397. console.warn('Not implemented.');
  44398. return false;
  44399. };
  44400. Radar.create = function (ecModel, api) {
  44401. var radarList = [];
  44402. ecModel.eachComponent('radar', function (radarModel) {
  44403. var radar = new Radar(radarModel, ecModel, api);
  44404. radarList.push(radar);
  44405. radarModel.coordinateSystem = radar;
  44406. });
  44407. ecModel.eachSeriesByType('radar', function (radarSeries) {
  44408. if (radarSeries.get('coordinateSystem') === 'radar') {
  44409. // Inject coordinate system
  44410. // @ts-ignore
  44411. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  44412. }
  44413. });
  44414. return radarList;
  44415. };
  44416. /**
  44417. * Radar dimensions is based on the data
  44418. */
  44419. Radar.dimensions = [];
  44420. return Radar;
  44421. }();
  44422. function install$7(registers) {
  44423. registers.registerCoordinateSystem('radar', Radar);
  44424. registers.registerComponentModel(RadarModel);
  44425. registers.registerComponentView(RadarView$1);
  44426. registers.registerVisual({
  44427. seriesType: 'radar',
  44428. reset: function (seriesModel) {
  44429. var data = seriesModel.getData(); // itemVisual symbol is for selected data
  44430. data.each(function (idx) {
  44431. data.setItemVisual(idx, 'legendIcon', 'roundRect');
  44432. }); // visual is for unselected data
  44433. data.setVisual('legendIcon', 'roundRect');
  44434. }
  44435. });
  44436. }
  44437. function install$8(registers) {
  44438. use(install$7);
  44439. registers.registerChartView(RadarView);
  44440. registers.registerSeriesModel(RadarSeriesModel);
  44441. registers.registerLayout(radarLayout);
  44442. registers.registerProcessor(dataFilter('radar'));
  44443. registers.registerPreprocessor(radarBackwardCompat);
  44444. }
  44445. var ATTR = '\0_ec_interaction_mutex';
  44446. function take(zr, resourceKey, userKey) {
  44447. var store = getStore(zr);
  44448. store[resourceKey] = userKey;
  44449. }
  44450. function release(zr, resourceKey, userKey) {
  44451. var store = getStore(zr);
  44452. var uKey = store[resourceKey];
  44453. if (uKey === userKey) {
  44454. store[resourceKey] = null;
  44455. }
  44456. }
  44457. function isTaken(zr, resourceKey) {
  44458. return !!getStore(zr)[resourceKey];
  44459. }
  44460. function getStore(zr) {
  44461. return zr[ATTR] || (zr[ATTR] = {});
  44462. }
  44463. /**
  44464. * payload: {
  44465. * type: 'takeGlobalCursor',
  44466. * key: 'dataZoomSelect', or 'brush', or ...,
  44467. * If no userKey, release global cursor.
  44468. * }
  44469. */
  44470. // TODO: SELF REGISTERED.
  44471. registerAction({
  44472. type: 'takeGlobalCursor',
  44473. event: 'globalCursorTaken',
  44474. update: 'update'
  44475. }, noop);
  44476. var RoamController =
  44477. /** @class */
  44478. function (_super) {
  44479. __extends(RoamController, _super);
  44480. function RoamController(zr) {
  44481. var _this = _super.call(this) || this;
  44482. _this._zr = zr; // Avoid two roamController bind the same handler
  44483. var mousedownHandler = bind(_this._mousedownHandler, _this);
  44484. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  44485. var mouseupHandler = bind(_this._mouseupHandler, _this);
  44486. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  44487. var pinchHandler = bind(_this._pinchHandler, _this);
  44488. /**
  44489. * Notice: only enable needed types. For example, if 'zoom'
  44490. * is not needed, 'zoom' should not be enabled, otherwise
  44491. * default mousewheel behaviour (scroll page) will be disabled.
  44492. */
  44493. _this.enable = function (controlType, opt) {
  44494. // Disable previous first
  44495. this.disable();
  44496. this._opt = defaults(clone(opt) || {}, {
  44497. zoomOnMouseWheel: true,
  44498. moveOnMouseMove: true,
  44499. // By default, wheel do not trigger move.
  44500. moveOnMouseWheel: false,
  44501. preventDefaultMouseMove: true
  44502. });
  44503. if (controlType == null) {
  44504. controlType = true;
  44505. }
  44506. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  44507. zr.on('mousedown', mousedownHandler);
  44508. zr.on('mousemove', mousemoveHandler);
  44509. zr.on('mouseup', mouseupHandler);
  44510. }
  44511. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  44512. zr.on('mousewheel', mousewheelHandler);
  44513. zr.on('pinch', pinchHandler);
  44514. }
  44515. };
  44516. _this.disable = function () {
  44517. zr.off('mousedown', mousedownHandler);
  44518. zr.off('mousemove', mousemoveHandler);
  44519. zr.off('mouseup', mouseupHandler);
  44520. zr.off('mousewheel', mousewheelHandler);
  44521. zr.off('pinch', pinchHandler);
  44522. };
  44523. return _this;
  44524. }
  44525. RoamController.prototype.isDragging = function () {
  44526. return this._dragging;
  44527. };
  44528. RoamController.prototype.isPinching = function () {
  44529. return this._pinching;
  44530. };
  44531. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  44532. this.pointerChecker = pointerChecker;
  44533. };
  44534. RoamController.prototype.dispose = function () {
  44535. this.disable();
  44536. };
  44537. RoamController.prototype._mousedownHandler = function (e) {
  44538. if (isMiddleOrRightButtonOnMouseUpDown(e)) {
  44539. return;
  44540. }
  44541. var el = e.target;
  44542. while (el) {
  44543. if (el.draggable) {
  44544. return;
  44545. } // check if host is draggable
  44546. el = el.__hostTarget || el.parent;
  44547. }
  44548. var x = e.offsetX;
  44549. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  44550. // Mouse can be out of target when mouse moving.
  44551. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  44552. this._x = x;
  44553. this._y = y;
  44554. this._dragging = true;
  44555. }
  44556. };
  44557. RoamController.prototype._mousemoveHandler = function (e) {
  44558. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  44559. return;
  44560. }
  44561. var x = e.offsetX;
  44562. var y = e.offsetY;
  44563. var oldX = this._x;
  44564. var oldY = this._y;
  44565. var dx = x - oldX;
  44566. var dy = y - oldY;
  44567. this._x = x;
  44568. this._y = y;
  44569. this._opt.preventDefaultMouseMove && stop(e.event);
  44570. trigger(this, 'pan', 'moveOnMouseMove', e, {
  44571. dx: dx,
  44572. dy: dy,
  44573. oldX: oldX,
  44574. oldY: oldY,
  44575. newX: x,
  44576. newY: y,
  44577. isAvailableBehavior: null
  44578. });
  44579. };
  44580. RoamController.prototype._mouseupHandler = function (e) {
  44581. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  44582. this._dragging = false;
  44583. }
  44584. };
  44585. RoamController.prototype._mousewheelHandler = function (e) {
  44586. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  44587. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  44588. var wheelDelta = e.wheelDelta;
  44589. var absWheelDeltaDelta = Math.abs(wheelDelta);
  44590. var originX = e.offsetX;
  44591. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  44592. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  44593. return;
  44594. } // If both `shouldZoom` and `shouldMove` is true, trigger
  44595. // their event both, and the final behavior is determined
  44596. // by event listener themselves.
  44597. if (shouldZoom) {
  44598. // Convenience:
  44599. // Mac and VM Windows on Mac: scroll up: zoom out.
  44600. // Windows: scroll up: zoom in.
  44601. // FIXME: Should do more test in different environment.
  44602. // wheelDelta is too complicated in difference nvironment
  44603. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  44604. // although it has been normallized by zrender.
  44605. // wheelDelta of mouse wheel is bigger than touch pad.
  44606. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  44607. var scale = wheelDelta > 0 ? factor : 1 / factor;
  44608. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  44609. scale: scale,
  44610. originX: originX,
  44611. originY: originY,
  44612. isAvailableBehavior: null
  44613. });
  44614. }
  44615. if (shouldMove) {
  44616. // FIXME: Should do more test in different environment.
  44617. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  44618. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  44619. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  44620. scrollDelta: scrollDelta,
  44621. originX: originX,
  44622. originY: originY,
  44623. isAvailableBehavior: null
  44624. });
  44625. }
  44626. };
  44627. RoamController.prototype._pinchHandler = function (e) {
  44628. if (isTaken(this._zr, 'globalPan')) {
  44629. return;
  44630. }
  44631. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  44632. checkPointerAndTrigger(this, 'zoom', null, e, {
  44633. scale: scale,
  44634. originX: e.pinchX,
  44635. originY: e.pinchY,
  44636. isAvailableBehavior: null
  44637. });
  44638. };
  44639. return RoamController;
  44640. }(Eventful);
  44641. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44642. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  44643. // When mouse is out of roamController rect,
  44644. // default befavoius should not be be disabled, otherwise
  44645. // page sliding is disabled, contrary to expectation.
  44646. stop(e.event);
  44647. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  44648. }
  44649. }
  44650. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44651. // Also provide behavior checker for event listener, for some case that
  44652. // multiple components share one listener.
  44653. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e); // TODO should not have type issue.
  44654. controller.trigger(eventName, contollerEvent);
  44655. } // settings: {
  44656. // zoomOnMouseWheel
  44657. // moveOnMouseMove
  44658. // moveOnMouseWheel
  44659. // }
  44660. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  44661. function isAvailableBehavior(behaviorToCheck, e, settings) {
  44662. var setting = settings[behaviorToCheck];
  44663. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  44664. }
  44665. /*
  44666. * Licensed to the Apache Software Foundation (ASF) under one
  44667. * or more contributor license agreements. See the NOTICE file
  44668. * distributed with this work for additional information
  44669. * regarding copyright ownership. The ASF licenses this file
  44670. * to you under the Apache License, Version 2.0 (the
  44671. * "License"); you may not use this file except in compliance
  44672. * with the License. You may obtain a copy of the License at
  44673. *
  44674. * http://www.apache.org/licenses/LICENSE-2.0
  44675. *
  44676. * Unless required by applicable law or agreed to in writing,
  44677. * software distributed under the License is distributed on an
  44678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44679. * KIND, either express or implied. See the License for the
  44680. * specific language governing permissions and limitations
  44681. * under the License.
  44682. */
  44683. /**
  44684. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44685. */
  44686. /*
  44687. * Licensed to the Apache Software Foundation (ASF) under one
  44688. * or more contributor license agreements. See the NOTICE file
  44689. * distributed with this work for additional information
  44690. * regarding copyright ownership. The ASF licenses this file
  44691. * to you under the Apache License, Version 2.0 (the
  44692. * "License"); you may not use this file except in compliance
  44693. * with the License. You may obtain a copy of the License at
  44694. *
  44695. * http://www.apache.org/licenses/LICENSE-2.0
  44696. *
  44697. * Unless required by applicable law or agreed to in writing,
  44698. * software distributed under the License is distributed on an
  44699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44700. * KIND, either express or implied. See the License for the
  44701. * specific language governing permissions and limitations
  44702. * under the License.
  44703. */
  44704. /**
  44705. * For geo and graph.
  44706. */
  44707. function updateViewOnPan(controllerHost, dx, dy) {
  44708. var target = controllerHost.target;
  44709. target.x += dx;
  44710. target.y += dy;
  44711. target.dirty();
  44712. }
  44713. /**
  44714. * For geo and graph.
  44715. */
  44716. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  44717. var target = controllerHost.target;
  44718. var zoomLimit = controllerHost.zoomLimit;
  44719. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  44720. newZoom *= zoomDelta;
  44721. if (zoomLimit) {
  44722. var zoomMin = zoomLimit.min || 0;
  44723. var zoomMax = zoomLimit.max || Infinity;
  44724. newZoom = Math.max(Math.min(zoomMax, newZoom), zoomMin);
  44725. }
  44726. var zoomScale = newZoom / controllerHost.zoom;
  44727. controllerHost.zoom = newZoom; // Keep the mouse center when scaling
  44728. target.x -= (zoomX - target.x) * (zoomScale - 1);
  44729. target.y -= (zoomY - target.y) * (zoomScale - 1);
  44730. target.scaleX *= zoomScale;
  44731. target.scaleY *= zoomScale;
  44732. target.dirty();
  44733. }
  44734. /*
  44735. * Licensed to the Apache Software Foundation (ASF) under one
  44736. * or more contributor license agreements. See the NOTICE file
  44737. * distributed with this work for additional information
  44738. * regarding copyright ownership. The ASF licenses this file
  44739. * to you under the Apache License, Version 2.0 (the
  44740. * "License"); you may not use this file except in compliance
  44741. * with the License. You may obtain a copy of the License at
  44742. *
  44743. * http://www.apache.org/licenses/LICENSE-2.0
  44744. *
  44745. * Unless required by applicable law or agreed to in writing,
  44746. * software distributed under the License is distributed on an
  44747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44748. * KIND, either express or implied. See the License for the
  44749. * specific language governing permissions and limitations
  44750. * under the License.
  44751. */
  44752. /**
  44753. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44754. */
  44755. /*
  44756. * Licensed to the Apache Software Foundation (ASF) under one
  44757. * or more contributor license agreements. See the NOTICE file
  44758. * distributed with this work for additional information
  44759. * regarding copyright ownership. The ASF licenses this file
  44760. * to you under the Apache License, Version 2.0 (the
  44761. * "License"); you may not use this file except in compliance
  44762. * with the License. You may obtain a copy of the License at
  44763. *
  44764. * http://www.apache.org/licenses/LICENSE-2.0
  44765. *
  44766. * Unless required by applicable law or agreed to in writing,
  44767. * software distributed under the License is distributed on an
  44768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44769. * KIND, either express or implied. See the License for the
  44770. * specific language governing permissions and limitations
  44771. * under the License.
  44772. */
  44773. var IRRELEVANT_EXCLUDES = {
  44774. 'axisPointer': 1,
  44775. 'tooltip': 1,
  44776. 'brush': 1
  44777. };
  44778. /**
  44779. * Avoid that: mouse click on a elements that is over geo or graph,
  44780. * but roam is triggered.
  44781. */
  44782. function onIrrelevantElement(e, api, targetCoordSysModel) {
  44783. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  44784. var coordSys = model && model.coordinateSystem;
  44785. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  44786. }
  44787. function parseXML(svg) {
  44788. if (isString(svg)) {
  44789. var parser = new DOMParser();
  44790. svg = parser.parseFromString(svg, 'text/xml');
  44791. }
  44792. var svgNode = svg;
  44793. if (svgNode.nodeType === 9) {
  44794. svgNode = svgNode.firstChild;
  44795. }
  44796. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  44797. svgNode = svgNode.nextSibling;
  44798. }
  44799. return svgNode;
  44800. }
  44801. var nodeParsers;
  44802. var INHERITABLE_STYLE_ATTRIBUTES_MAP = {
  44803. 'fill': 'fill',
  44804. 'stroke': 'stroke',
  44805. 'stroke-width': 'lineWidth',
  44806. 'opacity': 'opacity',
  44807. 'fill-opacity': 'fillOpacity',
  44808. 'stroke-opacity': 'strokeOpacity',
  44809. 'stroke-dasharray': 'lineDash',
  44810. 'stroke-dashoffset': 'lineDashOffset',
  44811. 'stroke-linecap': 'lineCap',
  44812. 'stroke-linejoin': 'lineJoin',
  44813. 'stroke-miterlimit': 'miterLimit',
  44814. 'font-family': 'fontFamily',
  44815. 'font-size': 'fontSize',
  44816. 'font-style': 'fontStyle',
  44817. 'font-weight': 'fontWeight',
  44818. 'text-anchor': 'textAlign',
  44819. 'visibility': 'visibility',
  44820. 'display': 'display'
  44821. };
  44822. var INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP);
  44823. var SELF_STYLE_ATTRIBUTES_MAP = {
  44824. 'alignment-baseline': 'textBaseline',
  44825. 'stop-color': 'stopColor'
  44826. };
  44827. var SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP);
  44828. var SVGParser = (function () {
  44829. function SVGParser() {
  44830. this._defs = {};
  44831. this._root = null;
  44832. }
  44833. SVGParser.prototype.parse = function (xml, opt) {
  44834. opt = opt || {};
  44835. var svg = parseXML(xml);
  44836. if ("development" !== 'production') {
  44837. if (!svg) {
  44838. throw new Error('Illegal svg');
  44839. }
  44840. }
  44841. this._defsUsePending = [];
  44842. var root = new Group();
  44843. this._root = root;
  44844. var named = [];
  44845. var viewBox = svg.getAttribute('viewBox') || '';
  44846. var width = parseFloat((svg.getAttribute('width') || opt.width));
  44847. var height = parseFloat((svg.getAttribute('height') || opt.height));
  44848. isNaN(width) && (width = null);
  44849. isNaN(height) && (height = null);
  44850. parseAttributes(svg, root, null, true, false);
  44851. var child = svg.firstChild;
  44852. while (child) {
  44853. this._parseNode(child, root, named, null, false, false);
  44854. child = child.nextSibling;
  44855. }
  44856. applyDefs(this._defs, this._defsUsePending);
  44857. this._defsUsePending = [];
  44858. var viewBoxRect;
  44859. var viewBoxTransform;
  44860. if (viewBox) {
  44861. var viewBoxArr = splitNumberSequence(viewBox);
  44862. if (viewBoxArr.length >= 4) {
  44863. viewBoxRect = {
  44864. x: parseFloat((viewBoxArr[0] || 0)),
  44865. y: parseFloat((viewBoxArr[1] || 0)),
  44866. width: parseFloat(viewBoxArr[2]),
  44867. height: parseFloat(viewBoxArr[3])
  44868. };
  44869. }
  44870. }
  44871. if (viewBoxRect && width != null && height != null) {
  44872. viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height });
  44873. if (!opt.ignoreViewBox) {
  44874. var elRoot = root;
  44875. root = new Group();
  44876. root.add(elRoot);
  44877. elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale;
  44878. elRoot.x = viewBoxTransform.x;
  44879. elRoot.y = viewBoxTransform.y;
  44880. }
  44881. }
  44882. if (!opt.ignoreRootClip && width != null && height != null) {
  44883. root.setClipPath(new Rect({
  44884. shape: { x: 0, y: 0, width: width, height: height }
  44885. }));
  44886. }
  44887. return {
  44888. root: root,
  44889. width: width,
  44890. height: height,
  44891. viewBoxRect: viewBoxRect,
  44892. viewBoxTransform: viewBoxTransform,
  44893. named: named
  44894. };
  44895. };
  44896. SVGParser.prototype._parseNode = function (xmlNode, parentGroup, named, namedFrom, isInDefs, isInText) {
  44897. var nodeName = xmlNode.nodeName.toLowerCase();
  44898. var el;
  44899. var namedFromForSub = namedFrom;
  44900. if (nodeName === 'defs') {
  44901. isInDefs = true;
  44902. }
  44903. if (nodeName === 'text') {
  44904. isInText = true;
  44905. }
  44906. if (nodeName === 'defs' || nodeName === 'switch') {
  44907. el = parentGroup;
  44908. }
  44909. else {
  44910. if (!isInDefs) {
  44911. var parser_1 = nodeParsers[nodeName];
  44912. if (parser_1 && hasOwn(nodeParsers, nodeName)) {
  44913. el = parser_1.call(this, xmlNode, parentGroup);
  44914. var nameAttr = xmlNode.getAttribute('name');
  44915. if (nameAttr) {
  44916. var newNamed = {
  44917. name: nameAttr,
  44918. namedFrom: null,
  44919. svgNodeTagLower: nodeName,
  44920. el: el
  44921. };
  44922. named.push(newNamed);
  44923. if (nodeName === 'g') {
  44924. namedFromForSub = newNamed;
  44925. }
  44926. }
  44927. else if (namedFrom) {
  44928. named.push({
  44929. name: namedFrom.name,
  44930. namedFrom: namedFrom,
  44931. svgNodeTagLower: nodeName,
  44932. el: el
  44933. });
  44934. }
  44935. parentGroup.add(el);
  44936. }
  44937. }
  44938. var parser = paintServerParsers[nodeName];
  44939. if (parser && hasOwn(paintServerParsers, nodeName)) {
  44940. var def = parser.call(this, xmlNode);
  44941. var id = xmlNode.getAttribute('id');
  44942. if (id) {
  44943. this._defs[id] = def;
  44944. }
  44945. }
  44946. }
  44947. if (el && el.isGroup) {
  44948. var child = xmlNode.firstChild;
  44949. while (child) {
  44950. if (child.nodeType === 1) {
  44951. this._parseNode(child, el, named, namedFromForSub, isInDefs, isInText);
  44952. }
  44953. else if (child.nodeType === 3 && isInText) {
  44954. this._parseText(child, el);
  44955. }
  44956. child = child.nextSibling;
  44957. }
  44958. }
  44959. };
  44960. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  44961. var text = new TSpan({
  44962. style: {
  44963. text: xmlNode.textContent
  44964. },
  44965. silent: true,
  44966. x: this._textX || 0,
  44967. y: this._textY || 0
  44968. });
  44969. inheritStyle(parentGroup, text);
  44970. parseAttributes(xmlNode, text, this._defsUsePending, false, false);
  44971. applyTextAlignment(text, parentGroup);
  44972. var textStyle = text.style;
  44973. var fontSize = textStyle.fontSize;
  44974. if (fontSize && fontSize < 9) {
  44975. textStyle.fontSize = 9;
  44976. text.scaleX *= fontSize / 9;
  44977. text.scaleY *= fontSize / 9;
  44978. }
  44979. var font = (textStyle.fontSize || textStyle.fontFamily) && [
  44980. textStyle.fontStyle,
  44981. textStyle.fontWeight,
  44982. (textStyle.fontSize || 12) + 'px',
  44983. textStyle.fontFamily || 'sans-serif'
  44984. ].join(' ');
  44985. textStyle.font = font;
  44986. var rect = text.getBoundingRect();
  44987. this._textX += rect.width;
  44988. parentGroup.add(text);
  44989. return text;
  44990. };
  44991. SVGParser.internalField = (function () {
  44992. nodeParsers = {
  44993. 'g': function (xmlNode, parentGroup) {
  44994. var g = new Group();
  44995. inheritStyle(parentGroup, g);
  44996. parseAttributes(xmlNode, g, this._defsUsePending, false, false);
  44997. return g;
  44998. },
  44999. 'rect': function (xmlNode, parentGroup) {
  45000. var rect = new Rect();
  45001. inheritStyle(parentGroup, rect);
  45002. parseAttributes(xmlNode, rect, this._defsUsePending, false, false);
  45003. rect.setShape({
  45004. x: parseFloat(xmlNode.getAttribute('x') || '0'),
  45005. y: parseFloat(xmlNode.getAttribute('y') || '0'),
  45006. width: parseFloat(xmlNode.getAttribute('width') || '0'),
  45007. height: parseFloat(xmlNode.getAttribute('height') || '0')
  45008. });
  45009. rect.silent = true;
  45010. return rect;
  45011. },
  45012. 'circle': function (xmlNode, parentGroup) {
  45013. var circle = new Circle();
  45014. inheritStyle(parentGroup, circle);
  45015. parseAttributes(xmlNode, circle, this._defsUsePending, false, false);
  45016. circle.setShape({
  45017. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  45018. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  45019. r: parseFloat(xmlNode.getAttribute('r') || '0')
  45020. });
  45021. circle.silent = true;
  45022. return circle;
  45023. },
  45024. 'line': function (xmlNode, parentGroup) {
  45025. var line = new Line();
  45026. inheritStyle(parentGroup, line);
  45027. parseAttributes(xmlNode, line, this._defsUsePending, false, false);
  45028. line.setShape({
  45029. x1: parseFloat(xmlNode.getAttribute('x1') || '0'),
  45030. y1: parseFloat(xmlNode.getAttribute('y1') || '0'),
  45031. x2: parseFloat(xmlNode.getAttribute('x2') || '0'),
  45032. y2: parseFloat(xmlNode.getAttribute('y2') || '0')
  45033. });
  45034. line.silent = true;
  45035. return line;
  45036. },
  45037. 'ellipse': function (xmlNode, parentGroup) {
  45038. var ellipse = new Ellipse();
  45039. inheritStyle(parentGroup, ellipse);
  45040. parseAttributes(xmlNode, ellipse, this._defsUsePending, false, false);
  45041. ellipse.setShape({
  45042. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  45043. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  45044. rx: parseFloat(xmlNode.getAttribute('rx') || '0'),
  45045. ry: parseFloat(xmlNode.getAttribute('ry') || '0')
  45046. });
  45047. ellipse.silent = true;
  45048. return ellipse;
  45049. },
  45050. 'polygon': function (xmlNode, parentGroup) {
  45051. var pointsStr = xmlNode.getAttribute('points');
  45052. var pointsArr;
  45053. if (pointsStr) {
  45054. pointsArr = parsePoints(pointsStr);
  45055. }
  45056. var polygon = new Polygon({
  45057. shape: {
  45058. points: pointsArr || []
  45059. },
  45060. silent: true
  45061. });
  45062. inheritStyle(parentGroup, polygon);
  45063. parseAttributes(xmlNode, polygon, this._defsUsePending, false, false);
  45064. return polygon;
  45065. },
  45066. 'polyline': function (xmlNode, parentGroup) {
  45067. var pointsStr = xmlNode.getAttribute('points');
  45068. var pointsArr;
  45069. if (pointsStr) {
  45070. pointsArr = parsePoints(pointsStr);
  45071. }
  45072. var polyline = new Polyline({
  45073. shape: {
  45074. points: pointsArr || []
  45075. },
  45076. silent: true
  45077. });
  45078. inheritStyle(parentGroup, polyline);
  45079. parseAttributes(xmlNode, polyline, this._defsUsePending, false, false);
  45080. return polyline;
  45081. },
  45082. 'image': function (xmlNode, parentGroup) {
  45083. var img = new ZRImage();
  45084. inheritStyle(parentGroup, img);
  45085. parseAttributes(xmlNode, img, this._defsUsePending, false, false);
  45086. img.setStyle({
  45087. image: xmlNode.getAttribute('xlink:href') || xmlNode.getAttribute('href'),
  45088. x: +xmlNode.getAttribute('x'),
  45089. y: +xmlNode.getAttribute('y'),
  45090. width: +xmlNode.getAttribute('width'),
  45091. height: +xmlNode.getAttribute('height')
  45092. });
  45093. img.silent = true;
  45094. return img;
  45095. },
  45096. 'text': function (xmlNode, parentGroup) {
  45097. var x = xmlNode.getAttribute('x') || '0';
  45098. var y = xmlNode.getAttribute('y') || '0';
  45099. var dx = xmlNode.getAttribute('dx') || '0';
  45100. var dy = xmlNode.getAttribute('dy') || '0';
  45101. this._textX = parseFloat(x) + parseFloat(dx);
  45102. this._textY = parseFloat(y) + parseFloat(dy);
  45103. var g = new Group();
  45104. inheritStyle(parentGroup, g);
  45105. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  45106. return g;
  45107. },
  45108. 'tspan': function (xmlNode, parentGroup) {
  45109. var x = xmlNode.getAttribute('x');
  45110. var y = xmlNode.getAttribute('y');
  45111. if (x != null) {
  45112. this._textX = parseFloat(x);
  45113. }
  45114. if (y != null) {
  45115. this._textY = parseFloat(y);
  45116. }
  45117. var dx = xmlNode.getAttribute('dx') || '0';
  45118. var dy = xmlNode.getAttribute('dy') || '0';
  45119. var g = new Group();
  45120. inheritStyle(parentGroup, g);
  45121. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  45122. this._textX += parseFloat(dx);
  45123. this._textY += parseFloat(dy);
  45124. return g;
  45125. },
  45126. 'path': function (xmlNode, parentGroup) {
  45127. var d = xmlNode.getAttribute('d') || '';
  45128. var path = createFromString(d);
  45129. inheritStyle(parentGroup, path);
  45130. parseAttributes(xmlNode, path, this._defsUsePending, false, false);
  45131. path.silent = true;
  45132. return path;
  45133. }
  45134. };
  45135. })();
  45136. return SVGParser;
  45137. }());
  45138. var paintServerParsers = {
  45139. 'lineargradient': function (xmlNode) {
  45140. var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);
  45141. var y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10);
  45142. var x2 = parseInt(xmlNode.getAttribute('x2') || '10', 10);
  45143. var y2 = parseInt(xmlNode.getAttribute('y2') || '0', 10);
  45144. var gradient = new LinearGradient(x1, y1, x2, y2);
  45145. parsePaintServerUnit(xmlNode, gradient);
  45146. parseGradientColorStops(xmlNode, gradient);
  45147. return gradient;
  45148. },
  45149. 'radialgradient': function (xmlNode) {
  45150. var cx = parseInt(xmlNode.getAttribute('cx') || '0', 10);
  45151. var cy = parseInt(xmlNode.getAttribute('cy') || '0', 10);
  45152. var r = parseInt(xmlNode.getAttribute('r') || '0', 10);
  45153. var gradient = new RadialGradient(cx, cy, r);
  45154. parsePaintServerUnit(xmlNode, gradient);
  45155. parseGradientColorStops(xmlNode, gradient);
  45156. return gradient;
  45157. }
  45158. };
  45159. function parsePaintServerUnit(xmlNode, gradient) {
  45160. var gradientUnits = xmlNode.getAttribute('gradientUnits');
  45161. if (gradientUnits === 'userSpaceOnUse') {
  45162. gradient.global = true;
  45163. }
  45164. }
  45165. function parseGradientColorStops(xmlNode, gradient) {
  45166. var stop = xmlNode.firstChild;
  45167. while (stop) {
  45168. if (stop.nodeType === 1
  45169. && stop.nodeName.toLocaleLowerCase() === 'stop') {
  45170. var offsetStr = stop.getAttribute('offset');
  45171. var offset = void 0;
  45172. if (offsetStr && offsetStr.indexOf('%') > 0) {
  45173. offset = parseInt(offsetStr, 10) / 100;
  45174. }
  45175. else if (offsetStr) {
  45176. offset = parseFloat(offsetStr);
  45177. }
  45178. else {
  45179. offset = 0;
  45180. }
  45181. var styleVals = {};
  45182. parseInlineStyle(stop, styleVals, styleVals);
  45183. var stopColor = styleVals.stopColor
  45184. || stop.getAttribute('stop-color')
  45185. || '#000000';
  45186. gradient.colorStops.push({
  45187. offset: offset,
  45188. color: stopColor
  45189. });
  45190. }
  45191. stop = stop.nextSibling;
  45192. }
  45193. }
  45194. function inheritStyle(parent, child) {
  45195. if (parent && parent.__inheritedStyle) {
  45196. if (!child.__inheritedStyle) {
  45197. child.__inheritedStyle = {};
  45198. }
  45199. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  45200. }
  45201. }
  45202. function parsePoints(pointsString) {
  45203. var list = splitNumberSequence(pointsString);
  45204. var points = [];
  45205. for (var i = 0; i < list.length; i += 2) {
  45206. var x = parseFloat(list[i]);
  45207. var y = parseFloat(list[i + 1]);
  45208. points.push([x, y]);
  45209. }
  45210. return points;
  45211. }
  45212. function parseAttributes(xmlNode, el, defsUsePending, onlyInlineStyle, isTextGroup) {
  45213. var disp = el;
  45214. var inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {};
  45215. var selfStyle = {};
  45216. if (xmlNode.nodeType === 1) {
  45217. parseTransformAttribute(xmlNode, el);
  45218. parseInlineStyle(xmlNode, inheritedStyle, selfStyle);
  45219. if (!onlyInlineStyle) {
  45220. parseAttributeStyle(xmlNode, inheritedStyle, selfStyle);
  45221. }
  45222. }
  45223. disp.style = disp.style || {};
  45224. if (inheritedStyle.fill != null) {
  45225. disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending);
  45226. }
  45227. if (inheritedStyle.stroke != null) {
  45228. disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending);
  45229. }
  45230. each([
  45231. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  45232. ], function (propName) {
  45233. if (inheritedStyle[propName] != null) {
  45234. disp.style[propName] = parseFloat(inheritedStyle[propName]);
  45235. }
  45236. });
  45237. each([
  45238. 'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign'
  45239. ], function (propName) {
  45240. if (inheritedStyle[propName] != null) {
  45241. disp.style[propName] = inheritedStyle[propName];
  45242. }
  45243. });
  45244. if (isTextGroup) {
  45245. disp.__selfStyle = selfStyle;
  45246. }
  45247. if (inheritedStyle.lineDash) {
  45248. disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function (str) {
  45249. return parseFloat(str);
  45250. });
  45251. }
  45252. if (inheritedStyle.visibility === 'hidden' || inheritedStyle.visibility === 'collapse') {
  45253. disp.invisible = true;
  45254. }
  45255. if (inheritedStyle.display === 'none') {
  45256. disp.ignore = true;
  45257. }
  45258. }
  45259. function applyTextAlignment(text, parentGroup) {
  45260. var parentSelfStyle = parentGroup.__selfStyle;
  45261. if (parentSelfStyle) {
  45262. var textBaseline = parentSelfStyle.textBaseline;
  45263. var zrTextBaseline = textBaseline;
  45264. if (!textBaseline || textBaseline === 'auto') {
  45265. zrTextBaseline = 'alphabetic';
  45266. }
  45267. else if (textBaseline === 'baseline') {
  45268. zrTextBaseline = 'alphabetic';
  45269. }
  45270. else if (textBaseline === 'before-edge' || textBaseline === 'text-before-edge') {
  45271. zrTextBaseline = 'top';
  45272. }
  45273. else if (textBaseline === 'after-edge' || textBaseline === 'text-after-edge') {
  45274. zrTextBaseline = 'bottom';
  45275. }
  45276. else if (textBaseline === 'central' || textBaseline === 'mathematical') {
  45277. zrTextBaseline = 'middle';
  45278. }
  45279. text.style.textBaseline = zrTextBaseline;
  45280. }
  45281. var parentInheritedStyle = parentGroup.__inheritedStyle;
  45282. if (parentInheritedStyle) {
  45283. var textAlign = parentInheritedStyle.textAlign;
  45284. var zrTextAlign = textAlign;
  45285. if (textAlign) {
  45286. if (textAlign === 'middle') {
  45287. zrTextAlign = 'center';
  45288. }
  45289. text.style.textAlign = zrTextAlign;
  45290. }
  45291. }
  45292. }
  45293. var urlRegex = /^url\(\s*#(.*?)\)/;
  45294. function getFillStrokeStyle(el, method, str, defsUsePending) {
  45295. var urlMatch = str && str.match(urlRegex);
  45296. if (urlMatch) {
  45297. var url = trim(urlMatch[1]);
  45298. defsUsePending.push([el, method, url]);
  45299. return;
  45300. }
  45301. if (str === 'none') {
  45302. str = null;
  45303. }
  45304. return str;
  45305. }
  45306. function applyDefs(defs, defsUsePending) {
  45307. for (var i = 0; i < defsUsePending.length; i++) {
  45308. var item = defsUsePending[i];
  45309. item[0].style[item[1]] = defs[item[2]];
  45310. }
  45311. }
  45312. var numberReg$1 = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  45313. function splitNumberSequence(rawStr) {
  45314. return rawStr.match(numberReg$1) || [];
  45315. }
  45316. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g;
  45317. var DEGREE_TO_ANGLE = Math.PI / 180;
  45318. function parseTransformAttribute(xmlNode, node) {
  45319. var transform = xmlNode.getAttribute('transform');
  45320. if (transform) {
  45321. transform = transform.replace(/,/g, ' ');
  45322. var transformOps_1 = [];
  45323. var mt = null;
  45324. transform.replace(transformRegex, function (str, type, value) {
  45325. transformOps_1.push(type, value);
  45326. return '';
  45327. });
  45328. for (var i = transformOps_1.length - 1; i > 0; i -= 2) {
  45329. var value = transformOps_1[i];
  45330. var type = transformOps_1[i - 1];
  45331. var valueArr = splitNumberSequence(value);
  45332. mt = mt || create$1();
  45333. switch (type) {
  45334. case 'translate':
  45335. translate(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
  45336. break;
  45337. case 'scale':
  45338. scale$1(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
  45339. break;
  45340. case 'rotate':
  45341. rotate(mt, mt, -parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45342. break;
  45343. case 'skewX':
  45344. var sx = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45345. mul$1(mt, [1, 0, sx, 1, 0, 0], mt);
  45346. break;
  45347. case 'skewY':
  45348. var sy = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45349. mul$1(mt, [1, sy, 0, 1, 0, 0], mt);
  45350. break;
  45351. case 'matrix':
  45352. mt[0] = parseFloat(valueArr[0]);
  45353. mt[1] = parseFloat(valueArr[1]);
  45354. mt[2] = parseFloat(valueArr[2]);
  45355. mt[3] = parseFloat(valueArr[3]);
  45356. mt[4] = parseFloat(valueArr[4]);
  45357. mt[5] = parseFloat(valueArr[5]);
  45358. break;
  45359. }
  45360. }
  45361. node.setLocalTransform(mt);
  45362. }
  45363. }
  45364. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  45365. function parseInlineStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  45366. var style = xmlNode.getAttribute('style');
  45367. if (!style) {
  45368. return;
  45369. }
  45370. styleRegex.lastIndex = 0;
  45371. var styleRegResult;
  45372. while ((styleRegResult = styleRegex.exec(style)) != null) {
  45373. var svgStlAttr = styleRegResult[1];
  45374. var zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  45375. ? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  45376. : null;
  45377. if (zrInheritableStlAttr) {
  45378. inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2];
  45379. }
  45380. var zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  45381. ? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  45382. : null;
  45383. if (zrSelfStlAttr) {
  45384. selfStyleResult[zrSelfStlAttr] = styleRegResult[2];
  45385. }
  45386. }
  45387. }
  45388. function parseAttributeStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  45389. for (var i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  45390. var svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i];
  45391. var attrValue = xmlNode.getAttribute(svgAttrName);
  45392. if (attrValue != null) {
  45393. inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  45394. }
  45395. }
  45396. for (var i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  45397. var svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i];
  45398. var attrValue = xmlNode.getAttribute(svgAttrName);
  45399. if (attrValue != null) {
  45400. selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  45401. }
  45402. }
  45403. }
  45404. function makeViewBoxTransform(viewBoxRect, boundingRect) {
  45405. var scaleX = boundingRect.width / viewBoxRect.width;
  45406. var scaleY = boundingRect.height / viewBoxRect.height;
  45407. var scale = Math.min(scaleX, scaleY);
  45408. return {
  45409. scale: scale,
  45410. x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2),
  45411. y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2)
  45412. };
  45413. }
  45414. function parseSVG(xml, opt) {
  45415. var parser = new SVGParser();
  45416. return parser.parse(xml, opt);
  45417. }
  45418. /**
  45419. * "region available" means that: enable users to set attribute `name="xxx"` on those tags
  45420. * to make it be a region.
  45421. * 1. region styles and its label styles can be defined in echarts opton:
  45422. * ```js
  45423. * geo: {
  45424. * regions: [{
  45425. * name: 'xxx',
  45426. * itemStyle: { ... },
  45427. * label: { ... }
  45428. * }, {
  45429. * ...
  45430. * },
  45431. * ...]
  45432. * };
  45433. * ```
  45434. * 2. name can be duplicated in different SVG tag. All of the tags with the same name share
  45435. * a region option. For exampel if there are two <path> representing two lung lobes. They have
  45436. * no common parents but both of them need to display label "lung" inside.
  45437. */
  45438. var REGION_AVAILABLE_SVG_TAG_MAP = createHashMap(['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path', // <text> <tspan> are also enabled because some SVG might paint text itself,
  45439. // but still need to trigger events or tooltip.
  45440. 'text', 'tspan', // <g> is also enabled because this case: if multiple tags share one name
  45441. // and need label displayed, every tags will display the name, which is not
  45442. // expected. So we can put them into a <g name="xxx">. Thereby only one label
  45443. // displayed and located based on the bounding rect of the <g>.
  45444. 'g']);
  45445. var GeoSVGResource =
  45446. /** @class */
  45447. function () {
  45448. function GeoSVGResource(mapName, svg) {
  45449. this.type = 'geoSVG'; // All used graphics. key: hostKey, value: root
  45450. this._usedGraphicMap = createHashMap(); // All unused graphics.
  45451. this._freedGraphics = [];
  45452. this._mapName = mapName; // Only perform parse to XML object here, which might be time
  45453. // consiming for large SVG.
  45454. // Although convert XML to zrender element is also time consiming,
  45455. // if we do it here, the clone of zrender elements has to be
  45456. // required. So we do it once for each geo instance, util real
  45457. // performance issues call for optimizing it.
  45458. this._parsedXML = parseXML(svg);
  45459. }
  45460. GeoSVGResource.prototype.load = function ()
  45461. /* nameMap: NameMap */
  45462. {
  45463. // In the "load" stage, graphic need to be built to
  45464. // get boundingRect for geo coordinate system.
  45465. var firstGraphic = this._firstGraphic; // Create the return data structure only when first graphic created.
  45466. // Because they will be used in geo coordinate system update stage,
  45467. // and `regions` will be mounted at `geo` coordinate system,
  45468. // in which there is no "view" info, so that it should better not to
  45469. // make references to graphic elements.
  45470. if (!firstGraphic) {
  45471. firstGraphic = this._firstGraphic = this._buildGraphic(this._parsedXML);
  45472. this._freedGraphics.push(firstGraphic);
  45473. this._boundingRect = this._firstGraphic.boundingRect.clone(); // PENDING: `nameMap` will not be supported until some real requirement come.
  45474. // if (nameMap) {
  45475. // named = applyNameMap(named, nameMap);
  45476. // }
  45477. var _a = createRegions(firstGraphic.named),
  45478. regions = _a.regions,
  45479. regionsMap = _a.regionsMap;
  45480. this._regions = regions;
  45481. this._regionsMap = regionsMap;
  45482. }
  45483. return {
  45484. boundingRect: this._boundingRect,
  45485. regions: this._regions,
  45486. regionsMap: this._regionsMap
  45487. };
  45488. };
  45489. GeoSVGResource.prototype._buildGraphic = function (svgXML) {
  45490. var result;
  45491. var rootFromParse;
  45492. try {
  45493. result = svgXML && parseSVG(svgXML, {
  45494. ignoreViewBox: true,
  45495. ignoreRootClip: true
  45496. }) || {};
  45497. rootFromParse = result.root;
  45498. assert(rootFromParse != null);
  45499. } catch (e) {
  45500. throw new Error('Invalid svg format\n' + e.message);
  45501. } // Note: we keep the covenant that the root has no transform. So always add an extra root.
  45502. var root = new Group();
  45503. root.add(rootFromParse);
  45504. root.isGeoSVGGraphicRoot = true; // [THE_RULE_OF_VIEWPORT_AND_VIEWBOX]
  45505. //
  45506. // Consider: `<svg width="..." height="..." viewBox="...">`
  45507. // - the `width/height` we call it `svgWidth/svgHeight` for short.
  45508. // - `(0, 0, svgWidth, svgHeight)` defines the viewport of the SVG, or say,
  45509. // "viewport boundingRect", or `boundingRect` for short.
  45510. // - `viewBox` defines the transform from the real content ot the viewport.
  45511. // `viewBox` has the same unit as the content of SVG.
  45512. // If `viewBox` exists, a transform is defined, so the unit of `svgWidth/svgHeight` become
  45513. // different from the content of SVG. Otherwise, they are the same.
  45514. //
  45515. // If both `svgWidth/svgHeight/viewBox` are specified in a SVG file, the transform rule will be:
  45516. // 0. `boundingRect` is `(0, 0, svgWidth, svgHeight)`. Set it to Geo['_rect'] (View['_rect']).
  45517. // 1. Make a transform from `viewBox` to `boundingRect`.
  45518. // Note: only support `preserveAspectRatio 'xMidYMid'` here. That is, this transform will preserve
  45519. // the aspect ratio.
  45520. // 2. Make a transform from boundingRect to Geo['_viewRect'] (View['_viewRect'])
  45521. // (`Geo`/`View` will do this job).
  45522. // Note: this transform might not preserve aspect radio, which depending on how users specify
  45523. // viewRect in echarts option (e.g., `geo.left/top/width/height` will not preserve aspect ratio,
  45524. // but `geo.layoutCenter/layoutSize` will preserve aspect ratio).
  45525. //
  45526. // If `svgWidth/svgHeight` not specified, we use `viewBox` as the `boundingRect` to make the SVG
  45527. // layout look good.
  45528. //
  45529. // If neither `svgWidth/svgHeight` nor `viewBox` are not specified, we calculate the boundingRect
  45530. // of the SVG content and use them to make SVG layout look good.
  45531. var svgWidth = result.width;
  45532. var svgHeight = result.height;
  45533. var viewBoxRect = result.viewBoxRect;
  45534. var boundingRect = this._boundingRect;
  45535. if (!boundingRect) {
  45536. var bRectX = void 0;
  45537. var bRectY = void 0;
  45538. var bRectWidth = void 0;
  45539. var bRectHeight = void 0;
  45540. if (svgWidth != null) {
  45541. bRectX = 0;
  45542. bRectWidth = svgWidth;
  45543. } else if (viewBoxRect) {
  45544. bRectX = viewBoxRect.x;
  45545. bRectWidth = viewBoxRect.width;
  45546. }
  45547. if (svgHeight != null) {
  45548. bRectY = 0;
  45549. bRectHeight = svgHeight;
  45550. } else if (viewBoxRect) {
  45551. bRectY = viewBoxRect.y;
  45552. bRectHeight = viewBoxRect.height;
  45553. } // If both viewBox and svgWidth/svgHeight not specified,
  45554. // we have to determine how to layout those element to make them look good.
  45555. if (bRectX == null || bRectY == null) {
  45556. var calculatedBoundingRect = rootFromParse.getBoundingRect();
  45557. if (bRectX == null) {
  45558. bRectX = calculatedBoundingRect.x;
  45559. bRectWidth = calculatedBoundingRect.width;
  45560. }
  45561. if (bRectY == null) {
  45562. bRectY = calculatedBoundingRect.y;
  45563. bRectHeight = calculatedBoundingRect.height;
  45564. }
  45565. }
  45566. boundingRect = this._boundingRect = new BoundingRect(bRectX, bRectY, bRectWidth, bRectHeight);
  45567. }
  45568. if (viewBoxRect) {
  45569. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect); // Only support `preserveAspectRatio 'xMidYMid'`
  45570. rootFromParse.scaleX = rootFromParse.scaleY = viewBoxTransform.scale;
  45571. rootFromParse.x = viewBoxTransform.x;
  45572. rootFromParse.y = viewBoxTransform.y;
  45573. } // SVG needs to clip based on `viewBox`. And some SVG files really rely on this feature.
  45574. // They do not strictly confine all of the content inside a display rect, but deliberately
  45575. // use a `viewBox` to define a displayable rect.
  45576. // PENDING:
  45577. // The drawback of the `setClipPath` here is: the region label (genereted by echarts) near the
  45578. // edge might also be clipped, because region labels are put as `textContent` of the SVG path.
  45579. root.setClipPath(new Rect({
  45580. shape: boundingRect.plain()
  45581. }));
  45582. var named = [];
  45583. each(result.named, function (namedItem) {
  45584. if (REGION_AVAILABLE_SVG_TAG_MAP.get(namedItem.svgNodeTagLower) != null) {
  45585. named.push(namedItem);
  45586. setSilent(namedItem.el);
  45587. }
  45588. });
  45589. return {
  45590. root: root,
  45591. boundingRect: boundingRect,
  45592. named: named
  45593. };
  45594. };
  45595. /**
  45596. * Consider:
  45597. * (1) One graphic element can not be shared by different `geoView` running simultaneously.
  45598. * Notice, also need to consider multiple echarts instances share a `mapRecord`.
  45599. * (2) Converting SVG to graphic elements is time consuming.
  45600. * (3) In the current architecture, `load` should be called frequently to get boundingRect,
  45601. * and it is called without view info.
  45602. * So we maintain graphic elements in this module, and enables `view` to use/return these
  45603. * graphics from/to the pool with it's uid.
  45604. */
  45605. GeoSVGResource.prototype.useGraphic = function (hostKey
  45606. /* , nameMap: NameMap */
  45607. ) {
  45608. var usedRootMap = this._usedGraphicMap;
  45609. var svgGraphic = usedRootMap.get(hostKey);
  45610. if (svgGraphic) {
  45611. return svgGraphic;
  45612. }
  45613. svgGraphic = this._freedGraphics.pop() // use the first boundingRect to avoid duplicated boundingRect calculation.
  45614. || this._buildGraphic(this._parsedXML);
  45615. usedRootMap.set(hostKey, svgGraphic); // PENDING: `nameMap` will not be supported until some real requirement come.
  45616. // `nameMap` can only be obtained from echarts option.
  45617. // The original `named` must not be modified.
  45618. // if (nameMap) {
  45619. // svgGraphic = extend({}, svgGraphic);
  45620. // svgGraphic.named = applyNameMap(svgGraphic.named, nameMap);
  45621. // }
  45622. return svgGraphic;
  45623. };
  45624. GeoSVGResource.prototype.freeGraphic = function (hostKey) {
  45625. var usedRootMap = this._usedGraphicMap;
  45626. var svgGraphic = usedRootMap.get(hostKey);
  45627. if (svgGraphic) {
  45628. usedRootMap.removeKey(hostKey);
  45629. this._freedGraphics.push(svgGraphic);
  45630. }
  45631. };
  45632. return GeoSVGResource;
  45633. }();
  45634. function setSilent(el) {
  45635. // Only named element has silent: false, other elements should
  45636. // act as background and has no user interaction.
  45637. el.silent = false; // text|tspan will be converted to group.
  45638. if (el.isGroup) {
  45639. el.traverse(function (child) {
  45640. child.silent = false;
  45641. });
  45642. }
  45643. }
  45644. function createRegions(named) {
  45645. var regions = [];
  45646. var regionsMap = createHashMap(); // Create resions only for the first graphic.
  45647. each(named, function (namedItem) {
  45648. // Region has feature to calculate center for tooltip or other features.
  45649. // If there is a <g name="xxx">, the center should be the center of the
  45650. // bounding rect of the g.
  45651. if (namedItem.namedFrom != null) {
  45652. return;
  45653. }
  45654. var region = new GeoSVGRegion(namedItem.name, namedItem.el); // PENDING: if `nameMap` supported, this region can not be mounted on
  45655. // `this`, but can only be created each time `load()` called.
  45656. regions.push(region); // PENDING: if multiple tag named with the same name, only one will be
  45657. // found by `_regionsMap`. `_regionsMap` is used to find a coordinate
  45658. // by name. We use `region.getCenter()` as the coordinate.
  45659. regionsMap.set(namedItem.name, region);
  45660. });
  45661. return {
  45662. regions: regions,
  45663. regionsMap: regionsMap
  45664. };
  45665. } // PENDING: `nameMap` will not be supported until some real requirement come.
  45666. // /**
  45667. // * Use the alias in geoNameMap.
  45668. // * The input `named` must not be modified.
  45669. // */
  45670. // function applyNameMap(
  45671. // named: GeoSVGGraphicRecord['named'],
  45672. // nameMap: NameMap
  45673. // ): GeoSVGGraphicRecord['named'] {
  45674. // const result = [] as GeoSVGGraphicRecord['named'];
  45675. // for (let i = 0; i < named.length; i++) {
  45676. // let regionGraphic = named[i];
  45677. // const name = regionGraphic.name;
  45678. // if (nameMap && nameMap.hasOwnProperty(name)) {
  45679. // regionGraphic = extend({}, regionGraphic);
  45680. // regionGraphic.name = name;
  45681. // }
  45682. // result.push(regionGraphic);
  45683. // }
  45684. // return result;
  45685. // }
  45686. var geoCoord = [126, 25];
  45687. var nanhaiName = '南海诸岛';
  45688. var points$1 = [[[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7], [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]], [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]], [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]], [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]], [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]], [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]], [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]], [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]], [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]], [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]], [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]], [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4], [1, 92.4], [1, 3.5], [0, 3.5]]];
  45689. for (var i = 0; i < points$1.length; i++) {
  45690. for (var k = 0; k < points$1[i].length; k++) {
  45691. points$1[i][k][0] /= 10.5;
  45692. points$1[i][k][1] /= -10.5 / 0.75;
  45693. points$1[i][k][0] += geoCoord[0];
  45694. points$1[i][k][1] += geoCoord[1];
  45695. }
  45696. }
  45697. function fixNanhai(mapType, regions) {
  45698. if (mapType === 'china') {
  45699. for (var i = 0; i < regions.length; i++) {
  45700. // Already exists.
  45701. if (regions[i].name === nanhaiName) {
  45702. return;
  45703. }
  45704. }
  45705. regions.push(new GeoJSONRegion(nanhaiName, map(points$1, function (exterior) {
  45706. return {
  45707. type: 'polygon',
  45708. exterior: exterior
  45709. };
  45710. }), geoCoord));
  45711. }
  45712. }
  45713. /*
  45714. * Licensed to the Apache Software Foundation (ASF) under one
  45715. * or more contributor license agreements. See the NOTICE file
  45716. * distributed with this work for additional information
  45717. * regarding copyright ownership. The ASF licenses this file
  45718. * to you under the Apache License, Version 2.0 (the
  45719. * "License"); you may not use this file except in compliance
  45720. * with the License. You may obtain a copy of the License at
  45721. *
  45722. * http://www.apache.org/licenses/LICENSE-2.0
  45723. *
  45724. * Unless required by applicable law or agreed to in writing,
  45725. * software distributed under the License is distributed on an
  45726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45727. * KIND, either express or implied. See the License for the
  45728. * specific language governing permissions and limitations
  45729. * under the License.
  45730. */
  45731. /**
  45732. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45733. */
  45734. /*
  45735. * Licensed to the Apache Software Foundation (ASF) under one
  45736. * or more contributor license agreements. See the NOTICE file
  45737. * distributed with this work for additional information
  45738. * regarding copyright ownership. The ASF licenses this file
  45739. * to you under the Apache License, Version 2.0 (the
  45740. * "License"); you may not use this file except in compliance
  45741. * with the License. You may obtain a copy of the License at
  45742. *
  45743. * http://www.apache.org/licenses/LICENSE-2.0
  45744. *
  45745. * Unless required by applicable law or agreed to in writing,
  45746. * software distributed under the License is distributed on an
  45747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45748. * KIND, either express or implied. See the License for the
  45749. * specific language governing permissions and limitations
  45750. * under the License.
  45751. */
  45752. var coordsOffsetMap = {
  45753. '南海诸岛': [32, 80],
  45754. // 全国
  45755. '广东': [0, -10],
  45756. '香港': [10, 5],
  45757. '澳门': [-10, 10],
  45758. // '北京': [-10, 0],
  45759. '天津': [5, 5]
  45760. };
  45761. function fixTextCoords(mapType, region) {
  45762. if (mapType === 'china') {
  45763. var coordFix = coordsOffsetMap[region.name];
  45764. if (coordFix) {
  45765. var cp = region.getCenter();
  45766. cp[0] += coordFix[0] / 10.5;
  45767. cp[1] += -coordFix[1] / (10.5 / 0.75);
  45768. region.setCenter(cp);
  45769. }
  45770. }
  45771. }
  45772. /*
  45773. * Licensed to the Apache Software Foundation (ASF) under one
  45774. * or more contributor license agreements. See the NOTICE file
  45775. * distributed with this work for additional information
  45776. * regarding copyright ownership. The ASF licenses this file
  45777. * to you under the Apache License, Version 2.0 (the
  45778. * "License"); you may not use this file except in compliance
  45779. * with the License. You may obtain a copy of the License at
  45780. *
  45781. * http://www.apache.org/licenses/LICENSE-2.0
  45782. *
  45783. * Unless required by applicable law or agreed to in writing,
  45784. * software distributed under the License is distributed on an
  45785. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45786. * KIND, either express or implied. See the License for the
  45787. * specific language governing permissions and limitations
  45788. * under the License.
  45789. */
  45790. /**
  45791. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45792. */
  45793. /*
  45794. * Licensed to the Apache Software Foundation (ASF) under one
  45795. * or more contributor license agreements. See the NOTICE file
  45796. * distributed with this work for additional information
  45797. * regarding copyright ownership. The ASF licenses this file
  45798. * to you under the Apache License, Version 2.0 (the
  45799. * "License"); you may not use this file except in compliance
  45800. * with the License. You may obtain a copy of the License at
  45801. *
  45802. * http://www.apache.org/licenses/LICENSE-2.0
  45803. *
  45804. * Unless required by applicable law or agreed to in writing,
  45805. * software distributed under the License is distributed on an
  45806. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45807. * KIND, either express or implied. See the License for the
  45808. * specific language governing permissions and limitations
  45809. * under the License.
  45810. */
  45811. // Fix for 钓鱼岛
  45812. // let Region = require('../Region');
  45813. // let zrUtil = require('zrender/lib/core/util');
  45814. // let geoCoord = [126, 25];
  45815. var points$2 = [[[123.45165252685547, 25.73527164402261], [123.49731445312499, 25.73527164402261], [123.49731445312499, 25.750734064600884], [123.45165252685547, 25.750734064600884], [123.45165252685547, 25.73527164402261]]];
  45816. function fixDiaoyuIsland(mapType, region) {
  45817. if (mapType === 'china' && region.name === '台湾') {
  45818. region.geometries.push({
  45819. type: 'polygon',
  45820. exterior: points$2[0]
  45821. });
  45822. }
  45823. }
  45824. var DEFAULT_NAME_PROPERTY = 'name';
  45825. var GeoJSONResource =
  45826. /** @class */
  45827. function () {
  45828. function GeoJSONResource(mapName, geoJSON, specialAreas) {
  45829. this.type = 'geoJSON';
  45830. this._parsedMap = createHashMap();
  45831. this._mapName = mapName;
  45832. this._specialAreas = specialAreas; // PENDING: delay the parse to the first usage to rapid up the FMP?
  45833. this._geoJSON = parseInput(geoJSON);
  45834. }
  45835. /**
  45836. * @param nameMap can be null/undefined
  45837. * @param nameProperty can be null/undefined
  45838. */
  45839. GeoJSONResource.prototype.load = function (nameMap, nameProperty) {
  45840. nameProperty = nameProperty || DEFAULT_NAME_PROPERTY;
  45841. var parsed = this._parsedMap.get(nameProperty);
  45842. if (!parsed) {
  45843. var rawRegions = this._parseToRegions(nameProperty);
  45844. parsed = this._parsedMap.set(nameProperty, {
  45845. regions: rawRegions,
  45846. boundingRect: calculateBoundingRect(rawRegions)
  45847. });
  45848. }
  45849. var regionsMap = createHashMap();
  45850. var finalRegions = [];
  45851. each(parsed.regions, function (region) {
  45852. var regionName = region.name; // Try use the alias in geoNameMap
  45853. if (nameMap && hasOwn(nameMap, regionName)) {
  45854. region = region.cloneShallow(regionName = nameMap[regionName]);
  45855. }
  45856. finalRegions.push(region);
  45857. regionsMap.set(regionName, region);
  45858. });
  45859. return {
  45860. regions: finalRegions,
  45861. boundingRect: parsed.boundingRect || new BoundingRect(0, 0, 0, 0),
  45862. regionsMap: regionsMap
  45863. };
  45864. };
  45865. GeoJSONResource.prototype._parseToRegions = function (nameProperty) {
  45866. var mapName = this._mapName;
  45867. var geoJSON = this._geoJSON;
  45868. var rawRegions; // https://jsperf.com/try-catch-performance-overhead
  45869. try {
  45870. rawRegions = geoJSON ? parseGeoJSON(geoJSON, nameProperty) : [];
  45871. } catch (e) {
  45872. throw new Error('Invalid geoJson format\n' + e.message);
  45873. }
  45874. fixNanhai(mapName, rawRegions);
  45875. each(rawRegions, function (region) {
  45876. var regionName = region.name;
  45877. fixTextCoords(mapName, region);
  45878. fixDiaoyuIsland(mapName, region); // Some area like Alaska in USA map needs to be tansformed
  45879. // to look better
  45880. var specialArea = this._specialAreas && this._specialAreas[regionName];
  45881. if (specialArea) {
  45882. region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height);
  45883. }
  45884. }, this);
  45885. return rawRegions;
  45886. };
  45887. /**
  45888. * Only for exporting to users.
  45889. * **MUST NOT** used internally.
  45890. */
  45891. GeoJSONResource.prototype.getMapForUser = function () {
  45892. return {
  45893. // For backward compatibility, use geoJson
  45894. // PENDING: it has been returning them without clone.
  45895. // do we need to avoid outsite modification?
  45896. geoJson: this._geoJSON,
  45897. geoJSON: this._geoJSON,
  45898. specialAreas: this._specialAreas
  45899. };
  45900. };
  45901. return GeoJSONResource;
  45902. }();
  45903. function calculateBoundingRect(regions) {
  45904. var rect;
  45905. for (var i = 0; i < regions.length; i++) {
  45906. var regionRect = regions[i].getBoundingRect();
  45907. rect = rect || regionRect.clone();
  45908. rect.union(regionRect);
  45909. }
  45910. return rect;
  45911. }
  45912. function parseInput(source) {
  45913. return !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  45914. }
  45915. var storage = createHashMap();
  45916. var geoSourceManager = {
  45917. /**
  45918. * Compatible with previous `echarts.registerMap`.
  45919. *
  45920. * @usage
  45921. * ```js
  45922. *
  45923. * echarts.registerMap('USA', geoJson, specialAreas);
  45924. *
  45925. * echarts.registerMap('USA', {
  45926. * geoJson: geoJson,
  45927. * specialAreas: {...}
  45928. * });
  45929. * echarts.registerMap('USA', {
  45930. * geoJSON: geoJson,
  45931. * specialAreas: {...}
  45932. * });
  45933. *
  45934. * echarts.registerMap('airport', {
  45935. * svg: svg
  45936. * }
  45937. * ```
  45938. *
  45939. * Note:
  45940. * Do not support that register multiple geoJSON or SVG
  45941. * one map name. Because different geoJSON and SVG have
  45942. * different unit. It's not easy to make sure how those
  45943. * units are mapping/normalize.
  45944. * If intending to use multiple geoJSON or SVG, we can
  45945. * use multiple geo coordinate system.
  45946. */
  45947. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  45948. if (rawDef.svg) {
  45949. var resource = new GeoSVGResource(mapName, rawDef.svg);
  45950. storage.set(mapName, resource);
  45951. } else {
  45952. // Recommend:
  45953. // echarts.registerMap('eu', { geoJSON: xxx, specialAreas: xxx });
  45954. // Backward compatibility:
  45955. // echarts.registerMap('eu', geoJSON, specialAreas);
  45956. // echarts.registerMap('eu', { geoJson: xxx, specialAreas: xxx });
  45957. var geoJSON = rawDef.geoJson || rawDef.geoJSON;
  45958. if (geoJSON && !rawDef.features) {
  45959. rawSpecialAreas = rawDef.specialAreas;
  45960. } else {
  45961. geoJSON = rawDef;
  45962. }
  45963. var resource = new GeoJSONResource(mapName, geoJSON, rawSpecialAreas);
  45964. storage.set(mapName, resource);
  45965. }
  45966. },
  45967. getGeoResource: function (mapName) {
  45968. return storage.get(mapName);
  45969. },
  45970. /**
  45971. * Only for exporting to users.
  45972. * **MUST NOT** used internally.
  45973. */
  45974. getMapForUser: function (mapName) {
  45975. var resource = storage.get(mapName); // Do not support return SVG until some real requirement come.
  45976. return resource && resource.type === 'geoJSON' && resource.getMapForUser();
  45977. },
  45978. load: function (mapName, nameMap, nameProperty) {
  45979. var resource = storage.get(mapName);
  45980. if (!resource) {
  45981. if ("development" !== 'production') {
  45982. console.error('Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.');
  45983. }
  45984. return;
  45985. }
  45986. return resource.load(nameMap, nameProperty);
  45987. }
  45988. };
  45989. /**
  45990. * Only these tags enable use `itemStyle` if they are named in SVG.
  45991. * Other tags like <text> <tspan> <image> might not suitable for `itemStyle`.
  45992. * They will not be considered to be styled until some requirements come.
  45993. */
  45994. var OPTION_STYLE_ENABLED_TAGS = ['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path'];
  45995. var OPTION_STYLE_ENABLED_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS);
  45996. var STATE_TRIGGER_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  45997. var LABEL_HOST_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  45998. var mapLabelRaw = makeInner();
  45999. function getFixedItemStyle(model) {
  46000. var itemStyle = model.getItemStyle();
  46001. var areaColor = model.get('areaColor'); // If user want the color not to be changed when hover,
  46002. // they should both set areaColor and color to be null.
  46003. if (areaColor != null) {
  46004. itemStyle.fill = areaColor;
  46005. }
  46006. return itemStyle;
  46007. } // Only stroke can be used for line.
  46008. // Using fill in style if stroke not exits.
  46009. // TODO Not sure yet. Perhaps a separate `lineStyle`?
  46010. function fixLineStyle(styleHost) {
  46011. var style = styleHost.style;
  46012. if (style) {
  46013. style.stroke = style.stroke || style.fill;
  46014. style.fill = null;
  46015. }
  46016. }
  46017. var MapDraw =
  46018. /** @class */
  46019. function () {
  46020. function MapDraw(api) {
  46021. var group = new Group();
  46022. this.uid = getUID('ec_map_draw');
  46023. this._controller = new RoamController(api.getZr());
  46024. this._controllerHost = {
  46025. target: group
  46026. };
  46027. this.group = group;
  46028. group.add(this._regionsGroup = new Group());
  46029. group.add(this._svgGroup = new Group());
  46030. }
  46031. MapDraw.prototype.draw = function (mapOrGeoModel, ecModel, api, fromView, payload) {
  46032. var isGeo = mapOrGeoModel.mainType === 'geo'; // Map series has data. GEO model that controlled by map series
  46033. // will be assigned with map data. Other GEO model has no data.
  46034. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  46035. isGeo && ecModel.eachComponent({
  46036. mainType: 'series',
  46037. subType: 'map'
  46038. }, function (mapSeries) {
  46039. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  46040. data = mapSeries.getData();
  46041. }
  46042. });
  46043. var geo = mapOrGeoModel.coordinateSystem;
  46044. var regionsGroup = this._regionsGroup;
  46045. var group = this.group;
  46046. var transformInfo = geo.getTransformInfo();
  46047. var transformInfoRaw = transformInfo.raw;
  46048. var transformInfoRoam = transformInfo.roam; // No animation when first draw or in action
  46049. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  46050. if (isFirstDraw) {
  46051. group.x = transformInfoRoam.x;
  46052. group.y = transformInfoRoam.y;
  46053. group.scaleX = transformInfoRoam.scaleX;
  46054. group.scaleY = transformInfoRoam.scaleY;
  46055. group.dirty();
  46056. } else {
  46057. updateProps(group, transformInfoRoam, mapOrGeoModel);
  46058. }
  46059. var isVisualEncodedByVisualMap = data && data.getVisual('visualMeta') && data.getVisual('visualMeta').length > 0;
  46060. var viewBuildCtx = {
  46061. api: api,
  46062. geo: geo,
  46063. mapOrGeoModel: mapOrGeoModel,
  46064. data: data,
  46065. isVisualEncodedByVisualMap: isVisualEncodedByVisualMap,
  46066. isGeo: isGeo,
  46067. transformInfoRaw: transformInfoRaw
  46068. };
  46069. if (geo.resourceType === 'geoJSON') {
  46070. this._buildGeoJSON(viewBuildCtx);
  46071. } else if (geo.resourceType === 'geoSVG') {
  46072. this._buildSVG(viewBuildCtx);
  46073. }
  46074. this._updateController(mapOrGeoModel, ecModel, api);
  46075. this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView);
  46076. };
  46077. MapDraw.prototype._buildGeoJSON = function (viewBuildCtx) {
  46078. var regionsGroupByName = this._regionsGroupByName = createHashMap();
  46079. var regionsInfoByName = createHashMap();
  46080. var regionsGroup = this._regionsGroup;
  46081. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  46082. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  46083. var data = viewBuildCtx.data;
  46084. var projection = viewBuildCtx.geo.projection;
  46085. var projectionStream = projection && projection.stream;
  46086. function transformPoint(point, project) {
  46087. if (project) {
  46088. // projection may return null point.
  46089. point = project(point);
  46090. }
  46091. return point && [point[0] * transformInfoRaw.scaleX + transformInfoRaw.x, point[1] * transformInfoRaw.scaleY + transformInfoRaw.y];
  46092. }
  46093. function transformPolygonPoints(inPoints) {
  46094. var outPoints = []; // If projectionStream is provided. Use it instead of single point project.
  46095. var project = !projectionStream && projection && projection.project;
  46096. for (var i = 0; i < inPoints.length; ++i) {
  46097. var newPt = transformPoint(inPoints[i], project);
  46098. newPt && outPoints.push(newPt);
  46099. }
  46100. return outPoints;
  46101. }
  46102. function getPolyShape(points) {
  46103. return {
  46104. shape: {
  46105. points: transformPolygonPoints(points)
  46106. }
  46107. };
  46108. }
  46109. regionsGroup.removeAll(); // Only when the resource is GeoJSON, there is `geo.regions`.
  46110. each(viewBuildCtx.geo.regions, function (region) {
  46111. var regionName = region.name; // Consider in GeoJson properties.name may be duplicated, for example,
  46112. // there is multiple region named "United Kindom" or "France" (so many
  46113. // colonies). And it is not appropriate to merge them in geo, which
  46114. // will make them share the same label and bring trouble in label
  46115. // location calculation.
  46116. var regionGroup = regionsGroupByName.get(regionName);
  46117. var _a = regionsInfoByName.get(regionName) || {},
  46118. dataIdx = _a.dataIdx,
  46119. regionModel = _a.regionModel;
  46120. if (!regionGroup) {
  46121. regionGroup = regionsGroupByName.set(regionName, new Group());
  46122. regionsGroup.add(regionGroup);
  46123. dataIdx = data ? data.indexOfName(regionName) : null;
  46124. regionModel = viewBuildCtx.isGeo ? mapOrGeoModel.getRegionModel(regionName) : data ? data.getItemModel(dataIdx) : null;
  46125. regionsInfoByName.set(regionName, {
  46126. dataIdx: dataIdx,
  46127. regionModel: regionModel
  46128. });
  46129. }
  46130. var polygonSubpaths = [];
  46131. var polylineSubpaths = [];
  46132. each(region.geometries, function (geometry) {
  46133. // Polygon and MultiPolygon
  46134. if (geometry.type === 'polygon') {
  46135. var polys = [geometry.exterior].concat(geometry.interiors || []);
  46136. if (projectionStream) {
  46137. polys = projectPolys(polys, projectionStream);
  46138. }
  46139. each(polys, function (poly) {
  46140. polygonSubpaths.push(new Polygon(getPolyShape(poly)));
  46141. });
  46142. } // LineString and MultiLineString
  46143. else {
  46144. var points = geometry.points;
  46145. if (projectionStream) {
  46146. points = projectPolys(points, projectionStream, true);
  46147. }
  46148. each(points, function (points) {
  46149. polylineSubpaths.push(new Polyline(getPolyShape(points)));
  46150. });
  46151. }
  46152. });
  46153. var centerPt = transformPoint(region.getCenter(), projection && projection.project);
  46154. function createCompoundPath(subpaths, isLine) {
  46155. if (!subpaths.length) {
  46156. return;
  46157. }
  46158. var compoundPath = new CompoundPath({
  46159. culling: true,
  46160. segmentIgnoreThreshold: 1,
  46161. shape: {
  46162. paths: subpaths
  46163. }
  46164. });
  46165. regionGroup.add(compoundPath);
  46166. applyOptionStyleForRegion(viewBuildCtx, compoundPath, dataIdx, regionModel);
  46167. resetLabelForRegion(viewBuildCtx, compoundPath, regionName, regionModel, mapOrGeoModel, dataIdx, centerPt);
  46168. if (isLine) {
  46169. fixLineStyle(compoundPath);
  46170. each(compoundPath.states, fixLineStyle);
  46171. }
  46172. }
  46173. createCompoundPath(polygonSubpaths);
  46174. createCompoundPath(polylineSubpaths, true);
  46175. }); // Ensure children have been added to `regionGroup` before calling them.
  46176. regionsGroupByName.each(function (regionGroup, regionName) {
  46177. var _a = regionsInfoByName.get(regionName),
  46178. dataIdx = _a.dataIdx,
  46179. regionModel = _a.regionModel;
  46180. resetEventTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel, dataIdx);
  46181. resetTooltipForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  46182. resetStateTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  46183. }, this);
  46184. };
  46185. MapDraw.prototype._buildSVG = function (viewBuildCtx) {
  46186. var mapName = viewBuildCtx.geo.map;
  46187. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  46188. this._svgGroup.x = transformInfoRaw.x;
  46189. this._svgGroup.y = transformInfoRaw.y;
  46190. this._svgGroup.scaleX = transformInfoRaw.scaleX;
  46191. this._svgGroup.scaleY = transformInfoRaw.scaleY;
  46192. if (this._svgResourceChanged(mapName)) {
  46193. this._freeSVG();
  46194. this._useSVG(mapName);
  46195. }
  46196. var svgDispatcherMap = this._svgDispatcherMap = createHashMap();
  46197. var focusSelf = false;
  46198. each(this._svgGraphicRecord.named, function (namedItem) {
  46199. // Note that we also allow different elements have the same name.
  46200. // For example, a glyph of a city and the label of the city have
  46201. // the same name and their tooltip info can be defined in a single
  46202. // region option.
  46203. var regionName = namedItem.name;
  46204. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  46205. var data = viewBuildCtx.data;
  46206. var svgNodeTagLower = namedItem.svgNodeTagLower;
  46207. var el = namedItem.el;
  46208. var dataIdx = data ? data.indexOfName(regionName) : null;
  46209. var regionModel = mapOrGeoModel.getRegionModel(regionName);
  46210. if (OPTION_STYLE_ENABLED_TAG_MAP.get(svgNodeTagLower) != null && el instanceof Displayable) {
  46211. applyOptionStyleForRegion(viewBuildCtx, el, dataIdx, regionModel);
  46212. }
  46213. if (el instanceof Displayable) {
  46214. el.culling = true;
  46215. } // We do not know how the SVG like so we'd better not to change z2.
  46216. // Otherwise it might bring some unexpected result. For example,
  46217. // an area hovered that make some inner city can not be clicked.
  46218. el.z2EmphasisLift = 0; // If self named:
  46219. if (!namedItem.namedFrom) {
  46220. // label should batter to be displayed based on the center of <g>
  46221. // if it is named rather than displayed on each child.
  46222. if (LABEL_HOST_MAP.get(svgNodeTagLower) != null) {
  46223. resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, null);
  46224. }
  46225. resetEventTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx);
  46226. resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  46227. if (STATE_TRIGGER_TAG_MAP.get(svgNodeTagLower) != null) {
  46228. var focus_1 = resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  46229. if (focus_1 === 'self') {
  46230. focusSelf = true;
  46231. }
  46232. var els = svgDispatcherMap.get(regionName) || svgDispatcherMap.set(regionName, []);
  46233. els.push(el);
  46234. }
  46235. }
  46236. }, this);
  46237. this._enableBlurEntireSVG(focusSelf, viewBuildCtx);
  46238. };
  46239. MapDraw.prototype._enableBlurEntireSVG = function (focusSelf, viewBuildCtx) {
  46240. // It's a little complicated to support blurring the entire geoSVG in series-map.
  46241. // So do not support it until some requirements come.
  46242. // At present, in series-map, only regions can be blurred.
  46243. if (focusSelf && viewBuildCtx.isGeo) {
  46244. var blurStyle = viewBuildCtx.mapOrGeoModel.getModel(['blur', 'itemStyle']).getItemStyle(); // Only support `opacity` here. Because not sure that other props are suitable for
  46245. // all of the elements generated by SVG (especially for Text/TSpan/Image/... ).
  46246. var opacity_1 = blurStyle.opacity;
  46247. this._svgGraphicRecord.root.traverse(function (el) {
  46248. if (!el.isGroup) {
  46249. // PENDING: clear those settings to SVG elements when `_freeSVG`.
  46250. // (Currently it happen not to be needed.)
  46251. setDefaultStateProxy(el);
  46252. var style = el.ensureState('blur').style || {}; // Do not overwrite the region style that already set from region option.
  46253. if (style.opacity == null && opacity_1 != null) {
  46254. style.opacity = opacity_1;
  46255. } // If `ensureState('blur').style = {}`, there will be default opacity.
  46256. // Enable `stateTransition` (animation).
  46257. el.ensureState('emphasis');
  46258. }
  46259. });
  46260. }
  46261. };
  46262. MapDraw.prototype.remove = function () {
  46263. this._regionsGroup.removeAll();
  46264. this._regionsGroupByName = null;
  46265. this._svgGroup.removeAll();
  46266. this._freeSVG();
  46267. this._controller.dispose();
  46268. this._controllerHost = null;
  46269. };
  46270. MapDraw.prototype.findHighDownDispatchers = function (name, geoModel) {
  46271. if (name == null) {
  46272. return [];
  46273. }
  46274. var geo = geoModel.coordinateSystem;
  46275. if (geo.resourceType === 'geoJSON') {
  46276. var regionsGroupByName = this._regionsGroupByName;
  46277. if (regionsGroupByName) {
  46278. var regionGroup = regionsGroupByName.get(name);
  46279. return regionGroup ? [regionGroup] : [];
  46280. }
  46281. } else if (geo.resourceType === 'geoSVG') {
  46282. return this._svgDispatcherMap && this._svgDispatcherMap.get(name) || [];
  46283. }
  46284. };
  46285. MapDraw.prototype._svgResourceChanged = function (mapName) {
  46286. return this._svgMapName !== mapName;
  46287. };
  46288. MapDraw.prototype._useSVG = function (mapName) {
  46289. var resource = geoSourceManager.getGeoResource(mapName);
  46290. if (resource && resource.type === 'geoSVG') {
  46291. var svgGraphic = resource.useGraphic(this.uid);
  46292. this._svgGroup.add(svgGraphic.root);
  46293. this._svgGraphicRecord = svgGraphic;
  46294. this._svgMapName = mapName;
  46295. }
  46296. };
  46297. MapDraw.prototype._freeSVG = function () {
  46298. var mapName = this._svgMapName;
  46299. if (mapName == null) {
  46300. return;
  46301. }
  46302. var resource = geoSourceManager.getGeoResource(mapName);
  46303. if (resource && resource.type === 'geoSVG') {
  46304. resource.freeGraphic(this.uid);
  46305. }
  46306. this._svgGraphicRecord = null;
  46307. this._svgDispatcherMap = null;
  46308. this._svgGroup.removeAll();
  46309. this._svgMapName = null;
  46310. };
  46311. MapDraw.prototype._updateController = function (mapOrGeoModel, ecModel, api) {
  46312. var geo = mapOrGeoModel.coordinateSystem;
  46313. var controller = this._controller;
  46314. var controllerHost = this._controllerHost; // @ts-ignore FIXME:TS
  46315. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  46316. controllerHost.zoom = geo.getZoom(); // roamType is will be set default true if it is null
  46317. // @ts-ignore FIXME:TS
  46318. controller.enable(mapOrGeoModel.get('roam') || false);
  46319. var mainType = mapOrGeoModel.mainType;
  46320. function makeActionBase() {
  46321. var action = {
  46322. type: 'geoRoam',
  46323. componentType: mainType
  46324. };
  46325. action[mainType + 'Id'] = mapOrGeoModel.id;
  46326. return action;
  46327. }
  46328. controller.off('pan').on('pan', function (e) {
  46329. this._mouseDownFlag = false;
  46330. updateViewOnPan(controllerHost, e.dx, e.dy);
  46331. api.dispatchAction(extend(makeActionBase(), {
  46332. dx: e.dx,
  46333. dy: e.dy,
  46334. animation: {
  46335. duration: 0
  46336. }
  46337. }));
  46338. }, this);
  46339. controller.off('zoom').on('zoom', function (e) {
  46340. this._mouseDownFlag = false;
  46341. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  46342. api.dispatchAction(extend(makeActionBase(), {
  46343. zoom: e.scale,
  46344. originX: e.originX,
  46345. originY: e.originY,
  46346. animation: {
  46347. duration: 0
  46348. }
  46349. }));
  46350. }, this);
  46351. controller.setPointerChecker(function (e, x, y) {
  46352. return geo.containPoint([x, y]) && !onIrrelevantElement(e, api, mapOrGeoModel);
  46353. });
  46354. };
  46355. /**
  46356. * FIXME: this is a temporarily workaround.
  46357. * When `geoRoam` the elements need to be reset in `MapView['render']`, because the props like
  46358. * `ignore` might have been modified by `LabelManager`, and `LabelManager#addLabelsOfSeries`
  46359. * will subsequently cache `defaultAttr` like `ignore`. If do not do this reset, the modified
  46360. * props will have no chance to be restored.
  46361. * Note: This reset should be after `clearStates` in `renderSeries` because `useStates` in
  46362. * `renderSeries` will cache the modified `ignore` to `el._normalState`.
  46363. * TODO:
  46364. * Use clone/immutable in `LabelManager`?
  46365. */
  46366. MapDraw.prototype.resetForLabelLayout = function () {
  46367. this.group.traverse(function (el) {
  46368. var label = el.getTextContent();
  46369. if (label) {
  46370. label.ignore = mapLabelRaw(label).ignore;
  46371. }
  46372. });
  46373. };
  46374. MapDraw.prototype._updateMapSelectHandler = function (mapOrGeoModel, regionsGroup, api, fromView) {
  46375. var mapDraw = this;
  46376. regionsGroup.off('mousedown');
  46377. regionsGroup.off('click'); // @ts-ignore FIXME:TS resolve type conflict
  46378. if (mapOrGeoModel.get('selectedMode')) {
  46379. regionsGroup.on('mousedown', function () {
  46380. mapDraw._mouseDownFlag = true;
  46381. });
  46382. regionsGroup.on('click', function (e) {
  46383. if (!mapDraw._mouseDownFlag) {
  46384. return;
  46385. }
  46386. mapDraw._mouseDownFlag = false;
  46387. });
  46388. }
  46389. };
  46390. return MapDraw;
  46391. }();
  46392. function applyOptionStyleForRegion(viewBuildCtx, el, dataIndex, regionModel) {
  46393. // All of the path are using `itemStyle`, because
  46394. // (1) Some SVG also use fill on polyline (The different between
  46395. // polyline and polygon is "open" or "close" but not fill or not).
  46396. // (2) For the common props like opacity, if some use itemStyle
  46397. // and some use `lineStyle`, it might confuse users.
  46398. // (3) Most SVG use <path>, where can not detect whether to draw a "line"
  46399. // or a filled shape, so use `itemStyle` for <path>.
  46400. var normalStyleModel = regionModel.getModel('itemStyle');
  46401. var emphasisStyleModel = regionModel.getModel(['emphasis', 'itemStyle']);
  46402. var blurStyleModel = regionModel.getModel(['blur', 'itemStyle']);
  46403. var selectStyleModel = regionModel.getModel(['select', 'itemStyle']); // NOTE: DON'T use 'style' in visual when drawing map.
  46404. // This component is used for drawing underlying map for both geo component and map series.
  46405. var normalStyle = getFixedItemStyle(normalStyleModel);
  46406. var emphasisStyle = getFixedItemStyle(emphasisStyleModel);
  46407. var selectStyle = getFixedItemStyle(selectStyleModel);
  46408. var blurStyle = getFixedItemStyle(blurStyleModel); // Update the itemStyle if has data visual
  46409. var data = viewBuildCtx.data;
  46410. if (data) {
  46411. // Only visual color of each item will be used. It can be encoded by visualMap
  46412. // But visual color of series is used in symbol drawing
  46413. // Visual color for each series is for the symbol draw
  46414. var style = data.getItemVisual(dataIndex, 'style');
  46415. var decal = data.getItemVisual(dataIndex, 'decal');
  46416. if (viewBuildCtx.isVisualEncodedByVisualMap && style.fill) {
  46417. normalStyle.fill = style.fill;
  46418. }
  46419. if (decal) {
  46420. normalStyle.decal = createOrUpdatePatternFromDecal(decal, viewBuildCtx.api);
  46421. }
  46422. } // SVG text, tspan and image can be named but not supporeted
  46423. // to be styled by region option yet.
  46424. el.setStyle(normalStyle);
  46425. el.style.strokeNoScale = true;
  46426. el.ensureState('emphasis').style = emphasisStyle;
  46427. el.ensureState('select').style = selectStyle;
  46428. el.ensureState('blur').style = blurStyle; // Enable blur
  46429. setDefaultStateProxy(el);
  46430. }
  46431. function resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  46432. dataIdx, // If labelXY not provided, use `textConfig.position: 'inside'`
  46433. labelXY) {
  46434. var data = viewBuildCtx.data;
  46435. var isGeo = viewBuildCtx.isGeo;
  46436. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  46437. var itemLayout = data && data.getItemLayout(dataIdx); // In the following cases label will be drawn
  46438. // 1. In map series and data value is NaN
  46439. // 2. In geo component
  46440. // 3. Region has no series legendIcon, which will be add a showLabel flag in mapSymbolLayout
  46441. if (isGeo || isDataNaN || itemLayout && itemLayout.showLabel) {
  46442. var query = !isGeo ? dataIdx : regionName;
  46443. var labelFetcher = void 0; // Consider dataIdx not found.
  46444. if (!data || dataIdx >= 0) {
  46445. labelFetcher = mapOrGeoModel;
  46446. }
  46447. var specifiedTextOpt = labelXY ? {
  46448. normal: {
  46449. align: 'center',
  46450. verticalAlign: 'middle'
  46451. }
  46452. } : null; // Caveat: must be called after `setDefaultStateProxy(el);` called.
  46453. // because textContent will be assign with `el.stateProxy` inside.
  46454. setLabelStyle(el, getLabelStatesModels(regionModel), {
  46455. labelFetcher: labelFetcher,
  46456. labelDataIndex: query,
  46457. defaultText: regionName
  46458. }, specifiedTextOpt);
  46459. var textEl = el.getTextContent();
  46460. if (textEl) {
  46461. mapLabelRaw(textEl).ignore = textEl.ignore;
  46462. if (el.textConfig && labelXY) {
  46463. // Compute a relative offset based on the el bounding rect.
  46464. var rect = el.getBoundingRect().clone(); // Need to make sure the percent position base on the same rect in normal and
  46465. // emphasis state. Otherwise if using boundingRect of el, but the emphasis state
  46466. // has borderWidth (even 0.5px), the text position will be changed obviously
  46467. // if the position is very big like ['1234%', '1345%'].
  46468. el.textConfig.layoutRect = rect;
  46469. el.textConfig.position = [(labelXY[0] - rect.x) / rect.width * 100 + '%', (labelXY[1] - rect.y) / rect.height * 100 + '%'];
  46470. }
  46471. } // PENDING:
  46472. // If labelLayout is enabled (test/label-layout.html), el.dataIndex should be specified.
  46473. // But el.dataIndex is also used to determine whether user event should be triggered,
  46474. // where el.seriesIndex or el.dataModel must be specified. At present for a single el
  46475. // there is not case that "only label layout enabled but user event disabled", so here
  46476. // we depends `resetEventTriggerForRegion` to do the job of setting `el.dataIndex`.
  46477. el.disableLabelAnimation = true;
  46478. } else {
  46479. el.removeTextContent();
  46480. el.removeTextConfig();
  46481. el.disableLabelAnimation = null;
  46482. }
  46483. }
  46484. function resetEventTriggerForRegion(viewBuildCtx, eventTrigger, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  46485. dataIdx) {
  46486. // setItemGraphicEl, setHoverStyle after all polygons and labels
  46487. // are added to the regionGroup
  46488. if (viewBuildCtx.data) {
  46489. // FIXME: when series-map use a SVG map, and there are duplicated name specified
  46490. // on different SVG elements, after `data.setItemGraphicEl(...)`:
  46491. // (1) all of them will be mounted with `dataIndex`, `seriesIndex`, so that tooltip
  46492. // can be triggered only mouse hover. That's correct.
  46493. // (2) only the last element will be kept in `data`, so that if trigger tooltip
  46494. // by `dispatchAction`, only the last one can be found and triggered. That might be
  46495. // not correct. We will fix it in future if anyone demanding that.
  46496. viewBuildCtx.data.setItemGraphicEl(dataIdx, eventTrigger);
  46497. } // series-map will not trigger "geoselectchange" no matter it is
  46498. // based on a declared geo component. Because series-map will
  46499. // trigger "selectchange". If it trigger both the two events,
  46500. // If users call `chart.dispatchAction({type: 'toggleSelect'})`,
  46501. // it not easy to also fire event "geoselectchanged".
  46502. else {
  46503. // Package custom mouse event for geo component
  46504. getECData(eventTrigger).eventData = {
  46505. componentType: 'geo',
  46506. componentIndex: mapOrGeoModel.componentIndex,
  46507. geoIndex: mapOrGeoModel.componentIndex,
  46508. name: regionName,
  46509. region: regionModel && regionModel.option || {}
  46510. };
  46511. }
  46512. }
  46513. function resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  46514. if (!viewBuildCtx.data) {
  46515. setTooltipConfig({
  46516. el: el,
  46517. componentModel: mapOrGeoModel,
  46518. itemName: regionName,
  46519. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46520. itemTooltipOption: regionModel.get('tooltip')
  46521. });
  46522. }
  46523. }
  46524. function resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  46525. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46526. el.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode'); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46527. var emphasisModel = regionModel.getModel('emphasis');
  46528. var focus = emphasisModel.get('focus');
  46529. toggleHoverEmphasis(el, focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  46530. if (viewBuildCtx.isGeo) {
  46531. enableComponentHighDownFeatures(el, mapOrGeoModel, regionName);
  46532. }
  46533. return focus;
  46534. }
  46535. function projectPolys(rings, // Polygons include exterior and interiors. Or polylines.
  46536. createStream, isLine) {
  46537. var polygons = [];
  46538. var curPoly;
  46539. function startPolygon() {
  46540. curPoly = [];
  46541. }
  46542. function endPolygon() {
  46543. if (curPoly.length) {
  46544. polygons.push(curPoly);
  46545. curPoly = [];
  46546. }
  46547. }
  46548. var stream = createStream({
  46549. polygonStart: startPolygon,
  46550. polygonEnd: endPolygon,
  46551. lineStart: startPolygon,
  46552. lineEnd: endPolygon,
  46553. point: function (x, y) {
  46554. // May have NaN values from stream.
  46555. if (isFinite(x) && isFinite(y)) {
  46556. curPoly.push([x, y]);
  46557. }
  46558. },
  46559. sphere: function () {}
  46560. });
  46561. !isLine && stream.polygonStart();
  46562. each(rings, function (ring) {
  46563. stream.lineStart();
  46564. for (var i = 0; i < ring.length; i++) {
  46565. stream.point(ring[i][0], ring[i][1]);
  46566. }
  46567. stream.lineEnd();
  46568. });
  46569. !isLine && stream.polygonEnd();
  46570. return polygons;
  46571. }
  46572. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46573. var MapView =
  46574. /** @class */
  46575. function (_super) {
  46576. __extends(MapView, _super);
  46577. function MapView() {
  46578. var _this = _super !== null && _super.apply(this, arguments) || this;
  46579. _this.type = MapView.type;
  46580. return _this;
  46581. }
  46582. MapView.prototype.render = function (mapModel, ecModel, api, payload) {
  46583. // Not render if it is an toggleSelect action from self
  46584. if (payload && payload.type === 'mapToggleSelect' && payload.from === this.uid) {
  46585. return;
  46586. }
  46587. var group = this.group;
  46588. group.removeAll();
  46589. if (mapModel.getHostGeoModel()) {
  46590. return;
  46591. }
  46592. if (this._mapDraw && payload && payload.type === 'geoRoam') {
  46593. this._mapDraw.resetForLabelLayout();
  46594. } // Not update map if it is an roam action from self
  46595. if (!(payload && payload.type === 'geoRoam' && payload.componentType === 'series' && payload.seriesId === mapModel.id)) {
  46596. if (mapModel.needsDrawMap) {
  46597. var mapDraw = this._mapDraw || new MapDraw(api);
  46598. group.add(mapDraw.group);
  46599. mapDraw.draw(mapModel, ecModel, api, this, payload);
  46600. this._mapDraw = mapDraw;
  46601. } else {
  46602. // Remove drawn map
  46603. this._mapDraw && this._mapDraw.remove();
  46604. this._mapDraw = null;
  46605. }
  46606. } else {
  46607. var mapDraw = this._mapDraw;
  46608. mapDraw && group.add(mapDraw.group);
  46609. }
  46610. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api);
  46611. };
  46612. MapView.prototype.remove = function () {
  46613. this._mapDraw && this._mapDraw.remove();
  46614. this._mapDraw = null;
  46615. this.group.removeAll();
  46616. };
  46617. MapView.prototype.dispose = function () {
  46618. this._mapDraw && this._mapDraw.remove();
  46619. this._mapDraw = null;
  46620. };
  46621. MapView.prototype._renderSymbols = function (mapModel, ecModel, api) {
  46622. var originalData = mapModel.originalData;
  46623. var group = this.group;
  46624. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  46625. if (isNaN(value)) {
  46626. return;
  46627. }
  46628. var layout = originalData.getItemLayout(originalDataIndex);
  46629. if (!layout || !layout.point) {
  46630. // Not exists in map
  46631. return;
  46632. }
  46633. var point = layout.point;
  46634. var offset = layout.offset;
  46635. var circle = new Circle({
  46636. style: {
  46637. // Because the special of map draw.
  46638. // Which needs statistic of multiple series and draw on one map.
  46639. // And each series also need a symbol with legend color
  46640. //
  46641. // Layout and visual are put one the different data
  46642. // TODO
  46643. fill: mapModel.getData().getVisual('style').fill
  46644. },
  46645. shape: {
  46646. cx: point[0] + offset * 9,
  46647. cy: point[1],
  46648. r: 3
  46649. },
  46650. silent: true,
  46651. // Do not overlap the first series, on which labels are displayed.
  46652. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  46653. }); // Only the series that has the first value on the same region is in charge of rendering the label.
  46654. // But consider the case:
  46655. // series: [
  46656. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  46657. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  46658. // ]
  46659. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  46660. // For backward compatibility, we follow the rule that render label `A` by the
  46661. // settings on series `X` but render label `C` by the settings on series `Y`.
  46662. if (!offset) {
  46663. var fullData = mapModel.mainSeries.getData();
  46664. var name_1 = originalData.getName(originalDataIndex);
  46665. var fullIndex_1 = fullData.indexOfName(name_1);
  46666. var itemModel = originalData.getItemModel(originalDataIndex);
  46667. var labelModel = itemModel.getModel('label');
  46668. var regionGroup = fullData.getItemGraphicEl(fullIndex_1); // `getFormattedLabel` needs to use `getData` inside. Here
  46669. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  46670. // FIXME
  46671. // If this is not the `mainSeries`, the item model (like label formatter)
  46672. // set on original data item will never get. But it has been working
  46673. // like that from the beginning, and this scenario is rarely encountered.
  46674. // So it won't be fixed until we have to.
  46675. setLabelStyle(circle, getLabelStatesModels(itemModel), {
  46676. labelFetcher: {
  46677. getFormattedLabel: function (idx, state) {
  46678. return mapModel.getFormattedLabel(fullIndex_1, state);
  46679. }
  46680. },
  46681. defaultText: name_1
  46682. });
  46683. circle.disableLabelAnimation = true;
  46684. if (!labelModel.get('position')) {
  46685. circle.setTextConfig({
  46686. position: 'bottom'
  46687. });
  46688. }
  46689. regionGroup.onHoverStateChange = function (toState) {
  46690. setStatesFlag(circle, toState);
  46691. };
  46692. }
  46693. group.add(circle);
  46694. });
  46695. };
  46696. MapView.type = 'map';
  46697. return MapView;
  46698. }(ChartView);
  46699. var MapSeries =
  46700. /** @class */
  46701. function (_super) {
  46702. __extends(MapSeries, _super);
  46703. function MapSeries() {
  46704. var _this = _super !== null && _super.apply(this, arguments) || this;
  46705. _this.type = MapSeries.type; // Only first map series of same mapType will drawMap.
  46706. _this.needsDrawMap = false; // Group of all map series with same mapType
  46707. _this.seriesGroup = [];
  46708. _this.getTooltipPosition = function (dataIndex) {
  46709. if (dataIndex != null) {
  46710. var name_1 = this.getData().getName(dataIndex);
  46711. var geo = this.coordinateSystem;
  46712. var region = geo.getRegion(name_1);
  46713. return region && geo.dataToPoint(region.getCenter());
  46714. }
  46715. };
  46716. return _this;
  46717. }
  46718. MapSeries.prototype.getInitialData = function (option) {
  46719. var data = createSeriesDataSimply(this, {
  46720. coordDimensions: ['value'],
  46721. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  46722. });
  46723. var dataNameMap = createHashMap();
  46724. var toAppendNames = [];
  46725. for (var i = 0, len = data.count(); i < len; i++) {
  46726. var name_2 = data.getName(i);
  46727. dataNameMap.set(name_2, true);
  46728. }
  46729. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  46730. each(geoSource.regions, function (region) {
  46731. var name = region.name;
  46732. if (!dataNameMap.get(name)) {
  46733. toAppendNames.push(name);
  46734. }
  46735. }); // Complete data with missing regions. The consequent processes (like visual
  46736. // map and render) can not be performed without a "full data". For example,
  46737. // find `dataIndex` by name.
  46738. data.appendValues([], toAppendNames);
  46739. return data;
  46740. };
  46741. /**
  46742. * If no host geo model, return null, which means using a
  46743. * inner exclusive geo model.
  46744. */
  46745. MapSeries.prototype.getHostGeoModel = function () {
  46746. var geoIndex = this.option.geoIndex;
  46747. return geoIndex != null ? this.ecModel.getComponent('geo', geoIndex) : null;
  46748. };
  46749. MapSeries.prototype.getMapType = function () {
  46750. return (this.getHostGeoModel() || this).option.map;
  46751. }; // _fillOption(option, mapName) {
  46752. // Shallow clone
  46753. // option = zrUtil.extend({}, option);
  46754. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  46755. // return option;
  46756. // }
  46757. MapSeries.prototype.getRawValue = function (dataIndex) {
  46758. // Use value stored in data instead because it is calculated from multiple series
  46759. // FIXME Provide all value of multiple series ?
  46760. var data = this.getData();
  46761. return data.get(data.mapDimension('value'), dataIndex);
  46762. };
  46763. /**
  46764. * Get model of region
  46765. */
  46766. MapSeries.prototype.getRegionModel = function (regionName) {
  46767. var data = this.getData();
  46768. return data.getItemModel(data.indexOfName(regionName));
  46769. };
  46770. /**
  46771. * Map tooltip formatter
  46772. */
  46773. MapSeries.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  46774. // FIXME orignalData and data is a bit confusing
  46775. var data = this.getData();
  46776. var value = this.getRawValue(dataIndex);
  46777. var name = data.getName(dataIndex);
  46778. var seriesGroup = this.seriesGroup;
  46779. var seriesNames = [];
  46780. for (var i = 0; i < seriesGroup.length; i++) {
  46781. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  46782. var valueDim = data.mapDimension('value');
  46783. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  46784. seriesNames.push(seriesGroup[i].name);
  46785. }
  46786. }
  46787. return createTooltipMarkup('section', {
  46788. header: seriesNames.join(', '),
  46789. noHeader: !seriesNames.length,
  46790. blocks: [createTooltipMarkup('nameValue', {
  46791. name: name,
  46792. value: value
  46793. })]
  46794. });
  46795. };
  46796. MapSeries.prototype.setZoom = function (zoom) {
  46797. this.option.zoom = zoom;
  46798. };
  46799. MapSeries.prototype.setCenter = function (center) {
  46800. this.option.center = center;
  46801. };
  46802. MapSeries.prototype.getLegendIcon = function (opt) {
  46803. var iconType = opt.icon || 'roundRect';
  46804. var icon = createSymbol(iconType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill);
  46805. icon.setStyle(opt.itemStyle); // Map do not use itemStyle.borderWidth as border width
  46806. icon.style.stroke = 'none'; // No rotation because no series visual symbol for map
  46807. if (iconType.indexOf('empty') > -1) {
  46808. icon.style.stroke = icon.style.fill;
  46809. icon.style.fill = '#fff';
  46810. icon.style.lineWidth = 2;
  46811. }
  46812. return icon;
  46813. };
  46814. MapSeries.type = 'series.map';
  46815. MapSeries.dependencies = ['geo'];
  46816. MapSeries.layoutMode = 'box';
  46817. MapSeries.defaultOption = {
  46818. // 一级层叠
  46819. // zlevel: 0,
  46820. // 二级层叠
  46821. z: 2,
  46822. coordinateSystem: 'geo',
  46823. // map should be explicitly specified since ec3.
  46824. map: '',
  46825. // If `geoIndex` is not specified, a exclusive geo will be
  46826. // created. Otherwise use the specified geo component, and
  46827. // `map` and `mapType` are ignored.
  46828. // geoIndex: 0,
  46829. // 'center' | 'left' | 'right' | 'x%' | {number}
  46830. left: 'center',
  46831. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  46832. top: 'center',
  46833. // right
  46834. // bottom
  46835. // width:
  46836. // height
  46837. // Aspect is width / height. Inited to be geoJson bbox aspect
  46838. // This parameter is used for scale this aspect
  46839. // Default value:
  46840. // for geoSVG source: 1,
  46841. // for geoJSON source: 0.75.
  46842. aspectScale: null,
  46843. // Layout with center and size
  46844. // If you want to put map in a fixed size box with right aspect ratio
  46845. // This two properties may be more convenient.
  46846. // layoutCenter: [50%, 50%]
  46847. // layoutSize: 100
  46848. showLegendSymbol: true,
  46849. // Define left-top, right-bottom coords to control view
  46850. // For example, [ [180, 90], [-180, -90] ],
  46851. // higher priority than center and zoom
  46852. boundingCoords: null,
  46853. // Default on center of map
  46854. center: null,
  46855. zoom: 1,
  46856. scaleLimit: null,
  46857. selectedMode: true,
  46858. label: {
  46859. show: false,
  46860. color: '#000'
  46861. },
  46862. // scaleLimit: null,
  46863. itemStyle: {
  46864. borderWidth: 0.5,
  46865. borderColor: '#444',
  46866. areaColor: '#eee'
  46867. },
  46868. emphasis: {
  46869. label: {
  46870. show: true,
  46871. color: 'rgb(100,0,0)'
  46872. },
  46873. itemStyle: {
  46874. areaColor: 'rgba(255,215,0,0.8)'
  46875. }
  46876. },
  46877. select: {
  46878. label: {
  46879. show: true,
  46880. color: 'rgb(100,0,0)'
  46881. },
  46882. itemStyle: {
  46883. color: 'rgba(255,215,0,0.8)'
  46884. }
  46885. },
  46886. nameProperty: 'name'
  46887. };
  46888. return MapSeries;
  46889. }(SeriesModel);
  46890. function dataStatistics(datas, statisticType) {
  46891. var dataNameMap = {};
  46892. each(datas, function (data) {
  46893. data.each(data.mapDimension('value'), function (value, idx) {
  46894. // Add prefix to avoid conflict with Object.prototype.
  46895. var mapKey = 'ec-' + data.getName(idx);
  46896. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  46897. if (!isNaN(value)) {
  46898. dataNameMap[mapKey].push(value);
  46899. }
  46900. });
  46901. });
  46902. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  46903. var mapKey = 'ec-' + datas[0].getName(idx);
  46904. var sum = 0;
  46905. var min = Infinity;
  46906. var max = -Infinity;
  46907. var len = dataNameMap[mapKey].length;
  46908. for (var i = 0; i < len; i++) {
  46909. min = Math.min(min, dataNameMap[mapKey][i]);
  46910. max = Math.max(max, dataNameMap[mapKey][i]);
  46911. sum += dataNameMap[mapKey][i];
  46912. }
  46913. var result;
  46914. if (statisticType === 'min') {
  46915. result = min;
  46916. } else if (statisticType === 'max') {
  46917. result = max;
  46918. } else if (statisticType === 'average') {
  46919. result = sum / len;
  46920. } else {
  46921. result = sum;
  46922. }
  46923. return len === 0 ? NaN : result;
  46924. });
  46925. }
  46926. function mapDataStatistic(ecModel) {
  46927. var seriesGroups = {};
  46928. ecModel.eachSeriesByType('map', function (seriesModel) {
  46929. var hostGeoModel = seriesModel.getHostGeoModel();
  46930. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  46931. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  46932. });
  46933. each(seriesGroups, function (seriesList, key) {
  46934. var data = dataStatistics(map(seriesList, function (seriesModel) {
  46935. return seriesModel.getData();
  46936. }), seriesList[0].get('mapValueCalculation'));
  46937. for (var i = 0; i < seriesList.length; i++) {
  46938. seriesList[i].originalData = seriesList[i].getData();
  46939. } // FIXME Put where?
  46940. for (var i = 0; i < seriesList.length; i++) {
  46941. seriesList[i].seriesGroup = seriesList;
  46942. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  46943. seriesList[i].setData(data.cloneShallow());
  46944. seriesList[i].mainSeries = seriesList[0];
  46945. }
  46946. });
  46947. }
  46948. function mapSymbolLayout(ecModel) {
  46949. var processedMapType = {};
  46950. ecModel.eachSeriesByType('map', function (mapSeries) {
  46951. var mapType = mapSeries.getMapType();
  46952. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  46953. return;
  46954. }
  46955. var mapSymbolOffsets = {};
  46956. each(mapSeries.seriesGroup, function (subMapSeries) {
  46957. var geo = subMapSeries.coordinateSystem;
  46958. var data = subMapSeries.originalData;
  46959. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  46960. data.each(data.mapDimension('value'), function (value, idx) {
  46961. var name = data.getName(idx);
  46962. var region = geo.getRegion(name); // If input series.data is [11, 22, '-'/null/undefined, 44],
  46963. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  46964. // not be drawn. So here must validate if value is NaN.
  46965. if (!region || isNaN(value)) {
  46966. return;
  46967. }
  46968. var offset = mapSymbolOffsets[name] || 0;
  46969. var point = geo.dataToPoint(region.getCenter());
  46970. mapSymbolOffsets[name] = offset + 1;
  46971. data.setItemLayout(idx, {
  46972. point: point,
  46973. offset: offset
  46974. });
  46975. });
  46976. }
  46977. }); // Show label of those region not has legendIcon (which is offset 0)
  46978. var data = mapSeries.getData();
  46979. data.each(function (idx) {
  46980. var name = data.getName(idx);
  46981. var layout = data.getItemLayout(idx) || {};
  46982. layout.showLabel = !mapSymbolOffsets[name];
  46983. data.setItemLayout(idx, layout);
  46984. });
  46985. processedMapType[mapType] = true;
  46986. });
  46987. }
  46988. var v2ApplyTransform = applyTransform;
  46989. var View =
  46990. /** @class */
  46991. function (_super) {
  46992. __extends(View, _super);
  46993. function View(name) {
  46994. var _this = _super.call(this) || this;
  46995. _this.type = 'view';
  46996. _this.dimensions = ['x', 'y'];
  46997. /**
  46998. * Represents the transform brought by roam/zoom.
  46999. * If `View['_viewRect']` applies roam transform,
  47000. * we can get the final displayed rect.
  47001. */
  47002. _this._roamTransformable = new Transformable();
  47003. /**
  47004. * Represents the transform from `View['_rect']` to `View['_viewRect']`.
  47005. */
  47006. _this._rawTransformable = new Transformable();
  47007. _this.name = name;
  47008. return _this;
  47009. }
  47010. View.prototype.setBoundingRect = function (x, y, width, height) {
  47011. this._rect = new BoundingRect(x, y, width, height);
  47012. return this._rect;
  47013. };
  47014. /**
  47015. * @return {module:zrender/core/BoundingRect}
  47016. */
  47017. View.prototype.getBoundingRect = function () {
  47018. return this._rect;
  47019. };
  47020. View.prototype.setViewRect = function (x, y, width, height) {
  47021. this._transformTo(x, y, width, height);
  47022. this._viewRect = new BoundingRect(x, y, width, height);
  47023. };
  47024. /**
  47025. * Transformed to particular position and size
  47026. */
  47027. View.prototype._transformTo = function (x, y, width, height) {
  47028. var rect = this.getBoundingRect();
  47029. var rawTransform = this._rawTransformable;
  47030. rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  47031. var rawParent = rawTransform.parent;
  47032. rawTransform.parent = null;
  47033. rawTransform.decomposeTransform();
  47034. rawTransform.parent = rawParent;
  47035. this._updateTransform();
  47036. };
  47037. /**
  47038. * Set center of view
  47039. */
  47040. View.prototype.setCenter = function (centerCoord, api) {
  47041. if (!centerCoord) {
  47042. return;
  47043. }
  47044. this._center = [parsePercent$1(centerCoord[0], api.getWidth()), parsePercent$1(centerCoord[1], api.getHeight())];
  47045. this._updateCenterAndZoom();
  47046. };
  47047. View.prototype.setZoom = function (zoom) {
  47048. zoom = zoom || 1;
  47049. var zoomLimit = this.zoomLimit;
  47050. if (zoomLimit) {
  47051. if (zoomLimit.max != null) {
  47052. zoom = Math.min(zoomLimit.max, zoom);
  47053. }
  47054. if (zoomLimit.min != null) {
  47055. zoom = Math.max(zoomLimit.min, zoom);
  47056. }
  47057. }
  47058. this._zoom = zoom;
  47059. this._updateCenterAndZoom();
  47060. };
  47061. /**
  47062. * Get default center without roam
  47063. */
  47064. View.prototype.getDefaultCenter = function () {
  47065. // Rect before any transform
  47066. var rawRect = this.getBoundingRect();
  47067. var cx = rawRect.x + rawRect.width / 2;
  47068. var cy = rawRect.y + rawRect.height / 2;
  47069. return [cx, cy];
  47070. };
  47071. View.prototype.getCenter = function () {
  47072. return this._center || this.getDefaultCenter();
  47073. };
  47074. View.prototype.getZoom = function () {
  47075. return this._zoom || 1;
  47076. };
  47077. View.prototype.getRoamTransform = function () {
  47078. return this._roamTransformable.getLocalTransform();
  47079. };
  47080. /**
  47081. * Remove roam
  47082. */
  47083. View.prototype._updateCenterAndZoom = function () {
  47084. // Must update after view transform updated
  47085. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  47086. var roamTransform = this._roamTransformable;
  47087. var defaultCenter = this.getDefaultCenter();
  47088. var center = this.getCenter();
  47089. var zoom = this.getZoom();
  47090. center = applyTransform([], center, rawTransformMatrix);
  47091. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  47092. roamTransform.originX = center[0];
  47093. roamTransform.originY = center[1];
  47094. roamTransform.x = defaultCenter[0] - center[0];
  47095. roamTransform.y = defaultCenter[1] - center[1];
  47096. roamTransform.scaleX = roamTransform.scaleY = zoom;
  47097. this._updateTransform();
  47098. };
  47099. /**
  47100. * Update transform props on `this` based on the current
  47101. * `this._roamTransformable` and `this._rawTransformable`.
  47102. */
  47103. View.prototype._updateTransform = function () {
  47104. var roamTransformable = this._roamTransformable;
  47105. var rawTransformable = this._rawTransformable;
  47106. rawTransformable.parent = roamTransformable;
  47107. roamTransformable.updateTransform();
  47108. rawTransformable.updateTransform();
  47109. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  47110. this._rawTransform = rawTransformable.getLocalTransform();
  47111. this.invTransform = this.invTransform || [];
  47112. invert(this.invTransform, this.transform);
  47113. this.decomposeTransform();
  47114. };
  47115. View.prototype.getTransformInfo = function () {
  47116. var rawTransformable = this._rawTransformable;
  47117. var roamTransformable = this._roamTransformable; // Because roamTransformabel has `originX/originY` modified,
  47118. // but the caller of `getTransformInfo` can not handle `originX/originY`,
  47119. // so need to recalculate them.
  47120. var dummyTransformable = new Transformable();
  47121. dummyTransformable.transform = roamTransformable.transform;
  47122. dummyTransformable.decomposeTransform();
  47123. return {
  47124. roam: {
  47125. x: dummyTransformable.x,
  47126. y: dummyTransformable.y,
  47127. scaleX: dummyTransformable.scaleX,
  47128. scaleY: dummyTransformable.scaleY
  47129. },
  47130. raw: {
  47131. x: rawTransformable.x,
  47132. y: rawTransformable.y,
  47133. scaleX: rawTransformable.scaleX,
  47134. scaleY: rawTransformable.scaleY
  47135. }
  47136. };
  47137. };
  47138. View.prototype.getViewRect = function () {
  47139. return this._viewRect;
  47140. };
  47141. /**
  47142. * Get view rect after roam transform
  47143. */
  47144. View.prototype.getViewRectAfterRoam = function () {
  47145. var rect = this.getBoundingRect().clone();
  47146. rect.applyTransform(this.transform);
  47147. return rect;
  47148. };
  47149. /**
  47150. * Convert a single (lon, lat) data item to (x, y) point.
  47151. */
  47152. View.prototype.dataToPoint = function (data, noRoam, out) {
  47153. var transform = noRoam ? this._rawTransform : this.transform;
  47154. out = out || [];
  47155. return transform ? v2ApplyTransform(out, data, transform) : copy(out, data);
  47156. };
  47157. /**
  47158. * Convert a (x, y) point to (lon, lat) data
  47159. */
  47160. View.prototype.pointToData = function (point) {
  47161. var invTransform = this.invTransform;
  47162. return invTransform ? v2ApplyTransform([], point, invTransform) : [point[0], point[1]];
  47163. };
  47164. View.prototype.convertToPixel = function (ecModel, finder, value) {
  47165. var coordSys = getCoordSys(finder);
  47166. return coordSys === this ? coordSys.dataToPoint(value) : null;
  47167. };
  47168. View.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  47169. var coordSys = getCoordSys(finder);
  47170. return coordSys === this ? coordSys.pointToData(pixel) : null;
  47171. };
  47172. /**
  47173. * @implements
  47174. */
  47175. View.prototype.containPoint = function (point) {
  47176. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  47177. };
  47178. View.dimensions = ['x', 'y'];
  47179. return View;
  47180. }(Transformable);
  47181. function getCoordSys(finder) {
  47182. var seriesModel = finder.seriesModel;
  47183. return seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  47184. }
  47185. var GEO_DEFAULT_PARAMS = {
  47186. 'geoJSON': {
  47187. aspectScale: 0.75,
  47188. invertLongitute: true
  47189. },
  47190. 'geoSVG': {
  47191. aspectScale: 1,
  47192. invertLongitute: false
  47193. }
  47194. };
  47195. var geo2DDimensions = ['lng', 'lat'];
  47196. var Geo =
  47197. /** @class */
  47198. function (_super) {
  47199. __extends(Geo, _super);
  47200. function Geo(name, map, opt) {
  47201. var _this = _super.call(this, name) || this;
  47202. _this.dimensions = geo2DDimensions;
  47203. _this.type = 'geo'; // Only store specified name coord via `addGeoCoord`.
  47204. _this._nameCoordMap = createHashMap();
  47205. _this.map = map;
  47206. var projection = opt.projection;
  47207. var source = geoSourceManager.load(map, opt.nameMap, opt.nameProperty);
  47208. var resource = geoSourceManager.getGeoResource(map);
  47209. var resourceType = _this.resourceType = resource ? resource.type : null;
  47210. var regions = _this.regions = source.regions;
  47211. var defaultParams = GEO_DEFAULT_PARAMS[resource.type];
  47212. _this._regionsMap = source.regionsMap;
  47213. _this.regions = source.regions;
  47214. if ("development" !== 'production' && projection) {
  47215. // Do some check
  47216. if (resourceType === 'geoSVG') {
  47217. if ("development" !== 'production') {
  47218. warn("Map " + map + " with SVG source can't use projection. Only GeoJSON source supports projection.");
  47219. }
  47220. projection = null;
  47221. }
  47222. if (!(projection.project && projection.unproject)) {
  47223. if ("development" !== 'production') {
  47224. warn('project and unproject must be both provided in the projeciton.');
  47225. }
  47226. projection = null;
  47227. }
  47228. }
  47229. _this.projection = projection;
  47230. var boundingRect;
  47231. if (projection) {
  47232. // Can't reuse the raw bounding rect
  47233. for (var i = 0; i < regions.length; i++) {
  47234. var regionRect = regions[i].getBoundingRect(projection);
  47235. boundingRect = boundingRect || regionRect.clone();
  47236. boundingRect.union(regionRect);
  47237. }
  47238. } else {
  47239. boundingRect = source.boundingRect;
  47240. }
  47241. _this.setBoundingRect(boundingRect.x, boundingRect.y, boundingRect.width, boundingRect.height); // aspectScale and invertLongitute actually is the parameters default raw projection.
  47242. // So we ignore them if projection is given.
  47243. // Ignore default aspect scale if projection exits.
  47244. _this.aspectScale = projection ? 1 : retrieve2(opt.aspectScale, defaultParams.aspectScale); // Not invert longitude if projection exits.
  47245. _this._invertLongitute = projection ? false : defaultParams.invertLongitute;
  47246. return _this;
  47247. }
  47248. Geo.prototype._transformTo = function (x, y, width, height) {
  47249. var rect = this.getBoundingRect();
  47250. var invertLongitute = this._invertLongitute;
  47251. rect = rect.clone();
  47252. if (invertLongitute) {
  47253. // Longitude is inverted.
  47254. rect.y = -rect.y - rect.height;
  47255. }
  47256. var rawTransformable = this._rawTransformable;
  47257. rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  47258. var rawParent = rawTransformable.parent;
  47259. rawTransformable.parent = null;
  47260. rawTransformable.decomposeTransform();
  47261. rawTransformable.parent = rawParent;
  47262. if (invertLongitute) {
  47263. rawTransformable.scaleY = -rawTransformable.scaleY;
  47264. }
  47265. this._updateTransform();
  47266. };
  47267. Geo.prototype.getRegion = function (name) {
  47268. return this._regionsMap.get(name);
  47269. };
  47270. Geo.prototype.getRegionByCoord = function (coord) {
  47271. var regions = this.regions;
  47272. for (var i = 0; i < regions.length; i++) {
  47273. var region = regions[i];
  47274. if (region.type === 'geoJSON' && region.contain(coord)) {
  47275. return regions[i];
  47276. }
  47277. }
  47278. };
  47279. /**
  47280. * Add geoCoord for indexing by name
  47281. */
  47282. Geo.prototype.addGeoCoord = function (name, geoCoord) {
  47283. this._nameCoordMap.set(name, geoCoord);
  47284. };
  47285. /**
  47286. * Get geoCoord by name
  47287. */
  47288. Geo.prototype.getGeoCoord = function (name) {
  47289. var region = this._regionsMap.get(name); // Calculate center only on demand.
  47290. return this._nameCoordMap.get(name) || region && region.getCenter();
  47291. };
  47292. Geo.prototype.dataToPoint = function (data, noRoam, out) {
  47293. if (isString(data)) {
  47294. // Map area name to geoCoord
  47295. data = this.getGeoCoord(data);
  47296. }
  47297. if (data) {
  47298. var projection = this.projection;
  47299. if (projection) {
  47300. // projection may return null point.
  47301. data = projection.project(data);
  47302. }
  47303. return data && this.projectedToPoint(data, noRoam, out);
  47304. }
  47305. };
  47306. Geo.prototype.pointToData = function (point) {
  47307. var projection = this.projection;
  47308. if (projection) {
  47309. // projection may return null point.
  47310. point = projection.unproject(point);
  47311. }
  47312. return point && this.pointToProjected(point);
  47313. };
  47314. /**
  47315. * Point to projected data. Same with pointToData when projection is used.
  47316. */
  47317. Geo.prototype.pointToProjected = function (point) {
  47318. return _super.prototype.pointToData.call(this, point);
  47319. };
  47320. Geo.prototype.projectedToPoint = function (projected, noRoam, out) {
  47321. return _super.prototype.dataToPoint.call(this, projected, noRoam, out);
  47322. };
  47323. Geo.prototype.convertToPixel = function (ecModel, finder, value) {
  47324. var coordSys = getCoordSys$1(finder);
  47325. return coordSys === this ? coordSys.dataToPoint(value) : null;
  47326. };
  47327. Geo.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  47328. var coordSys = getCoordSys$1(finder);
  47329. return coordSys === this ? coordSys.pointToData(pixel) : null;
  47330. };
  47331. return Geo;
  47332. }(View);
  47333. mixin(Geo, View);
  47334. function getCoordSys$1(finder) {
  47335. var geoModel = finder.geoModel;
  47336. var seriesModel = finder.seriesModel;
  47337. return geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem // For map series.
  47338. || (seriesModel.getReferringComponents('geo', SINGLE_REFERRING).models[0] || {}).coordinateSystem : null;
  47339. }
  47340. /**
  47341. * Resize method bound to the geo
  47342. */
  47343. function resizeGeo(geoModel, api) {
  47344. var boundingCoords = geoModel.get('boundingCoords');
  47345. if (boundingCoords != null) {
  47346. var leftTop_1 = boundingCoords[0];
  47347. var rightBottom_1 = boundingCoords[1];
  47348. if (!(isFinite(leftTop_1[0]) && isFinite(leftTop_1[1]) && isFinite(rightBottom_1[0]) && isFinite(rightBottom_1[1]))) {
  47349. if ("development" !== 'production') {
  47350. console.error('Invalid boundingCoords');
  47351. }
  47352. } else {
  47353. // Sample around the lng/lat rect and use projection to calculate actual bounding rect.
  47354. var projection_1 = this.projection;
  47355. if (projection_1) {
  47356. var xMin = leftTop_1[0];
  47357. var yMin = leftTop_1[1];
  47358. var xMax = rightBottom_1[0];
  47359. var yMax = rightBottom_1[1];
  47360. leftTop_1 = [Infinity, Infinity];
  47361. rightBottom_1 = [-Infinity, -Infinity]; // TODO better way?
  47362. var sampleLine = function (x0, y0, x1, y1) {
  47363. var dx = x1 - x0;
  47364. var dy = y1 - y0;
  47365. for (var i = 0; i <= 100; i++) {
  47366. var p = i / 100;
  47367. var pt = projection_1.project([x0 + dx * p, y0 + dy * p]);
  47368. min(leftTop_1, leftTop_1, pt);
  47369. max(rightBottom_1, rightBottom_1, pt);
  47370. }
  47371. }; // Top
  47372. sampleLine(xMin, yMin, xMax, yMin); // Right
  47373. sampleLine(xMax, yMin, xMax, yMax); // Bottom
  47374. sampleLine(xMax, yMax, xMin, yMax); // Left
  47375. sampleLine(xMin, yMax, xMax, yMin);
  47376. }
  47377. this.setBoundingRect(leftTop_1[0], leftTop_1[1], rightBottom_1[0] - leftTop_1[0], rightBottom_1[1] - leftTop_1[1]);
  47378. }
  47379. }
  47380. var rect = this.getBoundingRect();
  47381. var centerOption = geoModel.get('layoutCenter');
  47382. var sizeOption = geoModel.get('layoutSize');
  47383. var viewWidth = api.getWidth();
  47384. var viewHeight = api.getHeight();
  47385. var aspect = rect.width / rect.height * this.aspectScale;
  47386. var useCenterAndSize = false;
  47387. var center;
  47388. var size;
  47389. if (centerOption && sizeOption) {
  47390. center = [parsePercent$1(centerOption[0], viewWidth), parsePercent$1(centerOption[1], viewHeight)];
  47391. size = parsePercent$1(sizeOption, Math.min(viewWidth, viewHeight));
  47392. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  47393. useCenterAndSize = true;
  47394. } else {
  47395. if ("development" !== 'production') {
  47396. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  47397. }
  47398. }
  47399. }
  47400. var viewRect;
  47401. if (useCenterAndSize) {
  47402. viewRect = {};
  47403. if (aspect > 1) {
  47404. // Width is same with size
  47405. viewRect.width = size;
  47406. viewRect.height = size / aspect;
  47407. } else {
  47408. viewRect.height = size;
  47409. viewRect.width = size * aspect;
  47410. }
  47411. viewRect.y = center[1] - viewRect.height / 2;
  47412. viewRect.x = center[0] - viewRect.width / 2;
  47413. } else {
  47414. // Use left/top/width/height
  47415. var boxLayoutOption = geoModel.getBoxLayoutParams();
  47416. boxLayoutOption.aspect = aspect;
  47417. viewRect = getLayoutRect(boxLayoutOption, {
  47418. width: viewWidth,
  47419. height: viewHeight
  47420. });
  47421. }
  47422. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  47423. this.setCenter(geoModel.get('center'), api);
  47424. this.setZoom(geoModel.get('zoom'));
  47425. } // Back compat for ECharts2, where the coord map is set on map series:
  47426. // {type: 'map', geoCoord: {'cityA': [116.46,39.92], 'cityA': [119.12,24.61]}},
  47427. function setGeoCoords(geo, model) {
  47428. each(model.get('geoCoord'), function (geoCoord, name) {
  47429. geo.addGeoCoord(name, geoCoord);
  47430. });
  47431. }
  47432. var GeoCreator =
  47433. /** @class */
  47434. function () {
  47435. function GeoCreator() {
  47436. // For deciding which dimensions to use when creating list data
  47437. this.dimensions = geo2DDimensions;
  47438. }
  47439. GeoCreator.prototype.create = function (ecModel, api) {
  47440. var geoList = [];
  47441. function getCommonGeoProperties(model) {
  47442. return {
  47443. nameProperty: model.get('nameProperty'),
  47444. aspectScale: model.get('aspectScale'),
  47445. projection: model.get('projection')
  47446. };
  47447. } // FIXME Create each time may be slow
  47448. ecModel.eachComponent('geo', function (geoModel, idx) {
  47449. var mapName = geoModel.get('map');
  47450. var geo = new Geo(mapName + idx, mapName, extend({
  47451. nameMap: geoModel.get('nameMap')
  47452. }, getCommonGeoProperties(geoModel)));
  47453. geo.zoomLimit = geoModel.get('scaleLimit');
  47454. geoList.push(geo); // setGeoCoords(geo, geoModel);
  47455. geoModel.coordinateSystem = geo;
  47456. geo.model = geoModel; // Inject resize method
  47457. geo.resize = resizeGeo;
  47458. geo.resize(geoModel, api);
  47459. });
  47460. ecModel.eachSeries(function (seriesModel) {
  47461. var coordSys = seriesModel.get('coordinateSystem');
  47462. if (coordSys === 'geo') {
  47463. var geoIndex = seriesModel.get('geoIndex') || 0;
  47464. seriesModel.coordinateSystem = geoList[geoIndex];
  47465. }
  47466. }); // If has map series
  47467. var mapModelGroupBySeries = {};
  47468. ecModel.eachSeriesByType('map', function (seriesModel) {
  47469. if (!seriesModel.getHostGeoModel()) {
  47470. var mapType = seriesModel.getMapType();
  47471. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  47472. mapModelGroupBySeries[mapType].push(seriesModel);
  47473. }
  47474. });
  47475. each(mapModelGroupBySeries, function (mapSeries, mapType) {
  47476. var nameMapList = map(mapSeries, function (singleMapSeries) {
  47477. return singleMapSeries.get('nameMap');
  47478. });
  47479. var geo = new Geo(mapType, mapType, extend({
  47480. nameMap: mergeAll(nameMapList)
  47481. }, getCommonGeoProperties(mapSeries[0])));
  47482. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  47483. return singleMapSeries.get('scaleLimit');
  47484. }));
  47485. geoList.push(geo); // Inject resize method
  47486. geo.resize = resizeGeo;
  47487. geo.resize(mapSeries[0], api);
  47488. each(mapSeries, function (singleMapSeries) {
  47489. singleMapSeries.coordinateSystem = geo;
  47490. setGeoCoords(geo, singleMapSeries);
  47491. });
  47492. });
  47493. return geoList;
  47494. };
  47495. /**
  47496. * Fill given regions array
  47497. */
  47498. GeoCreator.prototype.getFilledRegions = function (originRegionArr, mapName, nameMap, nameProperty) {
  47499. // Not use the original
  47500. var regionsArr = (originRegionArr || []).slice();
  47501. var dataNameMap = createHashMap();
  47502. for (var i = 0; i < regionsArr.length; i++) {
  47503. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  47504. }
  47505. var source = geoSourceManager.load(mapName, nameMap, nameProperty);
  47506. each(source.regions, function (region) {
  47507. var name = region.name;
  47508. !dataNameMap.get(name) && regionsArr.push({
  47509. name: name
  47510. });
  47511. });
  47512. return regionsArr;
  47513. };
  47514. return GeoCreator;
  47515. }();
  47516. var geoCreator = new GeoCreator();
  47517. var GeoModel =
  47518. /** @class */
  47519. function (_super) {
  47520. __extends(GeoModel, _super);
  47521. function GeoModel() {
  47522. var _this = _super !== null && _super.apply(this, arguments) || this;
  47523. _this.type = GeoModel.type;
  47524. return _this;
  47525. }
  47526. GeoModel.prototype.init = function (option, parentModel, ecModel) {
  47527. var source = geoSourceManager.getGeoResource(option.map);
  47528. if (source && source.type === 'geoJSON') {
  47529. var itemStyle = option.itemStyle = option.itemStyle || {};
  47530. if (!('color' in itemStyle)) {
  47531. itemStyle.color = '#eee';
  47532. }
  47533. }
  47534. this.mergeDefaultAndTheme(option, ecModel); // Default label emphasis `show`
  47535. defaultEmphasis(option, 'label', ['show']);
  47536. };
  47537. GeoModel.prototype.optionUpdated = function () {
  47538. var _this = this;
  47539. var option = this.option;
  47540. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap, option.nameProperty);
  47541. var selectedMap = {};
  47542. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  47543. var regionName = regionOpt.name;
  47544. if (regionName) {
  47545. optionModelMap.set(regionName, new Model(regionOpt, _this, _this.ecModel));
  47546. if (regionOpt.selected) {
  47547. selectedMap[regionName] = true;
  47548. }
  47549. }
  47550. return optionModelMap;
  47551. }, createHashMap());
  47552. if (!option.selectedMap) {
  47553. option.selectedMap = selectedMap;
  47554. }
  47555. };
  47556. /**
  47557. * Get model of region.
  47558. */
  47559. GeoModel.prototype.getRegionModel = function (name) {
  47560. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  47561. };
  47562. /**
  47563. * Format label
  47564. * @param name Region name
  47565. */
  47566. GeoModel.prototype.getFormattedLabel = function (name, status) {
  47567. var regionModel = this.getRegionModel(name);
  47568. var formatter = status === 'normal' ? regionModel.get(['label', 'formatter']) : regionModel.get(['emphasis', 'label', 'formatter']);
  47569. var params = {
  47570. name: name
  47571. };
  47572. if (isFunction(formatter)) {
  47573. params.status = status;
  47574. return formatter(params);
  47575. } else if (isString(formatter)) {
  47576. return formatter.replace('{a}', name != null ? name : '');
  47577. }
  47578. };
  47579. GeoModel.prototype.setZoom = function (zoom) {
  47580. this.option.zoom = zoom;
  47581. };
  47582. GeoModel.prototype.setCenter = function (center) {
  47583. this.option.center = center;
  47584. }; // PENGING If selectedMode is null ?
  47585. GeoModel.prototype.select = function (name) {
  47586. var option = this.option;
  47587. var selectedMode = option.selectedMode;
  47588. if (!selectedMode) {
  47589. return;
  47590. }
  47591. if (selectedMode !== 'multiple') {
  47592. option.selectedMap = null;
  47593. }
  47594. var selectedMap = option.selectedMap || (option.selectedMap = {});
  47595. selectedMap[name] = true;
  47596. };
  47597. GeoModel.prototype.unSelect = function (name) {
  47598. var selectedMap = this.option.selectedMap;
  47599. if (selectedMap) {
  47600. selectedMap[name] = false;
  47601. }
  47602. };
  47603. GeoModel.prototype.toggleSelected = function (name) {
  47604. this[this.isSelected(name) ? 'unSelect' : 'select'](name);
  47605. };
  47606. GeoModel.prototype.isSelected = function (name) {
  47607. var selectedMap = this.option.selectedMap;
  47608. return !!(selectedMap && selectedMap[name]);
  47609. };
  47610. GeoModel.type = 'geo';
  47611. GeoModel.layoutMode = 'box';
  47612. GeoModel.defaultOption = {
  47613. // zlevel: 0,
  47614. z: 0,
  47615. show: true,
  47616. left: 'center',
  47617. top: 'center',
  47618. // Default value:
  47619. // for geoSVG source: 1,
  47620. // for geoJSON source: 0.75.
  47621. aspectScale: null,
  47622. // /// Layout with center and size
  47623. // If you want to put map in a fixed size box with right aspect ratio
  47624. // This two properties may be more convenient
  47625. // layoutCenter: [50%, 50%]
  47626. // layoutSize: 100
  47627. silent: false,
  47628. // Map type
  47629. map: '',
  47630. // Define left-top, right-bottom coords to control view
  47631. // For example, [ [180, 90], [-180, -90] ]
  47632. boundingCoords: null,
  47633. // Default on center of map
  47634. center: null,
  47635. zoom: 1,
  47636. scaleLimit: null,
  47637. // selectedMode: false
  47638. label: {
  47639. show: false,
  47640. color: '#000'
  47641. },
  47642. itemStyle: {
  47643. borderWidth: 0.5,
  47644. borderColor: '#444' // Default color:
  47645. // + geoJSON: #eee
  47646. // + geoSVG: null (use SVG original `fill`)
  47647. // color: '#eee'
  47648. },
  47649. emphasis: {
  47650. label: {
  47651. show: true,
  47652. color: 'rgb(100,0,0)'
  47653. },
  47654. itemStyle: {
  47655. color: 'rgba(255,215,0,0.8)'
  47656. }
  47657. },
  47658. select: {
  47659. label: {
  47660. show: true,
  47661. color: 'rgb(100,0,0)'
  47662. },
  47663. itemStyle: {
  47664. color: 'rgba(255,215,0,0.8)'
  47665. }
  47666. },
  47667. regions: [] // tooltip: {
  47668. // show: false
  47669. // }
  47670. };
  47671. return GeoModel;
  47672. }(ComponentModel);
  47673. /*
  47674. * Licensed to the Apache Software Foundation (ASF) under one
  47675. * or more contributor license agreements. See the NOTICE file
  47676. * distributed with this work for additional information
  47677. * regarding copyright ownership. The ASF licenses this file
  47678. * to you under the Apache License, Version 2.0 (the
  47679. * "License"); you may not use this file except in compliance
  47680. * with the License. You may obtain a copy of the License at
  47681. *
  47682. * http://www.apache.org/licenses/LICENSE-2.0
  47683. *
  47684. * Unless required by applicable law or agreed to in writing,
  47685. * software distributed under the License is distributed on an
  47686. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47687. * KIND, either express or implied. See the License for the
  47688. * specific language governing permissions and limitations
  47689. * under the License.
  47690. */
  47691. /**
  47692. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47693. */
  47694. /*
  47695. * Licensed to the Apache Software Foundation (ASF) under one
  47696. * or more contributor license agreements. See the NOTICE file
  47697. * distributed with this work for additional information
  47698. * regarding copyright ownership. The ASF licenses this file
  47699. * to you under the Apache License, Version 2.0 (the
  47700. * "License"); you may not use this file except in compliance
  47701. * with the License. You may obtain a copy of the License at
  47702. *
  47703. * http://www.apache.org/licenses/LICENSE-2.0
  47704. *
  47705. * Unless required by applicable law or agreed to in writing,
  47706. * software distributed under the License is distributed on an
  47707. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47708. * KIND, either express or implied. See the License for the
  47709. * specific language governing permissions and limitations
  47710. * under the License.
  47711. */
  47712. function getCenterCoord(view, point) {
  47713. // Use projected coord as center because it's linear.
  47714. return view.pointToProjected ? view.pointToProjected(point) : view.pointToData(point);
  47715. }
  47716. function updateCenterAndZoom(view, payload, zoomLimit, api) {
  47717. var previousZoom = view.getZoom();
  47718. var center = view.getCenter();
  47719. var zoom = payload.zoom;
  47720. var point = view.projectedToPoint ? view.projectedToPoint(center) : view.dataToPoint(center);
  47721. if (payload.dx != null && payload.dy != null) {
  47722. point[0] -= payload.dx;
  47723. point[1] -= payload.dy;
  47724. view.setCenter(getCenterCoord(view, point), api);
  47725. }
  47726. if (zoom != null) {
  47727. if (zoomLimit) {
  47728. var zoomMin = zoomLimit.min || 0;
  47729. var zoomMax = zoomLimit.max || Infinity;
  47730. zoom = Math.max(Math.min(previousZoom * zoom, zoomMax), zoomMin) / previousZoom;
  47731. } // Zoom on given point(originX, originY)
  47732. view.scaleX *= zoom;
  47733. view.scaleY *= zoom;
  47734. var fixX = (payload.originX - view.x) * (zoom - 1);
  47735. var fixY = (payload.originY - view.y) * (zoom - 1);
  47736. view.x -= fixX;
  47737. view.y -= fixY;
  47738. view.updateTransform(); // Get the new center
  47739. view.setCenter(getCenterCoord(view, point), api);
  47740. view.setZoom(zoom * previousZoom);
  47741. }
  47742. return {
  47743. center: view.getCenter(),
  47744. zoom: view.getZoom()
  47745. };
  47746. }
  47747. var GeoView =
  47748. /** @class */
  47749. function (_super) {
  47750. __extends(GeoView, _super);
  47751. function GeoView() {
  47752. var _this = _super !== null && _super.apply(this, arguments) || this;
  47753. _this.type = GeoView.type;
  47754. _this.focusBlurEnabled = true;
  47755. return _this;
  47756. }
  47757. GeoView.prototype.init = function (ecModel, api) {
  47758. this._api = api;
  47759. };
  47760. GeoView.prototype.render = function (geoModel, ecModel, api, payload) {
  47761. this._model = geoModel;
  47762. if (!geoModel.get('show')) {
  47763. this._mapDraw && this._mapDraw.remove();
  47764. this._mapDraw = null;
  47765. return;
  47766. }
  47767. if (!this._mapDraw) {
  47768. this._mapDraw = new MapDraw(api);
  47769. }
  47770. var mapDraw = this._mapDraw;
  47771. mapDraw.draw(geoModel, ecModel, api, this, payload);
  47772. mapDraw.group.on('click', this._handleRegionClick, this);
  47773. mapDraw.group.silent = geoModel.get('silent');
  47774. this.group.add(mapDraw.group);
  47775. this.updateSelectStatus(geoModel, ecModel, api);
  47776. };
  47777. GeoView.prototype._handleRegionClick = function (e) {
  47778. var eventData;
  47779. findEventDispatcher(e.target, function (current) {
  47780. return (eventData = getECData(current).eventData) != null;
  47781. }, true);
  47782. if (eventData) {
  47783. this._api.dispatchAction({
  47784. type: 'geoToggleSelect',
  47785. geoId: this._model.id,
  47786. name: eventData.name
  47787. });
  47788. }
  47789. };
  47790. GeoView.prototype.updateSelectStatus = function (model, ecModel, api) {
  47791. var _this = this;
  47792. this._mapDraw.group.traverse(function (node) {
  47793. var eventData = getECData(node).eventData;
  47794. if (eventData) {
  47795. _this._model.isSelected(eventData.name) ? api.enterSelect(node) : api.leaveSelect(node); // No need to traverse children.
  47796. return true;
  47797. }
  47798. });
  47799. };
  47800. GeoView.prototype.findHighDownDispatchers = function (name) {
  47801. return this._mapDraw && this._mapDraw.findHighDownDispatchers(name, this._model);
  47802. };
  47803. GeoView.prototype.dispose = function () {
  47804. this._mapDraw && this._mapDraw.remove();
  47805. };
  47806. GeoView.type = 'geo';
  47807. return GeoView;
  47808. }(ComponentView);
  47809. function registerMap$1(mapName, geoJson, specialAreas) {
  47810. geoSourceManager.registerMap(mapName, geoJson, specialAreas);
  47811. }
  47812. function install$9(registers) {
  47813. registers.registerCoordinateSystem('geo', geoCreator);
  47814. registers.registerComponentModel(GeoModel);
  47815. registers.registerComponentView(GeoView);
  47816. registers.registerImpl('registerMap', registerMap$1);
  47817. registers.registerImpl('getMap', function (mapName) {
  47818. return geoSourceManager.getMapForUser(mapName);
  47819. });
  47820. function makeAction(method, actionInfo) {
  47821. actionInfo.update = 'geo:updateSelectStatus';
  47822. registers.registerAction(actionInfo, function (payload, ecModel) {
  47823. var selected = {};
  47824. var allSelected = [];
  47825. ecModel.eachComponent({
  47826. mainType: 'geo',
  47827. query: payload
  47828. }, function (geoModel) {
  47829. geoModel[method](payload.name);
  47830. var geo = geoModel.coordinateSystem;
  47831. each(geo.regions, function (region) {
  47832. selected[region.name] = geoModel.isSelected(region.name) || false;
  47833. }); // Notice: there might be duplicated name in different regions.
  47834. var names = [];
  47835. each(selected, function (v, name) {
  47836. selected[name] && names.push(name);
  47837. });
  47838. allSelected.push({
  47839. geoIndex: geoModel.componentIndex,
  47840. // Use singular, the same naming convention as the event `selectchanged`.
  47841. name: names
  47842. });
  47843. });
  47844. return {
  47845. selected: selected,
  47846. allSelected: allSelected,
  47847. name: payload.name
  47848. };
  47849. });
  47850. }
  47851. makeAction('toggleSelected', {
  47852. type: 'geoToggleSelect',
  47853. event: 'geoselectchanged'
  47854. });
  47855. makeAction('select', {
  47856. type: 'geoSelect',
  47857. event: 'geoselected'
  47858. });
  47859. makeAction('unSelect', {
  47860. type: 'geoUnSelect',
  47861. event: 'geounselected'
  47862. });
  47863. /**
  47864. * @payload
  47865. * @property {string} [componentType=series]
  47866. * @property {number} [dx]
  47867. * @property {number} [dy]
  47868. * @property {number} [zoom]
  47869. * @property {number} [originX]
  47870. * @property {number} [originY]
  47871. */
  47872. registers.registerAction({
  47873. type: 'geoRoam',
  47874. event: 'geoRoam',
  47875. update: 'updateTransform'
  47876. }, function (payload, ecModel, api) {
  47877. var componentType = payload.componentType || 'series';
  47878. ecModel.eachComponent({
  47879. mainType: componentType,
  47880. query: payload
  47881. }, function (componentModel) {
  47882. var geo = componentModel.coordinateSystem;
  47883. if (geo.type !== 'geo') {
  47884. return;
  47885. }
  47886. var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit'), api);
  47887. componentModel.setCenter && componentModel.setCenter(res.center);
  47888. componentModel.setZoom && componentModel.setZoom(res.zoom); // All map series with same `map` use the same geo coordinate system
  47889. // So the center and zoom must be in sync. Include the series not selected by legend
  47890. if (componentType === 'series') {
  47891. each(componentModel.seriesGroup, function (seriesModel) {
  47892. seriesModel.setCenter(res.center);
  47893. seriesModel.setZoom(res.zoom);
  47894. });
  47895. }
  47896. });
  47897. });
  47898. }
  47899. function install$a(registers) {
  47900. use(install$9);
  47901. registers.registerChartView(MapView);
  47902. registers.registerSeriesModel(MapSeries);
  47903. registers.registerLayout(mapSymbolLayout);
  47904. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  47905. createLegacyDataSelectAction('map', registers.registerAction);
  47906. }
  47907. /**
  47908. * Initialize all computational message for following algorithm.
  47909. */
  47910. function init$2(inRoot) {
  47911. var root = inRoot;
  47912. root.hierNode = {
  47913. defaultAncestor: null,
  47914. ancestor: root,
  47915. prelim: 0,
  47916. modifier: 0,
  47917. change: 0,
  47918. shift: 0,
  47919. i: 0,
  47920. thread: null
  47921. };
  47922. var nodes = [root];
  47923. var node;
  47924. var children;
  47925. while (node = nodes.pop()) {
  47926. // jshint ignore:line
  47927. children = node.children;
  47928. if (node.isExpand && children.length) {
  47929. var n = children.length;
  47930. for (var i = n - 1; i >= 0; i--) {
  47931. var child = children[i];
  47932. child.hierNode = {
  47933. defaultAncestor: null,
  47934. ancestor: child,
  47935. prelim: 0,
  47936. modifier: 0,
  47937. change: 0,
  47938. shift: 0,
  47939. i: i,
  47940. thread: null
  47941. };
  47942. nodes.push(child);
  47943. }
  47944. }
  47945. }
  47946. }
  47947. /**
  47948. * The implementation of this function was originally copied from "d3.js"
  47949. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47950. * with some modifications made for this program.
  47951. * See the license statement at the head of this file.
  47952. *
  47953. * Computes a preliminary x coordinate for node. Before that, this function is
  47954. * applied recursively to the children of node, as well as the function
  47955. * apportion(). After spacing out the children by calling executeShifts(), the
  47956. * node is placed to the midpoint of its outermost children.
  47957. */
  47958. function firstWalk(node, separation) {
  47959. var children = node.isExpand ? node.children : [];
  47960. var siblings = node.parentNode.children;
  47961. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  47962. if (children.length) {
  47963. executeShifts(node);
  47964. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  47965. if (subtreeW) {
  47966. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  47967. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  47968. } else {
  47969. node.hierNode.prelim = midPoint;
  47970. }
  47971. } else if (subtreeW) {
  47972. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  47973. }
  47974. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  47975. }
  47976. /**
  47977. * The implementation of this function was originally copied from "d3.js"
  47978. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47979. * with some modifications made for this program.
  47980. * See the license statement at the head of this file.
  47981. *
  47982. * Computes all real x-coordinates by summing up the modifiers recursively.
  47983. */
  47984. function secondWalk(node) {
  47985. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  47986. node.setLayout({
  47987. x: nodeX
  47988. }, true);
  47989. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  47990. }
  47991. function separation(cb) {
  47992. return arguments.length ? cb : defaultSeparation;
  47993. }
  47994. /**
  47995. * Transform the common coordinate to radial coordinate.
  47996. */
  47997. function radialCoordinate(rad, r) {
  47998. rad -= Math.PI / 2;
  47999. return {
  48000. x: r * Math.cos(rad),
  48001. y: r * Math.sin(rad)
  48002. };
  48003. }
  48004. /**
  48005. * Get the layout position of the whole view.
  48006. */
  48007. function getViewRect$1(seriesModel, api) {
  48008. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  48009. width: api.getWidth(),
  48010. height: api.getHeight()
  48011. });
  48012. }
  48013. /**
  48014. * All other shifts, applied to the smaller subtrees between w- and w+, are
  48015. * performed by this function.
  48016. *
  48017. * The implementation of this function was originally copied from "d3.js"
  48018. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48019. * with some modifications made for this program.
  48020. * See the license statement at the head of this file.
  48021. */
  48022. function executeShifts(node) {
  48023. var children = node.children;
  48024. var n = children.length;
  48025. var shift = 0;
  48026. var change = 0;
  48027. while (--n >= 0) {
  48028. var child = children[n];
  48029. child.hierNode.prelim += shift;
  48030. child.hierNode.modifier += shift;
  48031. change += child.hierNode.change;
  48032. shift += child.hierNode.shift + change;
  48033. }
  48034. }
  48035. /**
  48036. * The implementation of this function was originally copied from "d3.js"
  48037. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48038. * with some modifications made for this program.
  48039. * See the license statement at the head of this file.
  48040. *
  48041. * The core of the algorithm. Here, a new subtree is combined with the
  48042. * previous subtrees. Threads are used to traverse the inside and outside
  48043. * contours of the left and right subtree up to the highest common level.
  48044. * Whenever two nodes of the inside contours conflict, we compute the left
  48045. * one of the greatest uncommon ancestors using the function nextAncestor()
  48046. * and call moveSubtree() to shift the subtree and prepare the shifts of
  48047. * smaller subtrees. Finally, we add a new thread (if necessary).
  48048. */
  48049. function apportion(subtreeV, subtreeW, ancestor, separation) {
  48050. if (subtreeW) {
  48051. var nodeOutRight = subtreeV;
  48052. var nodeInRight = subtreeV;
  48053. var nodeOutLeft = nodeInRight.parentNode.children[0];
  48054. var nodeInLeft = subtreeW;
  48055. var sumOutRight = nodeOutRight.hierNode.modifier;
  48056. var sumInRight = nodeInRight.hierNode.modifier;
  48057. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  48058. var sumInLeft = nodeInLeft.hierNode.modifier;
  48059. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  48060. nodeOutRight = nextRight(nodeOutRight);
  48061. nodeOutLeft = nextLeft(nodeOutLeft);
  48062. nodeOutRight.hierNode.ancestor = subtreeV;
  48063. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight);
  48064. if (shift > 0) {
  48065. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  48066. sumInRight += shift;
  48067. sumOutRight += shift;
  48068. }
  48069. sumInLeft += nodeInLeft.hierNode.modifier;
  48070. sumInRight += nodeInRight.hierNode.modifier;
  48071. sumOutRight += nodeOutRight.hierNode.modifier;
  48072. sumOutLeft += nodeOutLeft.hierNode.modifier;
  48073. }
  48074. if (nodeInLeft && !nextRight(nodeOutRight)) {
  48075. nodeOutRight.hierNode.thread = nodeInLeft;
  48076. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  48077. }
  48078. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  48079. nodeOutLeft.hierNode.thread = nodeInRight;
  48080. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  48081. ancestor = subtreeV;
  48082. }
  48083. }
  48084. return ancestor;
  48085. }
  48086. /**
  48087. * This function is used to traverse the right contour of a subtree.
  48088. * It returns the rightmost child of node or the thread of node. The function
  48089. * returns null if and only if node is on the highest depth of its subtree.
  48090. */
  48091. function nextRight(node) {
  48092. var children = node.children;
  48093. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  48094. }
  48095. /**
  48096. * This function is used to traverse the left contour of a subtree (or a subforest).
  48097. * It returns the leftmost child of node or the thread of node. The function
  48098. * returns null if and only if node is on the highest depth of its subtree.
  48099. */
  48100. function nextLeft(node) {
  48101. var children = node.children;
  48102. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  48103. }
  48104. /**
  48105. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  48106. * Otherwise, returns the specified ancestor.
  48107. */
  48108. function nextAncestor(nodeInLeft, node, ancestor) {
  48109. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor;
  48110. }
  48111. /**
  48112. * The implementation of this function was originally copied from "d3.js"
  48113. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48114. * with some modifications made for this program.
  48115. * See the license statement at the head of this file.
  48116. *
  48117. * Shifts the current subtree rooted at wr.
  48118. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  48119. */
  48120. function moveSubtree(wl, wr, shift) {
  48121. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  48122. wr.hierNode.change -= change;
  48123. wr.hierNode.shift += shift;
  48124. wr.hierNode.modifier += shift;
  48125. wr.hierNode.prelim += shift;
  48126. wl.hierNode.change += change;
  48127. }
  48128. /**
  48129. * The implementation of this function was originally copied from "d3.js"
  48130. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48131. * with some modifications made for this program.
  48132. * See the license statement at the head of this file.
  48133. */
  48134. function defaultSeparation(node1, node2) {
  48135. return node1.parentNode === node2.parentNode ? 1 : 2;
  48136. }
  48137. var TreeEdgeShape =
  48138. /** @class */
  48139. function () {
  48140. function TreeEdgeShape() {
  48141. this.parentPoint = [];
  48142. this.childPoints = [];
  48143. }
  48144. return TreeEdgeShape;
  48145. }();
  48146. var TreePath =
  48147. /** @class */
  48148. function (_super) {
  48149. __extends(TreePath, _super);
  48150. function TreePath(opts) {
  48151. return _super.call(this, opts) || this;
  48152. }
  48153. TreePath.prototype.getDefaultStyle = function () {
  48154. return {
  48155. stroke: '#000',
  48156. fill: null
  48157. };
  48158. };
  48159. TreePath.prototype.getDefaultShape = function () {
  48160. return new TreeEdgeShape();
  48161. };
  48162. TreePath.prototype.buildPath = function (ctx, shape) {
  48163. var childPoints = shape.childPoints;
  48164. var childLen = childPoints.length;
  48165. var parentPoint = shape.parentPoint;
  48166. var firstChildPos = childPoints[0];
  48167. var lastChildPos = childPoints[childLen - 1];
  48168. if (childLen === 1) {
  48169. ctx.moveTo(parentPoint[0], parentPoint[1]);
  48170. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  48171. return;
  48172. }
  48173. var orient = shape.orient;
  48174. var forkDim = orient === 'TB' || orient === 'BT' ? 0 : 1;
  48175. var otherDim = 1 - forkDim;
  48176. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  48177. var tmpPoint = [];
  48178. tmpPoint[forkDim] = parentPoint[forkDim];
  48179. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  48180. ctx.moveTo(parentPoint[0], parentPoint[1]);
  48181. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48182. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  48183. tmpPoint[forkDim] = firstChildPos[forkDim];
  48184. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48185. tmpPoint[forkDim] = lastChildPos[forkDim];
  48186. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48187. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  48188. for (var i = 1; i < childLen - 1; i++) {
  48189. var point = childPoints[i];
  48190. ctx.moveTo(point[0], point[1]);
  48191. tmpPoint[forkDim] = point[forkDim];
  48192. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48193. }
  48194. };
  48195. return TreePath;
  48196. }(Path);
  48197. var TreeView =
  48198. /** @class */
  48199. function (_super) {
  48200. __extends(TreeView, _super);
  48201. function TreeView() {
  48202. var _this = _super !== null && _super.apply(this, arguments) || this;
  48203. _this.type = TreeView.type;
  48204. _this._mainGroup = new Group();
  48205. return _this;
  48206. }
  48207. TreeView.prototype.init = function (ecModel, api) {
  48208. this._controller = new RoamController(api.getZr());
  48209. this._controllerHost = {
  48210. target: this.group
  48211. };
  48212. this.group.add(this._mainGroup);
  48213. };
  48214. TreeView.prototype.render = function (seriesModel, ecModel, api) {
  48215. var data = seriesModel.getData();
  48216. var layoutInfo = seriesModel.layoutInfo;
  48217. var group = this._mainGroup;
  48218. var layout = seriesModel.get('layout');
  48219. if (layout === 'radial') {
  48220. group.x = layoutInfo.x + layoutInfo.width / 2;
  48221. group.y = layoutInfo.y + layoutInfo.height / 2;
  48222. } else {
  48223. group.x = layoutInfo.x;
  48224. group.y = layoutInfo.y;
  48225. }
  48226. this._updateViewCoordSys(seriesModel, api);
  48227. this._updateController(seriesModel, ecModel, api);
  48228. var oldData = this._data;
  48229. data.diff(oldData).add(function (newIdx) {
  48230. if (symbolNeedsDraw$1(data, newIdx)) {
  48231. // Create node and edge
  48232. updateNode(data, newIdx, null, group, seriesModel);
  48233. }
  48234. }).update(function (newIdx, oldIdx) {
  48235. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  48236. if (!symbolNeedsDraw$1(data, newIdx)) {
  48237. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  48238. return;
  48239. } // Update node and edge
  48240. updateNode(data, newIdx, symbolEl, group, seriesModel);
  48241. }).remove(function (oldIdx) {
  48242. var symbolEl = oldData.getItemGraphicEl(oldIdx); // When remove a collapsed node of subtree, since the collapsed
  48243. // node haven't been initialized with a symbol element,
  48244. // you can't found it's symbol element through index.
  48245. // so if we want to remove the symbol element we should insure
  48246. // that the symbol element is not null.
  48247. if (symbolEl) {
  48248. removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  48249. }
  48250. }).execute();
  48251. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  48252. this._updateNodeAndLinkScale(seriesModel);
  48253. if (seriesModel.get('expandAndCollapse') === true) {
  48254. data.eachItemGraphicEl(function (el, dataIndex) {
  48255. el.off('click').on('click', function () {
  48256. api.dispatchAction({
  48257. type: 'treeExpandAndCollapse',
  48258. seriesId: seriesModel.id,
  48259. dataIndex: dataIndex
  48260. });
  48261. });
  48262. });
  48263. }
  48264. this._data = data;
  48265. };
  48266. TreeView.prototype._updateViewCoordSys = function (seriesModel, api) {
  48267. var data = seriesModel.getData();
  48268. var points = [];
  48269. data.each(function (idx) {
  48270. var layout = data.getItemLayout(idx);
  48271. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  48272. points.push([+layout.x, +layout.y]);
  48273. }
  48274. });
  48275. var min = [];
  48276. var max = [];
  48277. fromPoints(points, min, max); // If don't Store min max when collapse the root node after roam,
  48278. // the root node will disappear.
  48279. var oldMin = this._min;
  48280. var oldMax = this._max; // If width or height is 0
  48281. if (max[0] - min[0] === 0) {
  48282. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  48283. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  48284. }
  48285. if (max[1] - min[1] === 0) {
  48286. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  48287. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  48288. }
  48289. var viewCoordSys = seriesModel.coordinateSystem = new View();
  48290. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  48291. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  48292. viewCoordSys.setCenter(seriesModel.get('center'), api);
  48293. viewCoordSys.setZoom(seriesModel.get('zoom')); // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  48294. this.group.attr({
  48295. x: viewCoordSys.x,
  48296. y: viewCoordSys.y,
  48297. scaleX: viewCoordSys.scaleX,
  48298. scaleY: viewCoordSys.scaleY
  48299. });
  48300. this._min = min;
  48301. this._max = max;
  48302. };
  48303. TreeView.prototype._updateController = function (seriesModel, ecModel, api) {
  48304. var _this = this;
  48305. var controller = this._controller;
  48306. var controllerHost = this._controllerHost;
  48307. var group = this.group;
  48308. controller.setPointerChecker(function (e, x, y) {
  48309. var rect = group.getBoundingRect();
  48310. rect.applyTransform(group.transform);
  48311. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  48312. });
  48313. controller.enable(seriesModel.get('roam'));
  48314. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  48315. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  48316. controller.off('pan').off('zoom').on('pan', function (e) {
  48317. updateViewOnPan(controllerHost, e.dx, e.dy);
  48318. api.dispatchAction({
  48319. seriesId: seriesModel.id,
  48320. type: 'treeRoam',
  48321. dx: e.dx,
  48322. dy: e.dy
  48323. });
  48324. }).on('zoom', function (e) {
  48325. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  48326. api.dispatchAction({
  48327. seriesId: seriesModel.id,
  48328. type: 'treeRoam',
  48329. zoom: e.scale,
  48330. originX: e.originX,
  48331. originY: e.originY
  48332. });
  48333. _this._updateNodeAndLinkScale(seriesModel); // Only update label layout on zoom
  48334. api.updateLabelLayout();
  48335. });
  48336. };
  48337. TreeView.prototype._updateNodeAndLinkScale = function (seriesModel) {
  48338. var data = seriesModel.getData();
  48339. var nodeScale = this._getNodeGlobalScale(seriesModel);
  48340. data.eachItemGraphicEl(function (el, idx) {
  48341. el.setSymbolScale(nodeScale);
  48342. });
  48343. };
  48344. TreeView.prototype._getNodeGlobalScale = function (seriesModel) {
  48345. var coordSys = seriesModel.coordinateSystem;
  48346. if (coordSys.type !== 'view') {
  48347. return 1;
  48348. }
  48349. var nodeScaleRatio = this._nodeScaleRatio;
  48350. var groupZoom = coordSys.scaleX || 1; // Scale node when zoom changes
  48351. var roamZoom = coordSys.getZoom();
  48352. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  48353. return nodeScale / groupZoom;
  48354. };
  48355. TreeView.prototype.dispose = function () {
  48356. this._controller && this._controller.dispose();
  48357. this._controllerHost = null;
  48358. };
  48359. TreeView.prototype.remove = function () {
  48360. this._mainGroup.removeAll();
  48361. this._data = null;
  48362. };
  48363. TreeView.type = 'tree';
  48364. return TreeView;
  48365. }(ChartView);
  48366. function symbolNeedsDraw$1(data, dataIndex) {
  48367. var layout = data.getItemLayout(dataIndex);
  48368. return layout && !isNaN(layout.x) && !isNaN(layout.y);
  48369. }
  48370. function updateNode(data, dataIndex, symbolEl, group, seriesModel) {
  48371. var isInit = !symbolEl;
  48372. var node = data.tree.getNodeByDataIndex(dataIndex);
  48373. var itemModel = node.getModel();
  48374. var visualColor = node.getVisual('style').fill;
  48375. var symbolInnerColor = node.isExpand === false && node.children.length !== 0 ? visualColor : '#fff';
  48376. var virtualRoot = data.tree.root;
  48377. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  48378. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  48379. var sourceLayout = source.getLayout();
  48380. var sourceOldLayout = sourceSymbolEl ? {
  48381. x: sourceSymbolEl.__oldX,
  48382. y: sourceSymbolEl.__oldY,
  48383. rawX: sourceSymbolEl.__radialOldRawX,
  48384. rawY: sourceSymbolEl.__radialOldRawY
  48385. } : sourceLayout;
  48386. var targetLayout = node.getLayout();
  48387. if (isInit) {
  48388. symbolEl = new Symbol(data, dataIndex, null, {
  48389. symbolInnerColor: symbolInnerColor,
  48390. useNameLabel: true
  48391. });
  48392. symbolEl.x = sourceOldLayout.x;
  48393. symbolEl.y = sourceOldLayout.y;
  48394. } else {
  48395. symbolEl.updateData(data, dataIndex, null, {
  48396. symbolInnerColor: symbolInnerColor,
  48397. useNameLabel: true
  48398. });
  48399. }
  48400. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  48401. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  48402. symbolEl.__radialRawX = targetLayout.rawX;
  48403. symbolEl.__radialRawY = targetLayout.rawY;
  48404. group.add(symbolEl);
  48405. data.setItemGraphicEl(dataIndex, symbolEl);
  48406. symbolEl.__oldX = symbolEl.x;
  48407. symbolEl.__oldY = symbolEl.y;
  48408. updateProps(symbolEl, {
  48409. x: targetLayout.x,
  48410. y: targetLayout.y
  48411. }, seriesModel);
  48412. var symbolPath = symbolEl.getSymbolPath();
  48413. if (seriesModel.get('layout') === 'radial') {
  48414. var realRoot = virtualRoot.children[0];
  48415. var rootLayout = realRoot.getLayout();
  48416. var length_1 = realRoot.children.length;
  48417. var rad = void 0;
  48418. var isLeft = void 0;
  48419. if (targetLayout.x === rootLayout.x && node.isExpand === true && realRoot.children.length) {
  48420. var center = {
  48421. x: (realRoot.children[0].getLayout().x + realRoot.children[length_1 - 1].getLayout().x) / 2,
  48422. y: (realRoot.children[0].getLayout().y + realRoot.children[length_1 - 1].getLayout().y) / 2
  48423. };
  48424. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  48425. if (rad < 0) {
  48426. rad = Math.PI * 2 + rad;
  48427. }
  48428. isLeft = center.x < rootLayout.x;
  48429. if (isLeft) {
  48430. rad = rad - Math.PI;
  48431. }
  48432. } else {
  48433. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  48434. if (rad < 0) {
  48435. rad = Math.PI * 2 + rad;
  48436. }
  48437. if (node.children.length === 0 || node.children.length !== 0 && node.isExpand === false) {
  48438. isLeft = targetLayout.x < rootLayout.x;
  48439. if (isLeft) {
  48440. rad = rad - Math.PI;
  48441. }
  48442. } else {
  48443. isLeft = targetLayout.x > rootLayout.x;
  48444. if (!isLeft) {
  48445. rad = rad - Math.PI;
  48446. }
  48447. }
  48448. }
  48449. var textPosition = isLeft ? 'left' : 'right';
  48450. var normalLabelModel = itemModel.getModel('label');
  48451. var rotate = normalLabelModel.get('rotate');
  48452. var labelRotateRadian = rotate * (Math.PI / 180);
  48453. var textContent = symbolPath.getTextContent();
  48454. if (textContent) {
  48455. symbolPath.setTextConfig({
  48456. position: normalLabelModel.get('position') || textPosition,
  48457. rotation: rotate == null ? -rad : labelRotateRadian,
  48458. origin: 'center'
  48459. });
  48460. textContent.setStyle('verticalAlign', 'middle');
  48461. }
  48462. } // Handle status
  48463. var focus = itemModel.get(['emphasis', 'focus']);
  48464. var focusDataIndices = focus === 'relative' ? concatArray(node.getAncestorsIndices(), node.getDescendantIndices()) : focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : null;
  48465. if (focusDataIndices) {
  48466. // Modify the focus to data indices.
  48467. getECData(symbolEl).focus = focusDataIndices;
  48468. }
  48469. drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group);
  48470. if (symbolEl.__edge) {
  48471. symbolEl.onHoverStateChange = function (toState) {
  48472. if (toState !== 'blur') {
  48473. // NOTE: Ensure the parent elements will been blurred firstly.
  48474. // According to the return of getAncestorsIndices and getDescendantIndices
  48475. // TODO: A bit tricky.
  48476. var parentEl = node.parentNode && data.getItemGraphicEl(node.parentNode.dataIndex);
  48477. if (!(parentEl && parentEl.hoverState === HOVER_STATE_BLUR)) {
  48478. setStatesFlag(symbolEl.__edge, toState);
  48479. }
  48480. }
  48481. };
  48482. }
  48483. }
  48484. function drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group) {
  48485. var itemModel = node.getModel();
  48486. var edgeShape = seriesModel.get('edgeShape');
  48487. var layout = seriesModel.get('layout');
  48488. var orient = seriesModel.getOrient();
  48489. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  48490. var edgeForkPosition = seriesModel.get('edgeForkPosition');
  48491. var lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  48492. var edge = symbolEl.__edge; // curve edge from node -> parent
  48493. // polyline edge from node -> children
  48494. if (edgeShape === 'curve') {
  48495. if (node.parentNode && node.parentNode !== virtualRoot) {
  48496. if (!edge) {
  48497. edge = symbolEl.__edge = new BezierCurve({
  48498. shape: getEdgeShape(layout, orient, curvature, sourceOldLayout, sourceOldLayout)
  48499. });
  48500. }
  48501. updateProps(edge, {
  48502. shape: getEdgeShape(layout, orient, curvature, sourceLayout, targetLayout)
  48503. }, seriesModel);
  48504. }
  48505. } else if (edgeShape === 'polyline') {
  48506. if (layout === 'orthogonal') {
  48507. if (node !== virtualRoot && node.children && node.children.length !== 0 && node.isExpand === true) {
  48508. var children = node.children;
  48509. var childPoints = [];
  48510. for (var i = 0; i < children.length; i++) {
  48511. var childLayout = children[i].getLayout();
  48512. childPoints.push([childLayout.x, childLayout.y]);
  48513. }
  48514. if (!edge) {
  48515. edge = symbolEl.__edge = new TreePath({
  48516. shape: {
  48517. parentPoint: [targetLayout.x, targetLayout.y],
  48518. childPoints: [[targetLayout.x, targetLayout.y]],
  48519. orient: orient,
  48520. forkPosition: edgeForkPosition
  48521. }
  48522. });
  48523. }
  48524. updateProps(edge, {
  48525. shape: {
  48526. parentPoint: [targetLayout.x, targetLayout.y],
  48527. childPoints: childPoints
  48528. }
  48529. }, seriesModel);
  48530. }
  48531. } else {
  48532. if ("development" !== 'production') {
  48533. throw new Error('The polyline edgeShape can only be used in orthogonal layout');
  48534. }
  48535. }
  48536. } // show all edge when edgeShape is 'curve', filter node `isExpand` is false when edgeShape is 'polyline'
  48537. if (edge && !(edgeShape === 'polyline' && !node.isExpand)) {
  48538. edge.useStyle(defaults({
  48539. strokeNoScale: true,
  48540. fill: null
  48541. }, lineStyle));
  48542. setStatesStylesFromModel(edge, itemModel, 'lineStyle');
  48543. setDefaultStateProxy(edge);
  48544. group.add(edge);
  48545. }
  48546. }
  48547. function removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt) {
  48548. var virtualRoot = data.tree.root;
  48549. var _a = getSourceNode(virtualRoot, node),
  48550. source = _a.source,
  48551. sourceLayout = _a.sourceLayout;
  48552. var symbolEl = data.getItemGraphicEl(node.dataIndex);
  48553. if (!symbolEl) {
  48554. return;
  48555. }
  48556. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  48557. var sourceEdge = sourceSymbolEl.__edge; // 1. when expand the sub tree, delete the children node should delete the edge of
  48558. // the source at the same time. because the polyline edge shape is only owned by the source.
  48559. // 2.when the node is the only children of the source, delete the node should delete the edge of
  48560. // the source at the same time. the same reason as above.
  48561. var edge = symbolEl.__edge || (source.isExpand === false || source.children.length === 1 ? sourceEdge : undefined);
  48562. var edgeShape = seriesModel.get('edgeShape');
  48563. var layoutOpt = seriesModel.get('layout');
  48564. var orient = seriesModel.get('orient');
  48565. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  48566. if (edge) {
  48567. if (edgeShape === 'curve') {
  48568. removeElement(edge, {
  48569. shape: getEdgeShape(layoutOpt, orient, curvature, sourceLayout, sourceLayout),
  48570. style: {
  48571. opacity: 0
  48572. }
  48573. }, seriesModel, {
  48574. cb: function () {
  48575. group.remove(edge);
  48576. },
  48577. removeOpt: removeAnimationOpt
  48578. });
  48579. } else if (edgeShape === 'polyline' && seriesModel.get('layout') === 'orthogonal') {
  48580. removeElement(edge, {
  48581. shape: {
  48582. parentPoint: [sourceLayout.x, sourceLayout.y],
  48583. childPoints: [[sourceLayout.x, sourceLayout.y]]
  48584. },
  48585. style: {
  48586. opacity: 0
  48587. }
  48588. }, seriesModel, {
  48589. cb: function () {
  48590. group.remove(edge);
  48591. },
  48592. removeOpt: removeAnimationOpt
  48593. });
  48594. }
  48595. }
  48596. }
  48597. function getSourceNode(virtualRoot, node) {
  48598. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  48599. var sourceLayout;
  48600. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  48601. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  48602. }
  48603. return {
  48604. source: source,
  48605. sourceLayout: sourceLayout
  48606. };
  48607. }
  48608. function removeNode(data, dataIndex, symbolEl, group, seriesModel) {
  48609. var node = data.tree.getNodeByDataIndex(dataIndex);
  48610. var virtualRoot = data.tree.root;
  48611. var sourceLayout = getSourceNode(virtualRoot, node).sourceLayout; // Use same duration and easing with update to have more consistent animation.
  48612. var removeAnimationOpt = {
  48613. duration: seriesModel.get('animationDurationUpdate'),
  48614. easing: seriesModel.get('animationEasingUpdate')
  48615. };
  48616. removeElement(symbolEl, {
  48617. x: sourceLayout.x + 1,
  48618. y: sourceLayout.y + 1
  48619. }, seriesModel, {
  48620. cb: function () {
  48621. group.remove(symbolEl);
  48622. data.setItemGraphicEl(dataIndex, null);
  48623. },
  48624. removeOpt: removeAnimationOpt
  48625. });
  48626. symbolEl.fadeOut(null, data.hostModel, {
  48627. fadeLabel: true,
  48628. animation: removeAnimationOpt
  48629. }); // remove edge as parent node
  48630. node.children.forEach(function (childNode) {
  48631. removeNodeEdge(childNode, data, group, seriesModel, removeAnimationOpt);
  48632. }); // remove edge as child node
  48633. removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt);
  48634. }
  48635. function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) {
  48636. var cpx1;
  48637. var cpy1;
  48638. var cpx2;
  48639. var cpy2;
  48640. var x1;
  48641. var x2;
  48642. var y1;
  48643. var y2;
  48644. if (layoutOpt === 'radial') {
  48645. x1 = sourceLayout.rawX;
  48646. y1 = sourceLayout.rawY;
  48647. x2 = targetLayout.rawX;
  48648. y2 = targetLayout.rawY;
  48649. var radialCoor1 = radialCoordinate(x1, y1);
  48650. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature);
  48651. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature);
  48652. var radialCoor4 = radialCoordinate(x2, y2);
  48653. return {
  48654. x1: radialCoor1.x || 0,
  48655. y1: radialCoor1.y || 0,
  48656. x2: radialCoor4.x || 0,
  48657. y2: radialCoor4.y || 0,
  48658. cpx1: radialCoor2.x || 0,
  48659. cpy1: radialCoor2.y || 0,
  48660. cpx2: radialCoor3.x || 0,
  48661. cpy2: radialCoor3.y || 0
  48662. };
  48663. } else {
  48664. x1 = sourceLayout.x;
  48665. y1 = sourceLayout.y;
  48666. x2 = targetLayout.x;
  48667. y2 = targetLayout.y;
  48668. if (orient === 'LR' || orient === 'RL') {
  48669. cpx1 = x1 + (x2 - x1) * curvature;
  48670. cpy1 = y1;
  48671. cpx2 = x2 + (x1 - x2) * curvature;
  48672. cpy2 = y2;
  48673. }
  48674. if (orient === 'TB' || orient === 'BT') {
  48675. cpx1 = x1;
  48676. cpy1 = y1 + (y2 - y1) * curvature;
  48677. cpx2 = x2;
  48678. cpy2 = y2 + (y1 - y2) * curvature;
  48679. }
  48680. }
  48681. return {
  48682. x1: x1,
  48683. y1: y1,
  48684. x2: x2,
  48685. y2: y2,
  48686. cpx1: cpx1,
  48687. cpy1: cpy1,
  48688. cpx2: cpx2,
  48689. cpy2: cpy2
  48690. };
  48691. }
  48692. var inner$7 = makeInner();
  48693. function linkSeriesData(opt) {
  48694. var mainData = opt.mainData;
  48695. var datas = opt.datas;
  48696. if (!datas) {
  48697. datas = {
  48698. main: mainData
  48699. };
  48700. opt.datasAttr = {
  48701. main: 'data'
  48702. };
  48703. }
  48704. opt.datas = opt.mainData = null;
  48705. linkAll(mainData, datas, opt); // Porxy data original methods.
  48706. each(datas, function (data) {
  48707. each(mainData.TRANSFERABLE_METHODS, function (methodName) {
  48708. data.wrapMethod(methodName, curry(transferInjection, opt));
  48709. });
  48710. }); // Beyond transfer, additional features should be added to `cloneShallow`.
  48711. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)); // Only mainData trigger change, because struct.update may trigger
  48712. // another changable methods, which may bring about dead lock.
  48713. each(mainData.CHANGABLE_METHODS, function (methodName) {
  48714. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  48715. }); // Make sure datas contains mainData.
  48716. assert(datas[mainData.dataType] === mainData);
  48717. }
  48718. function transferInjection(opt, res) {
  48719. if (isMainData(this)) {
  48720. // Transfer datas to new main data.
  48721. var datas = extend({}, inner$7(this).datas);
  48722. datas[this.dataType] = res;
  48723. linkAll(res, datas, opt);
  48724. } else {
  48725. // Modify the reference in main data to point newData.
  48726. linkSingle(res, this.dataType, inner$7(this).mainData, opt);
  48727. }
  48728. return res;
  48729. }
  48730. function changeInjection(opt, res) {
  48731. opt.struct && opt.struct.update();
  48732. return res;
  48733. }
  48734. function cloneShallowInjection(opt, res) {
  48735. // cloneShallow, which brings about some fragilities, may be inappropriate
  48736. // to be exposed as an API. So for implementation simplicity we can make
  48737. // the restriction that cloneShallow of not-mainData should not be invoked
  48738. // outside, but only be invoked here.
  48739. each(inner$7(res).datas, function (data, dataType) {
  48740. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  48741. });
  48742. return res;
  48743. }
  48744. /**
  48745. * Supplement method to List.
  48746. *
  48747. * @public
  48748. * @param [dataType] If not specified, return mainData.
  48749. */
  48750. function getLinkedData(dataType) {
  48751. var mainData = inner$7(this).mainData;
  48752. return dataType == null || mainData == null ? mainData : inner$7(mainData).datas[dataType];
  48753. }
  48754. /**
  48755. * Get list of all linked data
  48756. */
  48757. function getLinkedDataAll() {
  48758. var mainData = inner$7(this).mainData;
  48759. return mainData == null ? [{
  48760. data: mainData
  48761. }] : map(keys(inner$7(mainData).datas), function (type) {
  48762. return {
  48763. type: type,
  48764. data: inner$7(mainData).datas[type]
  48765. };
  48766. });
  48767. }
  48768. function isMainData(data) {
  48769. return inner$7(data).mainData === data;
  48770. }
  48771. function linkAll(mainData, datas, opt) {
  48772. inner$7(mainData).datas = {};
  48773. each(datas, function (data, dataType) {
  48774. linkSingle(data, dataType, mainData, opt);
  48775. });
  48776. }
  48777. function linkSingle(data, dataType, mainData, opt) {
  48778. inner$7(mainData).datas[dataType] = data;
  48779. inner$7(data).mainData = mainData;
  48780. data.dataType = dataType;
  48781. if (opt.struct) {
  48782. data[opt.structAttr] = opt.struct;
  48783. opt.struct[opt.datasAttr[dataType]] = data;
  48784. } // Supplement method.
  48785. data.getLinkedData = getLinkedData;
  48786. data.getLinkedDataAll = getLinkedDataAll;
  48787. }
  48788. var TreeNode =
  48789. /** @class */
  48790. function () {
  48791. function TreeNode(name, hostTree) {
  48792. this.depth = 0;
  48793. this.height = 0;
  48794. /**
  48795. * Reference to list item.
  48796. * Do not persistent dataIndex outside,
  48797. * besause it may be changed by list.
  48798. * If dataIndex -1,
  48799. * this node is logical deleted (filtered) in list.
  48800. */
  48801. this.dataIndex = -1;
  48802. this.children = [];
  48803. this.viewChildren = [];
  48804. this.isExpand = false;
  48805. this.name = name || '';
  48806. this.hostTree = hostTree;
  48807. }
  48808. /**
  48809. * The node is removed.
  48810. */
  48811. TreeNode.prototype.isRemoved = function () {
  48812. return this.dataIndex < 0;
  48813. };
  48814. TreeNode.prototype.eachNode = function (options, cb, context) {
  48815. if (isFunction(options)) {
  48816. context = cb;
  48817. cb = options;
  48818. options = null;
  48819. }
  48820. options = options || {};
  48821. if (isString(options)) {
  48822. options = {
  48823. order: options
  48824. };
  48825. }
  48826. var order = options.order || 'preorder';
  48827. var children = this[options.attr || 'children'];
  48828. var suppressVisitSub;
  48829. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  48830. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  48831. children[i].eachNode(options, cb, context);
  48832. }
  48833. order === 'postorder' && cb.call(context, this);
  48834. };
  48835. /**
  48836. * Update depth and height of this subtree.
  48837. */
  48838. TreeNode.prototype.updateDepthAndHeight = function (depth) {
  48839. var height = 0;
  48840. this.depth = depth;
  48841. for (var i = 0; i < this.children.length; i++) {
  48842. var child = this.children[i];
  48843. child.updateDepthAndHeight(depth + 1);
  48844. if (child.height > height) {
  48845. height = child.height;
  48846. }
  48847. }
  48848. this.height = height + 1;
  48849. };
  48850. TreeNode.prototype.getNodeById = function (id) {
  48851. if (this.getId() === id) {
  48852. return this;
  48853. }
  48854. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  48855. var res = children[i].getNodeById(id);
  48856. if (res) {
  48857. return res;
  48858. }
  48859. }
  48860. };
  48861. TreeNode.prototype.contains = function (node) {
  48862. if (node === this) {
  48863. return true;
  48864. }
  48865. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  48866. var res = children[i].contains(node);
  48867. if (res) {
  48868. return res;
  48869. }
  48870. }
  48871. };
  48872. /**
  48873. * @param includeSelf Default false.
  48874. * @return order: [root, child, grandchild, ...]
  48875. */
  48876. TreeNode.prototype.getAncestors = function (includeSelf) {
  48877. var ancestors = [];
  48878. var node = includeSelf ? this : this.parentNode;
  48879. while (node) {
  48880. ancestors.push(node);
  48881. node = node.parentNode;
  48882. }
  48883. ancestors.reverse();
  48884. return ancestors;
  48885. };
  48886. TreeNode.prototype.getAncestorsIndices = function () {
  48887. var indices = [];
  48888. var currNode = this;
  48889. while (currNode) {
  48890. indices.push(currNode.dataIndex);
  48891. currNode = currNode.parentNode;
  48892. }
  48893. indices.reverse();
  48894. return indices;
  48895. };
  48896. TreeNode.prototype.getDescendantIndices = function () {
  48897. var indices = [];
  48898. this.eachNode(function (childNode) {
  48899. indices.push(childNode.dataIndex);
  48900. });
  48901. return indices;
  48902. };
  48903. TreeNode.prototype.getValue = function (dimension) {
  48904. var data = this.hostTree.data;
  48905. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  48906. };
  48907. TreeNode.prototype.setLayout = function (layout, merge) {
  48908. this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge);
  48909. };
  48910. /**
  48911. * @return {Object} layout
  48912. */
  48913. TreeNode.prototype.getLayout = function () {
  48914. return this.hostTree.data.getItemLayout(this.dataIndex);
  48915. }; // @depcrecated
  48916. // getModel<T = unknown, S extends keyof T = keyof T>(path: S): Model<T[S]>
  48917. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  48918. TreeNode.prototype.getModel = function (path) {
  48919. if (this.dataIndex < 0) {
  48920. return;
  48921. }
  48922. var hostTree = this.hostTree;
  48923. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  48924. return itemModel.getModel(path);
  48925. }; // TODO: TYPE More specific model
  48926. TreeNode.prototype.getLevelModel = function () {
  48927. return (this.hostTree.levelModels || [])[this.depth];
  48928. };
  48929. TreeNode.prototype.setVisual = function (key, value) {
  48930. this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  48931. };
  48932. /**
  48933. * Get item visual
  48934. * FIXME: make return type better
  48935. */
  48936. TreeNode.prototype.getVisual = function (key) {
  48937. return this.hostTree.data.getItemVisual(this.dataIndex, key);
  48938. };
  48939. TreeNode.prototype.getRawIndex = function () {
  48940. return this.hostTree.data.getRawIndex(this.dataIndex);
  48941. };
  48942. TreeNode.prototype.getId = function () {
  48943. return this.hostTree.data.getId(this.dataIndex);
  48944. };
  48945. /**
  48946. * index in parent's children
  48947. */
  48948. TreeNode.prototype.getChildIndex = function () {
  48949. if (this.parentNode) {
  48950. var children = this.parentNode.children;
  48951. for (var i = 0; i < children.length; ++i) {
  48952. if (children[i] === this) {
  48953. return i;
  48954. }
  48955. }
  48956. return -1;
  48957. }
  48958. return -1;
  48959. };
  48960. /**
  48961. * if this is an ancestor of another node
  48962. *
  48963. * @param node another node
  48964. * @return if is ancestor
  48965. */
  48966. TreeNode.prototype.isAncestorOf = function (node) {
  48967. var parent = node.parentNode;
  48968. while (parent) {
  48969. if (parent === this) {
  48970. return true;
  48971. }
  48972. parent = parent.parentNode;
  48973. }
  48974. return false;
  48975. };
  48976. /**
  48977. * if this is an descendant of another node
  48978. *
  48979. * @param node another node
  48980. * @return if is descendant
  48981. */
  48982. TreeNode.prototype.isDescendantOf = function (node) {
  48983. return node !== this && node.isAncestorOf(this);
  48984. };
  48985. return TreeNode;
  48986. }();
  48987. var Tree =
  48988. /** @class */
  48989. function () {
  48990. function Tree(hostModel) {
  48991. this.type = 'tree';
  48992. this._nodes = [];
  48993. this.hostModel = hostModel;
  48994. }
  48995. Tree.prototype.eachNode = function (options, cb, context) {
  48996. this.root.eachNode(options, cb, context);
  48997. };
  48998. Tree.prototype.getNodeByDataIndex = function (dataIndex) {
  48999. var rawIndex = this.data.getRawIndex(dataIndex);
  49000. return this._nodes[rawIndex];
  49001. };
  49002. Tree.prototype.getNodeById = function (name) {
  49003. return this.root.getNodeById(name);
  49004. };
  49005. /**
  49006. * Update item available by list,
  49007. * when list has been performed options like 'filterSelf' or 'map'.
  49008. */
  49009. Tree.prototype.update = function () {
  49010. var data = this.data;
  49011. var nodes = this._nodes;
  49012. for (var i = 0, len = nodes.length; i < len; i++) {
  49013. nodes[i].dataIndex = -1;
  49014. }
  49015. for (var i = 0, len = data.count(); i < len; i++) {
  49016. nodes[data.getRawIndex(i)].dataIndex = i;
  49017. }
  49018. };
  49019. /**
  49020. * Clear all layouts
  49021. */
  49022. Tree.prototype.clearLayouts = function () {
  49023. this.data.clearItemLayouts();
  49024. };
  49025. /**
  49026. * data node format:
  49027. * {
  49028. * name: ...
  49029. * value: ...
  49030. * children: [
  49031. * {
  49032. * name: ...
  49033. * value: ...
  49034. * children: ...
  49035. * },
  49036. * ...
  49037. * ]
  49038. * }
  49039. */
  49040. Tree.createTree = function (dataRoot, hostModel, beforeLink) {
  49041. var tree = new Tree(hostModel);
  49042. var listData = [];
  49043. var dimMax = 1;
  49044. buildHierarchy(dataRoot);
  49045. function buildHierarchy(dataNode, parentNode) {
  49046. var value = dataNode.value;
  49047. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  49048. listData.push(dataNode);
  49049. var node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree);
  49050. parentNode ? addChild(node, parentNode) : tree.root = node;
  49051. tree._nodes.push(node);
  49052. var children = dataNode.children;
  49053. if (children) {
  49054. for (var i = 0; i < children.length; i++) {
  49055. buildHierarchy(children[i], node);
  49056. }
  49057. }
  49058. }
  49059. tree.root.updateDepthAndHeight(0);
  49060. var dimensions = prepareSeriesDataSchema(listData, {
  49061. coordDimensions: ['value'],
  49062. dimensionsCount: dimMax
  49063. }).dimensions;
  49064. var list = new SeriesData(dimensions, hostModel);
  49065. list.initData(listData);
  49066. beforeLink && beforeLink(list);
  49067. linkSeriesData({
  49068. mainData: list,
  49069. struct: tree,
  49070. structAttr: 'tree'
  49071. });
  49072. tree.update();
  49073. return tree;
  49074. };
  49075. return Tree;
  49076. }();
  49077. /**
  49078. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  49079. * so this function is not ready and not necessary to be public.
  49080. */
  49081. function addChild(child, node) {
  49082. var children = node.children;
  49083. if (child.parentNode === node) {
  49084. return;
  49085. }
  49086. children.push(child);
  49087. child.parentNode = node;
  49088. }
  49089. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  49090. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  49091. var root = seriesModel.getData().tree.root;
  49092. var targetNode = payload.targetNode;
  49093. if (isString(targetNode)) {
  49094. targetNode = root.getNodeById(targetNode);
  49095. }
  49096. if (targetNode && root.contains(targetNode)) {
  49097. return {
  49098. node: targetNode
  49099. };
  49100. }
  49101. var targetNodeId = payload.targetNodeId;
  49102. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  49103. return {
  49104. node: targetNode
  49105. };
  49106. }
  49107. }
  49108. } // Not includes the given node at the last item.
  49109. function getPathToRoot(node) {
  49110. var path = [];
  49111. while (node) {
  49112. node = node.parentNode;
  49113. node && path.push(node);
  49114. }
  49115. return path.reverse();
  49116. }
  49117. function aboveViewRoot(viewRoot, node) {
  49118. var viewPath = getPathToRoot(viewRoot);
  49119. return indexOf(viewPath, node) >= 0;
  49120. } // From root to the input node (the input node will be included).
  49121. function wrapTreePathInfo(node, seriesModel) {
  49122. var treePathInfo = [];
  49123. while (node) {
  49124. var nodeDataIndex = node.dataIndex;
  49125. treePathInfo.push({
  49126. name: node.name,
  49127. dataIndex: nodeDataIndex,
  49128. value: seriesModel.getRawValue(nodeDataIndex)
  49129. });
  49130. node = node.parentNode;
  49131. }
  49132. treePathInfo.reverse();
  49133. return treePathInfo;
  49134. }
  49135. var TreeSeriesModel =
  49136. /** @class */
  49137. function (_super) {
  49138. __extends(TreeSeriesModel, _super);
  49139. function TreeSeriesModel() {
  49140. var _this = _super !== null && _super.apply(this, arguments) || this;
  49141. _this.hasSymbolVisual = true; // Do it self.
  49142. _this.ignoreStyleOnData = true;
  49143. return _this;
  49144. }
  49145. /**
  49146. * Init a tree data structure from data in option series
  49147. */
  49148. TreeSeriesModel.prototype.getInitialData = function (option) {
  49149. // create a virtual root
  49150. var root = {
  49151. name: option.name,
  49152. children: option.data
  49153. };
  49154. var leaves = option.leaves || {};
  49155. var leavesModel = new Model(leaves, this, this.ecModel);
  49156. var tree = Tree.createTree(root, this, beforeLink);
  49157. function beforeLink(nodeData) {
  49158. nodeData.wrapMethod('getItemModel', function (model, idx) {
  49159. var node = tree.getNodeByDataIndex(idx);
  49160. if (!(node && node.children.length && node.isExpand)) {
  49161. model.parentModel = leavesModel;
  49162. }
  49163. return model;
  49164. });
  49165. }
  49166. var treeDepth = 0;
  49167. tree.eachNode('preorder', function (node) {
  49168. if (node.depth > treeDepth) {
  49169. treeDepth = node.depth;
  49170. }
  49171. });
  49172. var expandAndCollapse = option.expandAndCollapse;
  49173. var expandTreeDepth = expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth;
  49174. tree.root.eachNode('preorder', function (node) {
  49175. var item = node.hostTree.data.getRawDataItem(node.dataIndex); // Add item.collapsed != null, because users can collapse node original in the series.data.
  49176. node.isExpand = item && item.collapsed != null ? !item.collapsed : node.depth <= expandTreeDepth;
  49177. });
  49178. return tree.data;
  49179. };
  49180. /**
  49181. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  49182. * @returns {string} orient
  49183. */
  49184. TreeSeriesModel.prototype.getOrient = function () {
  49185. var orient = this.get('orient');
  49186. if (orient === 'horizontal') {
  49187. orient = 'LR';
  49188. } else if (orient === 'vertical') {
  49189. orient = 'TB';
  49190. }
  49191. return orient;
  49192. };
  49193. TreeSeriesModel.prototype.setZoom = function (zoom) {
  49194. this.option.zoom = zoom;
  49195. };
  49196. TreeSeriesModel.prototype.setCenter = function (center) {
  49197. this.option.center = center;
  49198. };
  49199. TreeSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49200. var tree = this.getData().tree;
  49201. var realRoot = tree.root.children[0];
  49202. var node = tree.getNodeByDataIndex(dataIndex);
  49203. var value = node.getValue();
  49204. var name = node.name;
  49205. while (node && node !== realRoot) {
  49206. name = node.parentNode.name + '.' + name;
  49207. node = node.parentNode;
  49208. }
  49209. return createTooltipMarkup('nameValue', {
  49210. name: name,
  49211. value: value,
  49212. noValue: isNaN(value) || value == null
  49213. });
  49214. }; // Add tree path to tooltip param
  49215. TreeSeriesModel.prototype.getDataParams = function (dataIndex) {
  49216. var params = _super.prototype.getDataParams.apply(this, arguments);
  49217. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  49218. params.treeAncestors = wrapTreePathInfo(node, this);
  49219. params.collapsed = !node.isExpand;
  49220. return params;
  49221. };
  49222. TreeSeriesModel.type = 'series.tree'; // can support the position parameters 'left', 'top','right','bottom', 'width',
  49223. // 'height' in the setOption() with 'merge' mode normal.
  49224. TreeSeriesModel.layoutMode = 'box';
  49225. TreeSeriesModel.defaultOption = {
  49226. // zlevel: 0,
  49227. z: 2,
  49228. coordinateSystem: 'view',
  49229. // the position of the whole view
  49230. left: '12%',
  49231. top: '12%',
  49232. right: '12%',
  49233. bottom: '12%',
  49234. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  49235. layout: 'orthogonal',
  49236. // value can be 'polyline'
  49237. edgeShape: 'curve',
  49238. edgeForkPosition: '50%',
  49239. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  49240. roam: false,
  49241. // Symbol size scale ratio in roam
  49242. nodeScaleRatio: 0.4,
  49243. // Default on center of graph
  49244. center: null,
  49245. zoom: 1,
  49246. orient: 'LR',
  49247. symbol: 'emptyCircle',
  49248. symbolSize: 7,
  49249. expandAndCollapse: true,
  49250. initialTreeDepth: 2,
  49251. lineStyle: {
  49252. color: '#ccc',
  49253. width: 1.5,
  49254. curveness: 0.5
  49255. },
  49256. itemStyle: {
  49257. color: 'lightsteelblue',
  49258. // borderColor: '#c23531',
  49259. borderWidth: 1.5
  49260. },
  49261. label: {
  49262. show: true
  49263. },
  49264. animationEasing: 'linear',
  49265. animationDuration: 700,
  49266. animationDurationUpdate: 500
  49267. };
  49268. return TreeSeriesModel;
  49269. }(SeriesModel);
  49270. /*
  49271. * Licensed to the Apache Software Foundation (ASF) under one
  49272. * or more contributor license agreements. See the NOTICE file
  49273. * distributed with this work for additional information
  49274. * regarding copyright ownership. The ASF licenses this file
  49275. * to you under the Apache License, Version 2.0 (the
  49276. * "License"); you may not use this file except in compliance
  49277. * with the License. You may obtain a copy of the License at
  49278. *
  49279. * http://www.apache.org/licenses/LICENSE-2.0
  49280. *
  49281. * Unless required by applicable law or agreed to in writing,
  49282. * software distributed under the License is distributed on an
  49283. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49284. * KIND, either express or implied. See the License for the
  49285. * specific language governing permissions and limitations
  49286. * under the License.
  49287. */
  49288. /**
  49289. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49290. */
  49291. /*
  49292. * Licensed to the Apache Software Foundation (ASF) under one
  49293. * or more contributor license agreements. See the NOTICE file
  49294. * distributed with this work for additional information
  49295. * regarding copyright ownership. The ASF licenses this file
  49296. * to you under the Apache License, Version 2.0 (the
  49297. * "License"); you may not use this file except in compliance
  49298. * with the License. You may obtain a copy of the License at
  49299. *
  49300. * http://www.apache.org/licenses/LICENSE-2.0
  49301. *
  49302. * Unless required by applicable law or agreed to in writing,
  49303. * software distributed under the License is distributed on an
  49304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49305. * KIND, either express or implied. See the License for the
  49306. * specific language governing permissions and limitations
  49307. * under the License.
  49308. */
  49309. /**
  49310. * Traverse the tree from bottom to top and do something
  49311. */
  49312. function eachAfter(root, callback, separation) {
  49313. var nodes = [root];
  49314. var next = [];
  49315. var node;
  49316. while (node = nodes.pop()) {
  49317. // jshint ignore:line
  49318. next.push(node);
  49319. if (node.isExpand) {
  49320. var children = node.children;
  49321. if (children.length) {
  49322. for (var i = 0; i < children.length; i++) {
  49323. nodes.push(children[i]);
  49324. }
  49325. }
  49326. }
  49327. }
  49328. while (node = next.pop()) {
  49329. // jshint ignore:line
  49330. callback(node, separation);
  49331. }
  49332. }
  49333. /**
  49334. * Traverse the tree from top to bottom and do something
  49335. */
  49336. function eachBefore(root, callback) {
  49337. var nodes = [root];
  49338. var node;
  49339. while (node = nodes.pop()) {
  49340. // jshint ignore:line
  49341. callback(node);
  49342. if (node.isExpand) {
  49343. var children = node.children;
  49344. if (children.length) {
  49345. for (var i = children.length - 1; i >= 0; i--) {
  49346. nodes.push(children[i]);
  49347. }
  49348. }
  49349. }
  49350. }
  49351. }
  49352. function treeLayout(ecModel, api) {
  49353. ecModel.eachSeriesByType('tree', function (seriesModel) {
  49354. commonLayout(seriesModel, api);
  49355. });
  49356. }
  49357. function commonLayout(seriesModel, api) {
  49358. var layoutInfo = getViewRect$1(seriesModel, api);
  49359. seriesModel.layoutInfo = layoutInfo;
  49360. var layout = seriesModel.get('layout');
  49361. var width = 0;
  49362. var height = 0;
  49363. var separation$1 = null;
  49364. if (layout === 'radial') {
  49365. width = 2 * Math.PI;
  49366. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  49367. separation$1 = separation(function (node1, node2) {
  49368. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  49369. });
  49370. } else {
  49371. width = layoutInfo.width;
  49372. height = layoutInfo.height;
  49373. separation$1 = separation();
  49374. }
  49375. var virtualRoot = seriesModel.getData().tree.root;
  49376. var realRoot = virtualRoot.children[0];
  49377. if (realRoot) {
  49378. init$2(virtualRoot);
  49379. eachAfter(realRoot, firstWalk, separation$1);
  49380. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  49381. eachBefore(realRoot, secondWalk);
  49382. var left_1 = realRoot;
  49383. var right_1 = realRoot;
  49384. var bottom_1 = realRoot;
  49385. eachBefore(realRoot, function (node) {
  49386. var x = node.getLayout().x;
  49387. if (x < left_1.getLayout().x) {
  49388. left_1 = node;
  49389. }
  49390. if (x > right_1.getLayout().x) {
  49391. right_1 = node;
  49392. }
  49393. if (node.depth > bottom_1.depth) {
  49394. bottom_1 = node;
  49395. }
  49396. });
  49397. var delta = left_1 === right_1 ? 1 : separation$1(left_1, right_1) / 2;
  49398. var tx_1 = delta - left_1.getLayout().x;
  49399. var kx_1 = 0;
  49400. var ky_1 = 0;
  49401. var coorX_1 = 0;
  49402. var coorY_1 = 0;
  49403. if (layout === 'radial') {
  49404. kx_1 = width / (right_1.getLayout().x + delta + tx_1); // here we use (node.depth - 1), bucause the real root's depth is 1
  49405. ky_1 = height / (bottom_1.depth - 1 || 1);
  49406. eachBefore(realRoot, function (node) {
  49407. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  49408. coorY_1 = (node.depth - 1) * ky_1;
  49409. var finalCoor = radialCoordinate(coorX_1, coorY_1);
  49410. node.setLayout({
  49411. x: finalCoor.x,
  49412. y: finalCoor.y,
  49413. rawX: coorX_1,
  49414. rawY: coorY_1
  49415. }, true);
  49416. });
  49417. } else {
  49418. var orient_1 = seriesModel.getOrient();
  49419. if (orient_1 === 'RL' || orient_1 === 'LR') {
  49420. ky_1 = height / (right_1.getLayout().x + delta + tx_1);
  49421. kx_1 = width / (bottom_1.depth - 1 || 1);
  49422. eachBefore(realRoot, function (node) {
  49423. coorY_1 = (node.getLayout().x + tx_1) * ky_1;
  49424. coorX_1 = orient_1 === 'LR' ? (node.depth - 1) * kx_1 : width - (node.depth - 1) * kx_1;
  49425. node.setLayout({
  49426. x: coorX_1,
  49427. y: coorY_1
  49428. }, true);
  49429. });
  49430. } else if (orient_1 === 'TB' || orient_1 === 'BT') {
  49431. kx_1 = width / (right_1.getLayout().x + delta + tx_1);
  49432. ky_1 = height / (bottom_1.depth - 1 || 1);
  49433. eachBefore(realRoot, function (node) {
  49434. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  49435. coorY_1 = orient_1 === 'TB' ? (node.depth - 1) * ky_1 : height - (node.depth - 1) * ky_1;
  49436. node.setLayout({
  49437. x: coorX_1,
  49438. y: coorY_1
  49439. }, true);
  49440. });
  49441. }
  49442. }
  49443. }
  49444. }
  49445. function treeVisual(ecModel) {
  49446. ecModel.eachSeriesByType('tree', function (seriesModel) {
  49447. var data = seriesModel.getData();
  49448. var tree = data.tree;
  49449. tree.eachNode(function (node) {
  49450. var model = node.getModel(); // TODO Optimize
  49451. var style = model.getModel('itemStyle').getItemStyle();
  49452. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  49453. extend(existsStyle, style);
  49454. });
  49455. });
  49456. }
  49457. function installTreeAction(registers) {
  49458. registers.registerAction({
  49459. type: 'treeExpandAndCollapse',
  49460. event: 'treeExpandAndCollapse',
  49461. update: 'update'
  49462. }, function (payload, ecModel) {
  49463. ecModel.eachComponent({
  49464. mainType: 'series',
  49465. subType: 'tree',
  49466. query: payload
  49467. }, function (seriesModel) {
  49468. var dataIndex = payload.dataIndex;
  49469. var tree = seriesModel.getData().tree;
  49470. var node = tree.getNodeByDataIndex(dataIndex);
  49471. node.isExpand = !node.isExpand;
  49472. });
  49473. });
  49474. registers.registerAction({
  49475. type: 'treeRoam',
  49476. event: 'treeRoam',
  49477. // Here we set 'none' instead of 'update', because roam action
  49478. // just need to update the transform matrix without having to recalculate
  49479. // the layout. So don't need to go through the whole update process, such
  49480. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  49481. update: 'none'
  49482. }, function (payload, ecModel, api) {
  49483. ecModel.eachComponent({
  49484. mainType: 'series',
  49485. subType: 'tree',
  49486. query: payload
  49487. }, function (seriesModel) {
  49488. var coordSys = seriesModel.coordinateSystem;
  49489. var res = updateCenterAndZoom(coordSys, payload, undefined, api);
  49490. seriesModel.setCenter && seriesModel.setCenter(res.center);
  49491. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  49492. });
  49493. });
  49494. }
  49495. function install$b(registers) {
  49496. registers.registerChartView(TreeView);
  49497. registers.registerSeriesModel(TreeSeriesModel);
  49498. registers.registerLayout(treeLayout);
  49499. registers.registerVisual(treeVisual);
  49500. installTreeAction(registers);
  49501. }
  49502. var actionTypes = ['treemapZoomToNode', 'treemapRender', 'treemapMove'];
  49503. function installTreemapAction(registers) {
  49504. for (var i = 0; i < actionTypes.length; i++) {
  49505. registers.registerAction({
  49506. type: actionTypes[i],
  49507. update: 'updateView'
  49508. }, noop);
  49509. }
  49510. registers.registerAction({
  49511. type: 'treemapRootToNode',
  49512. update: 'updateView'
  49513. }, function (payload, ecModel) {
  49514. ecModel.eachComponent({
  49515. mainType: 'series',
  49516. subType: 'treemap',
  49517. query: payload
  49518. }, handleRootToNode);
  49519. function handleRootToNode(model, index) {
  49520. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  49521. var targetInfo = retrieveTargetInfo(payload, types, model);
  49522. if (targetInfo) {
  49523. var originViewRoot = model.getViewRoot();
  49524. if (originViewRoot) {
  49525. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  49526. }
  49527. model.resetViewRoot(targetInfo.node);
  49528. }
  49529. }
  49530. });
  49531. }
  49532. function enableAriaDecalForTree(seriesModel) {
  49533. var data = seriesModel.getData();
  49534. var tree = data.tree;
  49535. var decalPaletteScope = {};
  49536. tree.eachNode(function (node) {
  49537. // Use decal of level 1 node
  49538. var current = node;
  49539. while (current && current.depth > 1) {
  49540. current = current.parentNode;
  49541. }
  49542. var decal = getDecalFromPalette(seriesModel.ecModel, current.name || current.dataIndex + '', decalPaletteScope);
  49543. node.setVisual('decal', decal);
  49544. });
  49545. }
  49546. var TreemapSeriesModel =
  49547. /** @class */
  49548. function (_super) {
  49549. __extends(TreemapSeriesModel, _super);
  49550. function TreemapSeriesModel() {
  49551. var _this = _super !== null && _super.apply(this, arguments) || this;
  49552. _this.type = TreemapSeriesModel.type;
  49553. _this.preventUsingHoverLayer = true;
  49554. return _this;
  49555. }
  49556. /**
  49557. * @override
  49558. */
  49559. TreemapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  49560. // Create a virtual root.
  49561. var root = {
  49562. name: option.name,
  49563. children: option.data
  49564. };
  49565. completeTreeValue(root);
  49566. var levels = option.levels || []; // Used in "visual priority" in `treemapVisual.js`.
  49567. // This way is a little tricky, must satisfy the precondition:
  49568. // 1. There is no `treeNode.getModel('itemStyle.xxx')` used.
  49569. // 2. The `Model.prototype.getModel()` will not use any clone-like way.
  49570. var designatedVisualItemStyle = this.designatedVisualItemStyle = {};
  49571. var designatedVisualModel = new Model({
  49572. itemStyle: designatedVisualItemStyle
  49573. }, this, ecModel);
  49574. levels = option.levels = setDefault(levels, ecModel);
  49575. var levelModels = map(levels || [], function (levelDefine) {
  49576. return new Model(levelDefine, designatedVisualModel, ecModel);
  49577. }, this); // Make sure always a new tree is created when setOption,
  49578. // in TreemapView, we check whether oldTree === newTree
  49579. // to choose mappings approach among old shapes and new shapes.
  49580. var tree = Tree.createTree(root, this, beforeLink);
  49581. function beforeLink(nodeData) {
  49582. nodeData.wrapMethod('getItemModel', function (model, idx) {
  49583. var node = tree.getNodeByDataIndex(idx);
  49584. var levelModel = node ? levelModels[node.depth] : null; // If no levelModel, we also need `designatedVisualModel`.
  49585. model.parentModel = levelModel || designatedVisualModel;
  49586. return model;
  49587. });
  49588. }
  49589. return tree.data;
  49590. };
  49591. TreemapSeriesModel.prototype.optionUpdated = function () {
  49592. this.resetViewRoot();
  49593. };
  49594. /**
  49595. * @override
  49596. * @param {number} dataIndex
  49597. * @param {boolean} [mutipleSeries=false]
  49598. */
  49599. TreemapSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49600. var data = this.getData();
  49601. var value = this.getRawValue(dataIndex);
  49602. var name = data.getName(dataIndex);
  49603. return createTooltipMarkup('nameValue', {
  49604. name: name,
  49605. value: value
  49606. });
  49607. };
  49608. /**
  49609. * Add tree path to tooltip param
  49610. *
  49611. * @override
  49612. * @param {number} dataIndex
  49613. * @return {Object}
  49614. */
  49615. TreemapSeriesModel.prototype.getDataParams = function (dataIndex) {
  49616. var params = _super.prototype.getDataParams.apply(this, arguments);
  49617. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  49618. params.treeAncestors = wrapTreePathInfo(node, this); // compatitable the previous code.
  49619. params.treePathInfo = params.treeAncestors;
  49620. return params;
  49621. };
  49622. /**
  49623. * @public
  49624. * @param {Object} layoutInfo {
  49625. * x: containerGroup x
  49626. * y: containerGroup y
  49627. * width: containerGroup width
  49628. * height: containerGroup height
  49629. * }
  49630. */
  49631. TreemapSeriesModel.prototype.setLayoutInfo = function (layoutInfo) {
  49632. /**
  49633. * @readOnly
  49634. * @type {Object}
  49635. */
  49636. this.layoutInfo = this.layoutInfo || {};
  49637. extend(this.layoutInfo, layoutInfo);
  49638. };
  49639. /**
  49640. * @param {string} id
  49641. * @return {number} index
  49642. */
  49643. TreemapSeriesModel.prototype.mapIdToIndex = function (id) {
  49644. // A feature is implemented:
  49645. // index is monotone increasing with the sequence of
  49646. // input id at the first time.
  49647. // This feature can make sure that each data item and its
  49648. // mapped color have the same index between data list and
  49649. // color list at the beginning, which is useful for user
  49650. // to adjust data-color mapping.
  49651. /**
  49652. * @private
  49653. * @type {Object}
  49654. */
  49655. var idIndexMap = this._idIndexMap;
  49656. if (!idIndexMap) {
  49657. idIndexMap = this._idIndexMap = createHashMap();
  49658. /**
  49659. * @private
  49660. * @type {number}
  49661. */
  49662. this._idIndexMapCount = 0;
  49663. }
  49664. var index = idIndexMap.get(id);
  49665. if (index == null) {
  49666. idIndexMap.set(id, index = this._idIndexMapCount++);
  49667. }
  49668. return index;
  49669. };
  49670. TreemapSeriesModel.prototype.getViewRoot = function () {
  49671. return this._viewRoot;
  49672. };
  49673. TreemapSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  49674. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  49675. var root = this.getRawData().tree.root;
  49676. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  49677. this._viewRoot = root;
  49678. }
  49679. };
  49680. TreemapSeriesModel.prototype.enableAriaDecal = function () {
  49681. enableAriaDecalForTree(this);
  49682. };
  49683. TreemapSeriesModel.type = 'series.treemap';
  49684. TreemapSeriesModel.layoutMode = 'box';
  49685. TreemapSeriesModel.defaultOption = {
  49686. // Disable progressive rendering
  49687. progressive: 0,
  49688. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  49689. left: 'center',
  49690. top: 'middle',
  49691. width: '80%',
  49692. height: '80%',
  49693. sort: true,
  49694. clipWindow: 'origin',
  49695. squareRatio: 0.5 * (1 + Math.sqrt(5)),
  49696. leafDepth: null,
  49697. drillDownIcon: '▶',
  49698. // to align specialized icon. ▷▶❒❐▼✚
  49699. zoomToNodeRatio: 0.32 * 0.32,
  49700. roam: true,
  49701. nodeClick: 'zoomToNode',
  49702. animation: true,
  49703. animationDurationUpdate: 900,
  49704. animationEasing: 'quinticInOut',
  49705. breadcrumb: {
  49706. show: true,
  49707. height: 22,
  49708. left: 'center',
  49709. top: 'bottom',
  49710. // right
  49711. // bottom
  49712. emptyItemWidth: 25,
  49713. itemStyle: {
  49714. color: 'rgba(0,0,0,0.7)',
  49715. textStyle: {
  49716. color: '#fff'
  49717. }
  49718. },
  49719. emphasis: {
  49720. itemStyle: {
  49721. color: 'rgba(0,0,0,0.9)' // '#5793f3',
  49722. }
  49723. }
  49724. },
  49725. label: {
  49726. show: true,
  49727. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  49728. distance: 0,
  49729. padding: 5,
  49730. position: 'inside',
  49731. // formatter: null,
  49732. color: '#fff',
  49733. overflow: 'truncate' // align
  49734. // verticalAlign
  49735. },
  49736. upperLabel: {
  49737. show: false,
  49738. position: [0, '50%'],
  49739. height: 20,
  49740. // formatter: null,
  49741. // color: '#fff',
  49742. overflow: 'truncate',
  49743. // align: null,
  49744. verticalAlign: 'middle'
  49745. },
  49746. itemStyle: {
  49747. color: null,
  49748. colorAlpha: null,
  49749. colorSaturation: null,
  49750. borderWidth: 0,
  49751. gapWidth: 0,
  49752. borderColor: '#fff',
  49753. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  49754. // border color is evaluated by color of current node and
  49755. // borderColorSaturation.
  49756. },
  49757. emphasis: {
  49758. upperLabel: {
  49759. show: true,
  49760. position: [0, '50%'],
  49761. overflow: 'truncate',
  49762. verticalAlign: 'middle'
  49763. }
  49764. },
  49765. visualDimension: 0,
  49766. visualMin: null,
  49767. visualMax: null,
  49768. color: [],
  49769. // level[n].color (if necessary).
  49770. // + Specify color list of each level. level[0].color would be global
  49771. // color list if not specified. (see method `setDefault`).
  49772. // + But set as a empty array to forbid fetch color from global palette
  49773. // when using nodeModel.get('color'), otherwise nodes on deep level
  49774. // will always has color palette set and are not able to inherit color
  49775. // from parent node.
  49776. // + TreemapSeries.color can not be set as 'none', otherwise effect
  49777. // legend color fetching (see seriesColor.js).
  49778. colorAlpha: null,
  49779. colorSaturation: null,
  49780. colorMappingBy: 'index',
  49781. visibleMin: 10,
  49782. // be rendered. Only works when sort is 'asc' or 'desc'.
  49783. childrenVisibleMin: null,
  49784. // grandchildren will not show.
  49785. // Why grandchildren? If not grandchildren but children,
  49786. // some siblings show children and some not,
  49787. // the appearance may be mess and not consistent,
  49788. levels: [] // Each item: {
  49789. // visibleMin, itemStyle, visualDimension, label
  49790. // }
  49791. };
  49792. return TreemapSeriesModel;
  49793. }(SeriesModel);
  49794. /**
  49795. * @param {Object} dataNode
  49796. */
  49797. function completeTreeValue(dataNode) {
  49798. // Postorder travel tree.
  49799. // If value of none-leaf node is not set,
  49800. // calculate it by suming up the value of all children.
  49801. var sum = 0;
  49802. each(dataNode.children, function (child) {
  49803. completeTreeValue(child);
  49804. var childValue = child.value;
  49805. isArray(childValue) && (childValue = childValue[0]);
  49806. sum += childValue;
  49807. });
  49808. var thisValue = dataNode.value;
  49809. if (isArray(thisValue)) {
  49810. thisValue = thisValue[0];
  49811. }
  49812. if (thisValue == null || isNaN(thisValue)) {
  49813. thisValue = sum;
  49814. } // Value should not less than 0.
  49815. if (thisValue < 0) {
  49816. thisValue = 0;
  49817. }
  49818. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  49819. }
  49820. /**
  49821. * set default to level configuration
  49822. */
  49823. function setDefault(levels, ecModel) {
  49824. var globalColorList = normalizeToArray(ecModel.get('color'));
  49825. var globalDecalList = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  49826. if (!globalColorList) {
  49827. return;
  49828. }
  49829. levels = levels || [];
  49830. var hasColorDefine;
  49831. var hasDecalDefine;
  49832. each(levels, function (levelDefine) {
  49833. var model = new Model(levelDefine);
  49834. var modelColor = model.get('color');
  49835. var modelDecal = model.get('decal');
  49836. if (model.get(['itemStyle', 'color']) || modelColor && modelColor !== 'none') {
  49837. hasColorDefine = true;
  49838. }
  49839. if (model.get(['itemStyle', 'decal']) || modelDecal && modelDecal !== 'none') {
  49840. hasDecalDefine = true;
  49841. }
  49842. });
  49843. var level0 = levels[0] || (levels[0] = {});
  49844. if (!hasColorDefine) {
  49845. level0.color = globalColorList.slice();
  49846. }
  49847. if (!hasDecalDefine && globalDecalList) {
  49848. level0.decal = globalDecalList.slice();
  49849. }
  49850. return levels;
  49851. }
  49852. var TEXT_PADDING = 8;
  49853. var ITEM_GAP = 8;
  49854. var ARRAY_LENGTH = 5;
  49855. var Breadcrumb =
  49856. /** @class */
  49857. function () {
  49858. function Breadcrumb(containerGroup) {
  49859. this.group = new Group();
  49860. containerGroup.add(this.group);
  49861. }
  49862. Breadcrumb.prototype.render = function (seriesModel, api, targetNode, onSelect) {
  49863. var model = seriesModel.getModel('breadcrumb');
  49864. var thisGroup = this.group;
  49865. thisGroup.removeAll();
  49866. if (!model.get('show') || !targetNode) {
  49867. return;
  49868. }
  49869. var normalStyleModel = model.getModel('itemStyle');
  49870. var emphasisModel = model.getModel('emphasis');
  49871. var textStyleModel = normalStyleModel.getModel('textStyle');
  49872. var emphasisTextStyleModel = emphasisModel.getModel(['itemStyle', 'textStyle']);
  49873. var layoutParam = {
  49874. pos: {
  49875. left: model.get('left'),
  49876. right: model.get('right'),
  49877. top: model.get('top'),
  49878. bottom: model.get('bottom')
  49879. },
  49880. box: {
  49881. width: api.getWidth(),
  49882. height: api.getHeight()
  49883. },
  49884. emptyItemWidth: model.get('emptyItemWidth'),
  49885. totalWidth: 0,
  49886. renderList: []
  49887. };
  49888. this._prepare(targetNode, layoutParam, textStyleModel);
  49889. this._renderContent(seriesModel, layoutParam, normalStyleModel, emphasisModel, textStyleModel, emphasisTextStyleModel, onSelect);
  49890. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  49891. };
  49892. /**
  49893. * Prepare render list and total width
  49894. * @private
  49895. */
  49896. Breadcrumb.prototype._prepare = function (targetNode, layoutParam, textStyleModel) {
  49897. for (var node = targetNode; node; node = node.parentNode) {
  49898. var text = convertOptionIdName(node.getModel().get('name'), '');
  49899. var textRect = textStyleModel.getTextRect(text);
  49900. var itemWidth = Math.max(textRect.width + TEXT_PADDING * 2, layoutParam.emptyItemWidth);
  49901. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  49902. layoutParam.renderList.push({
  49903. node: node,
  49904. text: text,
  49905. width: itemWidth
  49906. });
  49907. }
  49908. };
  49909. /**
  49910. * @private
  49911. */
  49912. Breadcrumb.prototype._renderContent = function (seriesModel, layoutParam, normalStyleModel, emphasisModel, textStyleModel, emphasisTextStyleModel, onSelect) {
  49913. // Start rendering.
  49914. var lastX = 0;
  49915. var emptyItemWidth = layoutParam.emptyItemWidth;
  49916. var height = seriesModel.get(['breadcrumb', 'height']);
  49917. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  49918. var totalWidth = layoutParam.totalWidth;
  49919. var renderList = layoutParam.renderList;
  49920. var emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  49921. for (var i = renderList.length - 1; i >= 0; i--) {
  49922. var item = renderList[i];
  49923. var itemNode = item.node;
  49924. var itemWidth = item.width;
  49925. var text = item.text; // Hdie text and shorten width if necessary.
  49926. if (totalWidth > availableSize.width) {
  49927. totalWidth -= itemWidth - emptyItemWidth;
  49928. itemWidth = emptyItemWidth;
  49929. text = null;
  49930. }
  49931. var el = new Polygon({
  49932. shape: {
  49933. points: makeItemPoints(lastX, 0, itemWidth, height, i === renderList.length - 1, i === 0)
  49934. },
  49935. style: defaults(normalStyleModel.getItemStyle(), {
  49936. lineJoin: 'bevel'
  49937. }),
  49938. textContent: new ZRText({
  49939. style: createTextStyle(textStyleModel, {
  49940. text: text
  49941. })
  49942. }),
  49943. textConfig: {
  49944. position: 'inside'
  49945. },
  49946. z2: Z2_EMPHASIS_LIFT * 1e4,
  49947. onclick: curry(onSelect, itemNode)
  49948. });
  49949. el.disableLabelAnimation = true;
  49950. el.getTextContent().ensureState('emphasis').style = createTextStyle(emphasisTextStyleModel, {
  49951. text: text
  49952. });
  49953. el.ensureState('emphasis').style = emphasisItemStyle;
  49954. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  49955. this.group.add(el);
  49956. packEventData(el, seriesModel, itemNode);
  49957. lastX += itemWidth + ITEM_GAP;
  49958. }
  49959. };
  49960. Breadcrumb.prototype.remove = function () {
  49961. this.group.removeAll();
  49962. };
  49963. return Breadcrumb;
  49964. }();
  49965. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  49966. var points = [[head ? x : x - ARRAY_LENGTH, y], [x + itemWidth, y], [x + itemWidth, y + itemHeight], [head ? x : x - ARRAY_LENGTH, y + itemHeight]];
  49967. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  49968. !head && points.push([x, y + itemHeight / 2]);
  49969. return points;
  49970. } // Package custom mouse event.
  49971. function packEventData(el, seriesModel, itemNode) {
  49972. getECData(el).eventData = {
  49973. componentType: 'series',
  49974. componentSubType: 'treemap',
  49975. componentIndex: seriesModel.componentIndex,
  49976. seriesIndex: seriesModel.seriesIndex,
  49977. seriesName: seriesModel.name,
  49978. seriesType: 'treemap',
  49979. selfType: 'breadcrumb',
  49980. nodeData: {
  49981. dataIndex: itemNode && itemNode.dataIndex,
  49982. name: itemNode && itemNode.name
  49983. },
  49984. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  49985. };
  49986. }
  49987. /*
  49988. * Licensed to the Apache Software Foundation (ASF) under one
  49989. * or more contributor license agreements. See the NOTICE file
  49990. * distributed with this work for additional information
  49991. * regarding copyright ownership. The ASF licenses this file
  49992. * to you under the Apache License, Version 2.0 (the
  49993. * "License"); you may not use this file except in compliance
  49994. * with the License. You may obtain a copy of the License at
  49995. *
  49996. * http://www.apache.org/licenses/LICENSE-2.0
  49997. *
  49998. * Unless required by applicable law or agreed to in writing,
  49999. * software distributed under the License is distributed on an
  50000. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50001. * KIND, either express or implied. See the License for the
  50002. * specific language governing permissions and limitations
  50003. * under the License.
  50004. */
  50005. /**
  50006. * AUTO-GENERATED FILE. DO NOT MODIFY.
  50007. */
  50008. /*
  50009. * Licensed to the Apache Software Foundation (ASF) under one
  50010. * or more contributor license agreements. See the NOTICE file
  50011. * distributed with this work for additional information
  50012. * regarding copyright ownership. The ASF licenses this file
  50013. * to you under the Apache License, Version 2.0 (the
  50014. * "License"); you may not use this file except in compliance
  50015. * with the License. You may obtain a copy of the License at
  50016. *
  50017. * http://www.apache.org/licenses/LICENSE-2.0
  50018. *
  50019. * Unless required by applicable law or agreed to in writing,
  50020. * software distributed under the License is distributed on an
  50021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50022. * KIND, either express or implied. See the License for the
  50023. * specific language governing permissions and limitations
  50024. * under the License.
  50025. */
  50026. /**
  50027. * Animate multiple elements with a single done-callback.
  50028. *
  50029. * @example
  50030. * animation
  50031. * .createWrap()
  50032. * .add(el1, {x: 10, y: 10})
  50033. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  50034. * .done(function () { // done })
  50035. * .start('cubicOut');
  50036. */
  50037. var AnimationWrap =
  50038. /** @class */
  50039. function () {
  50040. function AnimationWrap() {
  50041. this._storage = [];
  50042. this._elExistsMap = {};
  50043. }
  50044. /**
  50045. * Caution: a el can only be added once, otherwise 'done'
  50046. * might not be called. This method checks this (by el.id),
  50047. * suppresses adding and returns false when existing el found.
  50048. *
  50049. * @return Whether adding succeeded.
  50050. */
  50051. AnimationWrap.prototype.add = function (el, target, duration, delay, easing) {
  50052. if (this._elExistsMap[el.id]) {
  50053. return false;
  50054. }
  50055. this._elExistsMap[el.id] = true;
  50056. this._storage.push({
  50057. el: el,
  50058. target: target,
  50059. duration: duration,
  50060. delay: delay,
  50061. easing: easing
  50062. });
  50063. return true;
  50064. };
  50065. /**
  50066. * Only execute when animation done/aborted.
  50067. */
  50068. AnimationWrap.prototype.finished = function (callback) {
  50069. this._finishedCallback = callback;
  50070. return this;
  50071. };
  50072. /**
  50073. * Will stop exist animation firstly.
  50074. */
  50075. AnimationWrap.prototype.start = function () {
  50076. var _this = this;
  50077. var count = this._storage.length;
  50078. var checkTerminate = function () {
  50079. count--;
  50080. if (count <= 0) {
  50081. // Guard.
  50082. _this._storage.length = 0;
  50083. _this._elExistsMap = {};
  50084. _this._finishedCallback && _this._finishedCallback();
  50085. }
  50086. };
  50087. for (var i = 0, len = this._storage.length; i < len; i++) {
  50088. var item = this._storage[i];
  50089. item.el.animateTo(item.target, {
  50090. duration: item.duration,
  50091. delay: item.delay,
  50092. easing: item.easing,
  50093. setToFinal: true,
  50094. done: checkTerminate,
  50095. aborted: checkTerminate
  50096. });
  50097. }
  50098. return this;
  50099. };
  50100. return AnimationWrap;
  50101. }();
  50102. function createWrap() {
  50103. return new AnimationWrap();
  50104. }
  50105. var Group$1 = Group;
  50106. var Rect$1 = Rect;
  50107. var DRAG_THRESHOLD = 3;
  50108. var PATH_LABEL_NOAMAL = 'label';
  50109. var PATH_UPPERLABEL_NORMAL = 'upperLabel'; // Should larger than emphasis states lift z
  50110. var Z2_BASE = Z2_EMPHASIS_LIFT * 10; // Should bigger than every z2.
  50111. var Z2_BG = Z2_EMPHASIS_LIFT * 2;
  50112. var Z2_CONTENT = Z2_EMPHASIS_LIFT * 3;
  50113. var getStateItemStyle = makeStyleMapper([['fill', 'color'], // `borderColor` and `borderWidth` has been occupied,
  50114. // so use `stroke` to indicate the stroke of the rect.
  50115. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  50116. // So do not transfer decal directly.
  50117. ]);
  50118. var getItemStyleNormal = function (model) {
  50119. // Normal style props should include emphasis style props.
  50120. var itemStyle = getStateItemStyle(model); // Clear styles set by emphasis.
  50121. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  50122. return itemStyle;
  50123. };
  50124. var inner$8 = makeInner();
  50125. var TreemapView =
  50126. /** @class */
  50127. function (_super) {
  50128. __extends(TreemapView, _super);
  50129. function TreemapView() {
  50130. var _this = _super !== null && _super.apply(this, arguments) || this;
  50131. _this.type = TreemapView.type;
  50132. _this._state = 'ready';
  50133. _this._storage = createStorage();
  50134. return _this;
  50135. }
  50136. /**
  50137. * @override
  50138. */
  50139. TreemapView.prototype.render = function (seriesModel, ecModel, api, payload) {
  50140. var models = ecModel.findComponents({
  50141. mainType: 'series',
  50142. subType: 'treemap',
  50143. query: payload
  50144. });
  50145. if (indexOf(models, seriesModel) < 0) {
  50146. return;
  50147. }
  50148. this.seriesModel = seriesModel;
  50149. this.api = api;
  50150. this.ecModel = ecModel;
  50151. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  50152. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  50153. var payloadType = payload && payload.type;
  50154. var layoutInfo = seriesModel.layoutInfo;
  50155. var isInit = !this._oldTree;
  50156. var thisStorage = this._storage; // Mark new root when action is treemapRootToNode.
  50157. var reRoot = payloadType === 'treemapRootToNode' && targetInfo && thisStorage ? {
  50158. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  50159. direction: payload.direction
  50160. } : null;
  50161. var containerGroup = this._giveContainerGroup(layoutInfo);
  50162. var hasAnimation = seriesModel.get('animation');
  50163. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  50164. hasAnimation && !isInit && (!payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode') ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally();
  50165. this._resetController(api);
  50166. this._renderBreadcrumb(seriesModel, api, targetInfo);
  50167. };
  50168. TreemapView.prototype._giveContainerGroup = function (layoutInfo) {
  50169. var containerGroup = this._containerGroup;
  50170. if (!containerGroup) {
  50171. // FIXME
  50172. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  50173. containerGroup = this._containerGroup = new Group$1();
  50174. this._initEvents(containerGroup);
  50175. this.group.add(containerGroup);
  50176. }
  50177. containerGroup.x = layoutInfo.x;
  50178. containerGroup.y = layoutInfo.y;
  50179. return containerGroup;
  50180. };
  50181. TreemapView.prototype._doRender = function (containerGroup, seriesModel, reRoot) {
  50182. var thisTree = seriesModel.getData().tree;
  50183. var oldTree = this._oldTree; // Clear last shape records.
  50184. var lastsForAnimation = createStorage();
  50185. var thisStorage = createStorage();
  50186. var oldStorage = this._storage;
  50187. var willInvisibleEls = [];
  50188. function doRenderNode(thisNode, oldNode, parentGroup, depth) {
  50189. return renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth);
  50190. } // Notice: When thisTree and oldTree are the same tree (see list.cloneShallow),
  50191. // the oldTree is actually losted, so we cannot find all of the old graphic
  50192. // elements from tree. So we use this strategy: make element storage, move
  50193. // from old storage to new storage, clear old storage.
  50194. dualTravel(thisTree.root ? [thisTree.root] : [], oldTree && oldTree.root ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0); // Process all removing.
  50195. var willDeleteEls = clearStorage(oldStorage);
  50196. this._oldTree = thisTree;
  50197. this._storage = thisStorage;
  50198. return {
  50199. lastsForAnimation: lastsForAnimation,
  50200. willDeleteEls: willDeleteEls,
  50201. renderFinally: renderFinally
  50202. };
  50203. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  50204. // When 'render' is triggered by action,
  50205. // 'this' and 'old' may be the same tree,
  50206. // we use rawIndex in that case.
  50207. if (sameTree) {
  50208. oldViewChildren = thisViewChildren;
  50209. each(thisViewChildren, function (child, index) {
  50210. !child.isRemoved() && processNode(index, index);
  50211. });
  50212. } // Diff hierarchically (diff only in each subtree, but not whole).
  50213. // because, consistency of view is important.
  50214. else {
  50215. new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  50216. }
  50217. function getKey(node) {
  50218. // Identify by name or raw index.
  50219. return node.getId();
  50220. }
  50221. function processNode(newIndex, oldIndex) {
  50222. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  50223. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  50224. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  50225. group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1);
  50226. }
  50227. }
  50228. function clearStorage(storage) {
  50229. var willDeleteEls = createStorage();
  50230. storage && each(storage, function (store, storageName) {
  50231. var delEls = willDeleteEls[storageName];
  50232. each(store, function (el) {
  50233. el && (delEls.push(el), inner$8(el).willDelete = true);
  50234. });
  50235. });
  50236. return willDeleteEls;
  50237. }
  50238. function renderFinally() {
  50239. each(willDeleteEls, function (els) {
  50240. each(els, function (el) {
  50241. el.parent && el.parent.remove(el);
  50242. });
  50243. });
  50244. each(willInvisibleEls, function (el) {
  50245. el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty,
  50246. // just mark as invisible.
  50247. el.dirty();
  50248. });
  50249. }
  50250. };
  50251. TreemapView.prototype._doAnimation = function (containerGroup, renderResult, seriesModel, reRoot) {
  50252. var durationOption = seriesModel.get('animationDurationUpdate');
  50253. var easingOption = seriesModel.get('animationEasing'); // TODO: do not support function until necessary.
  50254. var duration = (isFunction(durationOption) ? 0 : durationOption) || 0;
  50255. var easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut';
  50256. var animationWrap = createWrap(); // Make delete animations.
  50257. each(renderResult.willDeleteEls, function (store, storageName) {
  50258. each(store, function (el, rawIndex) {
  50259. if (el.invisible) {
  50260. return;
  50261. }
  50262. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  50263. var target;
  50264. var innerStore = inner$8(parent);
  50265. if (reRoot && reRoot.direction === 'drillDown') {
  50266. target = parent === reRoot.rootNodeGroup // This is the content element of view root.
  50267. // Only `content` will enter this branch, because
  50268. // `background` and `nodeGroup` will not be deleted.
  50269. ? {
  50270. shape: {
  50271. x: 0,
  50272. y: 0,
  50273. width: innerStore.nodeWidth,
  50274. height: innerStore.nodeHeight
  50275. },
  50276. style: {
  50277. opacity: 0
  50278. }
  50279. } // Others.
  50280. : {
  50281. style: {
  50282. opacity: 0
  50283. }
  50284. };
  50285. } else {
  50286. var targetX = 0;
  50287. var targetY = 0;
  50288. if (!innerStore.willDelete) {
  50289. // Let node animate to right-bottom corner, cooperating with fadeout,
  50290. // which is appropriate for user understanding.
  50291. // Divided by 2 for reRoot rolling up effect.
  50292. targetX = innerStore.nodeWidth / 2;
  50293. targetY = innerStore.nodeHeight / 2;
  50294. }
  50295. target = storageName === 'nodeGroup' ? {
  50296. x: targetX,
  50297. y: targetY,
  50298. style: {
  50299. opacity: 0
  50300. }
  50301. } : {
  50302. shape: {
  50303. x: targetX,
  50304. y: targetY,
  50305. width: 0,
  50306. height: 0
  50307. },
  50308. style: {
  50309. opacity: 0
  50310. }
  50311. };
  50312. } // TODO: do not support delay until necessary.
  50313. target && animationWrap.add(el, target, duration, 0, easing);
  50314. });
  50315. }); // Make other animations
  50316. each(this._storage, function (store, storageName) {
  50317. each(store, function (el, rawIndex) {
  50318. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  50319. var target = {};
  50320. if (!last) {
  50321. return;
  50322. }
  50323. if (el instanceof Group) {
  50324. if (last.oldX != null) {
  50325. target.x = el.x;
  50326. target.y = el.y;
  50327. el.x = last.oldX;
  50328. el.y = last.oldY;
  50329. }
  50330. } else {
  50331. if (last.oldShape) {
  50332. target.shape = extend({}, el.shape);
  50333. el.setShape(last.oldShape);
  50334. }
  50335. if (last.fadein) {
  50336. el.setStyle('opacity', 0);
  50337. target.style = {
  50338. opacity: 1
  50339. };
  50340. } // When animation is stopped for succedent animation starting,
  50341. // el.style.opacity might not be 1
  50342. else if (el.style.opacity !== 1) {
  50343. target.style = {
  50344. opacity: 1
  50345. };
  50346. }
  50347. }
  50348. animationWrap.add(el, target, duration, 0, easing);
  50349. });
  50350. }, this);
  50351. this._state = 'animating';
  50352. animationWrap.finished(bind(function () {
  50353. this._state = 'ready';
  50354. renderResult.renderFinally();
  50355. }, this)).start();
  50356. };
  50357. TreemapView.prototype._resetController = function (api) {
  50358. var controller = this._controller; // Init controller.
  50359. if (!controller) {
  50360. controller = this._controller = new RoamController(api.getZr());
  50361. controller.enable(this.seriesModel.get('roam'));
  50362. controller.on('pan', bind(this._onPan, this));
  50363. controller.on('zoom', bind(this._onZoom, this));
  50364. }
  50365. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  50366. controller.setPointerChecker(function (e, x, y) {
  50367. return rect.contain(x, y);
  50368. });
  50369. };
  50370. TreemapView.prototype._clearController = function () {
  50371. var controller = this._controller;
  50372. if (controller) {
  50373. controller.dispose();
  50374. controller = null;
  50375. }
  50376. };
  50377. TreemapView.prototype._onPan = function (e) {
  50378. if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)) {
  50379. // These param must not be cached.
  50380. var root = this.seriesModel.getData().tree.root;
  50381. if (!root) {
  50382. return;
  50383. }
  50384. var rootLayout = root.getLayout();
  50385. if (!rootLayout) {
  50386. return;
  50387. }
  50388. this.api.dispatchAction({
  50389. type: 'treemapMove',
  50390. from: this.uid,
  50391. seriesId: this.seriesModel.id,
  50392. rootRect: {
  50393. x: rootLayout.x + e.dx,
  50394. y: rootLayout.y + e.dy,
  50395. width: rootLayout.width,
  50396. height: rootLayout.height
  50397. }
  50398. });
  50399. }
  50400. };
  50401. TreemapView.prototype._onZoom = function (e) {
  50402. var mouseX = e.originX;
  50403. var mouseY = e.originY;
  50404. if (this._state !== 'animating') {
  50405. // These param must not be cached.
  50406. var root = this.seriesModel.getData().tree.root;
  50407. if (!root) {
  50408. return;
  50409. }
  50410. var rootLayout = root.getLayout();
  50411. if (!rootLayout) {
  50412. return;
  50413. }
  50414. var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height);
  50415. var layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup.
  50416. mouseX -= layoutInfo.x;
  50417. mouseY -= layoutInfo.y; // Scale root bounding rect.
  50418. var m = create$1();
  50419. translate(m, m, [-mouseX, -mouseY]);
  50420. scale$1(m, m, [e.scale, e.scale]);
  50421. translate(m, m, [mouseX, mouseY]);
  50422. rect.applyTransform(m);
  50423. this.api.dispatchAction({
  50424. type: 'treemapRender',
  50425. from: this.uid,
  50426. seriesId: this.seriesModel.id,
  50427. rootRect: {
  50428. x: rect.x,
  50429. y: rect.y,
  50430. width: rect.width,
  50431. height: rect.height
  50432. }
  50433. });
  50434. }
  50435. };
  50436. TreemapView.prototype._initEvents = function (containerGroup) {
  50437. var _this = this;
  50438. containerGroup.on('click', function (e) {
  50439. if (_this._state !== 'ready') {
  50440. return;
  50441. }
  50442. var nodeClick = _this.seriesModel.get('nodeClick', true);
  50443. if (!nodeClick) {
  50444. return;
  50445. }
  50446. var targetInfo = _this.findTarget(e.offsetX, e.offsetY);
  50447. if (!targetInfo) {
  50448. return;
  50449. }
  50450. var node = targetInfo.node;
  50451. if (node.getLayout().isLeafRoot) {
  50452. _this._rootToNode(targetInfo);
  50453. } else {
  50454. if (nodeClick === 'zoomToNode') {
  50455. _this._zoomToNode(targetInfo);
  50456. } else if (nodeClick === 'link') {
  50457. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  50458. var link = itemModel.get('link', true);
  50459. var linkTarget = itemModel.get('target', true) || 'blank';
  50460. link && windowOpen(link, linkTarget);
  50461. }
  50462. }
  50463. }, this);
  50464. };
  50465. TreemapView.prototype._renderBreadcrumb = function (seriesModel, api, targetInfo) {
  50466. var _this = this;
  50467. if (!targetInfo) {
  50468. targetInfo = seriesModel.get('leafDepth', true) != null ? {
  50469. node: seriesModel.getViewRoot()
  50470. } // FIXME
  50471. // better way?
  50472. // Find breadcrumb tail on center of containerGroup.
  50473. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  50474. if (!targetInfo) {
  50475. targetInfo = {
  50476. node: seriesModel.getData().tree.root
  50477. };
  50478. }
  50479. }
  50480. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, function (node) {
  50481. if (_this._state !== 'animating') {
  50482. aboveViewRoot(seriesModel.getViewRoot(), node) ? _this._rootToNode({
  50483. node: node
  50484. }) : _this._zoomToNode({
  50485. node: node
  50486. });
  50487. }
  50488. });
  50489. };
  50490. /**
  50491. * @override
  50492. */
  50493. TreemapView.prototype.remove = function () {
  50494. this._clearController();
  50495. this._containerGroup && this._containerGroup.removeAll();
  50496. this._storage = createStorage();
  50497. this._state = 'ready';
  50498. this._breadcrumb && this._breadcrumb.remove();
  50499. };
  50500. TreemapView.prototype.dispose = function () {
  50501. this._clearController();
  50502. };
  50503. TreemapView.prototype._zoomToNode = function (targetInfo) {
  50504. this.api.dispatchAction({
  50505. type: 'treemapZoomToNode',
  50506. from: this.uid,
  50507. seriesId: this.seriesModel.id,
  50508. targetNode: targetInfo.node
  50509. });
  50510. };
  50511. TreemapView.prototype._rootToNode = function (targetInfo) {
  50512. this.api.dispatchAction({
  50513. type: 'treemapRootToNode',
  50514. from: this.uid,
  50515. seriesId: this.seriesModel.id,
  50516. targetNode: targetInfo.node
  50517. });
  50518. };
  50519. /**
  50520. * @public
  50521. * @param {number} x Global coord x.
  50522. * @param {number} y Global coord y.
  50523. * @return {Object} info If not found, return undefined;
  50524. * @return {number} info.node Target node.
  50525. * @return {number} info.offsetX x refer to target node.
  50526. * @return {number} info.offsetY y refer to target node.
  50527. */
  50528. TreemapView.prototype.findTarget = function (x, y) {
  50529. var targetInfo;
  50530. var viewRoot = this.seriesModel.getViewRoot();
  50531. viewRoot.eachNode({
  50532. attr: 'viewChildren',
  50533. order: 'preorder'
  50534. }, function (node) {
  50535. var bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element.
  50536. if (bgEl) {
  50537. var point = bgEl.transformCoordToLocal(x, y);
  50538. var shape = bgEl.shape; // For performance consideration, don't use 'getBoundingRect'.
  50539. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height) {
  50540. targetInfo = {
  50541. node: node,
  50542. offsetX: point[0],
  50543. offsetY: point[1]
  50544. };
  50545. } else {
  50546. return false; // Suppress visit subtree.
  50547. }
  50548. }
  50549. }, this);
  50550. return targetInfo;
  50551. };
  50552. TreemapView.type = 'treemap';
  50553. return TreemapView;
  50554. }(ChartView);
  50555. /**
  50556. * @inner
  50557. */
  50558. function createStorage() {
  50559. return {
  50560. nodeGroup: [],
  50561. background: [],
  50562. content: []
  50563. };
  50564. }
  50565. /**
  50566. * @inner
  50567. * @return Return undefined means do not travel further.
  50568. */
  50569. function renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) {
  50570. // Whether under viewRoot.
  50571. if (!thisNode) {
  50572. // Deleting nodes will be performed finally. This method just find
  50573. // element from old storage, or create new element, set them to new
  50574. // storage, and set styles.
  50575. return;
  50576. } // -------------------------------------------------------------------
  50577. // Start of closure variables available in "Procedures in renderNode".
  50578. var thisLayout = thisNode.getLayout();
  50579. var data = seriesModel.getData();
  50580. var nodeModel = thisNode.getModel(); // Only for enabling highlight/downplay. Clear firstly.
  50581. // Because some node will not be rendered.
  50582. data.setItemGraphicEl(thisNode.dataIndex, null);
  50583. if (!thisLayout || !thisLayout.isInView) {
  50584. return;
  50585. }
  50586. var thisWidth = thisLayout.width;
  50587. var thisHeight = thisLayout.height;
  50588. var borderWidth = thisLayout.borderWidth;
  50589. var thisInvisible = thisLayout.invisible;
  50590. var thisRawIndex = thisNode.getRawIndex();
  50591. var oldRawIndex = oldNode && oldNode.getRawIndex();
  50592. var thisViewChildren = thisNode.viewChildren;
  50593. var upperHeight = thisLayout.upperHeight;
  50594. var isParent = thisViewChildren && thisViewChildren.length;
  50595. var itemStyleNormalModel = nodeModel.getModel('itemStyle');
  50596. var itemStyleEmphasisModel = nodeModel.getModel(['emphasis', 'itemStyle']);
  50597. var itemStyleBlurModel = nodeModel.getModel(['blur', 'itemStyle']);
  50598. var itemStyleSelectModel = nodeModel.getModel(['select', 'itemStyle']);
  50599. var borderRadius = itemStyleNormalModel.get('borderRadius') || 0; // End of closure ariables available in "Procedures in renderNode".
  50600. // -----------------------------------------------------------------
  50601. // Node group
  50602. var group = giveGraphic('nodeGroup', Group$1);
  50603. if (!group) {
  50604. return;
  50605. }
  50606. parentGroup.add(group); // x,y are not set when el is above view root.
  50607. group.x = thisLayout.x || 0;
  50608. group.y = thisLayout.y || 0;
  50609. group.markRedraw();
  50610. inner$8(group).nodeWidth = thisWidth;
  50611. inner$8(group).nodeHeight = thisHeight;
  50612. if (thisLayout.isAboveViewRoot) {
  50613. return group;
  50614. } // Background
  50615. var bg = giveGraphic('background', Rect$1, depth, Z2_BG);
  50616. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight);
  50617. var emphasisModel = nodeModel.getModel('emphasis');
  50618. var focus = emphasisModel.get('focus');
  50619. var blurScope = emphasisModel.get('blurScope');
  50620. var isDisabled = emphasisModel.get('disabled');
  50621. var focusOrIndices = focus === 'ancestor' ? thisNode.getAncestorsIndices() : focus === 'descendant' ? thisNode.getDescendantIndices() : focus; // No children, render content.
  50622. if (isParent) {
  50623. // Because of the implementation about "traverse" in graphic hover style, we
  50624. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  50625. // hover event from the descendents will be listenered.
  50626. if (isHighDownDispatcher(group)) {
  50627. setAsHighDownDispatcher(group, false);
  50628. }
  50629. if (bg) {
  50630. setAsHighDownDispatcher(bg, !isDisabled); // Only for enabling highlight/downplay.
  50631. data.setItemGraphicEl(thisNode.dataIndex, bg);
  50632. enableHoverFocus(bg, focusOrIndices, blurScope);
  50633. }
  50634. } else {
  50635. var content = giveGraphic('content', Rect$1, depth, Z2_CONTENT);
  50636. content && renderContent(group, content);
  50637. bg.disableMorphing = true;
  50638. if (bg && isHighDownDispatcher(bg)) {
  50639. setAsHighDownDispatcher(bg, false);
  50640. }
  50641. setAsHighDownDispatcher(group, !isDisabled); // Only for enabling highlight/downplay.
  50642. data.setItemGraphicEl(thisNode.dataIndex, group);
  50643. enableHoverFocus(group, focusOrIndices, blurScope);
  50644. }
  50645. return group; // ----------------------------
  50646. // | Procedures in renderNode |
  50647. // ----------------------------
  50648. function renderBackground(group, bg, useUpperLabel) {
  50649. var ecData = getECData(bg); // For tooltip.
  50650. ecData.dataIndex = thisNode.dataIndex;
  50651. ecData.seriesIndex = seriesModel.seriesIndex;
  50652. bg.setShape({
  50653. x: 0,
  50654. y: 0,
  50655. width: thisWidth,
  50656. height: thisHeight,
  50657. r: borderRadius
  50658. });
  50659. if (thisInvisible) {
  50660. // If invisible, do not set visual, otherwise the element will
  50661. // change immediately before animation. We think it is OK to
  50662. // remain its origin color when moving out of the view window.
  50663. processInvisible(bg);
  50664. } else {
  50665. bg.invisible = false;
  50666. var style = thisNode.getVisual('style');
  50667. var visualBorderColor = style.stroke;
  50668. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  50669. normalStyle.fill = visualBorderColor;
  50670. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  50671. emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor');
  50672. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  50673. blurStyle.fill = itemStyleBlurModel.get('borderColor');
  50674. var selectStyle = getStateItemStyle(itemStyleSelectModel);
  50675. selectStyle.fill = itemStyleSelectModel.get('borderColor');
  50676. if (useUpperLabel) {
  50677. var upperLabelWidth = thisWidth - 2 * borderWidth;
  50678. prepareText( // PENDING: convert ZRColor to ColorString for text.
  50679. bg, visualBorderColor, style.opacity, {
  50680. x: borderWidth,
  50681. y: 0,
  50682. width: upperLabelWidth,
  50683. height: upperHeight
  50684. });
  50685. } // For old bg.
  50686. else {
  50687. bg.removeTextContent();
  50688. }
  50689. bg.setStyle(normalStyle);
  50690. bg.ensureState('emphasis').style = emphasisStyle;
  50691. bg.ensureState('blur').style = blurStyle;
  50692. bg.ensureState('select').style = selectStyle;
  50693. setDefaultStateProxy(bg);
  50694. }
  50695. group.add(bg);
  50696. }
  50697. function renderContent(group, content) {
  50698. var ecData = getECData(content); // For tooltip.
  50699. ecData.dataIndex = thisNode.dataIndex;
  50700. ecData.seriesIndex = seriesModel.seriesIndex;
  50701. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  50702. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  50703. content.culling = true;
  50704. content.setShape({
  50705. x: borderWidth,
  50706. y: borderWidth,
  50707. width: contentWidth,
  50708. height: contentHeight,
  50709. r: borderRadius
  50710. });
  50711. if (thisInvisible) {
  50712. // If invisible, do not set visual, otherwise the element will
  50713. // change immediately before animation. We think it is OK to
  50714. // remain its origin color when moving out of the view window.
  50715. processInvisible(content);
  50716. } else {
  50717. content.invisible = false;
  50718. var nodeStyle = thisNode.getVisual('style');
  50719. var visualColor = nodeStyle.fill;
  50720. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  50721. normalStyle.fill = visualColor;
  50722. normalStyle.decal = nodeStyle.decal;
  50723. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  50724. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  50725. var selectStyle = getStateItemStyle(itemStyleSelectModel); // PENDING: convert ZRColor to ColorString for text.
  50726. prepareText(content, visualColor, nodeStyle.opacity, null);
  50727. content.setStyle(normalStyle);
  50728. content.ensureState('emphasis').style = emphasisStyle;
  50729. content.ensureState('blur').style = blurStyle;
  50730. content.ensureState('select').style = selectStyle;
  50731. setDefaultStateProxy(content);
  50732. }
  50733. group.add(content);
  50734. }
  50735. function processInvisible(element) {
  50736. // Delay invisible setting utill animation finished,
  50737. // avoid element vanish suddenly before animation.
  50738. !element.invisible && willInvisibleEls.push(element);
  50739. }
  50740. function prepareText(rectEl, visualColor, visualOpacity, // Can be null/undefined
  50741. upperLabelRect) {
  50742. var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL);
  50743. var defaultText = convertOptionIdName(nodeModel.get('name'), null);
  50744. var isShow = normalLabelModel.getShallow('show');
  50745. setLabelStyle(rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), {
  50746. defaultText: isShow ? defaultText : null,
  50747. inheritColor: visualColor,
  50748. defaultOpacity: visualOpacity,
  50749. labelFetcher: seriesModel,
  50750. labelDataIndex: thisNode.dataIndex
  50751. });
  50752. var textEl = rectEl.getTextContent();
  50753. if (!textEl) {
  50754. return;
  50755. }
  50756. var textStyle = textEl.style;
  50757. var textPadding = normalizeCssArray(textStyle.padding || 0);
  50758. if (upperLabelRect) {
  50759. rectEl.setTextConfig({
  50760. layoutRect: upperLabelRect
  50761. });
  50762. textEl.disableLabelLayout = true;
  50763. }
  50764. textEl.beforeUpdate = function () {
  50765. var width = Math.max((upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0);
  50766. var height = Math.max((upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0);
  50767. if (textStyle.width !== width || textStyle.height !== height) {
  50768. textEl.setStyle({
  50769. width: width,
  50770. height: height
  50771. });
  50772. }
  50773. };
  50774. textStyle.truncateMinChar = 2;
  50775. textStyle.lineOverflow = 'truncate';
  50776. addDrillDownIcon(textStyle, upperLabelRect, thisLayout);
  50777. var textEmphasisState = textEl.getState('emphasis');
  50778. addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout);
  50779. }
  50780. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  50781. var text = style ? style.text : null;
  50782. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  50783. var iconChar = seriesModel.get('drillDownIcon', true);
  50784. style.text = iconChar ? iconChar + ' ' + text : text;
  50785. }
  50786. }
  50787. function giveGraphic(storageName, Ctor, depth, z) {
  50788. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  50789. var lasts = lastsForAnimation[storageName];
  50790. if (element) {
  50791. // Remove from oldStorage
  50792. oldStorage[storageName][oldRawIndex] = null;
  50793. prepareAnimationWhenHasOld(lasts, element);
  50794. } // If invisible and no old element, do not create new element (for optimizing).
  50795. else if (!thisInvisible) {
  50796. element = new Ctor();
  50797. if (element instanceof Displayable) {
  50798. element.z2 = calculateZ2(depth, z);
  50799. }
  50800. prepareAnimationWhenNoOld(lasts, element);
  50801. } // Set to thisStorage
  50802. return thisStorage[storageName][thisRawIndex] = element;
  50803. }
  50804. function prepareAnimationWhenHasOld(lasts, element) {
  50805. var lastCfg = lasts[thisRawIndex] = {};
  50806. if (element instanceof Group$1) {
  50807. lastCfg.oldX = element.x;
  50808. lastCfg.oldY = element.y;
  50809. } else {
  50810. lastCfg.oldShape = extend({}, element.shape);
  50811. }
  50812. } // If a element is new, we need to find the animation start point carefully,
  50813. // otherwise it will looks strange when 'zoomToNode'.
  50814. function prepareAnimationWhenNoOld(lasts, element) {
  50815. var lastCfg = lasts[thisRawIndex] = {};
  50816. var parentNode = thisNode.parentNode;
  50817. var isGroup = element instanceof Group;
  50818. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  50819. var parentOldX = 0;
  50820. var parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  50821. // For convenience, get old bounding rect from background.
  50822. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  50823. if (!reRoot && parentOldBg && parentOldBg.oldShape) {
  50824. parentOldX = parentOldBg.oldShape.width;
  50825. parentOldY = parentOldBg.oldShape.height;
  50826. } // When no parent old shape found, its parent is new too,
  50827. // so we can just use {x:0, y:0}.
  50828. if (isGroup) {
  50829. lastCfg.oldX = 0;
  50830. lastCfg.oldY = parentOldY;
  50831. } else {
  50832. lastCfg.oldShape = {
  50833. x: parentOldX,
  50834. y: parentOldY,
  50835. width: 0,
  50836. height: 0
  50837. };
  50838. }
  50839. } // Fade in, user can be aware that these nodes are new.
  50840. lastCfg.fadein = !isGroup;
  50841. }
  50842. } // We cannot set all background with the same z, because the behaviour of
  50843. // drill down and roll up differ background creation sequence from tree
  50844. // hierarchy sequence, which cause lower background elements to overlap
  50845. // upper ones. So we calculate z based on depth.
  50846. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  50847. // treemap with large z overlaps other components.
  50848. function calculateZ2(depth, z2InLevel) {
  50849. return depth * Z2_BASE + z2InLevel;
  50850. }
  50851. var each$3 = each;
  50852. var isObject$3 = isObject;
  50853. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  50854. var VisualMapping =
  50855. /** @class */
  50856. function () {
  50857. function VisualMapping(option) {
  50858. var mappingMethod = option.mappingMethod;
  50859. var visualType = option.type;
  50860. var thisOption = this.option = clone(option);
  50861. this.type = visualType;
  50862. this.mappingMethod = mappingMethod;
  50863. this._normalizeData = normalizers[mappingMethod];
  50864. var visualHandler = VisualMapping.visualHandlers[visualType];
  50865. this.applyVisual = visualHandler.applyVisual;
  50866. this.getColorMapper = visualHandler.getColorMapper;
  50867. this._normalizedToVisual = visualHandler._normalizedToVisual[mappingMethod];
  50868. if (mappingMethod === 'piecewise') {
  50869. normalizeVisualRange(thisOption);
  50870. preprocessForPiecewise(thisOption);
  50871. } else if (mappingMethod === 'category') {
  50872. thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified,
  50873. // which need no more preprocess except normalize visual.
  50874. : normalizeVisualRange(thisOption, true);
  50875. } else {
  50876. // mappingMethod === 'linear' or 'fixed'
  50877. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  50878. normalizeVisualRange(thisOption);
  50879. }
  50880. }
  50881. VisualMapping.prototype.mapValueToVisual = function (value) {
  50882. var normalized = this._normalizeData(value);
  50883. return this._normalizedToVisual(normalized, value);
  50884. };
  50885. VisualMapping.prototype.getNormalizer = function () {
  50886. return bind(this._normalizeData, this);
  50887. };
  50888. /**
  50889. * List available visual types.
  50890. *
  50891. * @public
  50892. * @return {Array.<string>}
  50893. */
  50894. VisualMapping.listVisualTypes = function () {
  50895. return keys(VisualMapping.visualHandlers);
  50896. }; // /**
  50897. // * @public
  50898. // */
  50899. // static addVisualHandler(name, handler) {
  50900. // visualHandlers[name] = handler;
  50901. // }
  50902. /**
  50903. * @public
  50904. */
  50905. VisualMapping.isValidType = function (visualType) {
  50906. return VisualMapping.visualHandlers.hasOwnProperty(visualType);
  50907. };
  50908. /**
  50909. * Convenient method.
  50910. * Visual can be Object or Array or primary type.
  50911. */
  50912. VisualMapping.eachVisual = function (visual, callback, context) {
  50913. if (isObject(visual)) {
  50914. each(visual, callback, context);
  50915. } else {
  50916. callback.call(context, visual);
  50917. }
  50918. };
  50919. VisualMapping.mapVisual = function (visual, callback, context) {
  50920. var isPrimary;
  50921. var newVisual = isArray(visual) ? [] : isObject(visual) ? {} : (isPrimary = true, null);
  50922. VisualMapping.eachVisual(visual, function (v, key) {
  50923. var newVal = callback.call(context, v, key);
  50924. isPrimary ? newVisual = newVal : newVisual[key] = newVal;
  50925. });
  50926. return newVisual;
  50927. };
  50928. /**
  50929. * Retrieve visual properties from given object.
  50930. */
  50931. VisualMapping.retrieveVisuals = function (obj) {
  50932. var ret = {};
  50933. var hasVisual;
  50934. obj && each$3(VisualMapping.visualHandlers, function (h, visualType) {
  50935. if (obj.hasOwnProperty(visualType)) {
  50936. ret[visualType] = obj[visualType];
  50937. hasVisual = true;
  50938. }
  50939. });
  50940. return hasVisual ? ret : null;
  50941. };
  50942. /**
  50943. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  50944. *
  50945. * @public
  50946. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  50947. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  50948. * @return {Array.<string>} Sorted visual types.
  50949. */
  50950. VisualMapping.prepareVisualTypes = function (visualTypes) {
  50951. if (isArray(visualTypes)) {
  50952. visualTypes = visualTypes.slice();
  50953. } else if (isObject$3(visualTypes)) {
  50954. var types_1 = [];
  50955. each$3(visualTypes, function (item, type) {
  50956. types_1.push(type);
  50957. });
  50958. visualTypes = types_1;
  50959. } else {
  50960. return [];
  50961. }
  50962. visualTypes.sort(function (type1, type2) {
  50963. // color should be front of colorSaturation, colorAlpha, ...
  50964. // symbol and symbolSize do not matter.
  50965. return type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0 ? 1 : -1;
  50966. });
  50967. return visualTypes;
  50968. };
  50969. /**
  50970. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  50971. * Other visuals are only depends on themself.
  50972. */
  50973. VisualMapping.dependsOn = function (visualType1, visualType2) {
  50974. return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2;
  50975. };
  50976. /**
  50977. * @param value
  50978. * @param pieceList [{value: ..., interval: [min, max]}, ...]
  50979. * Always from small to big.
  50980. * @param findClosestWhenOutside Default to be false
  50981. * @return index
  50982. */
  50983. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  50984. var possibleI;
  50985. var abs = Infinity; // value has the higher priority.
  50986. for (var i = 0, len = pieceList.length; i < len; i++) {
  50987. var pieceValue = pieceList[i].value;
  50988. if (pieceValue != null) {
  50989. if (pieceValue === value // FIXME
  50990. // It is supposed to compare value according to value type of dimension,
  50991. // but currently value type can exactly be string or number.
  50992. // Compromise for numeric-like string (like '12'), especially
  50993. // in the case that visualMap.categories is ['22', '33'].
  50994. || isString(pieceValue) && pieceValue === value + '') {
  50995. return i;
  50996. }
  50997. findClosestWhenOutside && updatePossible(pieceValue, i);
  50998. }
  50999. }
  51000. for (var i = 0, len = pieceList.length; i < len; i++) {
  51001. var piece = pieceList[i];
  51002. var interval = piece.interval;
  51003. var close_1 = piece.close;
  51004. if (interval) {
  51005. if (interval[0] === -Infinity) {
  51006. if (littleThan(close_1[1], value, interval[1])) {
  51007. return i;
  51008. }
  51009. } else if (interval[1] === Infinity) {
  51010. if (littleThan(close_1[0], interval[0], value)) {
  51011. return i;
  51012. }
  51013. } else if (littleThan(close_1[0], interval[0], value) && littleThan(close_1[1], value, interval[1])) {
  51014. return i;
  51015. }
  51016. findClosestWhenOutside && updatePossible(interval[0], i);
  51017. findClosestWhenOutside && updatePossible(interval[1], i);
  51018. }
  51019. }
  51020. if (findClosestWhenOutside) {
  51021. return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI;
  51022. }
  51023. function updatePossible(val, index) {
  51024. var newAbs = Math.abs(val - value);
  51025. if (newAbs < abs) {
  51026. abs = newAbs;
  51027. possibleI = index;
  51028. }
  51029. }
  51030. };
  51031. VisualMapping.visualHandlers = {
  51032. color: {
  51033. applyVisual: makeApplyVisual('color'),
  51034. getColorMapper: function () {
  51035. var thisOption = this.option;
  51036. return bind(thisOption.mappingMethod === 'category' ? function (value, isNormalized) {
  51037. !isNormalized && (value = this._normalizeData(value));
  51038. return doMapCategory.call(this, value);
  51039. } : function (value, isNormalized, out) {
  51040. // If output rgb array
  51041. // which will be much faster and useful in pixel manipulation
  51042. var returnRGBArray = !!out;
  51043. !isNormalized && (value = this._normalizeData(value));
  51044. out = fastLerp(value, thisOption.parsedVisual, out);
  51045. return returnRGBArray ? out : stringify(out, 'rgba');
  51046. }, this);
  51047. },
  51048. _normalizedToVisual: {
  51049. linear: function (normalized) {
  51050. return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  51051. },
  51052. category: doMapCategory,
  51053. piecewise: function (normalized, value) {
  51054. var result = getSpecifiedVisual.call(this, value);
  51055. if (result == null) {
  51056. result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  51057. }
  51058. return result;
  51059. },
  51060. fixed: doMapFixed
  51061. }
  51062. },
  51063. colorHue: makePartialColorVisualHandler(function (color$1, value) {
  51064. return modifyHSL(color$1, value);
  51065. }),
  51066. colorSaturation: makePartialColorVisualHandler(function (color$1, value) {
  51067. return modifyHSL(color$1, null, value);
  51068. }),
  51069. colorLightness: makePartialColorVisualHandler(function (color$1, value) {
  51070. return modifyHSL(color$1, null, null, value);
  51071. }),
  51072. colorAlpha: makePartialColorVisualHandler(function (color$1, value) {
  51073. return modifyAlpha(color$1, value);
  51074. }),
  51075. decal: {
  51076. applyVisual: makeApplyVisual('decal'),
  51077. _normalizedToVisual: {
  51078. linear: null,
  51079. category: doMapCategory,
  51080. piecewise: null,
  51081. fixed: null
  51082. }
  51083. },
  51084. opacity: {
  51085. applyVisual: makeApplyVisual('opacity'),
  51086. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51087. },
  51088. liftZ: {
  51089. applyVisual: makeApplyVisual('liftZ'),
  51090. _normalizedToVisual: {
  51091. linear: doMapFixed,
  51092. category: doMapFixed,
  51093. piecewise: doMapFixed,
  51094. fixed: doMapFixed
  51095. }
  51096. },
  51097. symbol: {
  51098. applyVisual: function (value, getter, setter) {
  51099. var symbolCfg = this.mapValueToVisual(value);
  51100. setter('symbol', symbolCfg);
  51101. },
  51102. _normalizedToVisual: {
  51103. linear: doMapToArray,
  51104. category: doMapCategory,
  51105. piecewise: function (normalized, value) {
  51106. var result = getSpecifiedVisual.call(this, value);
  51107. if (result == null) {
  51108. result = doMapToArray.call(this, normalized);
  51109. }
  51110. return result;
  51111. },
  51112. fixed: doMapFixed
  51113. }
  51114. },
  51115. symbolSize: {
  51116. applyVisual: makeApplyVisual('symbolSize'),
  51117. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51118. }
  51119. };
  51120. return VisualMapping;
  51121. }();
  51122. function preprocessForPiecewise(thisOption) {
  51123. var pieceList = thisOption.pieceList;
  51124. thisOption.hasSpecialVisual = false;
  51125. each(pieceList, function (piece, index) {
  51126. piece.originIndex = index; // piece.visual is "result visual value" but not
  51127. // a visual range, so it does not need to be normalized.
  51128. if (piece.visual != null) {
  51129. thisOption.hasSpecialVisual = true;
  51130. }
  51131. });
  51132. }
  51133. function preprocessForSpecifiedCategory(thisOption) {
  51134. // Hash categories.
  51135. var categories = thisOption.categories;
  51136. var categoryMap = thisOption.categoryMap = {};
  51137. var visual = thisOption.visual;
  51138. each$3(categories, function (cate, index) {
  51139. categoryMap[cate] = index;
  51140. }); // Process visual map input.
  51141. if (!isArray(visual)) {
  51142. var visualArr_1 = [];
  51143. if (isObject(visual)) {
  51144. each$3(visual, function (v, cate) {
  51145. var index = categoryMap[cate];
  51146. visualArr_1[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  51147. });
  51148. } else {
  51149. // Is primary type, represents default visual.
  51150. visualArr_1[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  51151. }
  51152. visual = setVisualToOption(thisOption, visualArr_1);
  51153. } // Remove categories that has no visual,
  51154. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  51155. for (var i = categories.length - 1; i >= 0; i--) {
  51156. if (visual[i] == null) {
  51157. delete categoryMap[categories[i]];
  51158. categories.pop();
  51159. }
  51160. }
  51161. }
  51162. function normalizeVisualRange(thisOption, isCategory) {
  51163. var visual = thisOption.visual;
  51164. var visualArr = [];
  51165. if (isObject(visual)) {
  51166. each$3(visual, function (v) {
  51167. visualArr.push(v);
  51168. });
  51169. } else if (visual != null) {
  51170. visualArr.push(visual);
  51171. }
  51172. var doNotNeedPair = {
  51173. color: 1,
  51174. symbol: 1
  51175. };
  51176. if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type)) {
  51177. // Do not care visualArr.length === 0, which is illegal.
  51178. visualArr[1] = visualArr[0];
  51179. }
  51180. setVisualToOption(thisOption, visualArr);
  51181. }
  51182. function makePartialColorVisualHandler(applyValue) {
  51183. return {
  51184. applyVisual: function (value, getter, setter) {
  51185. // Only used in HSL
  51186. var colorChannel = this.mapValueToVisual(value); // Must not be array value
  51187. setter('color', applyValue(getter('color'), colorChannel));
  51188. },
  51189. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51190. };
  51191. }
  51192. function doMapToArray(normalized) {
  51193. var visual = this.option.visual;
  51194. return visual[Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))] || {}; // TODO {}?
  51195. }
  51196. function makeApplyVisual(visualType) {
  51197. return function (value, getter, setter) {
  51198. setter(visualType, this.mapValueToVisual(value));
  51199. };
  51200. }
  51201. function doMapCategory(normalized) {
  51202. var visual = this.option.visual;
  51203. return visual[this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX ? normalized % visual.length : normalized];
  51204. }
  51205. function doMapFixed() {
  51206. // visual will be convert to array.
  51207. return this.option.visual[0];
  51208. }
  51209. /**
  51210. * Create mapped to numeric visual
  51211. */
  51212. function createNormalizedToNumericVisual(sourceExtent) {
  51213. return {
  51214. linear: function (normalized) {
  51215. return linearMap(normalized, sourceExtent, this.option.visual, true);
  51216. },
  51217. category: doMapCategory,
  51218. piecewise: function (normalized, value) {
  51219. var result = getSpecifiedVisual.call(this, value);
  51220. if (result == null) {
  51221. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  51222. }
  51223. return result;
  51224. },
  51225. fixed: doMapFixed
  51226. };
  51227. }
  51228. function getSpecifiedVisual(value) {
  51229. var thisOption = this.option;
  51230. var pieceList = thisOption.pieceList;
  51231. if (thisOption.hasSpecialVisual) {
  51232. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  51233. var piece = pieceList[pieceIndex];
  51234. if (piece && piece.visual) {
  51235. return piece.visual[this.type];
  51236. }
  51237. }
  51238. }
  51239. function setVisualToOption(thisOption, visualArr) {
  51240. thisOption.visual = visualArr;
  51241. if (thisOption.type === 'color') {
  51242. thisOption.parsedVisual = map(visualArr, function (item) {
  51243. var color$1 = parse(item);
  51244. if (!color$1 && "development" !== 'production') {
  51245. warn("'" + item + "' is an illegal color, fallback to '#000000'", true);
  51246. }
  51247. return color$1 || [0, 0, 0, 1];
  51248. });
  51249. }
  51250. return visualArr;
  51251. }
  51252. /**
  51253. * Normalizers by mapping methods.
  51254. */
  51255. var normalizers = {
  51256. linear: function (value) {
  51257. return linearMap(value, this.option.dataExtent, [0, 1], true);
  51258. },
  51259. piecewise: function (value) {
  51260. var pieceList = this.option.pieceList;
  51261. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  51262. if (pieceIndex != null) {
  51263. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  51264. }
  51265. },
  51266. category: function (value) {
  51267. var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal value
  51268. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  51269. },
  51270. fixed: noop
  51271. };
  51272. function littleThan(close, a, b) {
  51273. return close ? a <= b : a < b;
  51274. }
  51275. var ITEM_STYLE_NORMAL = 'itemStyle';
  51276. var inner$9 = makeInner();
  51277. var treemapVisual = {
  51278. seriesType: 'treemap',
  51279. reset: function (seriesModel) {
  51280. var tree = seriesModel.getData().tree;
  51281. var root = tree.root;
  51282. if (root.isRemoved()) {
  51283. return;
  51284. }
  51285. travelTree(root, // Visual should calculate from tree root but not view root.
  51286. {}, seriesModel.getViewRoot().getAncestors(), seriesModel);
  51287. }
  51288. };
  51289. function travelTree(node, designatedVisual, viewRootAncestors, seriesModel) {
  51290. var nodeModel = node.getModel();
  51291. var nodeLayout = node.getLayout();
  51292. var data = node.hostTree.data; // Optimize
  51293. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  51294. return;
  51295. }
  51296. var nodeItemStyleModel = nodeModel.getModel(ITEM_STYLE_NORMAL);
  51297. var visuals = buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel);
  51298. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style'); // calculate border color
  51299. var borderColor = nodeItemStyleModel.get('borderColor');
  51300. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  51301. var thisNodeColor;
  51302. if (borderColorSaturation != null) {
  51303. // For performance, do not always execute 'calculateColor'.
  51304. thisNodeColor = calculateColor(visuals);
  51305. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  51306. }
  51307. existsStyle.stroke = borderColor;
  51308. var viewChildren = node.viewChildren;
  51309. if (!viewChildren || !viewChildren.length) {
  51310. thisNodeColor = calculateColor(visuals); // Apply visual to this node.
  51311. existsStyle.fill = thisNodeColor;
  51312. } else {
  51313. var mapping_1 = buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren); // Designate visual to children.
  51314. each(viewChildren, function (child, index) {
  51315. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  51316. if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) {
  51317. var childVisual = mapVisual(nodeModel, visuals, child, index, mapping_1, seriesModel);
  51318. travelTree(child, childVisual, viewRootAncestors, seriesModel);
  51319. }
  51320. });
  51321. }
  51322. }
  51323. function buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel) {
  51324. var visuals = extend({}, designatedVisual);
  51325. var designatedVisualItemStyle = seriesModel.designatedVisualItemStyle;
  51326. each(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  51327. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  51328. designatedVisualItemStyle[visualName] = designatedVisual[visualName];
  51329. var val = nodeItemStyleModel.get(visualName);
  51330. designatedVisualItemStyle[visualName] = null;
  51331. val != null && (visuals[visualName] = val);
  51332. });
  51333. return visuals;
  51334. }
  51335. function calculateColor(visuals) {
  51336. var color = getValueVisualDefine(visuals, 'color');
  51337. if (color) {
  51338. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  51339. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  51340. if (colorSaturation) {
  51341. color = modifyHSL(color, null, null, colorSaturation);
  51342. }
  51343. if (colorAlpha) {
  51344. color = modifyAlpha(color, colorAlpha);
  51345. }
  51346. return color;
  51347. }
  51348. }
  51349. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  51350. return thisNodeColor != null // Can only be string
  51351. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation) : null;
  51352. }
  51353. function getValueVisualDefine(visuals, name) {
  51354. var value = visuals[name];
  51355. if (value != null && value !== 'none') {
  51356. return value;
  51357. }
  51358. }
  51359. function buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) {
  51360. if (!viewChildren || !viewChildren.length) {
  51361. return;
  51362. }
  51363. var rangeVisual = getRangeVisual(nodeModel, 'color') || visuals.color != null && visuals.color !== 'none' && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation'));
  51364. if (!rangeVisual) {
  51365. return;
  51366. }
  51367. var visualMin = nodeModel.get('visualMin');
  51368. var visualMax = nodeModel.get('visualMax');
  51369. var dataExtent = nodeLayout.dataExtent.slice();
  51370. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  51371. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  51372. var colorMappingBy = nodeModel.get('colorMappingBy');
  51373. var opt = {
  51374. type: rangeVisual.name,
  51375. dataExtent: dataExtent,
  51376. visual: rangeVisual.range
  51377. };
  51378. if (opt.type === 'color' && (colorMappingBy === 'index' || colorMappingBy === 'id')) {
  51379. opt.mappingMethod = 'category';
  51380. opt.loop = true; // categories is ordinal, so do not set opt.categories.
  51381. } else {
  51382. opt.mappingMethod = 'linear';
  51383. }
  51384. var mapping = new VisualMapping(opt);
  51385. inner$9(mapping).drColorMappingBy = colorMappingBy;
  51386. return mapping;
  51387. } // Notice: If we don't have the attribute 'colorRange', but only use
  51388. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  51389. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  51390. // this problem will be encountered:
  51391. // If a level-1 node doesn't have children, and its siblings have children,
  51392. // and colorRange is set on level-1, then the node cannot be colored.
  51393. // So we separate 'colorRange' and 'color' to different attributes.
  51394. function getRangeVisual(nodeModel, name) {
  51395. // 'colorRange', 'colorARange', 'colorSRange'.
  51396. // If not exists on this node, fetch from levels and series.
  51397. var range = nodeModel.get(name);
  51398. return isArray(range) && range.length ? {
  51399. name: name,
  51400. range: range
  51401. } : null;
  51402. }
  51403. function mapVisual(nodeModel, visuals, child, index, mapping, seriesModel) {
  51404. var childVisuals = extend({}, visuals);
  51405. if (mapping) {
  51406. // Only support color, colorAlpha, colorSaturation.
  51407. var mappingType = mapping.type;
  51408. var colorMappingBy = mappingType === 'color' && inner$9(mapping).drColorMappingBy;
  51409. var value = colorMappingBy === 'index' ? index : colorMappingBy === 'id' ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension'));
  51410. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  51411. }
  51412. return childVisuals;
  51413. }
  51414. var mathMax$7 = Math.max;
  51415. var mathMin$7 = Math.min;
  51416. var retrieveValue = retrieve;
  51417. var each$4 = each;
  51418. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  51419. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  51420. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  51421. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  51422. /**
  51423. * @public
  51424. */
  51425. var treemapLayout = {
  51426. seriesType: 'treemap',
  51427. reset: function (seriesModel, ecModel, api, payload) {
  51428. // Layout result in each node:
  51429. // {x, y, width, height, area, borderWidth}
  51430. var ecWidth = api.getWidth();
  51431. var ecHeight = api.getHeight();
  51432. var seriesOption = seriesModel.option;
  51433. var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), {
  51434. width: api.getWidth(),
  51435. height: api.getHeight()
  51436. });
  51437. var size = seriesOption.size || []; // Compatible with ec2.
  51438. var containerWidth = parsePercent$1(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  51439. var containerHeight = parsePercent$1(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  51440. var payloadType = payload && payload.type;
  51441. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  51442. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  51443. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  51444. var viewRoot = seriesModel.getViewRoot();
  51445. var viewAbovePath = getPathToRoot(viewRoot);
  51446. if (payloadType !== 'treemapMove') {
  51447. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  51448. var sort_1 = seriesOption.sort;
  51449. if (sort_1 && sort_1 !== 'asc' && sort_1 !== 'desc') {
  51450. // Default to be desc order.
  51451. sort_1 = 'desc';
  51452. }
  51453. var options = {
  51454. squareRatio: seriesOption.squareRatio,
  51455. sort: sort_1,
  51456. leafDepth: seriesOption.leafDepth
  51457. }; // layout should be cleared because using updateView but not update.
  51458. viewRoot.hostTree.clearLayouts(); // TODO
  51459. // optimize: if out of view clip, do not layout.
  51460. // But take care that if do not render node out of view clip,
  51461. // how to calculate start po
  51462. var viewRootLayout_1 = {
  51463. x: 0,
  51464. y: 0,
  51465. width: rootSize[0],
  51466. height: rootSize[1],
  51467. area: rootSize[0] * rootSize[1]
  51468. };
  51469. viewRoot.setLayout(viewRootLayout_1);
  51470. squarify(viewRoot, options, false, 0); // Supplement layout.
  51471. viewRootLayout_1 = viewRoot.getLayout();
  51472. each$4(viewAbovePath, function (node, index) {
  51473. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  51474. node.setLayout(extend({
  51475. dataExtent: [childValue, childValue],
  51476. borderWidth: 0,
  51477. upperHeight: 0
  51478. }, viewRootLayout_1));
  51479. });
  51480. }
  51481. var treeRoot = seriesModel.getData().tree.root;
  51482. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  51483. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  51484. // 现在没有clip功能,暂时取ec高宽。
  51485. prunning(treeRoot, // Transform to base element coordinate system.
  51486. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  51487. }
  51488. };
  51489. /**
  51490. * Layout treemap with squarify algorithm.
  51491. * The original presentation of this algorithm
  51492. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  51493. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  51494. * The implementation of this algorithm was originally copied from "d3.js"
  51495. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  51496. * with some modifications made for this program.
  51497. * See the license statement at the head of this file.
  51498. *
  51499. * @protected
  51500. * @param {module:echarts/data/Tree~TreeNode} node
  51501. * @param {Object} options
  51502. * @param {string} options.sort 'asc' or 'desc'
  51503. * @param {number} options.squareRatio
  51504. * @param {boolean} hideChildren
  51505. * @param {number} depth
  51506. */
  51507. function squarify(node, options, hideChildren, depth) {
  51508. var width;
  51509. var height;
  51510. if (node.isRemoved()) {
  51511. return;
  51512. }
  51513. var thisLayout = node.getLayout();
  51514. width = thisLayout.width;
  51515. height = thisLayout.height; // Considering border and gap
  51516. var nodeModel = node.getModel();
  51517. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  51518. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  51519. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  51520. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  51521. var layoutOffset = borderWidth - halfGapWidth;
  51522. var layoutOffsetUpper = upperHeight - halfGapWidth;
  51523. node.setLayout({
  51524. borderWidth: borderWidth,
  51525. upperHeight: upperHeight,
  51526. upperLabelHeight: upperLabelHeight
  51527. }, true);
  51528. width = mathMax$7(width - 2 * layoutOffset, 0);
  51529. height = mathMax$7(height - layoutOffset - layoutOffsetUpper, 0);
  51530. var totalArea = width * height;
  51531. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  51532. if (!viewChildren.length) {
  51533. return;
  51534. }
  51535. var rect = {
  51536. x: layoutOffset,
  51537. y: layoutOffsetUpper,
  51538. width: width,
  51539. height: height
  51540. };
  51541. var rowFixedLength = mathMin$7(width, height);
  51542. var best = Infinity; // the best row score so far
  51543. var row = [];
  51544. row.area = 0;
  51545. for (var i = 0, len = viewChildren.length; i < len;) {
  51546. var child = viewChildren[i];
  51547. row.push(child);
  51548. row.area += child.getLayout().area;
  51549. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  51550. if (score <= best) {
  51551. i++;
  51552. best = score;
  51553. } // abort, and try a different orientation
  51554. else {
  51555. row.area -= row.pop().getLayout().area;
  51556. position(row, rowFixedLength, rect, halfGapWidth, false);
  51557. rowFixedLength = mathMin$7(rect.width, rect.height);
  51558. row.length = row.area = 0;
  51559. best = Infinity;
  51560. }
  51561. }
  51562. if (row.length) {
  51563. position(row, rowFixedLength, rect, halfGapWidth, true);
  51564. }
  51565. if (!hideChildren) {
  51566. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  51567. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  51568. hideChildren = true;
  51569. }
  51570. }
  51571. for (var i = 0, len = viewChildren.length; i < len; i++) {
  51572. squarify(viewChildren[i], options, hideChildren, depth + 1);
  51573. }
  51574. }
  51575. /**
  51576. * Set area to each child, and calculate data extent for visual coding.
  51577. */
  51578. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  51579. var viewChildren = node.children || [];
  51580. var orderBy = options.sort;
  51581. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  51582. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  51583. if (hideChildren && !overLeafDepth) {
  51584. return node.viewChildren = [];
  51585. } // Sort children, order by desc.
  51586. viewChildren = filter(viewChildren, function (child) {
  51587. return !child.isRemoved();
  51588. });
  51589. sort$1(viewChildren, orderBy);
  51590. var info = statistic(nodeModel, viewChildren, orderBy);
  51591. if (info.sum === 0) {
  51592. return node.viewChildren = [];
  51593. }
  51594. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  51595. if (info.sum === 0) {
  51596. return node.viewChildren = [];
  51597. } // Set area to each child.
  51598. for (var i = 0, len = viewChildren.length; i < len; i++) {
  51599. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  51600. viewChildren[i].setLayout({
  51601. area: area
  51602. });
  51603. }
  51604. if (overLeafDepth) {
  51605. viewChildren.length && node.setLayout({
  51606. isLeafRoot: true
  51607. }, true);
  51608. viewChildren.length = 0;
  51609. }
  51610. node.viewChildren = viewChildren;
  51611. node.setLayout({
  51612. dataExtent: info.dataExtent
  51613. }, true);
  51614. return viewChildren;
  51615. }
  51616. /**
  51617. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  51618. */
  51619. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  51620. // visibleMin is not supported yet when no option.sort.
  51621. if (!orderBy) {
  51622. return sum;
  51623. }
  51624. var visibleMin = nodeModel.get('visibleMin');
  51625. var len = orderedChildren.length;
  51626. var deletePoint = len; // Always travel from little value to big value.
  51627. for (var i = len - 1; i >= 0; i--) {
  51628. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  51629. if (value / sum * totalArea < visibleMin) {
  51630. deletePoint = i;
  51631. sum -= value;
  51632. }
  51633. }
  51634. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  51635. return sum;
  51636. }
  51637. /**
  51638. * Sort
  51639. */
  51640. function sort$1(viewChildren, orderBy) {
  51641. if (orderBy) {
  51642. viewChildren.sort(function (a, b) {
  51643. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  51644. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  51645. });
  51646. }
  51647. return viewChildren;
  51648. }
  51649. /**
  51650. * Statistic
  51651. */
  51652. function statistic(nodeModel, children, orderBy) {
  51653. // Calculate sum.
  51654. var sum = 0;
  51655. for (var i = 0, len = children.length; i < len; i++) {
  51656. sum += children[i].getValue();
  51657. } // Statistic data extent for latter visual coding.
  51658. // Notice: data extent should be calculate based on raw children
  51659. // but not filtered view children, otherwise visual mapping will not
  51660. // be stable when zoom (where children is filtered by visibleMin).
  51661. var dimension = nodeModel.get('visualDimension');
  51662. var dataExtent; // The same as area dimension.
  51663. if (!children || !children.length) {
  51664. dataExtent = [NaN, NaN];
  51665. } else if (dimension === 'value' && orderBy) {
  51666. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  51667. orderBy === 'asc' && dataExtent.reverse();
  51668. } // Other dimension.
  51669. else {
  51670. dataExtent = [Infinity, -Infinity];
  51671. each$4(children, function (child) {
  51672. var value = child.getValue(dimension);
  51673. value < dataExtent[0] && (dataExtent[0] = value);
  51674. value > dataExtent[1] && (dataExtent[1] = value);
  51675. });
  51676. }
  51677. return {
  51678. sum: sum,
  51679. dataExtent: dataExtent
  51680. };
  51681. }
  51682. /**
  51683. * Computes the score for the specified row,
  51684. * as the worst aspect ratio.
  51685. */
  51686. function worst(row, rowFixedLength, ratio) {
  51687. var areaMax = 0;
  51688. var areaMin = Infinity;
  51689. for (var i = 0, area = void 0, len = row.length; i < len; i++) {
  51690. area = row[i].getLayout().area;
  51691. if (area) {
  51692. area < areaMin && (areaMin = area);
  51693. area > areaMax && (areaMax = area);
  51694. }
  51695. }
  51696. var squareArea = row.area * row.area;
  51697. var f = rowFixedLength * rowFixedLength * ratio;
  51698. return squareArea ? mathMax$7(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  51699. }
  51700. /**
  51701. * Positions the specified row of nodes. Modifies `rect`.
  51702. */
  51703. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  51704. // When rowFixedLength === rect.width,
  51705. // it is horizontal subdivision,
  51706. // rowFixedLength is the width of the subdivision,
  51707. // rowOtherLength is the height of the subdivision,
  51708. // and nodes will be positioned from left to right.
  51709. // wh[idx0WhenH] means: when horizontal,
  51710. // wh[idx0WhenH] => wh[0] => 'width'.
  51711. // xy[idx1WhenH] => xy[1] => 'y'.
  51712. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  51713. var idx1WhenH = 1 - idx0WhenH;
  51714. var xy = ['x', 'y'];
  51715. var wh = ['width', 'height'];
  51716. var last = rect[xy[idx0WhenH]];
  51717. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  51718. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  51719. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  51720. }
  51721. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  51722. var node = row[i];
  51723. var nodeLayout = {};
  51724. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  51725. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$7(rowOtherLength - 2 * halfGapWidth, 0); // We use Math.max/min to avoid negative width/height when considering gap width.
  51726. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  51727. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  51728. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$7(modWH - 2 * halfGapWidth, 0);
  51729. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$7(halfGapWidth, wh1 / 2);
  51730. nodeLayout[xy[idx0WhenH]] = last + mathMin$7(halfGapWidth, wh0 / 2);
  51731. last += modWH;
  51732. node.setLayout(nodeLayout, true);
  51733. }
  51734. rect[xy[idx1WhenH]] += rowOtherLength;
  51735. rect[wh[idx1WhenH]] -= rowOtherLength;
  51736. } // Return [containerWidth, containerHeight] as default.
  51737. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  51738. // If targetInfo.node exists, we zoom to the node,
  51739. // so estimate whole width and height by target node.
  51740. var currNode = (targetInfo || {}).node;
  51741. var defaultSize = [containerWidth, containerHeight];
  51742. if (!currNode || currNode === viewRoot) {
  51743. return defaultSize;
  51744. }
  51745. var parent;
  51746. var viewArea = containerWidth * containerHeight;
  51747. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  51748. while (parent = currNode.parentNode) {
  51749. // jshint ignore:line
  51750. var sum = 0;
  51751. var siblings = parent.children;
  51752. for (var i = 0, len = siblings.length; i < len; i++) {
  51753. sum += siblings[i].getValue();
  51754. }
  51755. var currNodeValue = currNode.getValue();
  51756. if (currNodeValue === 0) {
  51757. return defaultSize;
  51758. }
  51759. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  51760. var parentModel = parent.getModel();
  51761. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  51762. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel));
  51763. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  51764. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  51765. currNode = parent;
  51766. }
  51767. area < viewArea && (area = viewArea);
  51768. var scale = Math.pow(area / viewArea, 0.5);
  51769. return [containerWidth * scale, containerHeight * scale];
  51770. } // Root position based on coord of containerGroup
  51771. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  51772. if (rootRect) {
  51773. return {
  51774. x: rootRect.x,
  51775. y: rootRect.y
  51776. };
  51777. }
  51778. var defaultPosition = {
  51779. x: 0,
  51780. y: 0
  51781. };
  51782. if (!targetInfo) {
  51783. return defaultPosition;
  51784. } // If targetInfo is fetched by 'retrieveTargetInfo',
  51785. // old tree and new tree are the same tree,
  51786. // so the node still exists and we can visit it.
  51787. var targetNode = targetInfo.node;
  51788. var layout = targetNode.getLayout();
  51789. if (!layout) {
  51790. return defaultPosition;
  51791. } // Transform coord from local to container.
  51792. var targetCenter = [layout.width / 2, layout.height / 2];
  51793. var node = targetNode;
  51794. while (node) {
  51795. var nodeLayout = node.getLayout();
  51796. targetCenter[0] += nodeLayout.x;
  51797. targetCenter[1] += nodeLayout.y;
  51798. node = node.parentNode;
  51799. }
  51800. return {
  51801. x: layoutInfo.width / 2 - targetCenter[0],
  51802. y: layoutInfo.height / 2 - targetCenter[1]
  51803. };
  51804. } // Mark nodes visible for prunning when visual coding and rendering.
  51805. // Prunning depends on layout and root position, so we have to do it after layout.
  51806. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  51807. var nodeLayout = node.getLayout();
  51808. var nodeInViewAbovePath = viewAbovePath[depth];
  51809. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  51810. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  51811. return;
  51812. }
  51813. node.setLayout({
  51814. // isInView means: viewRoot sub tree + viewAbovePath
  51815. isInView: true,
  51816. // invisible only means: outside view clip so that the node can not
  51817. // see but still layout for animation preparation but not render.
  51818. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  51819. isAboveViewRoot: isAboveViewRoot
  51820. }, true); // Transform to child coordinate.
  51821. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  51822. each$4(node.viewChildren || [], function (child) {
  51823. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  51824. });
  51825. }
  51826. function getUpperLabelHeight(model) {
  51827. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  51828. }
  51829. function install$c(registers) {
  51830. registers.registerSeriesModel(TreemapSeriesModel);
  51831. registers.registerChartView(TreemapView);
  51832. registers.registerVisual(treemapVisual);
  51833. registers.registerLayout(treemapLayout);
  51834. installTreemapAction(registers);
  51835. }
  51836. function categoryFilter(ecModel) {
  51837. var legendModels = ecModel.findComponents({
  51838. mainType: 'legend'
  51839. });
  51840. if (!legendModels || !legendModels.length) {
  51841. return;
  51842. }
  51843. ecModel.eachSeriesByType('graph', function (graphSeries) {
  51844. var categoriesData = graphSeries.getCategoriesData();
  51845. var graph = graphSeries.getGraph();
  51846. var data = graph.data;
  51847. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  51848. data.filterSelf(function (idx) {
  51849. var model = data.getItemModel(idx);
  51850. var category = model.getShallow('category');
  51851. if (category != null) {
  51852. if (isNumber(category)) {
  51853. category = categoryNames[category];
  51854. } // If in any legend component the status is not selected.
  51855. for (var i = 0; i < legendModels.length; i++) {
  51856. if (!legendModels[i].isSelected(category)) {
  51857. return false;
  51858. }
  51859. }
  51860. }
  51861. return true;
  51862. });
  51863. });
  51864. }
  51865. function categoryVisual(ecModel) {
  51866. var paletteScope = {};
  51867. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51868. var categoriesData = seriesModel.getCategoriesData();
  51869. var data = seriesModel.getData();
  51870. var categoryNameIdxMap = {};
  51871. categoriesData.each(function (idx) {
  51872. var name = categoriesData.getName(idx); // Add prefix to avoid conflict with Object.prototype.
  51873. categoryNameIdxMap['ec-' + name] = idx;
  51874. var itemModel = categoriesData.getItemModel(idx);
  51875. var style = itemModel.getModel('itemStyle').getItemStyle();
  51876. if (!style.fill) {
  51877. // Get color from palette.
  51878. style.fill = seriesModel.getColorFromPalette(name, paletteScope);
  51879. }
  51880. categoriesData.setItemVisual(idx, 'style', style);
  51881. var symbolVisualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  51882. for (var i = 0; i < symbolVisualList.length; i++) {
  51883. var symbolVisual = itemModel.getShallow(symbolVisualList[i], true);
  51884. if (symbolVisual != null) {
  51885. categoriesData.setItemVisual(idx, symbolVisualList[i], symbolVisual);
  51886. }
  51887. }
  51888. }); // Assign category color to visual
  51889. if (categoriesData.count()) {
  51890. data.each(function (idx) {
  51891. var model = data.getItemModel(idx);
  51892. var categoryIdx = model.getShallow('category');
  51893. if (categoryIdx != null) {
  51894. if (isString(categoryIdx)) {
  51895. categoryIdx = categoryNameIdxMap['ec-' + categoryIdx];
  51896. }
  51897. var categoryStyle = categoriesData.getItemVisual(categoryIdx, 'style');
  51898. var style = data.ensureUniqueItemVisual(idx, 'style');
  51899. extend(style, categoryStyle);
  51900. var visualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  51901. for (var i = 0; i < visualList.length; i++) {
  51902. data.setItemVisual(idx, visualList[i], categoriesData.getItemVisual(categoryIdx, visualList[i]));
  51903. }
  51904. }
  51905. });
  51906. }
  51907. });
  51908. }
  51909. function normalize$2(a) {
  51910. if (!(a instanceof Array)) {
  51911. a = [a, a];
  51912. }
  51913. return a;
  51914. }
  51915. function graphEdgeVisual(ecModel) {
  51916. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51917. var graph = seriesModel.getGraph();
  51918. var edgeData = seriesModel.getEdgeData();
  51919. var symbolType = normalize$2(seriesModel.get('edgeSymbol'));
  51920. var symbolSize = normalize$2(seriesModel.get('edgeSymbolSize')); // const colorQuery = ['lineStyle', 'color'] as const;
  51921. // const opacityQuery = ['lineStyle', 'opacity'] as const;
  51922. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  51923. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  51924. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  51925. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  51926. edgeData.setVisual('style', seriesModel.getModel('lineStyle').getLineStyle());
  51927. edgeData.each(function (idx) {
  51928. var itemModel = edgeData.getItemModel(idx);
  51929. var edge = graph.getEdgeByIndex(idx);
  51930. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  51931. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true)); // Edge visual must after node visual
  51932. var style = itemModel.getModel('lineStyle').getLineStyle();
  51933. var existsStyle = edgeData.ensureUniqueItemVisual(idx, 'style');
  51934. extend(existsStyle, style);
  51935. switch (existsStyle.stroke) {
  51936. case 'source':
  51937. {
  51938. var nodeStyle = edge.node1.getVisual('style');
  51939. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  51940. break;
  51941. }
  51942. case 'target':
  51943. {
  51944. var nodeStyle = edge.node2.getVisual('style');
  51945. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  51946. break;
  51947. }
  51948. }
  51949. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  51950. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  51951. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  51952. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  51953. });
  51954. });
  51955. }
  51956. var KEY_DELIMITER = '-->';
  51957. /**
  51958. * params handler
  51959. * @param {module:echarts/model/SeriesModel} seriesModel
  51960. * @returns {*}
  51961. */
  51962. var getAutoCurvenessParams = function (seriesModel) {
  51963. return seriesModel.get('autoCurveness') || null;
  51964. };
  51965. /**
  51966. * Generate a list of edge curvatures, 20 is the default
  51967. * @param {module:echarts/model/SeriesModel} seriesModel
  51968. * @param {number} appendLength
  51969. * @return 20 => [0, -0.2, 0.2, -0.4, 0.4, -0.6, 0.6, -0.8, 0.8, -1, 1, -1.2, 1.2, -1.4, 1.4, -1.6, 1.6, -1.8, 1.8, -2]
  51970. */
  51971. var createCurveness = function (seriesModel, appendLength) {
  51972. var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
  51973. var length = 20;
  51974. var curvenessList = []; // handler the function set
  51975. if (isNumber(autoCurvenessParmas)) {
  51976. length = autoCurvenessParmas;
  51977. } else if (isArray(autoCurvenessParmas)) {
  51978. seriesModel.__curvenessList = autoCurvenessParmas;
  51979. return;
  51980. } // append length
  51981. if (appendLength > length) {
  51982. length = appendLength;
  51983. } // make sure the length is even
  51984. var len = length % 2 ? length + 2 : length + 3;
  51985. curvenessList = [];
  51986. for (var i = 0; i < len; i++) {
  51987. curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
  51988. }
  51989. seriesModel.__curvenessList = curvenessList;
  51990. };
  51991. /**
  51992. * Create different cache key data in the positive and negative directions, in order to set the curvature later
  51993. * @param {number|string|module:echarts/data/Graph.Node} n1
  51994. * @param {number|string|module:echarts/data/Graph.Node} n2
  51995. * @param {module:echarts/model/SeriesModel} seriesModel
  51996. * @returns {string} key
  51997. */
  51998. var getKeyOfEdges = function (n1, n2, seriesModel) {
  51999. var source = [n1.id, n1.dataIndex].join('.');
  52000. var target = [n2.id, n2.dataIndex].join('.');
  52001. return [seriesModel.uid, source, target].join(KEY_DELIMITER);
  52002. };
  52003. /**
  52004. * get opposite key
  52005. * @param {string} key
  52006. * @returns {string}
  52007. */
  52008. var getOppositeKey = function (key) {
  52009. var keys = key.split(KEY_DELIMITER);
  52010. return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
  52011. };
  52012. /**
  52013. * get edgeMap with key
  52014. * @param edge
  52015. * @param {module:echarts/model/SeriesModel} seriesModel
  52016. */
  52017. var getEdgeFromMap = function (edge, seriesModel) {
  52018. var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  52019. return seriesModel.__edgeMap[key];
  52020. };
  52021. /**
  52022. * calculate all cases total length
  52023. * @param edge
  52024. * @param seriesModel
  52025. * @returns {number}
  52026. */
  52027. var getTotalLengthBetweenNodes = function (edge, seriesModel) {
  52028. var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
  52029. var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);
  52030. return len + lenV;
  52031. };
  52032. /**
  52033. *
  52034. * @param key
  52035. */
  52036. var getEdgeMapLengthWithKey = function (key, seriesModel) {
  52037. var edgeMap = seriesModel.__edgeMap;
  52038. return edgeMap[key] ? edgeMap[key].length : 0;
  52039. };
  52040. /**
  52041. * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
  52042. * @see /graph/GraphSeries.js@getInitialData
  52043. * @param {module:echarts/model/SeriesModel} seriesModel
  52044. */
  52045. function initCurvenessList(seriesModel) {
  52046. if (!getAutoCurvenessParams(seriesModel)) {
  52047. return;
  52048. }
  52049. seriesModel.__curvenessList = [];
  52050. seriesModel.__edgeMap = {}; // calc the array of curveness List
  52051. createCurveness(seriesModel);
  52052. }
  52053. /**
  52054. * set edgeMap with key
  52055. * @param {number|string|module:echarts/data/Graph.Node} n1
  52056. * @param {number|string|module:echarts/data/Graph.Node} n2
  52057. * @param {module:echarts/model/SeriesModel} seriesModel
  52058. * @param {number} index
  52059. */
  52060. function createEdgeMapForCurveness(n1, n2, seriesModel, index) {
  52061. if (!getAutoCurvenessParams(seriesModel)) {
  52062. return;
  52063. }
  52064. var key = getKeyOfEdges(n1, n2, seriesModel);
  52065. var edgeMap = seriesModel.__edgeMap;
  52066. var oppositeEdges = edgeMap[getOppositeKey(key)]; // set direction
  52067. if (edgeMap[key] && !oppositeEdges) {
  52068. edgeMap[key].isForward = true;
  52069. } else if (oppositeEdges && edgeMap[key]) {
  52070. oppositeEdges.isForward = true;
  52071. edgeMap[key].isForward = false;
  52072. }
  52073. edgeMap[key] = edgeMap[key] || [];
  52074. edgeMap[key].push(index);
  52075. }
  52076. /**
  52077. * get curvature for edge
  52078. * @param edge
  52079. * @param {module:echarts/model/SeriesModel} seriesModel
  52080. * @param index
  52081. */
  52082. function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
  52083. var autoCurvenessParams = getAutoCurvenessParams(seriesModel);
  52084. var isArrayParam = isArray(autoCurvenessParams);
  52085. if (!autoCurvenessParams) {
  52086. return null;
  52087. }
  52088. var edgeArray = getEdgeFromMap(edge, seriesModel);
  52089. if (!edgeArray) {
  52090. return null;
  52091. }
  52092. var edgeIndex = -1;
  52093. for (var i = 0; i < edgeArray.length; i++) {
  52094. if (edgeArray[i] === index) {
  52095. edgeIndex = i;
  52096. break;
  52097. }
  52098. } // if totalLen is Longer createCurveness
  52099. var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
  52100. createCurveness(seriesModel, totalLen);
  52101. edge.lineStyle = edge.lineStyle || {}; // if is opposite edge, must set curvenss to opposite number
  52102. var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  52103. var curvenessList = seriesModel.__curvenessList; // if pass array no need parity
  52104. var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;
  52105. if (!edgeArray.isForward) {
  52106. // the opposite edge show outside
  52107. var oppositeKey = getOppositeKey(curKey);
  52108. var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
  52109. var resValue = curvenessList[edgeIndex + len + parityCorrection]; // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
  52110. if (needReverse) {
  52111. // set as array may make the parity handle with the len of opposite
  52112. if (isArrayParam) {
  52113. if (autoCurvenessParams && autoCurvenessParams[0] === 0) {
  52114. return (len + parityCorrection) % 2 ? resValue : -resValue;
  52115. } else {
  52116. return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
  52117. }
  52118. } else {
  52119. return (len + parityCorrection) % 2 ? resValue : -resValue;
  52120. }
  52121. } else {
  52122. return curvenessList[edgeIndex + len + parityCorrection];
  52123. }
  52124. } else {
  52125. return curvenessList[parityCorrection + edgeIndex];
  52126. }
  52127. }
  52128. function simpleLayout(seriesModel) {
  52129. var coordSys = seriesModel.coordinateSystem;
  52130. if (coordSys && coordSys.type !== 'view') {
  52131. return;
  52132. }
  52133. var graph = seriesModel.getGraph();
  52134. graph.eachNode(function (node) {
  52135. var model = node.getModel();
  52136. node.setLayout([+model.get('x'), +model.get('y')]);
  52137. });
  52138. simpleLayoutEdge(graph, seriesModel);
  52139. }
  52140. function simpleLayoutEdge(graph, seriesModel) {
  52141. graph.eachEdge(function (edge, index) {
  52142. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, seriesModel, index, true), 0);
  52143. var p1 = clone$1(edge.node1.getLayout());
  52144. var p2 = clone$1(edge.node2.getLayout());
  52145. var points = [p1, p2];
  52146. if (+curveness) {
  52147. points.push([(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness]);
  52148. }
  52149. edge.setLayout(points);
  52150. });
  52151. }
  52152. function graphSimpleLayout(ecModel, api) {
  52153. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52154. var layout = seriesModel.get('layout');
  52155. var coordSys = seriesModel.coordinateSystem;
  52156. if (coordSys && coordSys.type !== 'view') {
  52157. var data_1 = seriesModel.getData();
  52158. var dimensions_1 = [];
  52159. each(coordSys.dimensions, function (coordDim) {
  52160. dimensions_1 = dimensions_1.concat(data_1.mapDimensionsAll(coordDim));
  52161. });
  52162. for (var dataIndex = 0; dataIndex < data_1.count(); dataIndex++) {
  52163. var value = [];
  52164. var hasValue = false;
  52165. for (var i = 0; i < dimensions_1.length; i++) {
  52166. var val = data_1.get(dimensions_1[i], dataIndex);
  52167. if (!isNaN(val)) {
  52168. hasValue = true;
  52169. }
  52170. value.push(val);
  52171. }
  52172. if (hasValue) {
  52173. data_1.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  52174. } else {
  52175. // Also {Array.<number>}, not undefined to avoid if...else... statement
  52176. data_1.setItemLayout(dataIndex, [NaN, NaN]);
  52177. }
  52178. }
  52179. simpleLayoutEdge(data_1.graph, seriesModel);
  52180. } else if (!layout || layout === 'none') {
  52181. simpleLayout(seriesModel);
  52182. }
  52183. });
  52184. }
  52185. /*
  52186. * Licensed to the Apache Software Foundation (ASF) under one
  52187. * or more contributor license agreements. See the NOTICE file
  52188. * distributed with this work for additional information
  52189. * regarding copyright ownership. The ASF licenses this file
  52190. * to you under the Apache License, Version 2.0 (the
  52191. * "License"); you may not use this file except in compliance
  52192. * with the License. You may obtain a copy of the License at
  52193. *
  52194. * http://www.apache.org/licenses/LICENSE-2.0
  52195. *
  52196. * Unless required by applicable law or agreed to in writing,
  52197. * software distributed under the License is distributed on an
  52198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52199. * KIND, either express or implied. See the License for the
  52200. * specific language governing permissions and limitations
  52201. * under the License.
  52202. */
  52203. /**
  52204. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52205. */
  52206. /*
  52207. * Licensed to the Apache Software Foundation (ASF) under one
  52208. * or more contributor license agreements. See the NOTICE file
  52209. * distributed with this work for additional information
  52210. * regarding copyright ownership. The ASF licenses this file
  52211. * to you under the Apache License, Version 2.0 (the
  52212. * "License"); you may not use this file except in compliance
  52213. * with the License. You may obtain a copy of the License at
  52214. *
  52215. * http://www.apache.org/licenses/LICENSE-2.0
  52216. *
  52217. * Unless required by applicable law or agreed to in writing,
  52218. * software distributed under the License is distributed on an
  52219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52220. * KIND, either express or implied. See the License for the
  52221. * specific language governing permissions and limitations
  52222. * under the License.
  52223. */
  52224. function getNodeGlobalScale(seriesModel) {
  52225. var coordSys = seriesModel.coordinateSystem;
  52226. if (coordSys.type !== 'view') {
  52227. return 1;
  52228. }
  52229. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  52230. var groupZoom = coordSys.scaleX; // Scale node when zoom changes
  52231. var roamZoom = coordSys.getZoom();
  52232. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  52233. return nodeScale / groupZoom;
  52234. }
  52235. function getSymbolSize(node) {
  52236. var symbolSize = node.getVisual('symbolSize');
  52237. if (symbolSize instanceof Array) {
  52238. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  52239. }
  52240. return +symbolSize;
  52241. }
  52242. var PI$6 = Math.PI;
  52243. var _symbolRadiansHalf = [];
  52244. /**
  52245. * `basedOn` can be:
  52246. * 'value':
  52247. * This layout is not accurate and have same bad case. For example,
  52248. * if the min value is very smaller than the max value, the nodes
  52249. * with the min value probably overlap even though there is enough
  52250. * space to layout them. So we only use this approach in the as the
  52251. * init layout of the force layout.
  52252. * FIXME
  52253. * Probably we do not need this method any more but use
  52254. * `basedOn: 'symbolSize'` in force layout if
  52255. * delay its init operations to GraphView.
  52256. * 'symbolSize':
  52257. * This approach work only if all of the symbol size calculated.
  52258. * That is, the progressive rendering is not applied to graph.
  52259. * FIXME
  52260. * If progressive rendering is applied to graph some day,
  52261. * probably we have to use `basedOn: 'value'`.
  52262. */
  52263. function circularLayout(seriesModel, basedOn, draggingNode, pointer) {
  52264. var coordSys = seriesModel.coordinateSystem;
  52265. if (coordSys && coordSys.type !== 'view') {
  52266. return;
  52267. }
  52268. var rect = coordSys.getBoundingRect();
  52269. var nodeData = seriesModel.getData();
  52270. var graph = nodeData.graph;
  52271. var cx = rect.width / 2 + rect.x;
  52272. var cy = rect.height / 2 + rect.y;
  52273. var r = Math.min(rect.width, rect.height) / 2;
  52274. var count = nodeData.count();
  52275. nodeData.setLayout({
  52276. cx: cx,
  52277. cy: cy
  52278. });
  52279. if (!count) {
  52280. return;
  52281. }
  52282. if (draggingNode) {
  52283. var _a = coordSys.pointToData(pointer),
  52284. tempX = _a[0],
  52285. tempY = _a[1];
  52286. var v = [tempX - cx, tempY - cy];
  52287. normalize(v, v);
  52288. scale(v, v, r);
  52289. draggingNode.setLayout([cx + v[0], cy + v[1]], true);
  52290. var circularRotateLabel = seriesModel.get(['circular', 'rotateLabel']);
  52291. rotateNodeLabel(draggingNode, circularRotateLabel, cx, cy);
  52292. }
  52293. _layoutNodesBasedOn[basedOn](seriesModel, graph, nodeData, r, cx, cy, count);
  52294. graph.eachEdge(function (edge, index) {
  52295. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), getCurvenessForEdge(edge, seriesModel, index), 0);
  52296. var p1 = clone$1(edge.node1.getLayout());
  52297. var p2 = clone$1(edge.node2.getLayout());
  52298. var cp1;
  52299. var x12 = (p1[0] + p2[0]) / 2;
  52300. var y12 = (p1[1] + p2[1]) / 2;
  52301. if (+curveness) {
  52302. curveness *= 3;
  52303. cp1 = [cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness)];
  52304. }
  52305. edge.setLayout([p1, p2, cp1]);
  52306. });
  52307. }
  52308. var _layoutNodesBasedOn = {
  52309. value: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  52310. var angle = 0;
  52311. var sum = nodeData.getSum('value');
  52312. var unitAngle = Math.PI * 2 / (sum || count);
  52313. graph.eachNode(function (node) {
  52314. var value = node.getValue('value');
  52315. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  52316. angle += radianHalf;
  52317. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  52318. angle += radianHalf;
  52319. });
  52320. },
  52321. symbolSize: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  52322. var sumRadian = 0;
  52323. _symbolRadiansHalf.length = count;
  52324. var nodeScale = getNodeGlobalScale(seriesModel);
  52325. graph.eachNode(function (node) {
  52326. var symbolSize = getSymbolSize(node); // Normally this case will not happen, but we still add
  52327. // some the defensive code (2px is an arbitrary value).
  52328. isNaN(symbolSize) && (symbolSize = 2);
  52329. symbolSize < 0 && (symbolSize = 0);
  52330. symbolSize *= nodeScale;
  52331. var symbolRadianHalf = Math.asin(symbolSize / 2 / r); // when `symbolSize / 2` is bigger than `r`.
  52332. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$6 / 2);
  52333. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  52334. sumRadian += symbolRadianHalf * 2;
  52335. });
  52336. var halfRemainRadian = (2 * PI$6 - sumRadian) / count / 2;
  52337. var angle = 0;
  52338. graph.eachNode(function (node) {
  52339. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  52340. angle += radianHalf; // init circular layout for
  52341. // 1. layout undefined node
  52342. // 2. not fixed node
  52343. (!node.getLayout() || !node.getLayout().fixed) && node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  52344. angle += radianHalf;
  52345. });
  52346. }
  52347. };
  52348. function rotateNodeLabel(node, circularRotateLabel, cx, cy) {
  52349. var el = node.getGraphicEl(); // need to check if el exists. '-' value may not create node element.
  52350. if (!el) {
  52351. return;
  52352. }
  52353. var nodeModel = node.getModel();
  52354. var labelRotate = nodeModel.get(['label', 'rotate']) || 0;
  52355. var symbolPath = el.getSymbolPath();
  52356. if (circularRotateLabel) {
  52357. var pos = node.getLayout();
  52358. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  52359. if (rad < 0) {
  52360. rad = Math.PI * 2 + rad;
  52361. }
  52362. var isLeft = pos[0] < cx;
  52363. if (isLeft) {
  52364. rad = rad - Math.PI;
  52365. }
  52366. var textPosition = isLeft ? 'left' : 'right';
  52367. symbolPath.setTextConfig({
  52368. rotation: -rad,
  52369. position: textPosition,
  52370. origin: 'center'
  52371. });
  52372. var emphasisState = symbolPath.ensureState('emphasis');
  52373. extend(emphasisState.textConfig || (emphasisState.textConfig = {}), {
  52374. position: textPosition
  52375. });
  52376. } else {
  52377. symbolPath.setTextConfig({
  52378. rotation: labelRotate *= Math.PI / 180
  52379. });
  52380. }
  52381. }
  52382. function graphCircularLayout(ecModel) {
  52383. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52384. if (seriesModel.get('layout') === 'circular') {
  52385. circularLayout(seriesModel, 'symbolSize');
  52386. }
  52387. });
  52388. }
  52389. var scaleAndAdd$1 = scaleAndAdd; // function adjacentNode(n, e) {
  52390. // return e.n1 === n ? e.n2 : e.n1;
  52391. // }
  52392. function forceLayout(inNodes, inEdges, opts) {
  52393. var nodes = inNodes;
  52394. var edges = inEdges;
  52395. var rect = opts.rect;
  52396. var width = rect.width;
  52397. var height = rect.height;
  52398. var center = [rect.x + width / 2, rect.y + height / 2]; // let scale = opts.scale || 1;
  52399. var gravity = opts.gravity == null ? 0.1 : opts.gravity; // for (let i = 0; i < edges.length; i++) {
  52400. // let e = edges[i];
  52401. // let n1 = e.n1;
  52402. // let n2 = e.n2;
  52403. // n1.edges = n1.edges || [];
  52404. // n2.edges = n2.edges || [];
  52405. // n1.edges.push(e);
  52406. // n2.edges.push(e);
  52407. // }
  52408. // Init position
  52409. for (var i = 0; i < nodes.length; i++) {
  52410. var n = nodes[i];
  52411. if (!n.p) {
  52412. n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1]);
  52413. }
  52414. n.pp = clone$1(n.p);
  52415. n.edges = null;
  52416. } // Formula in 'Graph Drawing by Force-directed Placement'
  52417. // let k = scale * Math.sqrt(width * height / nodes.length);
  52418. // let k2 = k * k;
  52419. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  52420. var friction = initialFriction;
  52421. var beforeStepCallback;
  52422. var afterStepCallback;
  52423. return {
  52424. warmUp: function () {
  52425. friction = initialFriction * 0.8;
  52426. },
  52427. setFixed: function (idx) {
  52428. nodes[idx].fixed = true;
  52429. },
  52430. setUnfixed: function (idx) {
  52431. nodes[idx].fixed = false;
  52432. },
  52433. /**
  52434. * Before step hook
  52435. */
  52436. beforeStep: function (cb) {
  52437. beforeStepCallback = cb;
  52438. },
  52439. /**
  52440. * After step hook
  52441. */
  52442. afterStep: function (cb) {
  52443. afterStepCallback = cb;
  52444. },
  52445. /**
  52446. * Some formulas were originally copied from "d3.js"
  52447. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  52448. * with some modifications made for this project.
  52449. * See the license statement at the head of this file.
  52450. */
  52451. step: function (cb) {
  52452. beforeStepCallback && beforeStepCallback(nodes, edges);
  52453. var v12 = [];
  52454. var nLen = nodes.length;
  52455. for (var i = 0; i < edges.length; i++) {
  52456. var e = edges[i];
  52457. if (e.ignoreForceLayout) {
  52458. continue;
  52459. }
  52460. var n1 = e.n1;
  52461. var n2 = e.n2;
  52462. sub(v12, n2.p, n1.p);
  52463. var d = len(v12) - e.d;
  52464. var w = n2.w / (n1.w + n2.w);
  52465. if (isNaN(w)) {
  52466. w = 0;
  52467. }
  52468. normalize(v12, v12);
  52469. !n1.fixed && scaleAndAdd$1(n1.p, n1.p, v12, w * d * friction);
  52470. !n2.fixed && scaleAndAdd$1(n2.p, n2.p, v12, -(1 - w) * d * friction);
  52471. } // Gravity
  52472. for (var i = 0; i < nLen; i++) {
  52473. var n = nodes[i];
  52474. if (!n.fixed) {
  52475. sub(v12, center, n.p); // let d = vec2.len(v12);
  52476. // vec2.scale(v12, v12, 1 / d);
  52477. // let gravityFactor = gravity;
  52478. scaleAndAdd$1(n.p, n.p, v12, gravity * friction);
  52479. }
  52480. } // Repulsive
  52481. // PENDING
  52482. for (var i = 0; i < nLen; i++) {
  52483. var n1 = nodes[i];
  52484. for (var j = i + 1; j < nLen; j++) {
  52485. var n2 = nodes[j];
  52486. sub(v12, n2.p, n1.p);
  52487. var d = len(v12);
  52488. if (d === 0) {
  52489. // Random repulse
  52490. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  52491. d = 1;
  52492. }
  52493. var repFact = (n1.rep + n2.rep) / d / d;
  52494. !n1.fixed && scaleAndAdd$1(n1.pp, n1.pp, v12, repFact);
  52495. !n2.fixed && scaleAndAdd$1(n2.pp, n2.pp, v12, -repFact);
  52496. }
  52497. }
  52498. var v = [];
  52499. for (var i = 0; i < nLen; i++) {
  52500. var n = nodes[i];
  52501. if (!n.fixed) {
  52502. sub(v, n.p, n.pp);
  52503. scaleAndAdd$1(n.p, n.p, v, friction);
  52504. copy(n.pp, n.p);
  52505. }
  52506. }
  52507. friction = friction * 0.992;
  52508. var finished = friction < 0.01;
  52509. afterStepCallback && afterStepCallback(nodes, edges, finished);
  52510. cb && cb(finished);
  52511. }
  52512. };
  52513. }
  52514. function graphForceLayout(ecModel) {
  52515. ecModel.eachSeriesByType('graph', function (graphSeries) {
  52516. var coordSys = graphSeries.coordinateSystem;
  52517. if (coordSys && coordSys.type !== 'view') {
  52518. return;
  52519. }
  52520. if (graphSeries.get('layout') === 'force') {
  52521. var preservedPoints_1 = graphSeries.preservedPoints || {};
  52522. var graph_1 = graphSeries.getGraph();
  52523. var nodeData_1 = graph_1.data;
  52524. var edgeData = graph_1.edgeData;
  52525. var forceModel = graphSeries.getModel('force');
  52526. var initLayout = forceModel.get('initLayout');
  52527. if (graphSeries.preservedPoints) {
  52528. nodeData_1.each(function (idx) {
  52529. var id = nodeData_1.getId(idx);
  52530. nodeData_1.setItemLayout(idx, preservedPoints_1[id] || [NaN, NaN]);
  52531. });
  52532. } else if (!initLayout || initLayout === 'none') {
  52533. simpleLayout(graphSeries);
  52534. } else if (initLayout === 'circular') {
  52535. circularLayout(graphSeries, 'value');
  52536. }
  52537. var nodeDataExtent_1 = nodeData_1.getDataExtent('value');
  52538. var edgeDataExtent_1 = edgeData.getDataExtent('value'); // let edgeDataExtent = edgeData.getDataExtent('value');
  52539. var repulsion = forceModel.get('repulsion');
  52540. var edgeLength = forceModel.get('edgeLength');
  52541. var repulsionArr_1 = isArray(repulsion) ? repulsion : [repulsion, repulsion];
  52542. var edgeLengthArr_1 = isArray(edgeLength) ? edgeLength : [edgeLength, edgeLength]; // Larger value has smaller length
  52543. edgeLengthArr_1 = [edgeLengthArr_1[1], edgeLengthArr_1[0]];
  52544. var nodes_1 = nodeData_1.mapArray('value', function (value, idx) {
  52545. var point = nodeData_1.getItemLayout(idx);
  52546. var rep = linearMap(value, nodeDataExtent_1, repulsionArr_1);
  52547. if (isNaN(rep)) {
  52548. rep = (repulsionArr_1[0] + repulsionArr_1[1]) / 2;
  52549. }
  52550. return {
  52551. w: rep,
  52552. rep: rep,
  52553. fixed: nodeData_1.getItemModel(idx).get('fixed'),
  52554. p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point
  52555. };
  52556. });
  52557. var edges = edgeData.mapArray('value', function (value, idx) {
  52558. var edge = graph_1.getEdgeByIndex(idx);
  52559. var d = linearMap(value, edgeDataExtent_1, edgeLengthArr_1);
  52560. if (isNaN(d)) {
  52561. d = (edgeLengthArr_1[0] + edgeLengthArr_1[1]) / 2;
  52562. }
  52563. var edgeModel = edge.getModel();
  52564. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, graphSeries, idx, true), 0);
  52565. return {
  52566. n1: nodes_1[edge.node1.dataIndex],
  52567. n2: nodes_1[edge.node2.dataIndex],
  52568. d: d,
  52569. curveness: curveness,
  52570. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  52571. };
  52572. }); // let coordSys = graphSeries.coordinateSystem;
  52573. var rect = coordSys.getBoundingRect();
  52574. var forceInstance = forceLayout(nodes_1, edges, {
  52575. rect: rect,
  52576. gravity: forceModel.get('gravity'),
  52577. friction: forceModel.get('friction')
  52578. });
  52579. forceInstance.beforeStep(function (nodes, edges) {
  52580. for (var i = 0, l = nodes.length; i < l; i++) {
  52581. if (nodes[i].fixed) {
  52582. // Write back to layout instance
  52583. copy(nodes[i].p, graph_1.getNodeByIndex(i).getLayout());
  52584. }
  52585. }
  52586. });
  52587. forceInstance.afterStep(function (nodes, edges, stopped) {
  52588. for (var i = 0, l = nodes.length; i < l; i++) {
  52589. if (!nodes[i].fixed) {
  52590. graph_1.getNodeByIndex(i).setLayout(nodes[i].p);
  52591. }
  52592. preservedPoints_1[nodeData_1.getId(i)] = nodes[i].p;
  52593. }
  52594. for (var i = 0, l = edges.length; i < l; i++) {
  52595. var e = edges[i];
  52596. var edge = graph_1.getEdgeByIndex(i);
  52597. var p1 = e.n1.p;
  52598. var p2 = e.n2.p;
  52599. var points = edge.getLayout();
  52600. points = points ? points.slice() : [];
  52601. points[0] = points[0] || [];
  52602. points[1] = points[1] || [];
  52603. copy(points[0], p1);
  52604. copy(points[1], p2);
  52605. if (+e.curveness) {
  52606. points[2] = [(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness];
  52607. }
  52608. edge.setLayout(points);
  52609. }
  52610. });
  52611. graphSeries.forceLayout = forceInstance;
  52612. graphSeries.preservedPoints = preservedPoints_1; // Step to get the layout
  52613. forceInstance.step();
  52614. } else {
  52615. // Remove prev injected forceLayout instance
  52616. graphSeries.forceLayout = null;
  52617. }
  52618. });
  52619. }
  52620. function getViewRect$2(seriesModel, api, aspect) {
  52621. var option = extend(seriesModel.getBoxLayoutParams(), {
  52622. aspect: aspect
  52623. });
  52624. return getLayoutRect(option, {
  52625. width: api.getWidth(),
  52626. height: api.getHeight()
  52627. });
  52628. }
  52629. function createViewCoordSys(ecModel, api) {
  52630. var viewList = [];
  52631. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52632. var coordSysType = seriesModel.get('coordinateSystem');
  52633. if (!coordSysType || coordSysType === 'view') {
  52634. var data_1 = seriesModel.getData();
  52635. var positions = data_1.mapArray(function (idx) {
  52636. var itemModel = data_1.getItemModel(idx);
  52637. return [+itemModel.get('x'), +itemModel.get('y')];
  52638. });
  52639. var min = [];
  52640. var max = [];
  52641. fromPoints(positions, min, max); // If width or height is 0
  52642. if (max[0] - min[0] === 0) {
  52643. max[0] += 1;
  52644. min[0] -= 1;
  52645. }
  52646. if (max[1] - min[1] === 0) {
  52647. max[1] += 1;
  52648. min[1] -= 1;
  52649. }
  52650. var aspect = (max[0] - min[0]) / (max[1] - min[1]); // FIXME If get view rect after data processed?
  52651. var viewRect = getViewRect$2(seriesModel, api, aspect); // Position may be NaN, use view rect instead
  52652. if (isNaN(aspect)) {
  52653. min = [viewRect.x, viewRect.y];
  52654. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  52655. }
  52656. var bbWidth = max[0] - min[0];
  52657. var bbHeight = max[1] - min[1];
  52658. var viewWidth = viewRect.width;
  52659. var viewHeight = viewRect.height;
  52660. var viewCoordSys = seriesModel.coordinateSystem = new View();
  52661. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  52662. viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight);
  52663. viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight); // Update roam info
  52664. viewCoordSys.setCenter(seriesModel.get('center'), api);
  52665. viewCoordSys.setZoom(seriesModel.get('zoom'));
  52666. viewList.push(viewCoordSys);
  52667. }
  52668. });
  52669. return viewList;
  52670. }
  52671. var straightLineProto = Line.prototype;
  52672. var bezierCurveProto = BezierCurve.prototype;
  52673. var StraightLineShape =
  52674. /** @class */
  52675. function () {
  52676. function StraightLineShape() {
  52677. // Start point
  52678. this.x1 = 0;
  52679. this.y1 = 0; // End point
  52680. this.x2 = 0;
  52681. this.y2 = 0;
  52682. this.percent = 1;
  52683. }
  52684. return StraightLineShape;
  52685. }();
  52686. var CurveShape =
  52687. /** @class */
  52688. function (_super) {
  52689. __extends(CurveShape, _super);
  52690. function CurveShape() {
  52691. return _super !== null && _super.apply(this, arguments) || this;
  52692. }
  52693. return CurveShape;
  52694. }(StraightLineShape);
  52695. function isStraightLine(shape) {
  52696. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  52697. }
  52698. var ECLinePath =
  52699. /** @class */
  52700. function (_super) {
  52701. __extends(ECLinePath, _super);
  52702. function ECLinePath(opts) {
  52703. var _this = _super.call(this, opts) || this;
  52704. _this.type = 'ec-line';
  52705. return _this;
  52706. }
  52707. ECLinePath.prototype.getDefaultStyle = function () {
  52708. return {
  52709. stroke: '#000',
  52710. fill: null
  52711. };
  52712. };
  52713. ECLinePath.prototype.getDefaultShape = function () {
  52714. return new StraightLineShape();
  52715. };
  52716. ECLinePath.prototype.buildPath = function (ctx, shape) {
  52717. if (isStraightLine(shape)) {
  52718. straightLineProto.buildPath.call(this, ctx, shape);
  52719. } else {
  52720. bezierCurveProto.buildPath.call(this, ctx, shape);
  52721. }
  52722. };
  52723. ECLinePath.prototype.pointAt = function (t) {
  52724. if (isStraightLine(this.shape)) {
  52725. return straightLineProto.pointAt.call(this, t);
  52726. } else {
  52727. return bezierCurveProto.pointAt.call(this, t);
  52728. }
  52729. };
  52730. ECLinePath.prototype.tangentAt = function (t) {
  52731. var shape = this.shape;
  52732. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  52733. return normalize(p, p);
  52734. };
  52735. return ECLinePath;
  52736. }(Path);
  52737. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  52738. function makeSymbolTypeKey(symbolCategory) {
  52739. return '_' + symbolCategory + 'Type';
  52740. }
  52741. /**
  52742. * @inner
  52743. */
  52744. function createSymbol$1(name, lineData, idx) {
  52745. var symbolType = lineData.getItemVisual(idx, name);
  52746. if (!symbolType || symbolType === 'none') {
  52747. return;
  52748. }
  52749. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  52750. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  52751. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  52752. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  52753. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  52754. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  52755. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  52756. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  52757. symbolPath.name = name;
  52758. return symbolPath;
  52759. }
  52760. function createLine(points) {
  52761. var line = new ECLinePath({
  52762. name: 'line',
  52763. subPixelOptimize: true
  52764. });
  52765. setLinePoints(line.shape, points);
  52766. return line;
  52767. }
  52768. function setLinePoints(targetShape, points) {
  52769. targetShape.x1 = points[0][0];
  52770. targetShape.y1 = points[0][1];
  52771. targetShape.x2 = points[1][0];
  52772. targetShape.y2 = points[1][1];
  52773. targetShape.percent = 1;
  52774. var cp1 = points[2];
  52775. if (cp1) {
  52776. targetShape.cpx1 = cp1[0];
  52777. targetShape.cpy1 = cp1[1];
  52778. } else {
  52779. targetShape.cpx1 = NaN;
  52780. targetShape.cpy1 = NaN;
  52781. }
  52782. }
  52783. var Line$1 =
  52784. /** @class */
  52785. function (_super) {
  52786. __extends(Line, _super);
  52787. function Line(lineData, idx, seriesScope) {
  52788. var _this = _super.call(this) || this;
  52789. _this._createLine(lineData, idx, seriesScope);
  52790. return _this;
  52791. }
  52792. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  52793. var seriesModel = lineData.hostModel;
  52794. var linePoints = lineData.getItemLayout(idx);
  52795. var line = createLine(linePoints);
  52796. line.shape.percent = 0;
  52797. initProps(line, {
  52798. shape: {
  52799. percent: 1
  52800. }
  52801. }, seriesModel, idx);
  52802. this.add(line);
  52803. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52804. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  52805. // it will be updated after line#update.
  52806. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  52807. this.add(symbol);
  52808. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  52809. }, this);
  52810. this._updateCommonStl(lineData, idx, seriesScope);
  52811. }; // TODO More strict on the List type in parameters?
  52812. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  52813. var seriesModel = lineData.hostModel;
  52814. var line = this.childOfName('line');
  52815. var linePoints = lineData.getItemLayout(idx);
  52816. var target = {
  52817. shape: {}
  52818. };
  52819. setLinePoints(target.shape, linePoints);
  52820. updateProps(line, target, seriesModel, idx);
  52821. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52822. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  52823. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  52824. if (this[key] !== symbolType) {
  52825. this.remove(this.childOfName(symbolCategory));
  52826. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52827. this.add(symbol);
  52828. }
  52829. this[key] = symbolType;
  52830. }, this);
  52831. this._updateCommonStl(lineData, idx, seriesScope);
  52832. };
  52833. Line.prototype.getLinePath = function () {
  52834. return this.childAt(0);
  52835. };
  52836. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  52837. var seriesModel = lineData.hostModel;
  52838. var line = this.childOfName('line');
  52839. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  52840. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  52841. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  52842. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  52843. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  52844. var focus = seriesScope && seriesScope.focus;
  52845. var blurScope = seriesScope && seriesScope.blurScope; // Optimization for large dataset
  52846. if (!seriesScope || lineData.hasItemOption) {
  52847. var itemModel = lineData.getItemModel(idx);
  52848. var emphasisModel = itemModel.getModel('emphasis');
  52849. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  52850. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  52851. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  52852. emphasisDisabled = emphasisModel.get('disabled');
  52853. focus = emphasisModel.get('focus');
  52854. blurScope = emphasisModel.get('blurScope');
  52855. labelStatesModels = getLabelStatesModels(itemModel);
  52856. }
  52857. var lineStyle = lineData.getItemVisual(idx, 'style');
  52858. var visualColor = lineStyle.stroke;
  52859. line.useStyle(lineStyle);
  52860. line.style.fill = null;
  52861. line.style.strokeNoScale = true;
  52862. line.ensureState('emphasis').style = emphasisLineStyle;
  52863. line.ensureState('blur').style = blurLineStyle;
  52864. line.ensureState('select').style = selectLineStyle; // Update symbol
  52865. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52866. var symbol = this.childOfName(symbolCategory);
  52867. if (symbol) {
  52868. // Share opacity and color with line.
  52869. symbol.setColor(visualColor);
  52870. symbol.style.opacity = lineStyle.opacity;
  52871. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  52872. var stateName = SPECIAL_STATES[i];
  52873. var lineState = line.getState(stateName);
  52874. if (lineState) {
  52875. var lineStateStyle = lineState.style || {};
  52876. var state = symbol.ensureState(stateName);
  52877. var stateStyle = state.style || (state.style = {});
  52878. if (lineStateStyle.stroke != null) {
  52879. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  52880. }
  52881. if (lineStateStyle.opacity != null) {
  52882. stateStyle.opacity = lineStateStyle.opacity;
  52883. }
  52884. }
  52885. }
  52886. symbol.markRedraw();
  52887. }
  52888. }, this);
  52889. var rawVal = seriesModel.getRawValue(idx);
  52890. setLabelStyle(this, labelStatesModels, {
  52891. labelDataIndex: idx,
  52892. labelFetcher: {
  52893. getFormattedLabel: function (dataIndex, stateName) {
  52894. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  52895. }
  52896. },
  52897. inheritColor: visualColor || '#000',
  52898. defaultOpacity: lineStyle.opacity,
  52899. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  52900. });
  52901. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  52902. // values have to be set on `normalStyle`.
  52903. if (label) {
  52904. var labelNormalModel = labelStatesModels.normal;
  52905. label.__align = label.style.align;
  52906. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  52907. label.__position = labelNormalModel.get('position') || 'middle';
  52908. var distance = labelNormalModel.get('distance');
  52909. if (!isArray(distance)) {
  52910. distance = [distance, distance];
  52911. }
  52912. label.__labelDistance = distance;
  52913. }
  52914. this.setTextConfig({
  52915. position: null,
  52916. local: true,
  52917. inside: false // Can't be inside for stroke element.
  52918. });
  52919. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  52920. };
  52921. Line.prototype.highlight = function () {
  52922. enterEmphasis(this);
  52923. };
  52924. Line.prototype.downplay = function () {
  52925. leaveEmphasis(this);
  52926. };
  52927. Line.prototype.updateLayout = function (lineData, idx) {
  52928. this.setLinePoints(lineData.getItemLayout(idx));
  52929. };
  52930. Line.prototype.setLinePoints = function (points) {
  52931. var linePath = this.childOfName('line');
  52932. setLinePoints(linePath.shape, points);
  52933. linePath.dirty();
  52934. };
  52935. Line.prototype.beforeUpdate = function () {
  52936. var lineGroup = this;
  52937. var symbolFrom = lineGroup.childOfName('fromSymbol');
  52938. var symbolTo = lineGroup.childOfName('toSymbol');
  52939. var label = lineGroup.getTextContent(); // Quick reject
  52940. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  52941. return;
  52942. }
  52943. var invScale = 1;
  52944. var parentNode = this.parent;
  52945. while (parentNode) {
  52946. if (parentNode.scaleX) {
  52947. invScale /= parentNode.scaleX;
  52948. }
  52949. parentNode = parentNode.parent;
  52950. }
  52951. var line = lineGroup.childOfName('line'); // If line not changed
  52952. // FIXME Parent scale changed
  52953. if (!this.__dirty && !line.__dirty) {
  52954. return;
  52955. }
  52956. var percent = line.shape.percent;
  52957. var fromPos = line.pointAt(0);
  52958. var toPos = line.pointAt(percent);
  52959. var d = sub([], toPos, fromPos);
  52960. normalize(d, d);
  52961. function setSymbolRotation(symbol, percent) {
  52962. // Fix #12388
  52963. // when symbol is set to be 'arrow' in markLine,
  52964. // symbolRotate value will be ignored, and compulsively use tangent angle.
  52965. // rotate by default if symbol rotation is not specified
  52966. var specifiedRotation = symbol.__specifiedRotation;
  52967. if (specifiedRotation == null) {
  52968. var tangent = line.tangentAt(percent);
  52969. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  52970. } else {
  52971. symbol.attr('rotation', specifiedRotation);
  52972. }
  52973. }
  52974. if (symbolFrom) {
  52975. symbolFrom.setPosition(fromPos);
  52976. setSymbolRotation(symbolFrom, 0);
  52977. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  52978. symbolFrom.markRedraw();
  52979. }
  52980. if (symbolTo) {
  52981. symbolTo.setPosition(toPos);
  52982. setSymbolRotation(symbolTo, 1);
  52983. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  52984. symbolTo.markRedraw();
  52985. }
  52986. if (label && !label.ignore) {
  52987. label.x = label.y = 0;
  52988. label.originX = label.originY = 0;
  52989. var textAlign = void 0;
  52990. var textVerticalAlign = void 0;
  52991. var distance = label.__labelDistance;
  52992. var distanceX = distance[0] * invScale;
  52993. var distanceY = distance[1] * invScale;
  52994. var halfPercent = percent / 2;
  52995. var tangent = line.tangentAt(halfPercent);
  52996. var n = [tangent[1], -tangent[0]];
  52997. var cp = line.pointAt(halfPercent);
  52998. if (n[1] > 0) {
  52999. n[0] = -n[0];
  53000. n[1] = -n[1];
  53001. }
  53002. var dir = tangent[0] < 0 ? -1 : 1;
  53003. if (label.__position !== 'start' && label.__position !== 'end') {
  53004. var rotation = -Math.atan2(tangent[1], tangent[0]);
  53005. if (toPos[0] < fromPos[0]) {
  53006. rotation = Math.PI + rotation;
  53007. }
  53008. label.rotation = rotation;
  53009. }
  53010. var dy = void 0;
  53011. switch (label.__position) {
  53012. case 'insideStartTop':
  53013. case 'insideMiddleTop':
  53014. case 'insideEndTop':
  53015. case 'middle':
  53016. dy = -distanceY;
  53017. textVerticalAlign = 'bottom';
  53018. break;
  53019. case 'insideStartBottom':
  53020. case 'insideMiddleBottom':
  53021. case 'insideEndBottom':
  53022. dy = distanceY;
  53023. textVerticalAlign = 'top';
  53024. break;
  53025. default:
  53026. dy = 0;
  53027. textVerticalAlign = 'middle';
  53028. }
  53029. switch (label.__position) {
  53030. case 'end':
  53031. label.x = d[0] * distanceX + toPos[0];
  53032. label.y = d[1] * distanceY + toPos[1];
  53033. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  53034. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  53035. break;
  53036. case 'start':
  53037. label.x = -d[0] * distanceX + fromPos[0];
  53038. label.y = -d[1] * distanceY + fromPos[1];
  53039. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  53040. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  53041. break;
  53042. case 'insideStartTop':
  53043. case 'insideStart':
  53044. case 'insideStartBottom':
  53045. label.x = distanceX * dir + fromPos[0];
  53046. label.y = fromPos[1] + dy;
  53047. textAlign = tangent[0] < 0 ? 'right' : 'left';
  53048. label.originX = -distanceX * dir;
  53049. label.originY = -dy;
  53050. break;
  53051. case 'insideMiddleTop':
  53052. case 'insideMiddle':
  53053. case 'insideMiddleBottom':
  53054. case 'middle':
  53055. label.x = cp[0];
  53056. label.y = cp[1] + dy;
  53057. textAlign = 'center';
  53058. label.originY = -dy;
  53059. break;
  53060. case 'insideEndTop':
  53061. case 'insideEnd':
  53062. case 'insideEndBottom':
  53063. label.x = -distanceX * dir + toPos[0];
  53064. label.y = toPos[1] + dy;
  53065. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  53066. label.originX = distanceX * dir;
  53067. label.originY = -dy;
  53068. break;
  53069. }
  53070. label.scaleX = label.scaleY = invScale;
  53071. label.setStyle({
  53072. // Use the user specified text align and baseline first
  53073. verticalAlign: label.__verticalAlign || textVerticalAlign,
  53074. align: label.__align || textAlign
  53075. });
  53076. }
  53077. };
  53078. return Line;
  53079. }(Group);
  53080. var LineDraw =
  53081. /** @class */
  53082. function () {
  53083. function LineDraw(LineCtor) {
  53084. this.group = new Group();
  53085. this._LineCtor = LineCtor || Line$1;
  53086. }
  53087. LineDraw.prototype.updateData = function (lineData) {
  53088. var _this = this; // Remove progressive els.
  53089. this._progressiveEls = null;
  53090. var lineDraw = this;
  53091. var group = lineDraw.group;
  53092. var oldLineData = lineDraw._lineData;
  53093. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  53094. // stream mode to normal mode, where previous elements should be removed.
  53095. if (!oldLineData) {
  53096. group.removeAll();
  53097. }
  53098. var seriesScope = makeSeriesScope$1(lineData);
  53099. lineData.diff(oldLineData).add(function (idx) {
  53100. _this._doAdd(lineData, idx, seriesScope);
  53101. }).update(function (newIdx, oldIdx) {
  53102. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  53103. }).remove(function (idx) {
  53104. group.remove(oldLineData.getItemGraphicEl(idx));
  53105. }).execute();
  53106. };
  53107. LineDraw.prototype.updateLayout = function () {
  53108. var lineData = this._lineData; // Do not support update layout in incremental mode.
  53109. if (!lineData) {
  53110. return;
  53111. }
  53112. lineData.eachItemGraphicEl(function (el, idx) {
  53113. el.updateLayout(lineData, idx);
  53114. }, this);
  53115. };
  53116. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  53117. this._seriesScope = makeSeriesScope$1(lineData);
  53118. this._lineData = null;
  53119. this.group.removeAll();
  53120. };
  53121. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  53122. this._progressiveEls = [];
  53123. function updateIncrementalAndHover(el) {
  53124. if (!el.isGroup && !isEffectObject(el)) {
  53125. el.incremental = true;
  53126. el.ensureState('emphasis').hoverLayer = true;
  53127. }
  53128. }
  53129. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  53130. var itemLayout = lineData.getItemLayout(idx);
  53131. if (lineNeedsDraw(itemLayout)) {
  53132. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  53133. el.traverse(updateIncrementalAndHover);
  53134. this.group.add(el);
  53135. lineData.setItemGraphicEl(idx, el);
  53136. this._progressiveEls.push(el);
  53137. }
  53138. }
  53139. };
  53140. LineDraw.prototype.remove = function () {
  53141. this.group.removeAll();
  53142. };
  53143. LineDraw.prototype.eachRendered = function (cb) {
  53144. traverseElements(this._progressiveEls || this.group, cb);
  53145. };
  53146. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  53147. var itemLayout = lineData.getItemLayout(idx);
  53148. if (!lineNeedsDraw(itemLayout)) {
  53149. return;
  53150. }
  53151. var el = new this._LineCtor(lineData, idx, seriesScope);
  53152. lineData.setItemGraphicEl(idx, el);
  53153. this.group.add(el);
  53154. };
  53155. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  53156. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  53157. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  53158. this.group.remove(itemEl);
  53159. return;
  53160. }
  53161. if (!itemEl) {
  53162. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  53163. } else {
  53164. itemEl.updateData(newLineData, newIdx, seriesScope);
  53165. }
  53166. newLineData.setItemGraphicEl(newIdx, itemEl);
  53167. this.group.add(itemEl);
  53168. };
  53169. return LineDraw;
  53170. }();
  53171. function isEffectObject(el) {
  53172. return el.animators && el.animators.length > 0;
  53173. }
  53174. function makeSeriesScope$1(lineData) {
  53175. var hostModel = lineData.hostModel;
  53176. var emphasisModel = hostModel.getModel('emphasis');
  53177. return {
  53178. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  53179. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  53180. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  53181. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  53182. emphasisDisabled: emphasisModel.get('disabled'),
  53183. blurScope: emphasisModel.get('blurScope'),
  53184. focus: emphasisModel.get('focus'),
  53185. labelStatesModels: getLabelStatesModels(hostModel)
  53186. };
  53187. }
  53188. function isPointNaN(pt) {
  53189. return isNaN(pt[0]) || isNaN(pt[1]);
  53190. }
  53191. function lineNeedsDraw(pts) {
  53192. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  53193. }
  53194. var v1 = [];
  53195. var v2 = [];
  53196. var v3 = [];
  53197. var quadraticAt$1 = quadraticAt;
  53198. var v2DistSquare = distSquare;
  53199. var mathAbs$2 = Math.abs;
  53200. function intersectCurveCircle(curvePoints, center, radius) {
  53201. var p0 = curvePoints[0];
  53202. var p1 = curvePoints[1];
  53203. var p2 = curvePoints[2];
  53204. var d = Infinity;
  53205. var t;
  53206. var radiusSquare = radius * radius;
  53207. var interval = 0.1;
  53208. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  53209. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  53210. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  53211. var diff = mathAbs$2(v2DistSquare(v1, center) - radiusSquare);
  53212. if (diff < d) {
  53213. d = diff;
  53214. t = _t;
  53215. }
  53216. } // Assume the segment is monotone,Find root through Bisection method
  53217. // At most 32 iteration
  53218. for (var i = 0; i < 32; i++) {
  53219. // let prev = t - interval;
  53220. var next = t + interval; // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  53221. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  53222. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  53223. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  53224. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  53225. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  53226. var diff = v2DistSquare(v2, center) - radiusSquare;
  53227. if (mathAbs$2(diff) < 1e-2) {
  53228. break;
  53229. } // let prevDiff = v2DistSquare(v1, center) - radiusSquare;
  53230. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  53231. interval /= 2;
  53232. if (diff < 0) {
  53233. if (nextDiff >= 0) {
  53234. t = t + interval;
  53235. } else {
  53236. t = t - interval;
  53237. }
  53238. } else {
  53239. if (nextDiff >= 0) {
  53240. t = t - interval;
  53241. } else {
  53242. t = t + interval;
  53243. }
  53244. }
  53245. }
  53246. return t;
  53247. } // Adjust edge to avoid
  53248. function adjustEdge(graph, scale) {
  53249. var tmp0 = [];
  53250. var quadraticSubdivide$1 = quadraticSubdivide;
  53251. var pts = [[], [], []];
  53252. var pts2 = [[], []];
  53253. var v = [];
  53254. scale /= 2;
  53255. graph.eachEdge(function (edge, idx) {
  53256. var linePoints = edge.getLayout();
  53257. var fromSymbol = edge.getVisual('fromSymbol');
  53258. var toSymbol = edge.getVisual('toSymbol');
  53259. if (!linePoints.__original) {
  53260. linePoints.__original = [clone$1(linePoints[0]), clone$1(linePoints[1])];
  53261. if (linePoints[2]) {
  53262. linePoints.__original.push(clone$1(linePoints[2]));
  53263. }
  53264. }
  53265. var originalPoints = linePoints.__original; // Quadratic curve
  53266. if (linePoints[2] != null) {
  53267. copy(pts[0], originalPoints[0]);
  53268. copy(pts[1], originalPoints[2]);
  53269. copy(pts[2], originalPoints[1]);
  53270. if (fromSymbol && fromSymbol !== 'none') {
  53271. var symbolSize = getSymbolSize(edge.node1);
  53272. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale); // Subdivide and get the second
  53273. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  53274. pts[0][0] = tmp0[3];
  53275. pts[1][0] = tmp0[4];
  53276. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  53277. pts[0][1] = tmp0[3];
  53278. pts[1][1] = tmp0[4];
  53279. }
  53280. if (toSymbol && toSymbol !== 'none') {
  53281. var symbolSize = getSymbolSize(edge.node2);
  53282. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale); // Subdivide and get the first
  53283. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  53284. pts[1][0] = tmp0[1];
  53285. pts[2][0] = tmp0[2];
  53286. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  53287. pts[1][1] = tmp0[1];
  53288. pts[2][1] = tmp0[2];
  53289. } // Copy back to layout
  53290. copy(linePoints[0], pts[0]);
  53291. copy(linePoints[1], pts[2]);
  53292. copy(linePoints[2], pts[1]);
  53293. } // Line
  53294. else {
  53295. copy(pts2[0], originalPoints[0]);
  53296. copy(pts2[1], originalPoints[1]);
  53297. sub(v, pts2[1], pts2[0]);
  53298. normalize(v, v);
  53299. if (fromSymbol && fromSymbol !== 'none') {
  53300. var symbolSize = getSymbolSize(edge.node1);
  53301. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale);
  53302. }
  53303. if (toSymbol && toSymbol !== 'none') {
  53304. var symbolSize = getSymbolSize(edge.node2);
  53305. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale);
  53306. }
  53307. copy(linePoints[0], pts2[0]);
  53308. copy(linePoints[1], pts2[1]);
  53309. }
  53310. });
  53311. }
  53312. function isViewCoordSys(coordSys) {
  53313. return coordSys.type === 'view';
  53314. }
  53315. var GraphView =
  53316. /** @class */
  53317. function (_super) {
  53318. __extends(GraphView, _super);
  53319. function GraphView() {
  53320. var _this = _super !== null && _super.apply(this, arguments) || this;
  53321. _this.type = GraphView.type;
  53322. return _this;
  53323. }
  53324. GraphView.prototype.init = function (ecModel, api) {
  53325. var symbolDraw = new SymbolDraw();
  53326. var lineDraw = new LineDraw();
  53327. var group = this.group;
  53328. this._controller = new RoamController(api.getZr());
  53329. this._controllerHost = {
  53330. target: group
  53331. };
  53332. group.add(symbolDraw.group);
  53333. group.add(lineDraw.group);
  53334. this._symbolDraw = symbolDraw;
  53335. this._lineDraw = lineDraw;
  53336. this._firstRender = true;
  53337. };
  53338. GraphView.prototype.render = function (seriesModel, ecModel, api) {
  53339. var _this = this;
  53340. var coordSys = seriesModel.coordinateSystem;
  53341. this._model = seriesModel;
  53342. var symbolDraw = this._symbolDraw;
  53343. var lineDraw = this._lineDraw;
  53344. var group = this.group;
  53345. if (isViewCoordSys(coordSys)) {
  53346. var groupNewProp = {
  53347. x: coordSys.x,
  53348. y: coordSys.y,
  53349. scaleX: coordSys.scaleX,
  53350. scaleY: coordSys.scaleY
  53351. };
  53352. if (this._firstRender) {
  53353. group.attr(groupNewProp);
  53354. } else {
  53355. updateProps(group, groupNewProp, seriesModel);
  53356. }
  53357. } // Fix edge contact point with node
  53358. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53359. var data = seriesModel.getData();
  53360. symbolDraw.updateData(data);
  53361. var edgeData = seriesModel.getEdgeData(); // TODO: TYPE
  53362. lineDraw.updateData(edgeData);
  53363. this._updateNodeAndLinkScale();
  53364. this._updateController(seriesModel, ecModel, api);
  53365. clearTimeout(this._layoutTimeout);
  53366. var forceLayout = seriesModel.forceLayout;
  53367. var layoutAnimation = seriesModel.get(['force', 'layoutAnimation']);
  53368. if (forceLayout) {
  53369. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  53370. }
  53371. var layout = seriesModel.get('layout');
  53372. data.graph.eachNode(function (node) {
  53373. var idx = node.dataIndex;
  53374. var el = node.getGraphicEl();
  53375. var itemModel = node.getModel();
  53376. if (!el) {
  53377. return;
  53378. } // Update draggable
  53379. el.off('drag').off('dragend');
  53380. var draggable = itemModel.get('draggable');
  53381. if (draggable) {
  53382. el.on('drag', function (e) {
  53383. switch (layout) {
  53384. case 'force':
  53385. forceLayout.warmUp();
  53386. !_this._layouting && _this._startForceLayoutIteration(forceLayout, layoutAnimation);
  53387. forceLayout.setFixed(idx); // Write position back to layout
  53388. data.setItemLayout(idx, [el.x, el.y]);
  53389. break;
  53390. case 'circular':
  53391. data.setItemLayout(idx, [el.x, el.y]); // mark node fixed
  53392. node.setLayout({
  53393. fixed: true
  53394. }, true); // recalculate circular layout
  53395. circularLayout(seriesModel, 'symbolSize', node, [e.offsetX, e.offsetY]);
  53396. _this.updateLayout(seriesModel);
  53397. break;
  53398. case 'none':
  53399. default:
  53400. data.setItemLayout(idx, [el.x, el.y]); // update edge
  53401. simpleLayoutEdge(seriesModel.getGraph(), seriesModel);
  53402. _this.updateLayout(seriesModel);
  53403. break;
  53404. }
  53405. }).on('dragend', function () {
  53406. if (forceLayout) {
  53407. forceLayout.setUnfixed(idx);
  53408. }
  53409. });
  53410. }
  53411. el.setDraggable(draggable, !!itemModel.get('cursor'));
  53412. var focus = itemModel.get(['emphasis', 'focus']);
  53413. if (focus === 'adjacency') {
  53414. getECData(el).focus = node.getAdjacentDataIndices();
  53415. }
  53416. });
  53417. data.graph.eachEdge(function (edge) {
  53418. var el = edge.getGraphicEl();
  53419. var focus = edge.getModel().get(['emphasis', 'focus']);
  53420. if (!el) {
  53421. return;
  53422. }
  53423. if (focus === 'adjacency') {
  53424. getECData(el).focus = {
  53425. edge: [edge.dataIndex],
  53426. node: [edge.node1.dataIndex, edge.node2.dataIndex]
  53427. };
  53428. }
  53429. });
  53430. var circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get(['circular', 'rotateLabel']);
  53431. var cx = data.getLayout('cx');
  53432. var cy = data.getLayout('cy');
  53433. data.graph.eachNode(function (node) {
  53434. rotateNodeLabel(node, circularRotateLabel, cx, cy);
  53435. });
  53436. this._firstRender = false;
  53437. };
  53438. GraphView.prototype.dispose = function () {
  53439. this._controller && this._controller.dispose();
  53440. this._controllerHost = null;
  53441. };
  53442. GraphView.prototype._startForceLayoutIteration = function (forceLayout, layoutAnimation) {
  53443. var self = this;
  53444. (function step() {
  53445. forceLayout.step(function (stopped) {
  53446. self.updateLayout(self._model);
  53447. (self._layouting = !stopped) && (layoutAnimation ? self._layoutTimeout = setTimeout(step, 16) : step());
  53448. });
  53449. })();
  53450. };
  53451. GraphView.prototype._updateController = function (seriesModel, ecModel, api) {
  53452. var _this = this;
  53453. var controller = this._controller;
  53454. var controllerHost = this._controllerHost;
  53455. var group = this.group;
  53456. controller.setPointerChecker(function (e, x, y) {
  53457. var rect = group.getBoundingRect();
  53458. rect.applyTransform(group.transform);
  53459. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  53460. });
  53461. if (!isViewCoordSys(seriesModel.coordinateSystem)) {
  53462. controller.disable();
  53463. return;
  53464. }
  53465. controller.enable(seriesModel.get('roam'));
  53466. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  53467. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  53468. controller.off('pan').off('zoom').on('pan', function (e) {
  53469. updateViewOnPan(controllerHost, e.dx, e.dy);
  53470. api.dispatchAction({
  53471. seriesId: seriesModel.id,
  53472. type: 'graphRoam',
  53473. dx: e.dx,
  53474. dy: e.dy
  53475. });
  53476. }).on('zoom', function (e) {
  53477. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  53478. api.dispatchAction({
  53479. seriesId: seriesModel.id,
  53480. type: 'graphRoam',
  53481. zoom: e.scale,
  53482. originX: e.originX,
  53483. originY: e.originY
  53484. });
  53485. _this._updateNodeAndLinkScale();
  53486. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53487. _this._lineDraw.updateLayout(); // Only update label layout on zoom
  53488. api.updateLabelLayout();
  53489. });
  53490. };
  53491. GraphView.prototype._updateNodeAndLinkScale = function () {
  53492. var seriesModel = this._model;
  53493. var data = seriesModel.getData();
  53494. var nodeScale = getNodeGlobalScale(seriesModel);
  53495. data.eachItemGraphicEl(function (el, idx) {
  53496. el && el.setSymbolScale(nodeScale);
  53497. });
  53498. };
  53499. GraphView.prototype.updateLayout = function (seriesModel) {
  53500. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53501. this._symbolDraw.updateLayout();
  53502. this._lineDraw.updateLayout();
  53503. };
  53504. GraphView.prototype.remove = function (ecModel, api) {
  53505. this._symbolDraw && this._symbolDraw.remove();
  53506. this._lineDraw && this._lineDraw.remove();
  53507. };
  53508. GraphView.type = 'graph';
  53509. return GraphView;
  53510. }(ChartView);
  53511. function generateNodeKey(id) {
  53512. return '_EC_' + id;
  53513. }
  53514. var Graph =
  53515. /** @class */
  53516. function () {
  53517. function Graph(directed) {
  53518. this.type = 'graph';
  53519. this.nodes = [];
  53520. this.edges = [];
  53521. this._nodesMap = {};
  53522. /**
  53523. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  53524. * @private
  53525. */
  53526. this._edgesMap = {};
  53527. this._directed = directed || false;
  53528. }
  53529. /**
  53530. * If is directed graph
  53531. */
  53532. Graph.prototype.isDirected = function () {
  53533. return this._directed;
  53534. };
  53535. /**
  53536. * Add a new node
  53537. */
  53538. Graph.prototype.addNode = function (id, dataIndex) {
  53539. id = id == null ? '' + dataIndex : '' + id;
  53540. var nodesMap = this._nodesMap;
  53541. if (nodesMap[generateNodeKey(id)]) {
  53542. if ("development" !== 'production') {
  53543. console.error('Graph nodes have duplicate name or id');
  53544. }
  53545. return;
  53546. }
  53547. var node = new GraphNode(id, dataIndex);
  53548. node.hostGraph = this;
  53549. this.nodes.push(node);
  53550. nodesMap[generateNodeKey(id)] = node;
  53551. return node;
  53552. };
  53553. /**
  53554. * Get node by data index
  53555. */
  53556. Graph.prototype.getNodeByIndex = function (dataIndex) {
  53557. var rawIdx = this.data.getRawIndex(dataIndex);
  53558. return this.nodes[rawIdx];
  53559. };
  53560. /**
  53561. * Get node by id
  53562. */
  53563. Graph.prototype.getNodeById = function (id) {
  53564. return this._nodesMap[generateNodeKey(id)];
  53565. };
  53566. /**
  53567. * Add a new edge
  53568. */
  53569. Graph.prototype.addEdge = function (n1, n2, dataIndex) {
  53570. var nodesMap = this._nodesMap;
  53571. var edgesMap = this._edgesMap; // PENDING
  53572. if (isNumber(n1)) {
  53573. n1 = this.nodes[n1];
  53574. }
  53575. if (isNumber(n2)) {
  53576. n2 = this.nodes[n2];
  53577. }
  53578. if (!(n1 instanceof GraphNode)) {
  53579. n1 = nodesMap[generateNodeKey(n1)];
  53580. }
  53581. if (!(n2 instanceof GraphNode)) {
  53582. n2 = nodesMap[generateNodeKey(n2)];
  53583. }
  53584. if (!n1 || !n2) {
  53585. return;
  53586. }
  53587. var key = n1.id + '-' + n2.id;
  53588. var edge = new GraphEdge(n1, n2, dataIndex);
  53589. edge.hostGraph = this;
  53590. if (this._directed) {
  53591. n1.outEdges.push(edge);
  53592. n2.inEdges.push(edge);
  53593. }
  53594. n1.edges.push(edge);
  53595. if (n1 !== n2) {
  53596. n2.edges.push(edge);
  53597. }
  53598. this.edges.push(edge);
  53599. edgesMap[key] = edge;
  53600. return edge;
  53601. };
  53602. /**
  53603. * Get edge by data index
  53604. */
  53605. Graph.prototype.getEdgeByIndex = function (dataIndex) {
  53606. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  53607. return this.edges[rawIdx];
  53608. };
  53609. /**
  53610. * Get edge by two linked nodes
  53611. */
  53612. Graph.prototype.getEdge = function (n1, n2) {
  53613. if (n1 instanceof GraphNode) {
  53614. n1 = n1.id;
  53615. }
  53616. if (n2 instanceof GraphNode) {
  53617. n2 = n2.id;
  53618. }
  53619. var edgesMap = this._edgesMap;
  53620. if (this._directed) {
  53621. return edgesMap[n1 + '-' + n2];
  53622. } else {
  53623. return edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1];
  53624. }
  53625. };
  53626. /**
  53627. * Iterate all nodes
  53628. */
  53629. Graph.prototype.eachNode = function (cb, context) {
  53630. var nodes = this.nodes;
  53631. var len = nodes.length;
  53632. for (var i = 0; i < len; i++) {
  53633. if (nodes[i].dataIndex >= 0) {
  53634. cb.call(context, nodes[i], i);
  53635. }
  53636. }
  53637. };
  53638. /**
  53639. * Iterate all edges
  53640. */
  53641. Graph.prototype.eachEdge = function (cb, context) {
  53642. var edges = this.edges;
  53643. var len = edges.length;
  53644. for (var i = 0; i < len; i++) {
  53645. if (edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0) {
  53646. cb.call(context, edges[i], i);
  53647. }
  53648. }
  53649. };
  53650. /**
  53651. * Breadth first traverse
  53652. * Return true to stop traversing
  53653. */
  53654. Graph.prototype.breadthFirstTraverse = function (cb, startNode, direction, context) {
  53655. if (!(startNode instanceof GraphNode)) {
  53656. startNode = this._nodesMap[generateNodeKey(startNode)];
  53657. }
  53658. if (!startNode) {
  53659. return;
  53660. }
  53661. var edgeType = direction === 'out' ? 'outEdges' : direction === 'in' ? 'inEdges' : 'edges';
  53662. for (var i = 0; i < this.nodes.length; i++) {
  53663. this.nodes[i].__visited = false;
  53664. }
  53665. if (cb.call(context, startNode, null)) {
  53666. return;
  53667. }
  53668. var queue = [startNode];
  53669. while (queue.length) {
  53670. var currentNode = queue.shift();
  53671. var edges = currentNode[edgeType];
  53672. for (var i = 0; i < edges.length; i++) {
  53673. var e = edges[i];
  53674. var otherNode = e.node1 === currentNode ? e.node2 : e.node1;
  53675. if (!otherNode.__visited) {
  53676. if (cb.call(context, otherNode, currentNode)) {
  53677. // Stop traversing
  53678. return;
  53679. }
  53680. queue.push(otherNode);
  53681. otherNode.__visited = true;
  53682. }
  53683. }
  53684. }
  53685. };
  53686. // depthFirstTraverse(
  53687. // cb, startNode, direction, context
  53688. // ) {
  53689. // };
  53690. // Filter update
  53691. Graph.prototype.update = function () {
  53692. var data = this.data;
  53693. var edgeData = this.edgeData;
  53694. var nodes = this.nodes;
  53695. var edges = this.edges;
  53696. for (var i = 0, len = nodes.length; i < len; i++) {
  53697. nodes[i].dataIndex = -1;
  53698. }
  53699. for (var i = 0, len = data.count(); i < len; i++) {
  53700. nodes[data.getRawIndex(i)].dataIndex = i;
  53701. }
  53702. edgeData.filterSelf(function (idx) {
  53703. var edge = edges[edgeData.getRawIndex(idx)];
  53704. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  53705. }); // Update edge
  53706. for (var i = 0, len = edges.length; i < len; i++) {
  53707. edges[i].dataIndex = -1;
  53708. }
  53709. for (var i = 0, len = edgeData.count(); i < len; i++) {
  53710. edges[edgeData.getRawIndex(i)].dataIndex = i;
  53711. }
  53712. };
  53713. /**
  53714. * @return {module:echarts/data/Graph}
  53715. */
  53716. Graph.prototype.clone = function () {
  53717. var graph = new Graph(this._directed);
  53718. var nodes = this.nodes;
  53719. var edges = this.edges;
  53720. for (var i = 0; i < nodes.length; i++) {
  53721. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  53722. }
  53723. for (var i = 0; i < edges.length; i++) {
  53724. var e = edges[i];
  53725. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  53726. }
  53727. return graph;
  53728. };
  53729. return Graph;
  53730. }();
  53731. var GraphNode =
  53732. /** @class */
  53733. function () {
  53734. function GraphNode(id, dataIndex) {
  53735. this.inEdges = [];
  53736. this.outEdges = [];
  53737. this.edges = [];
  53738. this.dataIndex = -1;
  53739. this.id = id == null ? '' : id;
  53740. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  53741. }
  53742. /**
  53743. * @return {number}
  53744. */
  53745. GraphNode.prototype.degree = function () {
  53746. return this.edges.length;
  53747. };
  53748. /**
  53749. * @return {number}
  53750. */
  53751. GraphNode.prototype.inDegree = function () {
  53752. return this.inEdges.length;
  53753. };
  53754. /**
  53755. * @return {number}
  53756. */
  53757. GraphNode.prototype.outDegree = function () {
  53758. return this.outEdges.length;
  53759. };
  53760. GraphNode.prototype.getModel = function (path) {
  53761. if (this.dataIndex < 0) {
  53762. return;
  53763. }
  53764. var graph = this.hostGraph;
  53765. var itemModel = graph.data.getItemModel(this.dataIndex);
  53766. return itemModel.getModel(path);
  53767. };
  53768. GraphNode.prototype.getAdjacentDataIndices = function () {
  53769. var dataIndices = {
  53770. edge: [],
  53771. node: []
  53772. };
  53773. for (var i = 0; i < this.edges.length; i++) {
  53774. var adjacentEdge = this.edges[i];
  53775. if (adjacentEdge.dataIndex < 0) {
  53776. continue;
  53777. }
  53778. dataIndices.edge.push(adjacentEdge.dataIndex);
  53779. dataIndices.node.push(adjacentEdge.node1.dataIndex, adjacentEdge.node2.dataIndex);
  53780. }
  53781. return dataIndices;
  53782. };
  53783. return GraphNode;
  53784. }();
  53785. var GraphEdge =
  53786. /** @class */
  53787. function () {
  53788. function GraphEdge(n1, n2, dataIndex) {
  53789. this.dataIndex = -1;
  53790. this.node1 = n1;
  53791. this.node2 = n2;
  53792. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  53793. } // eslint-disable-next-line @typescript-eslint/no-unused-vars
  53794. GraphEdge.prototype.getModel = function (path) {
  53795. if (this.dataIndex < 0) {
  53796. return;
  53797. }
  53798. var graph = this.hostGraph;
  53799. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  53800. return itemModel.getModel(path);
  53801. };
  53802. GraphEdge.prototype.getAdjacentDataIndices = function () {
  53803. return {
  53804. edge: [this.dataIndex],
  53805. node: [this.node1.dataIndex, this.node2.dataIndex]
  53806. };
  53807. };
  53808. return GraphEdge;
  53809. }();
  53810. function createGraphDataProxyMixin(hostName, dataName) {
  53811. return {
  53812. /**
  53813. * @param Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  53814. */
  53815. getValue: function (dimension) {
  53816. var data = this[hostName][dataName];
  53817. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  53818. },
  53819. // TODO: TYPE stricter type.
  53820. setVisual: function (key, value) {
  53821. this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  53822. },
  53823. getVisual: function (key) {
  53824. return this[hostName][dataName].getItemVisual(this.dataIndex, key);
  53825. },
  53826. setLayout: function (layout, merge) {
  53827. this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge);
  53828. },
  53829. getLayout: function () {
  53830. return this[hostName][dataName].getItemLayout(this.dataIndex);
  53831. },
  53832. getGraphicEl: function () {
  53833. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  53834. },
  53835. getRawIndex: function () {
  53836. return this[hostName][dataName].getRawIndex(this.dataIndex);
  53837. }
  53838. };
  53839. }
  53840. mixin(GraphNode, createGraphDataProxyMixin('hostGraph', 'data'));
  53841. mixin(GraphEdge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  53842. function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) {
  53843. // ??? TODO
  53844. // support dataset?
  53845. var graph = new Graph(directed);
  53846. for (var i = 0; i < nodes.length; i++) {
  53847. graph.addNode(retrieve( // Id, name, dataIndex
  53848. nodes[i].id, nodes[i].name, i), i);
  53849. }
  53850. var linkNameList = [];
  53851. var validEdges = [];
  53852. var linkCount = 0;
  53853. for (var i = 0; i < edges.length; i++) {
  53854. var link = edges[i];
  53855. var source = link.source;
  53856. var target = link.target; // addEdge may fail when source or target not exists
  53857. if (graph.addEdge(source, target, linkCount)) {
  53858. validEdges.push(link);
  53859. linkNameList.push(retrieve(convertOptionIdName(link.id, null), source + ' > ' + target));
  53860. linkCount++;
  53861. }
  53862. }
  53863. var coordSys = seriesModel.get('coordinateSystem');
  53864. var nodeData;
  53865. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  53866. nodeData = createSeriesData(nodes, seriesModel);
  53867. } else {
  53868. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  53869. var coordDimensions = coordSysCtor ? coordSysCtor.dimensions || [] : []; // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  53870. // `value` dimension, but graph need `value` dimension. It's better to
  53871. // uniform this behavior.
  53872. if (indexOf(coordDimensions, 'value') < 0) {
  53873. coordDimensions.concat(['value']);
  53874. }
  53875. var dimensions = prepareSeriesDataSchema(nodes, {
  53876. coordDimensions: coordDimensions,
  53877. encodeDefine: seriesModel.getEncode()
  53878. }).dimensions;
  53879. nodeData = new SeriesData(dimensions, seriesModel);
  53880. nodeData.initData(nodes);
  53881. }
  53882. var edgeData = new SeriesData(['value'], seriesModel);
  53883. edgeData.initData(validEdges, linkNameList);
  53884. beforeLink && beforeLink(nodeData, edgeData);
  53885. linkSeriesData({
  53886. mainData: nodeData,
  53887. struct: graph,
  53888. structAttr: 'graph',
  53889. datas: {
  53890. node: nodeData,
  53891. edge: edgeData
  53892. },
  53893. datasAttr: {
  53894. node: 'data',
  53895. edge: 'edgeData'
  53896. }
  53897. }); // Update dataIndex of nodes and edges because invalid edge may be removed
  53898. graph.update();
  53899. return graph;
  53900. }
  53901. var GraphSeriesModel =
  53902. /** @class */
  53903. function (_super) {
  53904. __extends(GraphSeriesModel, _super);
  53905. function GraphSeriesModel() {
  53906. var _this = _super !== null && _super.apply(this, arguments) || this;
  53907. _this.type = GraphSeriesModel.type;
  53908. _this.hasSymbolVisual = true;
  53909. return _this;
  53910. }
  53911. GraphSeriesModel.prototype.init = function (option) {
  53912. _super.prototype.init.apply(this, arguments);
  53913. var self = this;
  53914. function getCategoriesData() {
  53915. return self._categoriesData;
  53916. } // Provide data for legend select
  53917. this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData);
  53918. this.fillDataTextStyle(option.edges || option.links);
  53919. this._updateCategoriesData();
  53920. };
  53921. GraphSeriesModel.prototype.mergeOption = function (option) {
  53922. _super.prototype.mergeOption.apply(this, arguments);
  53923. this.fillDataTextStyle(option.edges || option.links);
  53924. this._updateCategoriesData();
  53925. };
  53926. GraphSeriesModel.prototype.mergeDefaultAndTheme = function (option) {
  53927. _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
  53928. defaultEmphasis(option, 'edgeLabel', ['show']);
  53929. };
  53930. GraphSeriesModel.prototype.getInitialData = function (option, ecModel) {
  53931. var edges = option.edges || option.links || [];
  53932. var nodes = option.data || option.nodes || [];
  53933. var self = this;
  53934. if (nodes && edges) {
  53935. // auto curveness
  53936. initCurvenessList(this);
  53937. var graph = createGraphFromNodeEdge(nodes, edges, this, true, beforeLink);
  53938. each(graph.edges, function (edge) {
  53939. createEdgeMapForCurveness(edge.node1, edge.node2, this, edge.dataIndex);
  53940. }, this);
  53941. return graph.data;
  53942. }
  53943. function beforeLink(nodeData, edgeData) {
  53944. // Overwrite nodeData.getItemModel to
  53945. nodeData.wrapMethod('getItemModel', function (model) {
  53946. var categoriesModels = self._categoriesModels;
  53947. var categoryIdx = model.getShallow('category');
  53948. var categoryModel = categoriesModels[categoryIdx];
  53949. if (categoryModel) {
  53950. categoryModel.parentModel = model.parentModel;
  53951. model.parentModel = categoryModel;
  53952. }
  53953. return model;
  53954. }); // TODO Inherit resolveParentPath by default in Model#getModel?
  53955. var oldGetModel = Model.prototype.getModel;
  53956. function newGetModel(path, parentModel) {
  53957. var model = oldGetModel.call(this, path, parentModel);
  53958. model.resolveParentPath = resolveParentPath;
  53959. return model;
  53960. }
  53961. edgeData.wrapMethod('getItemModel', function (model) {
  53962. model.resolveParentPath = resolveParentPath;
  53963. model.getModel = newGetModel;
  53964. return model;
  53965. });
  53966. function resolveParentPath(pathArr) {
  53967. if (pathArr && (pathArr[0] === 'label' || pathArr[1] === 'label')) {
  53968. var newPathArr = pathArr.slice();
  53969. if (pathArr[0] === 'label') {
  53970. newPathArr[0] = 'edgeLabel';
  53971. } else if (pathArr[1] === 'label') {
  53972. newPathArr[1] = 'edgeLabel';
  53973. }
  53974. return newPathArr;
  53975. }
  53976. return pathArr;
  53977. }
  53978. }
  53979. };
  53980. GraphSeriesModel.prototype.getGraph = function () {
  53981. return this.getData().graph;
  53982. };
  53983. GraphSeriesModel.prototype.getEdgeData = function () {
  53984. return this.getGraph().edgeData;
  53985. };
  53986. GraphSeriesModel.prototype.getCategoriesData = function () {
  53987. return this._categoriesData;
  53988. };
  53989. GraphSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  53990. if (dataType === 'edge') {
  53991. var nodeData = this.getData();
  53992. var params = this.getDataParams(dataIndex, dataType);
  53993. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  53994. var sourceName = nodeData.getName(edge.node1.dataIndex);
  53995. var targetName = nodeData.getName(edge.node2.dataIndex);
  53996. var nameArr = [];
  53997. sourceName != null && nameArr.push(sourceName);
  53998. targetName != null && nameArr.push(targetName);
  53999. return createTooltipMarkup('nameValue', {
  54000. name: nameArr.join(' > '),
  54001. value: params.value,
  54002. noValue: params.value == null
  54003. });
  54004. } // dataType === 'node' or empty
  54005. var nodeMarkup = defaultSeriesFormatTooltip({
  54006. series: this,
  54007. dataIndex: dataIndex,
  54008. multipleSeries: multipleSeries
  54009. });
  54010. return nodeMarkup;
  54011. };
  54012. GraphSeriesModel.prototype._updateCategoriesData = function () {
  54013. var categories = map(this.option.categories || [], function (category) {
  54014. // Data must has value
  54015. return category.value != null ? category : extend({
  54016. value: 0
  54017. }, category);
  54018. });
  54019. var categoriesData = new SeriesData(['value'], this);
  54020. categoriesData.initData(categories);
  54021. this._categoriesData = categoriesData;
  54022. this._categoriesModels = categoriesData.mapArray(function (idx) {
  54023. return categoriesData.getItemModel(idx);
  54024. });
  54025. };
  54026. GraphSeriesModel.prototype.setZoom = function (zoom) {
  54027. this.option.zoom = zoom;
  54028. };
  54029. GraphSeriesModel.prototype.setCenter = function (center) {
  54030. this.option.center = center;
  54031. };
  54032. GraphSeriesModel.prototype.isAnimationEnabled = function () {
  54033. return _super.prototype.isAnimationEnabled.call(this) // Not enable animation when do force layout
  54034. && !(this.get('layout') === 'force' && this.get(['force', 'layoutAnimation']));
  54035. };
  54036. GraphSeriesModel.type = 'series.graph';
  54037. GraphSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  54038. GraphSeriesModel.defaultOption = {
  54039. // zlevel: 0,
  54040. z: 2,
  54041. coordinateSystem: 'view',
  54042. // Default option for all coordinate systems
  54043. // xAxisIndex: 0,
  54044. // yAxisIndex: 0,
  54045. // polarIndex: 0,
  54046. // geoIndex: 0,
  54047. legendHoverLink: true,
  54048. layout: null,
  54049. // Configuration of circular layout
  54050. circular: {
  54051. rotateLabel: false
  54052. },
  54053. // Configuration of force directed layout
  54054. force: {
  54055. initLayout: null,
  54056. // Node repulsion. Can be an array to represent range.
  54057. repulsion: [0, 50],
  54058. gravity: 0.1,
  54059. // Initial friction
  54060. friction: 0.6,
  54061. // Edge length. Can be an array to represent range.
  54062. edgeLength: 30,
  54063. layoutAnimation: true
  54064. },
  54065. left: 'center',
  54066. top: 'center',
  54067. // right: null,
  54068. // bottom: null,
  54069. // width: '80%',
  54070. // height: '80%',
  54071. symbol: 'circle',
  54072. symbolSize: 10,
  54073. edgeSymbol: ['none', 'none'],
  54074. edgeSymbolSize: 10,
  54075. edgeLabel: {
  54076. position: 'middle',
  54077. distance: 5
  54078. },
  54079. draggable: false,
  54080. roam: false,
  54081. // Default on center of graph
  54082. center: null,
  54083. zoom: 1,
  54084. // Symbol size scale ratio in roam
  54085. nodeScaleRatio: 0.6,
  54086. // cursor: null,
  54087. // categories: [],
  54088. // data: []
  54089. // Or
  54090. // nodes: []
  54091. //
  54092. // links: []
  54093. // Or
  54094. // edges: []
  54095. label: {
  54096. show: false,
  54097. formatter: '{b}'
  54098. },
  54099. itemStyle: {},
  54100. lineStyle: {
  54101. color: '#aaa',
  54102. width: 1,
  54103. opacity: 0.5
  54104. },
  54105. emphasis: {
  54106. scale: true,
  54107. label: {
  54108. show: true
  54109. }
  54110. },
  54111. select: {
  54112. itemStyle: {
  54113. borderColor: '#212121'
  54114. }
  54115. }
  54116. };
  54117. return GraphSeriesModel;
  54118. }(SeriesModel);
  54119. var actionInfo = {
  54120. type: 'graphRoam',
  54121. event: 'graphRoam',
  54122. update: 'none'
  54123. };
  54124. function install$d(registers) {
  54125. registers.registerChartView(GraphView);
  54126. registers.registerSeriesModel(GraphSeriesModel);
  54127. registers.registerProcessor(categoryFilter);
  54128. registers.registerVisual(categoryVisual);
  54129. registers.registerVisual(graphEdgeVisual);
  54130. registers.registerLayout(graphSimpleLayout);
  54131. registers.registerLayout(registers.PRIORITY.VISUAL.POST_CHART_LAYOUT, graphCircularLayout);
  54132. registers.registerLayout(graphForceLayout);
  54133. registers.registerCoordinateSystem('graphView', {
  54134. dimensions: View.dimensions,
  54135. create: createViewCoordSys
  54136. }); // Register legacy focus actions
  54137. registers.registerAction({
  54138. type: 'focusNodeAdjacency',
  54139. event: 'focusNodeAdjacency',
  54140. update: 'series:focusNodeAdjacency'
  54141. }, noop);
  54142. registers.registerAction({
  54143. type: 'unfocusNodeAdjacency',
  54144. event: 'unfocusNodeAdjacency',
  54145. update: 'series:unfocusNodeAdjacency'
  54146. }, noop); // Register roam action.
  54147. registers.registerAction(actionInfo, function (payload, ecModel, api) {
  54148. ecModel.eachComponent({
  54149. mainType: 'series',
  54150. query: payload
  54151. }, function (seriesModel) {
  54152. var coordSys = seriesModel.coordinateSystem;
  54153. var res = updateCenterAndZoom(coordSys, payload, undefined, api);
  54154. seriesModel.setCenter && seriesModel.setCenter(res.center);
  54155. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  54156. });
  54157. });
  54158. }
  54159. var PointerShape =
  54160. /** @class */
  54161. function () {
  54162. function PointerShape() {
  54163. this.angle = 0;
  54164. this.width = 10;
  54165. this.r = 10;
  54166. this.x = 0;
  54167. this.y = 0;
  54168. }
  54169. return PointerShape;
  54170. }();
  54171. var PointerPath =
  54172. /** @class */
  54173. function (_super) {
  54174. __extends(PointerPath, _super);
  54175. function PointerPath(opts) {
  54176. var _this = _super.call(this, opts) || this;
  54177. _this.type = 'pointer';
  54178. return _this;
  54179. }
  54180. PointerPath.prototype.getDefaultShape = function () {
  54181. return new PointerShape();
  54182. };
  54183. PointerPath.prototype.buildPath = function (ctx, shape) {
  54184. var mathCos = Math.cos;
  54185. var mathSin = Math.sin;
  54186. var r = shape.r;
  54187. var width = shape.width;
  54188. var angle = shape.angle;
  54189. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  54190. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  54191. angle = shape.angle - Math.PI / 2;
  54192. ctx.moveTo(x, y);
  54193. ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width);
  54194. ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r);
  54195. ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width);
  54196. ctx.lineTo(x, y);
  54197. };
  54198. return PointerPath;
  54199. }(Path);
  54200. function parsePosition(seriesModel, api) {
  54201. var center = seriesModel.get('center');
  54202. var width = api.getWidth();
  54203. var height = api.getHeight();
  54204. var size = Math.min(width, height);
  54205. var cx = parsePercent$1(center[0], api.getWidth());
  54206. var cy = parsePercent$1(center[1], api.getHeight());
  54207. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  54208. return {
  54209. cx: cx,
  54210. cy: cy,
  54211. r: r
  54212. };
  54213. }
  54214. function formatLabel(value, labelFormatter) {
  54215. var label = value == null ? '' : value + '';
  54216. if (labelFormatter) {
  54217. if (isString(labelFormatter)) {
  54218. label = labelFormatter.replace('{value}', label);
  54219. } else if (isFunction(labelFormatter)) {
  54220. label = labelFormatter(value);
  54221. }
  54222. }
  54223. return label;
  54224. }
  54225. var GaugeView =
  54226. /** @class */
  54227. function (_super) {
  54228. __extends(GaugeView, _super);
  54229. function GaugeView() {
  54230. var _this = _super !== null && _super.apply(this, arguments) || this;
  54231. _this.type = GaugeView.type;
  54232. return _this;
  54233. }
  54234. GaugeView.prototype.render = function (seriesModel, ecModel, api) {
  54235. this.group.removeAll();
  54236. var colorList = seriesModel.get(['axisLine', 'lineStyle', 'color']);
  54237. var posInfo = parsePosition(seriesModel, api);
  54238. this._renderMain(seriesModel, ecModel, api, colorList, posInfo);
  54239. this._data = seriesModel.getData();
  54240. };
  54241. GaugeView.prototype.dispose = function () {};
  54242. GaugeView.prototype._renderMain = function (seriesModel, ecModel, api, colorList, posInfo) {
  54243. var group = this.group;
  54244. var clockwise = seriesModel.get('clockwise');
  54245. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  54246. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  54247. var axisLineModel = seriesModel.getModel('axisLine');
  54248. var roundCap = axisLineModel.get('roundCap');
  54249. var MainPath = roundCap ? SausagePath : Sector;
  54250. var showAxis = axisLineModel.get('show');
  54251. var lineStyleModel = axisLineModel.getModel('lineStyle');
  54252. var axisLineWidth = lineStyleModel.get('width');
  54253. var angles = [startAngle, endAngle];
  54254. normalizeArcAngles(angles, !clockwise);
  54255. startAngle = angles[0];
  54256. endAngle = angles[1];
  54257. var angleRangeSpan = endAngle - startAngle;
  54258. var prevEndAngle = startAngle;
  54259. var sectors = [];
  54260. for (var i = 0; showAxis && i < colorList.length; i++) {
  54261. // Clamp
  54262. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  54263. endAngle = startAngle + angleRangeSpan * percent;
  54264. var sector = new MainPath({
  54265. shape: {
  54266. startAngle: prevEndAngle,
  54267. endAngle: endAngle,
  54268. cx: posInfo.cx,
  54269. cy: posInfo.cy,
  54270. clockwise: clockwise,
  54271. r0: posInfo.r - axisLineWidth,
  54272. r: posInfo.r
  54273. },
  54274. silent: true
  54275. });
  54276. sector.setStyle({
  54277. fill: colorList[i][1]
  54278. });
  54279. sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc
  54280. // so the properties for stroking are useless
  54281. ['color', 'width']));
  54282. sectors.push(sector);
  54283. prevEndAngle = endAngle;
  54284. }
  54285. sectors.reverse();
  54286. each(sectors, function (sector) {
  54287. return group.add(sector);
  54288. });
  54289. var getColor = function (percent) {
  54290. // Less than 0
  54291. if (percent <= 0) {
  54292. return colorList[0][1];
  54293. }
  54294. var i;
  54295. for (i = 0; i < colorList.length; i++) {
  54296. if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent) {
  54297. return colorList[i][1];
  54298. }
  54299. } // More than 1
  54300. return colorList[i - 1][1];
  54301. };
  54302. this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  54303. this._renderTitleAndDetail(seriesModel, ecModel, api, getColor, posInfo);
  54304. this._renderAnchor(seriesModel, posInfo);
  54305. this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  54306. };
  54307. GaugeView.prototype._renderTicks = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  54308. var group = this.group;
  54309. var cx = posInfo.cx;
  54310. var cy = posInfo.cy;
  54311. var r = posInfo.r;
  54312. var minVal = +seriesModel.get('min');
  54313. var maxVal = +seriesModel.get('max');
  54314. var splitLineModel = seriesModel.getModel('splitLine');
  54315. var tickModel = seriesModel.getModel('axisTick');
  54316. var labelModel = seriesModel.getModel('axisLabel');
  54317. var splitNumber = seriesModel.get('splitNumber');
  54318. var subSplitNumber = tickModel.get('splitNumber');
  54319. var splitLineLen = parsePercent$1(splitLineModel.get('length'), r);
  54320. var tickLen = parsePercent$1(tickModel.get('length'), r);
  54321. var angle = startAngle;
  54322. var step = (endAngle - startAngle) / splitNumber;
  54323. var subStep = step / subSplitNumber;
  54324. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  54325. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  54326. var splitLineDistance = splitLineModel.get('distance');
  54327. var unitX;
  54328. var unitY;
  54329. for (var i = 0; i <= splitNumber; i++) {
  54330. unitX = Math.cos(angle);
  54331. unitY = Math.sin(angle); // Split line
  54332. if (splitLineModel.get('show')) {
  54333. var distance = splitLineDistance ? splitLineDistance + axisLineWidth : axisLineWidth;
  54334. var splitLine = new Line({
  54335. shape: {
  54336. x1: unitX * (r - distance) + cx,
  54337. y1: unitY * (r - distance) + cy,
  54338. x2: unitX * (r - splitLineLen - distance) + cx,
  54339. y2: unitY * (r - splitLineLen - distance) + cy
  54340. },
  54341. style: splitLineStyle,
  54342. silent: true
  54343. });
  54344. if (splitLineStyle.stroke === 'auto') {
  54345. splitLine.setStyle({
  54346. stroke: getColor(i / splitNumber)
  54347. });
  54348. }
  54349. group.add(splitLine);
  54350. } // Label
  54351. if (labelModel.get('show')) {
  54352. var distance = labelModel.get('distance') + splitLineDistance;
  54353. var label = formatLabel(round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter'));
  54354. var autoColor = getColor(i / splitNumber);
  54355. var textStyleX = unitX * (r - splitLineLen - distance) + cx;
  54356. var textStyleY = unitY * (r - splitLineLen - distance) + cy;
  54357. var rotateType = labelModel.get('rotate');
  54358. var rotate = 0;
  54359. if (rotateType === 'radial') {
  54360. rotate = -angle + 2 * Math.PI;
  54361. if (rotate > Math.PI / 2) {
  54362. rotate += Math.PI;
  54363. }
  54364. } else if (rotateType === 'tangential') {
  54365. rotate = -angle - Math.PI / 2;
  54366. } else if (isNumber(rotateType)) {
  54367. rotate = rotateType * Math.PI / 180;
  54368. }
  54369. if (rotate === 0) {
  54370. group.add(new ZRText({
  54371. style: createTextStyle(labelModel, {
  54372. text: label,
  54373. x: textStyleX,
  54374. y: textStyleY,
  54375. verticalAlign: unitY < -0.8 ? 'top' : unitY > 0.8 ? 'bottom' : 'middle',
  54376. align: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center'
  54377. }, {
  54378. inheritColor: autoColor
  54379. }),
  54380. silent: true
  54381. }));
  54382. } else {
  54383. group.add(new ZRText({
  54384. style: createTextStyle(labelModel, {
  54385. text: label,
  54386. x: textStyleX,
  54387. y: textStyleY,
  54388. verticalAlign: 'middle',
  54389. align: 'center'
  54390. }, {
  54391. inheritColor: autoColor
  54392. }),
  54393. silent: true,
  54394. originX: textStyleX,
  54395. originY: textStyleY,
  54396. rotation: rotate
  54397. }));
  54398. }
  54399. } // Axis tick
  54400. if (tickModel.get('show') && i !== splitNumber) {
  54401. var distance = tickModel.get('distance');
  54402. distance = distance ? distance + axisLineWidth : axisLineWidth;
  54403. for (var j = 0; j <= subSplitNumber; j++) {
  54404. unitX = Math.cos(angle);
  54405. unitY = Math.sin(angle);
  54406. var tickLine = new Line({
  54407. shape: {
  54408. x1: unitX * (r - distance) + cx,
  54409. y1: unitY * (r - distance) + cy,
  54410. x2: unitX * (r - tickLen - distance) + cx,
  54411. y2: unitY * (r - tickLen - distance) + cy
  54412. },
  54413. silent: true,
  54414. style: tickLineStyle
  54415. });
  54416. if (tickLineStyle.stroke === 'auto') {
  54417. tickLine.setStyle({
  54418. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  54419. });
  54420. }
  54421. group.add(tickLine);
  54422. angle += subStep;
  54423. }
  54424. angle -= subStep;
  54425. } else {
  54426. angle += step;
  54427. }
  54428. }
  54429. };
  54430. GaugeView.prototype._renderPointer = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  54431. var group = this.group;
  54432. var oldData = this._data;
  54433. var oldProgressData = this._progressEls;
  54434. var progressList = [];
  54435. var showPointer = seriesModel.get(['pointer', 'show']);
  54436. var progressModel = seriesModel.getModel('progress');
  54437. var showProgress = progressModel.get('show');
  54438. var data = seriesModel.getData();
  54439. var valueDim = data.mapDimension('value');
  54440. var minVal = +seriesModel.get('min');
  54441. var maxVal = +seriesModel.get('max');
  54442. var valueExtent = [minVal, maxVal];
  54443. var angleExtent = [startAngle, endAngle];
  54444. function createPointer(idx, angle) {
  54445. var itemModel = data.getItemModel(idx);
  54446. var pointerModel = itemModel.getModel('pointer');
  54447. var pointerWidth = parsePercent$1(pointerModel.get('width'), posInfo.r);
  54448. var pointerLength = parsePercent$1(pointerModel.get('length'), posInfo.r);
  54449. var pointerStr = seriesModel.get(['pointer', 'icon']);
  54450. var pointerOffset = pointerModel.get('offsetCenter');
  54451. var pointerOffsetX = parsePercent$1(pointerOffset[0], posInfo.r);
  54452. var pointerOffsetY = parsePercent$1(pointerOffset[1], posInfo.r);
  54453. var pointerKeepAspect = pointerModel.get('keepAspect');
  54454. var pointer; // not exist icon type will be set 'rect'
  54455. if (pointerStr) {
  54456. pointer = createSymbol(pointerStr, pointerOffsetX - pointerWidth / 2, pointerOffsetY - pointerLength, pointerWidth, pointerLength, null, pointerKeepAspect);
  54457. } else {
  54458. pointer = new PointerPath({
  54459. shape: {
  54460. angle: -Math.PI / 2,
  54461. width: pointerWidth,
  54462. r: pointerLength,
  54463. x: pointerOffsetX,
  54464. y: pointerOffsetY
  54465. }
  54466. });
  54467. }
  54468. pointer.rotation = -(angle + Math.PI / 2);
  54469. pointer.x = posInfo.cx;
  54470. pointer.y = posInfo.cy;
  54471. return pointer;
  54472. }
  54473. function createProgress(idx, endAngle) {
  54474. var roundCap = progressModel.get('roundCap');
  54475. var ProgressPath = roundCap ? SausagePath : Sector;
  54476. var isOverlap = progressModel.get('overlap');
  54477. var progressWidth = isOverlap ? progressModel.get('width') : axisLineWidth / data.count();
  54478. var r0 = isOverlap ? posInfo.r - progressWidth : posInfo.r - (idx + 1) * progressWidth;
  54479. var r = isOverlap ? posInfo.r : posInfo.r - idx * progressWidth;
  54480. var progress = new ProgressPath({
  54481. shape: {
  54482. startAngle: startAngle,
  54483. endAngle: endAngle,
  54484. cx: posInfo.cx,
  54485. cy: posInfo.cy,
  54486. clockwise: clockwise,
  54487. r0: r0,
  54488. r: r
  54489. }
  54490. });
  54491. isOverlap && (progress.z2 = maxVal - data.get(valueDim, idx) % maxVal);
  54492. return progress;
  54493. }
  54494. if (showProgress || showPointer) {
  54495. data.diff(oldData).add(function (idx) {
  54496. var val = data.get(valueDim, idx);
  54497. if (showPointer) {
  54498. var pointer = createPointer(idx, startAngle); // TODO hide pointer on NaN value?
  54499. initProps(pointer, {
  54500. rotation: -((isNaN(+val) ? angleExtent[0] : linearMap(val, valueExtent, angleExtent, true)) + Math.PI / 2)
  54501. }, seriesModel);
  54502. group.add(pointer);
  54503. data.setItemGraphicEl(idx, pointer);
  54504. }
  54505. if (showProgress) {
  54506. var progress = createProgress(idx, startAngle);
  54507. var isClip = progressModel.get('clip');
  54508. initProps(progress, {
  54509. shape: {
  54510. endAngle: linearMap(val, valueExtent, angleExtent, isClip)
  54511. }
  54512. }, seriesModel);
  54513. group.add(progress); // Add data index and series index for indexing the data by element
  54514. // Useful in tooltip
  54515. setCommonECData(seriesModel.seriesIndex, data.dataType, idx, progress);
  54516. progressList[idx] = progress;
  54517. }
  54518. }).update(function (newIdx, oldIdx) {
  54519. var val = data.get(valueDim, newIdx);
  54520. if (showPointer) {
  54521. var previousPointer = oldData.getItemGraphicEl(oldIdx);
  54522. var previousRotate = previousPointer ? previousPointer.rotation : startAngle;
  54523. var pointer = createPointer(newIdx, previousRotate);
  54524. pointer.rotation = previousRotate;
  54525. updateProps(pointer, {
  54526. rotation: -((isNaN(+val) ? angleExtent[0] : linearMap(val, valueExtent, angleExtent, true)) + Math.PI / 2)
  54527. }, seriesModel);
  54528. group.add(pointer);
  54529. data.setItemGraphicEl(newIdx, pointer);
  54530. }
  54531. if (showProgress) {
  54532. var previousProgress = oldProgressData[oldIdx];
  54533. var previousEndAngle = previousProgress ? previousProgress.shape.endAngle : startAngle;
  54534. var progress = createProgress(newIdx, previousEndAngle);
  54535. var isClip = progressModel.get('clip');
  54536. updateProps(progress, {
  54537. shape: {
  54538. endAngle: linearMap(val, valueExtent, angleExtent, isClip)
  54539. }
  54540. }, seriesModel);
  54541. group.add(progress); // Add data index and series index for indexing the data by element
  54542. // Useful in tooltip
  54543. setCommonECData(seriesModel.seriesIndex, data.dataType, newIdx, progress);
  54544. progressList[newIdx] = progress;
  54545. }
  54546. }).execute();
  54547. data.each(function (idx) {
  54548. var itemModel = data.getItemModel(idx);
  54549. var emphasisModel = itemModel.getModel('emphasis');
  54550. var focus = emphasisModel.get('focus');
  54551. var blurScope = emphasisModel.get('blurScope');
  54552. var emphasisDisabled = emphasisModel.get('disabled');
  54553. if (showPointer) {
  54554. var pointer = data.getItemGraphicEl(idx);
  54555. var symbolStyle = data.getItemVisual(idx, 'style');
  54556. var visualColor = symbolStyle.fill;
  54557. if (pointer instanceof ZRImage) {
  54558. var pathStyle = pointer.style;
  54559. pointer.useStyle(extend({
  54560. image: pathStyle.image,
  54561. x: pathStyle.x,
  54562. y: pathStyle.y,
  54563. width: pathStyle.width,
  54564. height: pathStyle.height
  54565. }, symbolStyle));
  54566. } else {
  54567. pointer.useStyle(symbolStyle);
  54568. pointer.type !== 'pointer' && pointer.setColor(visualColor);
  54569. }
  54570. pointer.setStyle(itemModel.getModel(['pointer', 'itemStyle']).getItemStyle());
  54571. if (pointer.style.fill === 'auto') {
  54572. pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)));
  54573. }
  54574. pointer.z2EmphasisLift = 0;
  54575. setStatesStylesFromModel(pointer, itemModel);
  54576. toggleHoverEmphasis(pointer, focus, blurScope, emphasisDisabled);
  54577. }
  54578. if (showProgress) {
  54579. var progress = progressList[idx];
  54580. progress.useStyle(data.getItemVisual(idx, 'style'));
  54581. progress.setStyle(itemModel.getModel(['progress', 'itemStyle']).getItemStyle());
  54582. progress.z2EmphasisLift = 0;
  54583. setStatesStylesFromModel(progress, itemModel);
  54584. toggleHoverEmphasis(progress, focus, blurScope, emphasisDisabled);
  54585. }
  54586. });
  54587. this._progressEls = progressList;
  54588. }
  54589. };
  54590. GaugeView.prototype._renderAnchor = function (seriesModel, posInfo) {
  54591. var anchorModel = seriesModel.getModel('anchor');
  54592. var showAnchor = anchorModel.get('show');
  54593. if (showAnchor) {
  54594. var anchorSize = anchorModel.get('size');
  54595. var anchorType = anchorModel.get('icon');
  54596. var offsetCenter = anchorModel.get('offsetCenter');
  54597. var anchorKeepAspect = anchorModel.get('keepAspect');
  54598. var anchor = createSymbol(anchorType, posInfo.cx - anchorSize / 2 + parsePercent$1(offsetCenter[0], posInfo.r), posInfo.cy - anchorSize / 2 + parsePercent$1(offsetCenter[1], posInfo.r), anchorSize, anchorSize, null, anchorKeepAspect);
  54599. anchor.z2 = anchorModel.get('showAbove') ? 1 : 0;
  54600. anchor.setStyle(anchorModel.getModel('itemStyle').getItemStyle());
  54601. this.group.add(anchor);
  54602. }
  54603. };
  54604. GaugeView.prototype._renderTitleAndDetail = function (seriesModel, ecModel, api, getColor, posInfo) {
  54605. var _this = this;
  54606. var data = seriesModel.getData();
  54607. var valueDim = data.mapDimension('value');
  54608. var minVal = +seriesModel.get('min');
  54609. var maxVal = +seriesModel.get('max');
  54610. var contentGroup = new Group();
  54611. var newTitleEls = [];
  54612. var newDetailEls = [];
  54613. var hasAnimation = seriesModel.isAnimationEnabled();
  54614. var showPointerAbove = seriesModel.get(['pointer', 'showAbove']);
  54615. data.diff(this._data).add(function (idx) {
  54616. newTitleEls[idx] = new ZRText({
  54617. silent: true
  54618. });
  54619. newDetailEls[idx] = new ZRText({
  54620. silent: true
  54621. });
  54622. }).update(function (idx, oldIdx) {
  54623. newTitleEls[idx] = _this._titleEls[oldIdx];
  54624. newDetailEls[idx] = _this._detailEls[oldIdx];
  54625. }).execute();
  54626. data.each(function (idx) {
  54627. var itemModel = data.getItemModel(idx);
  54628. var value = data.get(valueDim, idx);
  54629. var itemGroup = new Group();
  54630. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  54631. var itemTitleModel = itemModel.getModel('title');
  54632. if (itemTitleModel.get('show')) {
  54633. var titleOffsetCenter = itemTitleModel.get('offsetCenter');
  54634. var titleX = posInfo.cx + parsePercent$1(titleOffsetCenter[0], posInfo.r);
  54635. var titleY = posInfo.cy + parsePercent$1(titleOffsetCenter[1], posInfo.r);
  54636. var labelEl = newTitleEls[idx];
  54637. labelEl.attr({
  54638. z2: showPointerAbove ? 0 : 2,
  54639. style: createTextStyle(itemTitleModel, {
  54640. x: titleX,
  54641. y: titleY,
  54642. text: data.getName(idx),
  54643. align: 'center',
  54644. verticalAlign: 'middle'
  54645. }, {
  54646. inheritColor: autoColor
  54647. })
  54648. });
  54649. itemGroup.add(labelEl);
  54650. }
  54651. var itemDetailModel = itemModel.getModel('detail');
  54652. if (itemDetailModel.get('show')) {
  54653. var detailOffsetCenter = itemDetailModel.get('offsetCenter');
  54654. var detailX = posInfo.cx + parsePercent$1(detailOffsetCenter[0], posInfo.r);
  54655. var detailY = posInfo.cy + parsePercent$1(detailOffsetCenter[1], posInfo.r);
  54656. var width = parsePercent$1(itemDetailModel.get('width'), posInfo.r);
  54657. var height = parsePercent$1(itemDetailModel.get('height'), posInfo.r);
  54658. var detailColor = seriesModel.get(['progress', 'show']) ? data.getItemVisual(idx, 'style').fill : autoColor;
  54659. var labelEl = newDetailEls[idx];
  54660. var formatter_1 = itemDetailModel.get('formatter');
  54661. labelEl.attr({
  54662. z2: showPointerAbove ? 0 : 2,
  54663. style: createTextStyle(itemDetailModel, {
  54664. x: detailX,
  54665. y: detailY,
  54666. text: formatLabel(value, formatter_1),
  54667. width: isNaN(width) ? null : width,
  54668. height: isNaN(height) ? null : height,
  54669. align: 'center',
  54670. verticalAlign: 'middle'
  54671. }, {
  54672. inheritColor: detailColor
  54673. })
  54674. });
  54675. setLabelValueAnimation(labelEl, {
  54676. normal: itemDetailModel
  54677. }, value, function (value) {
  54678. return formatLabel(value, formatter_1);
  54679. });
  54680. hasAnimation && animateLabelValue(labelEl, idx, data, seriesModel, {
  54681. getFormattedLabel: function (labelDataIndex, status, dataType, labelDimIndex, fmt, extendParams) {
  54682. return formatLabel(extendParams ? extendParams.interpolatedValue : value, formatter_1);
  54683. }
  54684. });
  54685. itemGroup.add(labelEl);
  54686. }
  54687. contentGroup.add(itemGroup);
  54688. });
  54689. this.group.add(contentGroup);
  54690. this._titleEls = newTitleEls;
  54691. this._detailEls = newDetailEls;
  54692. };
  54693. GaugeView.type = 'gauge';
  54694. return GaugeView;
  54695. }(ChartView);
  54696. var GaugeSeriesModel =
  54697. /** @class */
  54698. function (_super) {
  54699. __extends(GaugeSeriesModel, _super);
  54700. function GaugeSeriesModel() {
  54701. var _this = _super !== null && _super.apply(this, arguments) || this;
  54702. _this.type = GaugeSeriesModel.type;
  54703. _this.visualStyleAccessPath = 'itemStyle';
  54704. return _this;
  54705. }
  54706. GaugeSeriesModel.prototype.getInitialData = function (option, ecModel) {
  54707. return createSeriesDataSimply(this, ['value']);
  54708. };
  54709. GaugeSeriesModel.type = 'series.gauge';
  54710. GaugeSeriesModel.defaultOption = {
  54711. // zlevel: 0,
  54712. z: 2,
  54713. colorBy: 'data',
  54714. // 默认全局居中
  54715. center: ['50%', '50%'],
  54716. legendHoverLink: true,
  54717. radius: '75%',
  54718. startAngle: 225,
  54719. endAngle: -45,
  54720. clockwise: true,
  54721. // 最小值
  54722. min: 0,
  54723. // 最大值
  54724. max: 100,
  54725. // 分割段数,默认为10
  54726. splitNumber: 10,
  54727. // 坐标轴线
  54728. axisLine: {
  54729. // 默认显示,属性show控制显示与否
  54730. show: true,
  54731. roundCap: false,
  54732. lineStyle: {
  54733. color: [[1, '#E6EBF8']],
  54734. width: 10
  54735. }
  54736. },
  54737. // 坐标轴线
  54738. progress: {
  54739. // 默认显示,属性show控制显示与否
  54740. show: false,
  54741. overlap: true,
  54742. width: 10,
  54743. roundCap: false,
  54744. clip: true
  54745. },
  54746. // 分隔线
  54747. splitLine: {
  54748. // 默认显示,属性show控制显示与否
  54749. show: true,
  54750. // 属性length控制线长
  54751. length: 10,
  54752. distance: 10,
  54753. // 属性lineStyle(详见lineStyle)控制线条样式
  54754. lineStyle: {
  54755. color: '#63677A',
  54756. width: 3,
  54757. type: 'solid'
  54758. }
  54759. },
  54760. // 坐标轴小标记
  54761. axisTick: {
  54762. // 属性show控制显示与否,默认不显示
  54763. show: true,
  54764. // 每份split细分多少段
  54765. splitNumber: 5,
  54766. // 属性length控制线长
  54767. length: 6,
  54768. distance: 10,
  54769. // 属性lineStyle控制线条样式
  54770. lineStyle: {
  54771. color: '#63677A',
  54772. width: 1,
  54773. type: 'solid'
  54774. }
  54775. },
  54776. axisLabel: {
  54777. show: true,
  54778. distance: 15,
  54779. // formatter: null,
  54780. color: '#464646',
  54781. fontSize: 12,
  54782. rotate: 0
  54783. },
  54784. pointer: {
  54785. icon: null,
  54786. offsetCenter: [0, 0],
  54787. show: true,
  54788. showAbove: true,
  54789. length: '60%',
  54790. width: 6,
  54791. keepAspect: false
  54792. },
  54793. anchor: {
  54794. show: false,
  54795. showAbove: false,
  54796. size: 6,
  54797. icon: 'circle',
  54798. offsetCenter: [0, 0],
  54799. keepAspect: false,
  54800. itemStyle: {
  54801. color: '#fff',
  54802. borderWidth: 0,
  54803. borderColor: '#5470c6'
  54804. }
  54805. },
  54806. title: {
  54807. show: true,
  54808. // x, y,单位px
  54809. offsetCenter: [0, '20%'],
  54810. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  54811. color: '#464646',
  54812. fontSize: 16,
  54813. valueAnimation: false
  54814. },
  54815. detail: {
  54816. show: true,
  54817. backgroundColor: 'rgba(0,0,0,0)',
  54818. borderWidth: 0,
  54819. borderColor: '#ccc',
  54820. width: 100,
  54821. height: null,
  54822. padding: [5, 10],
  54823. // x, y,单位px
  54824. offsetCenter: [0, '40%'],
  54825. // formatter: null,
  54826. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  54827. color: '#464646',
  54828. fontSize: 30,
  54829. fontWeight: 'bold',
  54830. lineHeight: 30,
  54831. valueAnimation: false
  54832. }
  54833. };
  54834. return GaugeSeriesModel;
  54835. }(SeriesModel);
  54836. function install$e(registers) {
  54837. registers.registerChartView(GaugeView);
  54838. registers.registerSeriesModel(GaugeSeriesModel);
  54839. }
  54840. var opacityAccessPath = ['itemStyle', 'opacity'];
  54841. /**
  54842. * Piece of pie including Sector, Label, LabelLine
  54843. */
  54844. var FunnelPiece =
  54845. /** @class */
  54846. function (_super) {
  54847. __extends(FunnelPiece, _super);
  54848. function FunnelPiece(data, idx) {
  54849. var _this = _super.call(this) || this;
  54850. var polygon = _this;
  54851. var labelLine = new Polyline();
  54852. var text = new ZRText();
  54853. polygon.setTextContent(text);
  54854. _this.setTextGuideLine(labelLine);
  54855. _this.updateData(data, idx, true);
  54856. return _this;
  54857. }
  54858. FunnelPiece.prototype.updateData = function (data, idx, firstCreate) {
  54859. var polygon = this;
  54860. var seriesModel = data.hostModel;
  54861. var itemModel = data.getItemModel(idx);
  54862. var layout = data.getItemLayout(idx);
  54863. var emphasisModel = itemModel.getModel('emphasis');
  54864. var opacity = itemModel.get(opacityAccessPath);
  54865. opacity = opacity == null ? 1 : opacity;
  54866. if (!firstCreate) {
  54867. saveOldStyle(polygon);
  54868. } // Update common style
  54869. polygon.useStyle(data.getItemVisual(idx, 'style'));
  54870. polygon.style.lineJoin = 'round';
  54871. if (firstCreate) {
  54872. polygon.setShape({
  54873. points: layout.points
  54874. });
  54875. polygon.style.opacity = 0;
  54876. initProps(polygon, {
  54877. style: {
  54878. opacity: opacity
  54879. }
  54880. }, seriesModel, idx);
  54881. } else {
  54882. updateProps(polygon, {
  54883. style: {
  54884. opacity: opacity
  54885. },
  54886. shape: {
  54887. points: layout.points
  54888. }
  54889. }, seriesModel, idx);
  54890. }
  54891. setStatesStylesFromModel(polygon, itemModel);
  54892. this._updateLabel(data, idx);
  54893. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  54894. };
  54895. FunnelPiece.prototype._updateLabel = function (data, idx) {
  54896. var polygon = this;
  54897. var labelLine = this.getTextGuideLine();
  54898. var labelText = polygon.getTextContent();
  54899. var seriesModel = data.hostModel;
  54900. var itemModel = data.getItemModel(idx);
  54901. var layout = data.getItemLayout(idx);
  54902. var labelLayout = layout.label;
  54903. var style = data.getItemVisual(idx, 'style');
  54904. var visualColor = style.fill;
  54905. setLabelStyle( // position will not be used in setLabelStyle
  54906. labelText, getLabelStatesModels(itemModel), {
  54907. labelFetcher: data.hostModel,
  54908. labelDataIndex: idx,
  54909. defaultOpacity: style.opacity,
  54910. defaultText: data.getName(idx)
  54911. }, {
  54912. normal: {
  54913. align: labelLayout.textAlign,
  54914. verticalAlign: labelLayout.verticalAlign
  54915. }
  54916. });
  54917. polygon.setTextConfig({
  54918. local: true,
  54919. inside: !!labelLayout.inside,
  54920. insideStroke: visualColor,
  54921. // insideFill: 'auto',
  54922. outsideFill: visualColor
  54923. });
  54924. var linePoints = labelLayout.linePoints;
  54925. labelLine.setShape({
  54926. points: linePoints
  54927. });
  54928. polygon.textGuideLineConfig = {
  54929. anchor: linePoints ? new Point(linePoints[0][0], linePoints[0][1]) : null
  54930. }; // Make sure update style on labelText after setLabelStyle.
  54931. // Because setLabelStyle will replace a new style on it.
  54932. updateProps(labelText, {
  54933. style: {
  54934. x: labelLayout.x,
  54935. y: labelLayout.y
  54936. }
  54937. }, seriesModel, idx);
  54938. labelText.attr({
  54939. rotation: labelLayout.rotation,
  54940. originX: labelLayout.x,
  54941. originY: labelLayout.y,
  54942. z2: 10
  54943. });
  54944. setLabelLineStyle(polygon, getLabelLineStatesModels(itemModel), {
  54945. // Default use item visual color
  54946. stroke: visualColor
  54947. });
  54948. };
  54949. return FunnelPiece;
  54950. }(Polygon);
  54951. var FunnelView =
  54952. /** @class */
  54953. function (_super) {
  54954. __extends(FunnelView, _super);
  54955. function FunnelView() {
  54956. var _this = _super !== null && _super.apply(this, arguments) || this;
  54957. _this.type = FunnelView.type;
  54958. _this.ignoreLabelLineUpdate = true;
  54959. return _this;
  54960. }
  54961. FunnelView.prototype.render = function (seriesModel, ecModel, api) {
  54962. var data = seriesModel.getData();
  54963. var oldData = this._data;
  54964. var group = this.group;
  54965. data.diff(oldData).add(function (idx) {
  54966. var funnelPiece = new FunnelPiece(data, idx);
  54967. data.setItemGraphicEl(idx, funnelPiece);
  54968. group.add(funnelPiece);
  54969. }).update(function (newIdx, oldIdx) {
  54970. var piece = oldData.getItemGraphicEl(oldIdx);
  54971. piece.updateData(data, newIdx);
  54972. group.add(piece);
  54973. data.setItemGraphicEl(newIdx, piece);
  54974. }).remove(function (idx) {
  54975. var piece = oldData.getItemGraphicEl(idx);
  54976. removeElementWithFadeOut(piece, seriesModel, idx);
  54977. }).execute();
  54978. this._data = data;
  54979. };
  54980. FunnelView.prototype.remove = function () {
  54981. this.group.removeAll();
  54982. this._data = null;
  54983. };
  54984. FunnelView.prototype.dispose = function () {};
  54985. FunnelView.type = 'funnel';
  54986. return FunnelView;
  54987. }(ChartView);
  54988. var FunnelSeriesModel =
  54989. /** @class */
  54990. function (_super) {
  54991. __extends(FunnelSeriesModel, _super);
  54992. function FunnelSeriesModel() {
  54993. var _this = _super !== null && _super.apply(this, arguments) || this;
  54994. _this.type = FunnelSeriesModel.type;
  54995. return _this;
  54996. }
  54997. FunnelSeriesModel.prototype.init = function (option) {
  54998. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  54999. // Use a function instead of direct access because data reference may changed
  55000. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); // Extend labelLine emphasis
  55001. this._defaultLabelLine(option);
  55002. };
  55003. FunnelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  55004. return createSeriesDataSimply(this, {
  55005. coordDimensions: ['value'],
  55006. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  55007. });
  55008. };
  55009. FunnelSeriesModel.prototype._defaultLabelLine = function (option) {
  55010. // Extend labelLine emphasis
  55011. defaultEmphasis(option, 'labelLine', ['show']);
  55012. var labelLineNormalOpt = option.labelLine;
  55013. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  55014. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  55015. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  55016. }; // Overwrite
  55017. FunnelSeriesModel.prototype.getDataParams = function (dataIndex) {
  55018. var data = this.getData();
  55019. var params = _super.prototype.getDataParams.call(this, dataIndex);
  55020. var valueDim = data.mapDimension('value');
  55021. var sum = data.getSum(valueDim); // Percent is 0 if sum is 0
  55022. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  55023. params.$vars.push('percent');
  55024. return params;
  55025. };
  55026. FunnelSeriesModel.type = 'series.funnel';
  55027. FunnelSeriesModel.defaultOption = {
  55028. // zlevel: 0, // 一级层叠
  55029. z: 2,
  55030. legendHoverLink: true,
  55031. colorBy: 'data',
  55032. left: 80,
  55033. top: 60,
  55034. right: 80,
  55035. bottom: 60,
  55036. // width: {totalWidth} - left - right,
  55037. // height: {totalHeight} - top - bottom,
  55038. // 默认取数据最小最大值
  55039. // min: 0,
  55040. // max: 100,
  55041. minSize: '0%',
  55042. maxSize: '100%',
  55043. sort: 'descending',
  55044. orient: 'vertical',
  55045. gap: 0,
  55046. funnelAlign: 'center',
  55047. label: {
  55048. show: true,
  55049. position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  55050. },
  55051. labelLine: {
  55052. show: true,
  55053. length: 20,
  55054. lineStyle: {
  55055. // color: 各异,
  55056. width: 1
  55057. }
  55058. },
  55059. itemStyle: {
  55060. // color: 各异,
  55061. borderColor: '#fff',
  55062. borderWidth: 1
  55063. },
  55064. emphasis: {
  55065. label: {
  55066. show: true
  55067. }
  55068. },
  55069. select: {
  55070. itemStyle: {
  55071. borderColor: '#212121'
  55072. }
  55073. }
  55074. };
  55075. return FunnelSeriesModel;
  55076. }(SeriesModel);
  55077. function getViewRect$3(seriesModel, api) {
  55078. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  55079. width: api.getWidth(),
  55080. height: api.getHeight()
  55081. });
  55082. }
  55083. function getSortedIndices(data, sort) {
  55084. var valueDim = data.mapDimension('value');
  55085. var valueArr = data.mapArray(valueDim, function (val) {
  55086. return val;
  55087. });
  55088. var indices = [];
  55089. var isAscending = sort === 'ascending';
  55090. for (var i = 0, len = data.count(); i < len; i++) {
  55091. indices[i] = i;
  55092. } // Add custom sortable function & none sortable opetion by "options.sort"
  55093. if (isFunction(sort)) {
  55094. indices.sort(sort);
  55095. } else if (sort !== 'none') {
  55096. indices.sort(function (a, b) {
  55097. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  55098. });
  55099. }
  55100. return indices;
  55101. }
  55102. function labelLayout(data) {
  55103. var seriesModel = data.hostModel;
  55104. var orient = seriesModel.get('orient');
  55105. data.each(function (idx) {
  55106. var itemModel = data.getItemModel(idx);
  55107. var labelModel = itemModel.getModel('label');
  55108. var labelPosition = labelModel.get('position');
  55109. var labelLineModel = itemModel.getModel('labelLine');
  55110. var layout = data.getItemLayout(idx);
  55111. var points = layout.points;
  55112. var isLabelInside = labelPosition === 'inner' || labelPosition === 'inside' || labelPosition === 'center' || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  55113. var textAlign;
  55114. var textX;
  55115. var textY;
  55116. var linePoints;
  55117. if (isLabelInside) {
  55118. if (labelPosition === 'insideLeft') {
  55119. textX = (points[0][0] + points[3][0]) / 2 + 5;
  55120. textY = (points[0][1] + points[3][1]) / 2;
  55121. textAlign = 'left';
  55122. } else if (labelPosition === 'insideRight') {
  55123. textX = (points[1][0] + points[2][0]) / 2 - 5;
  55124. textY = (points[1][1] + points[2][1]) / 2;
  55125. textAlign = 'right';
  55126. } else {
  55127. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  55128. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  55129. textAlign = 'center';
  55130. }
  55131. linePoints = [[textX, textY], [textX, textY]];
  55132. } else {
  55133. var x1 = void 0;
  55134. var y1 = void 0;
  55135. var x2 = void 0;
  55136. var y2 = void 0;
  55137. var labelLineLen = labelLineModel.get('length');
  55138. if ("development" !== 'production') {
  55139. if (orient === 'vertical' && ['top', 'bottom'].indexOf(labelPosition) > -1) {
  55140. labelPosition = 'left';
  55141. console.warn('Position error: Funnel chart on vertical orient dose not support top and bottom.');
  55142. }
  55143. if (orient === 'horizontal' && ['left', 'right'].indexOf(labelPosition) > -1) {
  55144. labelPosition = 'bottom';
  55145. console.warn('Position error: Funnel chart on horizontal orient dose not support left and right.');
  55146. }
  55147. }
  55148. if (labelPosition === 'left') {
  55149. // Left side
  55150. x1 = (points[3][0] + points[0][0]) / 2;
  55151. y1 = (points[3][1] + points[0][1]) / 2;
  55152. x2 = x1 - labelLineLen;
  55153. textX = x2 - 5;
  55154. textAlign = 'right';
  55155. } else if (labelPosition === 'right') {
  55156. // Right side
  55157. x1 = (points[1][0] + points[2][0]) / 2;
  55158. y1 = (points[1][1] + points[2][1]) / 2;
  55159. x2 = x1 + labelLineLen;
  55160. textX = x2 + 5;
  55161. textAlign = 'left';
  55162. } else if (labelPosition === 'top') {
  55163. // Top side
  55164. x1 = (points[3][0] + points[0][0]) / 2;
  55165. y1 = (points[3][1] + points[0][1]) / 2;
  55166. y2 = y1 - labelLineLen;
  55167. textY = y2 - 5;
  55168. textAlign = 'center';
  55169. } else if (labelPosition === 'bottom') {
  55170. // Bottom side
  55171. x1 = (points[1][0] + points[2][0]) / 2;
  55172. y1 = (points[1][1] + points[2][1]) / 2;
  55173. y2 = y1 + labelLineLen;
  55174. textY = y2 + 5;
  55175. textAlign = 'center';
  55176. } else if (labelPosition === 'rightTop') {
  55177. // RightTop side
  55178. x1 = orient === 'horizontal' ? points[3][0] : points[1][0];
  55179. y1 = orient === 'horizontal' ? points[3][1] : points[1][1];
  55180. if (orient === 'horizontal') {
  55181. y2 = y1 - labelLineLen;
  55182. textY = y2 - 5;
  55183. textAlign = 'center';
  55184. } else {
  55185. x2 = x1 + labelLineLen;
  55186. textX = x2 + 5;
  55187. textAlign = 'top';
  55188. }
  55189. } else if (labelPosition === 'rightBottom') {
  55190. // RightBottom side
  55191. x1 = points[2][0];
  55192. y1 = points[2][1];
  55193. if (orient === 'horizontal') {
  55194. y2 = y1 + labelLineLen;
  55195. textY = y2 + 5;
  55196. textAlign = 'center';
  55197. } else {
  55198. x2 = x1 + labelLineLen;
  55199. textX = x2 + 5;
  55200. textAlign = 'bottom';
  55201. }
  55202. } else if (labelPosition === 'leftTop') {
  55203. // LeftTop side
  55204. x1 = points[0][0];
  55205. y1 = orient === 'horizontal' ? points[0][1] : points[1][1];
  55206. if (orient === 'horizontal') {
  55207. y2 = y1 - labelLineLen;
  55208. textY = y2 - 5;
  55209. textAlign = 'center';
  55210. } else {
  55211. x2 = x1 - labelLineLen;
  55212. textX = x2 - 5;
  55213. textAlign = 'right';
  55214. }
  55215. } else if (labelPosition === 'leftBottom') {
  55216. // LeftBottom side
  55217. x1 = orient === 'horizontal' ? points[1][0] : points[3][0];
  55218. y1 = orient === 'horizontal' ? points[1][1] : points[2][1];
  55219. if (orient === 'horizontal') {
  55220. y2 = y1 + labelLineLen;
  55221. textY = y2 + 5;
  55222. textAlign = 'center';
  55223. } else {
  55224. x2 = x1 - labelLineLen;
  55225. textX = x2 - 5;
  55226. textAlign = 'right';
  55227. }
  55228. } else {
  55229. // Right side or Bottom side
  55230. x1 = (points[1][0] + points[2][0]) / 2;
  55231. y1 = (points[1][1] + points[2][1]) / 2;
  55232. if (orient === 'horizontal') {
  55233. y2 = y1 + labelLineLen;
  55234. textY = y2 + 5;
  55235. textAlign = 'center';
  55236. } else {
  55237. x2 = x1 + labelLineLen;
  55238. textX = x2 + 5;
  55239. textAlign = 'left';
  55240. }
  55241. }
  55242. if (orient === 'horizontal') {
  55243. x2 = x1;
  55244. textX = x2;
  55245. } else {
  55246. y2 = y1;
  55247. textY = y2;
  55248. }
  55249. linePoints = [[x1, y1], [x2, y2]];
  55250. }
  55251. layout.label = {
  55252. linePoints: linePoints,
  55253. x: textX,
  55254. y: textY,
  55255. verticalAlign: 'middle',
  55256. textAlign: textAlign,
  55257. inside: isLabelInside
  55258. };
  55259. });
  55260. }
  55261. function funnelLayout(ecModel, api) {
  55262. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  55263. var data = seriesModel.getData();
  55264. var valueDim = data.mapDimension('value');
  55265. var sort = seriesModel.get('sort');
  55266. var viewRect = getViewRect$3(seriesModel, api);
  55267. var orient = seriesModel.get('orient');
  55268. var viewWidth = viewRect.width;
  55269. var viewHeight = viewRect.height;
  55270. var indices = getSortedIndices(data, sort);
  55271. var x = viewRect.x;
  55272. var y = viewRect.y;
  55273. var sizeExtent = orient === 'horizontal' ? [parsePercent$1(seriesModel.get('minSize'), viewHeight), parsePercent$1(seriesModel.get('maxSize'), viewHeight)] : [parsePercent$1(seriesModel.get('minSize'), viewWidth), parsePercent$1(seriesModel.get('maxSize'), viewWidth)];
  55274. var dataExtent = data.getDataExtent(valueDim);
  55275. var min = seriesModel.get('min');
  55276. var max = seriesModel.get('max');
  55277. if (min == null) {
  55278. min = Math.min(dataExtent[0], 0);
  55279. }
  55280. if (max == null) {
  55281. max = dataExtent[1];
  55282. }
  55283. var funnelAlign = seriesModel.get('funnelAlign');
  55284. var gap = seriesModel.get('gap');
  55285. var viewSize = orient === 'horizontal' ? viewWidth : viewHeight;
  55286. var itemSize = (viewSize - gap * (data.count() - 1)) / data.count();
  55287. var getLinePoints = function (idx, offset) {
  55288. // End point index is data.count() and we assign it 0
  55289. if (orient === 'horizontal') {
  55290. var val_1 = data.get(valueDim, idx) || 0;
  55291. var itemHeight = linearMap(val_1, [min, max], sizeExtent, true);
  55292. var y0 = void 0;
  55293. switch (funnelAlign) {
  55294. case 'top':
  55295. y0 = y;
  55296. break;
  55297. case 'center':
  55298. y0 = y + (viewHeight - itemHeight) / 2;
  55299. break;
  55300. case 'bottom':
  55301. y0 = y + (viewHeight - itemHeight);
  55302. break;
  55303. }
  55304. return [[offset, y0], [offset, y0 + itemHeight]];
  55305. }
  55306. var val = data.get(valueDim, idx) || 0;
  55307. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  55308. var x0;
  55309. switch (funnelAlign) {
  55310. case 'left':
  55311. x0 = x;
  55312. break;
  55313. case 'center':
  55314. x0 = x + (viewWidth - itemWidth) / 2;
  55315. break;
  55316. case 'right':
  55317. x0 = x + viewWidth - itemWidth;
  55318. break;
  55319. }
  55320. return [[x0, offset], [x0 + itemWidth, offset]];
  55321. };
  55322. if (sort === 'ascending') {
  55323. // From bottom to top
  55324. itemSize = -itemSize;
  55325. gap = -gap;
  55326. if (orient === 'horizontal') {
  55327. x += viewWidth;
  55328. } else {
  55329. y += viewHeight;
  55330. }
  55331. indices = indices.reverse();
  55332. }
  55333. for (var i = 0; i < indices.length; i++) {
  55334. var idx = indices[i];
  55335. var nextIdx = indices[i + 1];
  55336. var itemModel = data.getItemModel(idx);
  55337. if (orient === 'horizontal') {
  55338. var width = itemModel.get(['itemStyle', 'width']);
  55339. if (width == null) {
  55340. width = itemSize;
  55341. } else {
  55342. width = parsePercent$1(width, viewWidth);
  55343. if (sort === 'ascending') {
  55344. width = -width;
  55345. }
  55346. }
  55347. var start = getLinePoints(idx, x);
  55348. var end = getLinePoints(nextIdx, x + width);
  55349. x += width + gap;
  55350. data.setItemLayout(idx, {
  55351. points: start.concat(end.slice().reverse())
  55352. });
  55353. } else {
  55354. var height = itemModel.get(['itemStyle', 'height']);
  55355. if (height == null) {
  55356. height = itemSize;
  55357. } else {
  55358. height = parsePercent$1(height, viewHeight);
  55359. if (sort === 'ascending') {
  55360. height = -height;
  55361. }
  55362. }
  55363. var start = getLinePoints(idx, y);
  55364. var end = getLinePoints(nextIdx, y + height);
  55365. y += height + gap;
  55366. data.setItemLayout(idx, {
  55367. points: start.concat(end.slice().reverse())
  55368. });
  55369. }
  55370. }
  55371. labelLayout(data);
  55372. });
  55373. }
  55374. function install$f(registers) {
  55375. registers.registerChartView(FunnelView);
  55376. registers.registerSeriesModel(FunnelSeriesModel);
  55377. registers.registerLayout(funnelLayout);
  55378. registers.registerProcessor(dataFilter('funnel'));
  55379. }
  55380. var DEFAULT_SMOOTH = 0.3;
  55381. var ParallelView =
  55382. /** @class */
  55383. function (_super) {
  55384. __extends(ParallelView, _super);
  55385. function ParallelView() {
  55386. var _this = _super !== null && _super.apply(this, arguments) || this;
  55387. _this.type = ParallelView.type;
  55388. _this._dataGroup = new Group();
  55389. _this._initialized = false;
  55390. return _this;
  55391. }
  55392. ParallelView.prototype.init = function () {
  55393. this.group.add(this._dataGroup);
  55394. };
  55395. /**
  55396. * @override
  55397. */
  55398. ParallelView.prototype.render = function (seriesModel, ecModel, api, payload) {
  55399. // Clear previously rendered progressive elements.
  55400. this._progressiveEls = null;
  55401. var dataGroup = this._dataGroup;
  55402. var data = seriesModel.getData();
  55403. var oldData = this._data;
  55404. var coordSys = seriesModel.coordinateSystem;
  55405. var dimensions = coordSys.dimensions;
  55406. var seriesScope = makeSeriesScope$2(seriesModel);
  55407. data.diff(oldData).add(add).update(update).remove(remove).execute();
  55408. function add(newDataIndex) {
  55409. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  55410. updateElCommon(line, data, newDataIndex, seriesScope);
  55411. }
  55412. function update(newDataIndex, oldDataIndex) {
  55413. var line = oldData.getItemGraphicEl(oldDataIndex);
  55414. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  55415. data.setItemGraphicEl(newDataIndex, line);
  55416. updateProps(line, {
  55417. shape: {
  55418. points: points
  55419. }
  55420. }, seriesModel, newDataIndex);
  55421. saveOldStyle(line);
  55422. updateElCommon(line, data, newDataIndex, seriesScope);
  55423. }
  55424. function remove(oldDataIndex) {
  55425. var line = oldData.getItemGraphicEl(oldDataIndex);
  55426. dataGroup.remove(line);
  55427. } // First create
  55428. if (!this._initialized) {
  55429. this._initialized = true;
  55430. var clipPath = createGridClipShape(coordSys, seriesModel, function () {
  55431. // Callback will be invoked immediately if there is no animation
  55432. setTimeout(function () {
  55433. dataGroup.removeClipPath();
  55434. });
  55435. });
  55436. dataGroup.setClipPath(clipPath);
  55437. }
  55438. this._data = data;
  55439. };
  55440. ParallelView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  55441. this._initialized = true;
  55442. this._data = null;
  55443. this._dataGroup.removeAll();
  55444. };
  55445. ParallelView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  55446. var data = seriesModel.getData();
  55447. var coordSys = seriesModel.coordinateSystem;
  55448. var dimensions = coordSys.dimensions;
  55449. var seriesScope = makeSeriesScope$2(seriesModel);
  55450. var progressiveEls = this._progressiveEls = [];
  55451. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  55452. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  55453. line.incremental = true;
  55454. updateElCommon(line, data, dataIndex, seriesScope);
  55455. progressiveEls.push(line);
  55456. }
  55457. };
  55458. ParallelView.prototype.remove = function () {
  55459. this._dataGroup && this._dataGroup.removeAll();
  55460. this._data = null;
  55461. };
  55462. ParallelView.type = 'parallel';
  55463. return ParallelView;
  55464. }(ChartView);
  55465. function createGridClipShape(coordSys, seriesModel, cb) {
  55466. var parallelModel = coordSys.model;
  55467. var rect = coordSys.getRect();
  55468. var rectEl = new Rect({
  55469. shape: {
  55470. x: rect.x,
  55471. y: rect.y,
  55472. width: rect.width,
  55473. height: rect.height
  55474. }
  55475. });
  55476. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  55477. rectEl.setShape(dim, 0);
  55478. initProps(rectEl, {
  55479. shape: {
  55480. width: rect.width,
  55481. height: rect.height
  55482. }
  55483. }, seriesModel, cb);
  55484. return rectEl;
  55485. }
  55486. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  55487. var points = [];
  55488. for (var i = 0; i < dimensions.length; i++) {
  55489. var dimName = dimensions[i];
  55490. var value = data.get(data.mapDimension(dimName), dataIndex);
  55491. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  55492. points.push(coordSys.dataToPoint(value, dimName));
  55493. }
  55494. }
  55495. return points;
  55496. }
  55497. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  55498. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  55499. var line = new Polyline({
  55500. shape: {
  55501. points: points
  55502. },
  55503. // silent: true,
  55504. z2: 10
  55505. });
  55506. dataGroup.add(line);
  55507. data.setItemGraphicEl(dataIndex, line);
  55508. return line;
  55509. }
  55510. function makeSeriesScope$2(seriesModel) {
  55511. var smooth = seriesModel.get('smooth', true);
  55512. smooth === true && (smooth = DEFAULT_SMOOTH);
  55513. smooth = numericToNumber(smooth);
  55514. eqNaN(smooth) && (smooth = 0);
  55515. return {
  55516. smooth: smooth
  55517. };
  55518. }
  55519. function updateElCommon(el, data, dataIndex, seriesScope) {
  55520. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  55521. el.style.fill = null;
  55522. el.setShape('smooth', seriesScope.smooth);
  55523. var itemModel = data.getItemModel(dataIndex);
  55524. var emphasisModel = itemModel.getModel('emphasis');
  55525. setStatesStylesFromModel(el, itemModel, 'lineStyle');
  55526. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  55527. } // function simpleDiff(oldData, newData, dimensions) {
  55528. // let oldLen;
  55529. // if (!oldData
  55530. // || !oldData.__plProgressive
  55531. // || (oldLen = oldData.count()) !== newData.count()
  55532. // ) {
  55533. // return true;
  55534. // }
  55535. // let dimLen = dimensions.length;
  55536. // for (let i = 0; i < oldLen; i++) {
  55537. // for (let j = 0; j < dimLen; j++) {
  55538. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  55539. // return true;
  55540. // }
  55541. // }
  55542. // }
  55543. // return false;
  55544. // }
  55545. // FIXME put in common util?
  55546. function isEmptyValue(val, axisType) {
  55547. return axisType === 'category' ? val == null : val == null || isNaN(val); // axisType === 'value'
  55548. }
  55549. var ParallelSeriesModel =
  55550. /** @class */
  55551. function (_super) {
  55552. __extends(ParallelSeriesModel, _super);
  55553. function ParallelSeriesModel() {
  55554. var _this = _super !== null && _super.apply(this, arguments) || this;
  55555. _this.type = ParallelSeriesModel.type;
  55556. _this.visualStyleAccessPath = 'lineStyle';
  55557. _this.visualDrawType = 'stroke';
  55558. return _this;
  55559. }
  55560. ParallelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  55561. return createSeriesData(null, this, {
  55562. useEncodeDefaulter: bind(makeDefaultEncode, null, this)
  55563. });
  55564. };
  55565. /**
  55566. * User can get data raw indices on 'axisAreaSelected' event received.
  55567. *
  55568. * @return Raw indices
  55569. */
  55570. ParallelSeriesModel.prototype.getRawIndicesByActiveState = function (activeState) {
  55571. var coordSys = this.coordinateSystem;
  55572. var data = this.getData();
  55573. var indices = [];
  55574. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  55575. if (activeState === theActiveState) {
  55576. indices.push(data.getRawIndex(dataIndex));
  55577. }
  55578. });
  55579. return indices;
  55580. };
  55581. ParallelSeriesModel.type = 'series.parallel';
  55582. ParallelSeriesModel.dependencies = ['parallel'];
  55583. ParallelSeriesModel.defaultOption = {
  55584. // zlevel: 0,
  55585. z: 2,
  55586. coordinateSystem: 'parallel',
  55587. parallelIndex: 0,
  55588. label: {
  55589. show: false
  55590. },
  55591. inactiveOpacity: 0.05,
  55592. activeOpacity: 1,
  55593. lineStyle: {
  55594. width: 1,
  55595. opacity: 0.45,
  55596. type: 'solid'
  55597. },
  55598. emphasis: {
  55599. label: {
  55600. show: false
  55601. }
  55602. },
  55603. progressive: 500,
  55604. smooth: false,
  55605. animationEasing: 'linear'
  55606. };
  55607. return ParallelSeriesModel;
  55608. }(SeriesModel);
  55609. function makeDefaultEncode(seriesModel) {
  55610. // The mapping of parallelAxis dimension to data dimension can
  55611. // be specified in parallelAxis.option.dim. For example, if
  55612. // parallelAxis.option.dim is 'dim3', it mapping to the third
  55613. // dimension of data. But `data.encode` has higher priority.
  55614. // Moreover, parallelModel.dimension should not be regarded as data
  55615. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  55616. var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  55617. if (!parallelModel) {
  55618. return;
  55619. }
  55620. var encodeDefine = {};
  55621. each(parallelModel.dimensions, function (axisDim) {
  55622. var dataDimIndex = convertDimNameToNumber(axisDim);
  55623. encodeDefine[axisDim] = dataDimIndex;
  55624. });
  55625. return encodeDefine;
  55626. }
  55627. function convertDimNameToNumber(dimName) {
  55628. return +dimName.replace('dim', '');
  55629. }
  55630. /*
  55631. * Licensed to the Apache Software Foundation (ASF) under one
  55632. * or more contributor license agreements. See the NOTICE file
  55633. * distributed with this work for additional information
  55634. * regarding copyright ownership. The ASF licenses this file
  55635. * to you under the Apache License, Version 2.0 (the
  55636. * "License"); you may not use this file except in compliance
  55637. * with the License. You may obtain a copy of the License at
  55638. *
  55639. * http://www.apache.org/licenses/LICENSE-2.0
  55640. *
  55641. * Unless required by applicable law or agreed to in writing,
  55642. * software distributed under the License is distributed on an
  55643. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55644. * KIND, either express or implied. See the License for the
  55645. * specific language governing permissions and limitations
  55646. * under the License.
  55647. */
  55648. /**
  55649. * AUTO-GENERATED FILE. DO NOT MODIFY.
  55650. */
  55651. /*
  55652. * Licensed to the Apache Software Foundation (ASF) under one
  55653. * or more contributor license agreements. See the NOTICE file
  55654. * distributed with this work for additional information
  55655. * regarding copyright ownership. The ASF licenses this file
  55656. * to you under the Apache License, Version 2.0 (the
  55657. * "License"); you may not use this file except in compliance
  55658. * with the License. You may obtain a copy of the License at
  55659. *
  55660. * http://www.apache.org/licenses/LICENSE-2.0
  55661. *
  55662. * Unless required by applicable law or agreed to in writing,
  55663. * software distributed under the License is distributed on an
  55664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55665. * KIND, either express or implied. See the License for the
  55666. * specific language governing permissions and limitations
  55667. * under the License.
  55668. */
  55669. var opacityAccessPath$1 = ['lineStyle', 'opacity'];
  55670. var parallelVisual = {
  55671. seriesType: 'parallel',
  55672. reset: function (seriesModel, ecModel) {
  55673. var coordSys = seriesModel.coordinateSystem;
  55674. var opacityMap = {
  55675. normal: seriesModel.get(['lineStyle', 'opacity']),
  55676. active: seriesModel.get('activeOpacity'),
  55677. inactive: seriesModel.get('inactiveOpacity')
  55678. };
  55679. return {
  55680. progress: function (params, data) {
  55681. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  55682. var opacity = opacityMap[activeState];
  55683. if (activeState === 'normal' && data.hasItemOption) {
  55684. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  55685. itemOpacity != null && (opacity = itemOpacity);
  55686. }
  55687. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  55688. existsStyle.opacity = opacity;
  55689. }, params.start, params.end);
  55690. }
  55691. };
  55692. }
  55693. };
  55694. function parallelPreprocessor(option) {
  55695. createParallelIfNeeded(option);
  55696. mergeAxisOptionFromParallel(option);
  55697. }
  55698. /**
  55699. * Create a parallel coordinate if not exists.
  55700. * @inner
  55701. */
  55702. function createParallelIfNeeded(option) {
  55703. if (option.parallel) {
  55704. return;
  55705. }
  55706. var hasParallelSeries = false;
  55707. each(option.series, function (seriesOpt) {
  55708. if (seriesOpt && seriesOpt.type === 'parallel') {
  55709. hasParallelSeries = true;
  55710. }
  55711. });
  55712. if (hasParallelSeries) {
  55713. option.parallel = [{}];
  55714. }
  55715. }
  55716. /**
  55717. * Merge aixs definition from parallel option (if exists) to axis option.
  55718. * @inner
  55719. */
  55720. function mergeAxisOptionFromParallel(option) {
  55721. var axes = normalizeToArray(option.parallelAxis);
  55722. each(axes, function (axisOption) {
  55723. if (!isObject(axisOption)) {
  55724. return;
  55725. }
  55726. var parallelIndex = axisOption.parallelIndex || 0;
  55727. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  55728. if (parallelOption && parallelOption.parallelAxisDefault) {
  55729. merge(axisOption, parallelOption.parallelAxisDefault, false);
  55730. }
  55731. });
  55732. }
  55733. var CLICK_THRESHOLD = 5; // > 4
  55734. var ParallelView$1 =
  55735. /** @class */
  55736. function (_super) {
  55737. __extends(ParallelView, _super);
  55738. function ParallelView() {
  55739. var _this = _super !== null && _super.apply(this, arguments) || this;
  55740. _this.type = ParallelView.type;
  55741. return _this;
  55742. }
  55743. ParallelView.prototype.render = function (parallelModel, ecModel, api) {
  55744. this._model = parallelModel;
  55745. this._api = api;
  55746. if (!this._handlers) {
  55747. this._handlers = {};
  55748. each(handlers, function (handler, eventName) {
  55749. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  55750. }, this);
  55751. }
  55752. createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate');
  55753. };
  55754. ParallelView.prototype.dispose = function (ecModel, api) {
  55755. clear(this, '_throttledDispatchExpand');
  55756. each(this._handlers, function (handler, eventName) {
  55757. api.getZr().off(eventName, handler);
  55758. });
  55759. this._handlers = null;
  55760. };
  55761. /**
  55762. * @internal
  55763. * @param {Object} [opt] If null, cancel the last action triggering for debounce.
  55764. */
  55765. ParallelView.prototype._throttledDispatchExpand = function (opt) {
  55766. this._dispatchExpand(opt);
  55767. };
  55768. /**
  55769. * @internal
  55770. */
  55771. ParallelView.prototype._dispatchExpand = function (opt) {
  55772. opt && this._api.dispatchAction(extend({
  55773. type: 'parallelAxisExpand'
  55774. }, opt));
  55775. };
  55776. ParallelView.type = 'parallel';
  55777. return ParallelView;
  55778. }(ComponentView);
  55779. var handlers = {
  55780. mousedown: function (e) {
  55781. if (checkTrigger(this, 'click')) {
  55782. this._mouseDownPoint = [e.offsetX, e.offsetY];
  55783. }
  55784. },
  55785. mouseup: function (e) {
  55786. var mouseDownPoint = this._mouseDownPoint;
  55787. if (checkTrigger(this, 'click') && mouseDownPoint) {
  55788. var point = [e.offsetX, e.offsetY];
  55789. var dist = Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2);
  55790. if (dist > CLICK_THRESHOLD) {
  55791. return;
  55792. }
  55793. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  55794. result.behavior !== 'none' && this._dispatchExpand({
  55795. axisExpandWindow: result.axisExpandWindow
  55796. });
  55797. }
  55798. this._mouseDownPoint = null;
  55799. },
  55800. mousemove: function (e) {
  55801. // Should do nothing when brushing.
  55802. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  55803. return;
  55804. }
  55805. var model = this._model;
  55806. var result = model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  55807. var behavior = result.behavior;
  55808. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  55809. this._throttledDispatchExpand(behavior === 'none' ? null // Cancel the last trigger, in case that mouse slide out of the area quickly.
  55810. : {
  55811. axisExpandWindow: result.axisExpandWindow,
  55812. // Jumping uses animation, and sliding suppresses animation.
  55813. animation: behavior === 'jump' ? null : {
  55814. duration: 0 // Disable animation.
  55815. }
  55816. });
  55817. }
  55818. };
  55819. function checkTrigger(view, triggerOn) {
  55820. var model = view._model;
  55821. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  55822. }
  55823. var ParallelModel =
  55824. /** @class */
  55825. function (_super) {
  55826. __extends(ParallelModel, _super);
  55827. function ParallelModel() {
  55828. var _this = _super !== null && _super.apply(this, arguments) || this;
  55829. _this.type = ParallelModel.type;
  55830. return _this;
  55831. }
  55832. ParallelModel.prototype.init = function () {
  55833. _super.prototype.init.apply(this, arguments);
  55834. this.mergeOption({});
  55835. };
  55836. ParallelModel.prototype.mergeOption = function (newOption) {
  55837. var thisOption = this.option;
  55838. newOption && merge(thisOption, newOption, true);
  55839. this._initDimensions();
  55840. };
  55841. /**
  55842. * Whether series or axis is in this coordinate system.
  55843. */
  55844. ParallelModel.prototype.contains = function (model, ecModel) {
  55845. var parallelIndex = model.get('parallelIndex');
  55846. return parallelIndex != null && ecModel.getComponent('parallel', parallelIndex) === this;
  55847. };
  55848. ParallelModel.prototype.setAxisExpand = function (opt) {
  55849. each(['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'], function (name) {
  55850. if (opt.hasOwnProperty(name)) {
  55851. // @ts-ignore FIXME: why "never" inferred in this.option[name]?
  55852. this.option[name] = opt[name];
  55853. }
  55854. }, this);
  55855. };
  55856. ParallelModel.prototype._initDimensions = function () {
  55857. var dimensions = this.dimensions = [];
  55858. var parallelAxisIndex = this.parallelAxisIndex = [];
  55859. var axisModels = filter(this.ecModel.queryComponents({
  55860. mainType: 'parallelAxis'
  55861. }), function (axisModel) {
  55862. // Can not use this.contains here, because
  55863. // initialization has not been completed yet.
  55864. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  55865. }, this);
  55866. each(axisModels, function (axisModel) {
  55867. dimensions.push('dim' + axisModel.get('dim'));
  55868. parallelAxisIndex.push(axisModel.componentIndex);
  55869. });
  55870. };
  55871. ParallelModel.type = 'parallel';
  55872. ParallelModel.dependencies = ['parallelAxis'];
  55873. ParallelModel.layoutMode = 'box';
  55874. ParallelModel.defaultOption = {
  55875. // zlevel: 0,
  55876. z: 0,
  55877. left: 80,
  55878. top: 60,
  55879. right: 80,
  55880. bottom: 60,
  55881. // width: {totalWidth} - left - right,
  55882. // height: {totalHeight} - top - bottom,
  55883. layout: 'horizontal',
  55884. // FIXME
  55885. // naming?
  55886. axisExpandable: false,
  55887. axisExpandCenter: null,
  55888. axisExpandCount: 0,
  55889. axisExpandWidth: 50,
  55890. axisExpandRate: 17,
  55891. axisExpandDebounce: 50,
  55892. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  55893. // Do not doc to user until necessary.
  55894. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  55895. axisExpandTriggerOn: 'click',
  55896. parallelAxisDefault: null
  55897. };
  55898. return ParallelModel;
  55899. }(ComponentModel);
  55900. var ParallelAxis =
  55901. /** @class */
  55902. function (_super) {
  55903. __extends(ParallelAxis, _super);
  55904. function ParallelAxis(dim, scale, coordExtent, axisType, axisIndex) {
  55905. var _this = _super.call(this, dim, scale, coordExtent) || this;
  55906. _this.type = axisType || 'value';
  55907. _this.axisIndex = axisIndex;
  55908. return _this;
  55909. }
  55910. ParallelAxis.prototype.isHorizontal = function () {
  55911. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  55912. };
  55913. return ParallelAxis;
  55914. }(Axis);
  55915. /*
  55916. * Licensed to the Apache Software Foundation (ASF) under one
  55917. * or more contributor license agreements. See the NOTICE file
  55918. * distributed with this work for additional information
  55919. * regarding copyright ownership. The ASF licenses this file
  55920. * to you under the Apache License, Version 2.0 (the
  55921. * "License"); you may not use this file except in compliance
  55922. * with the License. You may obtain a copy of the License at
  55923. *
  55924. * http://www.apache.org/licenses/LICENSE-2.0
  55925. *
  55926. * Unless required by applicable law or agreed to in writing,
  55927. * software distributed under the License is distributed on an
  55928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55929. * KIND, either express or implied. See the License for the
  55930. * specific language governing permissions and limitations
  55931. * under the License.
  55932. */
  55933. /**
  55934. * AUTO-GENERATED FILE. DO NOT MODIFY.
  55935. */
  55936. /*
  55937. * Licensed to the Apache Software Foundation (ASF) under one
  55938. * or more contributor license agreements. See the NOTICE file
  55939. * distributed with this work for additional information
  55940. * regarding copyright ownership. The ASF licenses this file
  55941. * to you under the Apache License, Version 2.0 (the
  55942. * "License"); you may not use this file except in compliance
  55943. * with the License. You may obtain a copy of the License at
  55944. *
  55945. * http://www.apache.org/licenses/LICENSE-2.0
  55946. *
  55947. * Unless required by applicable law or agreed to in writing,
  55948. * software distributed under the License is distributed on an
  55949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55950. * KIND, either express or implied. See the License for the
  55951. * specific language governing permissions and limitations
  55952. * under the License.
  55953. */
  55954. /**
  55955. * Calculate slider move result.
  55956. * Usage:
  55957. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  55958. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  55959. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  55960. *
  55961. * @param delta Move length.
  55962. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  55963. * handleEnds will be modified in this method.
  55964. * @param extent handleEnds is restricted by extent.
  55965. * extent[0] should less or equals than extent[1].
  55966. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  55967. * @param minSpan The range of dataZoom can not be smaller than that.
  55968. * If not set, handle0 and cross handle1. If set as a non-negative
  55969. * number (including `0`), handles will push each other when reaching
  55970. * the minSpan.
  55971. * @param maxSpan The range of dataZoom can not be larger than that.
  55972. * @return The input handleEnds.
  55973. */
  55974. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  55975. delta = delta || 0;
  55976. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  55977. if (minSpan != null) {
  55978. minSpan = restrict(minSpan, [0, extentSpan]);
  55979. }
  55980. if (maxSpan != null) {
  55981. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  55982. }
  55983. if (handleIndex === 'all') {
  55984. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  55985. handleSpan = restrict(handleSpan, [0, extentSpan]);
  55986. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  55987. handleIndex = 0;
  55988. }
  55989. handleEnds[0] = restrict(handleEnds[0], extent);
  55990. handleEnds[1] = restrict(handleEnds[1], extent);
  55991. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  55992. handleEnds[handleIndex] += delta; // Restrict in extent.
  55993. var extentMinSpan = minSpan || 0;
  55994. var realExtent = extent.slice();
  55995. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  55996. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  55997. var currDistSign;
  55998. currDistSign = getSpanSign(handleEnds, handleIndex);
  55999. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  56000. // If minSpan exists, 'cross' is forbidden.
  56001. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  56002. } // Shrink span.
  56003. currDistSign = getSpanSign(handleEnds, handleIndex);
  56004. if (maxSpan != null && currDistSign.span > maxSpan) {
  56005. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  56006. }
  56007. return handleEnds;
  56008. }
  56009. function getSpanSign(handleEnds, handleIndex) {
  56010. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  56011. // is at left of handleEnds[1] for non-cross case.
  56012. return {
  56013. span: Math.abs(dist),
  56014. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  56015. };
  56016. }
  56017. function restrict(value, extend) {
  56018. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  56019. }
  56020. var each$5 = each;
  56021. var mathMin$8 = Math.min;
  56022. var mathMax$8 = Math.max;
  56023. var mathFloor$1 = Math.floor;
  56024. var mathCeil$1 = Math.ceil;
  56025. var round$3 = round;
  56026. var PI$7 = Math.PI;
  56027. var Parallel =
  56028. /** @class */
  56029. function () {
  56030. function Parallel(parallelModel, ecModel, api) {
  56031. this.type = 'parallel';
  56032. /**
  56033. * key: dimension
  56034. */
  56035. this._axesMap = createHashMap();
  56036. /**
  56037. * key: dimension
  56038. * value: {position: [], rotation, }
  56039. */
  56040. this._axesLayout = {};
  56041. this.dimensions = parallelModel.dimensions;
  56042. this._model = parallelModel;
  56043. this._init(parallelModel, ecModel, api);
  56044. }
  56045. Parallel.prototype._init = function (parallelModel, ecModel, api) {
  56046. var dimensions = parallelModel.dimensions;
  56047. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  56048. each$5(dimensions, function (dim, idx) {
  56049. var axisIndex = parallelAxisIndex[idx];
  56050. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  56051. var axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisIndex));
  56052. var isCategory = axis.type === 'category';
  56053. axis.onBand = isCategory && axisModel.get('boundaryGap');
  56054. axis.inverse = axisModel.get('inverse'); // Injection
  56055. axisModel.axis = axis;
  56056. axis.model = axisModel;
  56057. axis.coordinateSystem = axisModel.coordinateSystem = this;
  56058. }, this);
  56059. };
  56060. /**
  56061. * Update axis scale after data processed
  56062. */
  56063. Parallel.prototype.update = function (ecModel, api) {
  56064. this._updateAxesFromSeries(this._model, ecModel);
  56065. };
  56066. Parallel.prototype.containPoint = function (point) {
  56067. var layoutInfo = this._makeLayoutInfo();
  56068. var axisBase = layoutInfo.axisBase;
  56069. var layoutBase = layoutInfo.layoutBase;
  56070. var pixelDimIndex = layoutInfo.pixelDimIndex;
  56071. var pAxis = point[1 - pixelDimIndex];
  56072. var pLayout = point[pixelDimIndex];
  56073. return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength;
  56074. };
  56075. Parallel.prototype.getModel = function () {
  56076. return this._model;
  56077. };
  56078. /**
  56079. * Update properties from series
  56080. */
  56081. Parallel.prototype._updateAxesFromSeries = function (parallelModel, ecModel) {
  56082. ecModel.eachSeries(function (seriesModel) {
  56083. if (!parallelModel.contains(seriesModel, ecModel)) {
  56084. return;
  56085. }
  56086. var data = seriesModel.getData();
  56087. each$5(this.dimensions, function (dim) {
  56088. var axis = this._axesMap.get(dim);
  56089. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  56090. niceScaleExtent(axis.scale, axis.model);
  56091. }, this);
  56092. }, this);
  56093. };
  56094. /**
  56095. * Resize the parallel coordinate system.
  56096. */
  56097. Parallel.prototype.resize = function (parallelModel, api) {
  56098. this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), {
  56099. width: api.getWidth(),
  56100. height: api.getHeight()
  56101. });
  56102. this._layoutAxes();
  56103. };
  56104. Parallel.prototype.getRect = function () {
  56105. return this._rect;
  56106. };
  56107. Parallel.prototype._makeLayoutInfo = function () {
  56108. var parallelModel = this._model;
  56109. var rect = this._rect;
  56110. var xy = ['x', 'y'];
  56111. var wh = ['width', 'height'];
  56112. var layout = parallelModel.get('layout');
  56113. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  56114. var layoutLength = rect[wh[pixelDimIndex]];
  56115. var layoutExtent = [0, layoutLength];
  56116. var axisCount = this.dimensions.length;
  56117. var axisExpandWidth = restrict$1(parallelModel.get('axisExpandWidth'), layoutExtent);
  56118. var axisExpandCount = restrict$1(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  56119. var axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0; // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  56120. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  56121. // where collapsed axes should be overlapped.
  56122. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  56123. var winSize;
  56124. if (!axisExpandWindow) {
  56125. winSize = restrict$1(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  56126. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$1(axisCount / 2);
  56127. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  56128. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  56129. } else {
  56130. winSize = restrict$1(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  56131. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  56132. }
  56133. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); // Avoid axisCollapseWidth is too small.
  56134. axisCollapseWidth < 3 && (axisCollapseWidth = 0); // Find the first and last indices > ewin[0] and < ewin[1].
  56135. var winInnerIndices = [mathFloor$1(round$3(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$1(round$3(axisExpandWindow[1] / axisExpandWidth, 1)) - 1]; // Pos in ec coordinates.
  56136. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  56137. return {
  56138. layout: layout,
  56139. pixelDimIndex: pixelDimIndex,
  56140. layoutBase: rect[xy[pixelDimIndex]],
  56141. layoutLength: layoutLength,
  56142. axisBase: rect[xy[1 - pixelDimIndex]],
  56143. axisLength: rect[wh[1 - pixelDimIndex]],
  56144. axisExpandable: axisExpandable,
  56145. axisExpandWidth: axisExpandWidth,
  56146. axisCollapseWidth: axisCollapseWidth,
  56147. axisExpandWindow: axisExpandWindow,
  56148. axisCount: axisCount,
  56149. winInnerIndices: winInnerIndices,
  56150. axisExpandWindow0Pos: axisExpandWindow0Pos
  56151. };
  56152. };
  56153. Parallel.prototype._layoutAxes = function () {
  56154. var rect = this._rect;
  56155. var axes = this._axesMap;
  56156. var dimensions = this.dimensions;
  56157. var layoutInfo = this._makeLayoutInfo();
  56158. var layout = layoutInfo.layout;
  56159. axes.each(function (axis) {
  56160. var axisExtent = [0, layoutInfo.axisLength];
  56161. var idx = axis.inverse ? 1 : 0;
  56162. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  56163. });
  56164. each$5(dimensions, function (dim, idx) {
  56165. var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo);
  56166. var positionTable = {
  56167. horizontal: {
  56168. x: posInfo.position,
  56169. y: layoutInfo.axisLength
  56170. },
  56171. vertical: {
  56172. x: 0,
  56173. y: posInfo.position
  56174. }
  56175. };
  56176. var rotationTable = {
  56177. horizontal: PI$7 / 2,
  56178. vertical: 0
  56179. };
  56180. var position = [positionTable[layout].x + rect.x, positionTable[layout].y + rect.y];
  56181. var rotation = rotationTable[layout];
  56182. var transform = create$1();
  56183. rotate(transform, transform, rotation);
  56184. translate(transform, transform, position); // TODO
  56185. // tick layout info
  56186. // TODO
  56187. // update dimensions info based on axis order.
  56188. this._axesLayout[dim] = {
  56189. position: position,
  56190. rotation: rotation,
  56191. transform: transform,
  56192. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  56193. axisLabelShow: posInfo.axisLabelShow,
  56194. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  56195. tickDirection: 1,
  56196. labelDirection: 1
  56197. };
  56198. }, this);
  56199. };
  56200. /**
  56201. * Get axis by dim.
  56202. */
  56203. Parallel.prototype.getAxis = function (dim) {
  56204. return this._axesMap.get(dim);
  56205. };
  56206. /**
  56207. * Convert a dim value of a single item of series data to Point.
  56208. */
  56209. Parallel.prototype.dataToPoint = function (value, dim) {
  56210. return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim);
  56211. };
  56212. /**
  56213. * Travel data for one time, get activeState of each data item.
  56214. * @param start the start dataIndex that travel from.
  56215. * @param end the next dataIndex of the last dataIndex will be travel.
  56216. */
  56217. Parallel.prototype.eachActiveState = function (data, callback, start, end) {
  56218. start == null && (start = 0);
  56219. end == null && (end = data.count());
  56220. var axesMap = this._axesMap;
  56221. var dimensions = this.dimensions;
  56222. var dataDimensions = [];
  56223. var axisModels = [];
  56224. each(dimensions, function (axisDim) {
  56225. dataDimensions.push(data.mapDimension(axisDim));
  56226. axisModels.push(axesMap.get(axisDim).model);
  56227. });
  56228. var hasActiveSet = this.hasAxisBrushed();
  56229. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  56230. var activeState = void 0;
  56231. if (!hasActiveSet) {
  56232. activeState = 'normal';
  56233. } else {
  56234. activeState = 'active';
  56235. var values = data.getValues(dataDimensions, dataIndex);
  56236. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  56237. var state = axisModels[j].getActiveState(values[j]);
  56238. if (state === 'inactive') {
  56239. activeState = 'inactive';
  56240. break;
  56241. }
  56242. }
  56243. }
  56244. callback(activeState, dataIndex);
  56245. }
  56246. };
  56247. /**
  56248. * Whether has any activeSet.
  56249. */
  56250. Parallel.prototype.hasAxisBrushed = function () {
  56251. var dimensions = this.dimensions;
  56252. var axesMap = this._axesMap;
  56253. var hasActiveSet = false;
  56254. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  56255. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  56256. hasActiveSet = true;
  56257. }
  56258. }
  56259. return hasActiveSet;
  56260. };
  56261. /**
  56262. * Convert coords of each axis to Point.
  56263. * Return point. For example: [10, 20]
  56264. */
  56265. Parallel.prototype.axisCoordToPoint = function (coord, dim) {
  56266. var axisLayout = this._axesLayout[dim];
  56267. return applyTransform$1([coord, 0], axisLayout.transform);
  56268. };
  56269. /**
  56270. * Get axis layout.
  56271. */
  56272. Parallel.prototype.getAxisLayout = function (dim) {
  56273. return clone(this._axesLayout[dim]);
  56274. };
  56275. /**
  56276. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  56277. */
  56278. Parallel.prototype.getSlidedAxisExpandWindow = function (point) {
  56279. var layoutInfo = this._makeLayoutInfo();
  56280. var pixelDimIndex = layoutInfo.pixelDimIndex;
  56281. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  56282. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  56283. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)]; // Out of the area of coordinate system.
  56284. if (!this.containPoint(point)) {
  56285. return {
  56286. behavior: 'none',
  56287. axisExpandWindow: axisExpandWindow
  56288. };
  56289. } // Convert the point from global to expand coordinates.
  56290. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos; // For dragging operation convenience, the window should not be
  56291. // slided when mouse is the center area of the window.
  56292. var delta;
  56293. var behavior = 'slide';
  56294. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  56295. var triggerArea = this._model.get('axisExpandSlideTriggerArea'); // But consider touch device, jump is necessary.
  56296. var useJump = triggerArea[0] != null;
  56297. if (axisCollapseWidth) {
  56298. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  56299. behavior = 'jump';
  56300. delta = pointCoord - winSize * triggerArea[2];
  56301. } else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  56302. behavior = 'jump';
  56303. delta = pointCoord - winSize * (1 - triggerArea[2]);
  56304. } else {
  56305. (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0);
  56306. }
  56307. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  56308. delta ? sliderMove(delta, axisExpandWindow, extent, 'all') // Avoid nonsense triger on mousemove.
  56309. : behavior = 'none';
  56310. } // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  56311. else {
  56312. var winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
  56313. var pos = extent[1] * pointCoord / winSize2;
  56314. axisExpandWindow = [mathMax$8(0, pos - winSize2 / 2)];
  56315. axisExpandWindow[1] = mathMin$8(extent[1], axisExpandWindow[0] + winSize2);
  56316. axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
  56317. }
  56318. return {
  56319. axisExpandWindow: axisExpandWindow,
  56320. behavior: behavior
  56321. };
  56322. };
  56323. return Parallel;
  56324. }();
  56325. function restrict$1(len, extent) {
  56326. return mathMin$8(mathMax$8(len, extent[0]), extent[1]);
  56327. }
  56328. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  56329. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  56330. return {
  56331. position: step * axisIndex,
  56332. axisNameAvailableWidth: step,
  56333. axisLabelShow: true
  56334. };
  56335. }
  56336. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  56337. var layoutLength = layoutInfo.layoutLength;
  56338. var axisExpandWidth = layoutInfo.axisExpandWidth;
  56339. var axisCount = layoutInfo.axisCount;
  56340. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  56341. var winInnerIndices = layoutInfo.winInnerIndices;
  56342. var position;
  56343. var axisNameAvailableWidth = axisCollapseWidth;
  56344. var axisLabelShow = false;
  56345. var nameTruncateMaxWidth;
  56346. if (axisIndex < winInnerIndices[0]) {
  56347. position = axisIndex * axisCollapseWidth;
  56348. nameTruncateMaxWidth = axisCollapseWidth;
  56349. } else if (axisIndex <= winInnerIndices[1]) {
  56350. position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  56351. axisNameAvailableWidth = axisExpandWidth;
  56352. axisLabelShow = true;
  56353. } else {
  56354. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  56355. nameTruncateMaxWidth = axisCollapseWidth;
  56356. }
  56357. return {
  56358. position: position,
  56359. axisNameAvailableWidth: axisNameAvailableWidth,
  56360. axisLabelShow: axisLabelShow,
  56361. nameTruncateMaxWidth: nameTruncateMaxWidth
  56362. };
  56363. }
  56364. function createParallelCoordSys(ecModel, api) {
  56365. var coordSysList = [];
  56366. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  56367. var coordSys = new Parallel(parallelModel, ecModel, api);
  56368. coordSys.name = 'parallel_' + idx;
  56369. coordSys.resize(parallelModel, api);
  56370. parallelModel.coordinateSystem = coordSys;
  56371. coordSys.model = parallelModel;
  56372. coordSysList.push(coordSys);
  56373. }); // Inject the coordinateSystems into seriesModel
  56374. ecModel.eachSeries(function (seriesModel) {
  56375. if (seriesModel.get('coordinateSystem') === 'parallel') {
  56376. var parallelModel = seriesModel.getReferringComponents('parallel', SINGLE_REFERRING).models[0];
  56377. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  56378. }
  56379. });
  56380. return coordSysList;
  56381. }
  56382. var parallelCoordSysCreator = {
  56383. create: createParallelCoordSys
  56384. };
  56385. var ParallelAxisModel =
  56386. /** @class */
  56387. function (_super) {
  56388. __extends(ParallelAxisModel, _super);
  56389. function ParallelAxisModel() {
  56390. var _this = _super !== null && _super.apply(this, arguments) || this;
  56391. _this.type = ParallelAxisModel.type;
  56392. /**
  56393. * @readOnly
  56394. */
  56395. _this.activeIntervals = [];
  56396. return _this;
  56397. }
  56398. ParallelAxisModel.prototype.getAreaSelectStyle = function () {
  56399. return makeStyleMapper([['fill', 'color'], ['lineWidth', 'borderWidth'], ['stroke', 'borderColor'], ['width', 'width'], ['opacity', 'opacity'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  56400. // So do not transfer decal directly.
  56401. ])(this.getModel('areaSelectStyle'));
  56402. };
  56403. /**
  56404. * The code of this feature is put on AxisModel but not ParallelAxis,
  56405. * because axisModel can be alive after echarts updating but instance of
  56406. * ParallelAxis having been disposed. this._activeInterval should be kept
  56407. * when action dispatched (i.e. legend click).
  56408. *
  56409. * @param intervals `interval.length === 0` means set all active.
  56410. */
  56411. ParallelAxisModel.prototype.setActiveIntervals = function (intervals) {
  56412. var activeIntervals = this.activeIntervals = clone(intervals); // Normalize
  56413. if (activeIntervals) {
  56414. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  56415. asc(activeIntervals[i]);
  56416. }
  56417. }
  56418. };
  56419. /**
  56420. * @param value When only attempting detect whether 'no activeIntervals set',
  56421. * `value` is not needed to be input.
  56422. */
  56423. ParallelAxisModel.prototype.getActiveState = function (value) {
  56424. var activeIntervals = this.activeIntervals;
  56425. if (!activeIntervals.length) {
  56426. return 'normal';
  56427. }
  56428. if (value == null || isNaN(+value)) {
  56429. return 'inactive';
  56430. } // Simple optimization
  56431. if (activeIntervals.length === 1) {
  56432. var interval = activeIntervals[0];
  56433. if (interval[0] <= value && value <= interval[1]) {
  56434. return 'active';
  56435. }
  56436. } else {
  56437. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  56438. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  56439. return 'active';
  56440. }
  56441. }
  56442. }
  56443. return 'inactive';
  56444. };
  56445. return ParallelAxisModel;
  56446. }(ComponentModel);
  56447. mixin(ParallelAxisModel, AxisModelCommonMixin);
  56448. var BRUSH_PANEL_GLOBAL = true;
  56449. var mathMin$9 = Math.min;
  56450. var mathMax$9 = Math.max;
  56451. var mathPow$2 = Math.pow;
  56452. var COVER_Z = 10000;
  56453. var UNSELECT_THRESHOLD = 6;
  56454. var MIN_RESIZE_LINE_WIDTH = 6;
  56455. var MUTEX_RESOURCE_KEY = 'globalPan';
  56456. var DIRECTION_MAP = {
  56457. w: [0, 0],
  56458. e: [0, 1],
  56459. n: [1, 0],
  56460. s: [1, 1]
  56461. };
  56462. var CURSOR_MAP = {
  56463. w: 'ew',
  56464. e: 'ew',
  56465. n: 'ns',
  56466. s: 'ns',
  56467. ne: 'nesw',
  56468. sw: 'nesw',
  56469. nw: 'nwse',
  56470. se: 'nwse'
  56471. };
  56472. var DEFAULT_BRUSH_OPT = {
  56473. brushStyle: {
  56474. lineWidth: 2,
  56475. stroke: 'rgba(210,219,238,0.3)',
  56476. fill: '#D2DBEE'
  56477. },
  56478. transformable: true,
  56479. brushMode: 'single',
  56480. removeOnClick: false
  56481. };
  56482. var baseUID = 0;
  56483. /**
  56484. * params:
  56485. * areas: Array.<Array>, coord relates to container group,
  56486. * If no container specified, to global.
  56487. * opt {
  56488. * isEnd: boolean,
  56489. * removeOnClick: boolean
  56490. * }
  56491. */
  56492. var BrushController =
  56493. /** @class */
  56494. function (_super) {
  56495. __extends(BrushController, _super);
  56496. function BrushController(zr) {
  56497. var _this = _super.call(this) || this;
  56498. /**
  56499. * @internal
  56500. */
  56501. _this._track = [];
  56502. /**
  56503. * @internal
  56504. */
  56505. _this._covers = [];
  56506. _this._handlers = {};
  56507. if ("development" !== 'production') {
  56508. assert(zr);
  56509. }
  56510. _this._zr = zr;
  56511. _this.group = new Group();
  56512. _this._uid = 'brushController_' + baseUID++;
  56513. each(pointerHandlers, function (handler, eventName) {
  56514. this._handlers[eventName] = bind(handler, this);
  56515. }, _this);
  56516. return _this;
  56517. }
  56518. /**
  56519. * If set to `false`, select disabled.
  56520. */
  56521. BrushController.prototype.enableBrush = function (brushOption) {
  56522. if ("development" !== 'production') {
  56523. assert(this._mounted);
  56524. }
  56525. this._brushType && this._doDisableBrush();
  56526. brushOption.brushType && this._doEnableBrush(brushOption);
  56527. return this;
  56528. };
  56529. BrushController.prototype._doEnableBrush = function (brushOption) {
  56530. var zr = this._zr; // Consider roam, which takes globalPan too.
  56531. if (!this._enableGlobalPan) {
  56532. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  56533. }
  56534. each(this._handlers, function (handler, eventName) {
  56535. zr.on(eventName, handler);
  56536. });
  56537. this._brushType = brushOption.brushType;
  56538. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  56539. };
  56540. BrushController.prototype._doDisableBrush = function () {
  56541. var zr = this._zr;
  56542. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  56543. each(this._handlers, function (handler, eventName) {
  56544. zr.off(eventName, handler);
  56545. });
  56546. this._brushType = this._brushOption = null;
  56547. };
  56548. /**
  56549. * @param panelOpts If not pass, it is global brush.
  56550. */
  56551. BrushController.prototype.setPanels = function (panelOpts) {
  56552. if (panelOpts && panelOpts.length) {
  56553. var panels_1 = this._panels = {};
  56554. each(panelOpts, function (panelOpts) {
  56555. panels_1[panelOpts.panelId] = clone(panelOpts);
  56556. });
  56557. } else {
  56558. this._panels = null;
  56559. }
  56560. return this;
  56561. };
  56562. BrushController.prototype.mount = function (opt) {
  56563. opt = opt || {};
  56564. if ("development" !== 'production') {
  56565. this._mounted = true; // should be at first.
  56566. }
  56567. this._enableGlobalPan = opt.enableGlobalPan;
  56568. var thisGroup = this.group;
  56569. this._zr.add(thisGroup);
  56570. thisGroup.attr({
  56571. x: opt.x || 0,
  56572. y: opt.y || 0,
  56573. rotation: opt.rotation || 0,
  56574. scaleX: opt.scaleX || 1,
  56575. scaleY: opt.scaleY || 1
  56576. });
  56577. this._transform = thisGroup.getLocalTransform();
  56578. return this;
  56579. }; // eachCover(cb, context): void {
  56580. // each(this._covers, cb, context);
  56581. // }
  56582. /**
  56583. * Update covers.
  56584. * @param coverConfigList
  56585. * If coverConfigList is null/undefined, all covers removed.
  56586. */
  56587. BrushController.prototype.updateCovers = function (coverConfigList) {
  56588. if ("development" !== 'production') {
  56589. assert(this._mounted);
  56590. }
  56591. coverConfigList = map(coverConfigList, function (coverConfig) {
  56592. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  56593. });
  56594. var tmpIdPrefix = '\0-brush-index-';
  56595. var oldCovers = this._covers;
  56596. var newCovers = this._covers = [];
  56597. var controller = this;
  56598. var creatingCover = this._creatingCover;
  56599. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  56600. return this;
  56601. function getKey(brushOption, index) {
  56602. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  56603. }
  56604. function oldGetKey(cover, index) {
  56605. return getKey(cover.__brushOption, index);
  56606. }
  56607. function addOrUpdate(newIndex, oldIndex) {
  56608. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  56609. // where updating cover when creating should be forbidden.
  56610. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  56611. newCovers[newIndex] = oldCovers[oldIndex];
  56612. } else {
  56613. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  56614. updateCoverAfterCreation(controller, cover);
  56615. }
  56616. }
  56617. function remove(oldIndex) {
  56618. if (oldCovers[oldIndex] !== creatingCover) {
  56619. controller.group.remove(oldCovers[oldIndex]);
  56620. }
  56621. }
  56622. };
  56623. BrushController.prototype.unmount = function () {
  56624. if ("development" !== 'production') {
  56625. if (!this._mounted) {
  56626. return;
  56627. }
  56628. }
  56629. this.enableBrush(false); // container may 'removeAll' outside.
  56630. clearCovers(this);
  56631. this._zr.remove(this.group);
  56632. if ("development" !== 'production') {
  56633. this._mounted = false; // should be at last.
  56634. }
  56635. return this;
  56636. };
  56637. BrushController.prototype.dispose = function () {
  56638. this.unmount();
  56639. this.off();
  56640. };
  56641. return BrushController;
  56642. }(Eventful);
  56643. function createCover(controller, brushOption) {
  56644. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  56645. cover.__brushOption = brushOption;
  56646. updateZ(cover, brushOption);
  56647. controller.group.add(cover);
  56648. return cover;
  56649. }
  56650. function endCreating(controller, creatingCover) {
  56651. var coverRenderer = getCoverRenderer(creatingCover);
  56652. if (coverRenderer.endCreating) {
  56653. coverRenderer.endCreating(controller, creatingCover);
  56654. updateZ(creatingCover, creatingCover.__brushOption);
  56655. }
  56656. return creatingCover;
  56657. }
  56658. function updateCoverShape(controller, cover) {
  56659. var brushOption = cover.__brushOption;
  56660. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  56661. }
  56662. function updateZ(cover, brushOption) {
  56663. var z = brushOption.z;
  56664. z == null && (z = COVER_Z);
  56665. cover.traverse(function (el) {
  56666. el.z = z;
  56667. el.z2 = z; // Consider in given container.
  56668. });
  56669. }
  56670. function updateCoverAfterCreation(controller, cover) {
  56671. getCoverRenderer(cover).updateCommon(controller, cover);
  56672. updateCoverShape(controller, cover);
  56673. }
  56674. function getCoverRenderer(cover) {
  56675. return coverRenderers[cover.__brushOption.brushType];
  56676. } // return target panel or `true` (means global panel)
  56677. function getPanelByPoint(controller, e, localCursorPoint) {
  56678. var panels = controller._panels;
  56679. if (!panels) {
  56680. return BRUSH_PANEL_GLOBAL; // Global panel
  56681. }
  56682. var panel;
  56683. var transform = controller._transform;
  56684. each(panels, function (pn) {
  56685. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  56686. });
  56687. return panel;
  56688. } // Return a panel or true
  56689. function getPanelByCover(controller, cover) {
  56690. var panels = controller._panels;
  56691. if (!panels) {
  56692. return BRUSH_PANEL_GLOBAL; // Global panel
  56693. }
  56694. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  56695. // which is then treated as global panel.
  56696. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  56697. }
  56698. function clearCovers(controller) {
  56699. var covers = controller._covers;
  56700. var originalLength = covers.length;
  56701. each(covers, function (cover) {
  56702. controller.group.remove(cover);
  56703. }, controller);
  56704. covers.length = 0;
  56705. return !!originalLength;
  56706. }
  56707. function trigger$1(controller, opt) {
  56708. var areas = map(controller._covers, function (cover) {
  56709. var brushOption = cover.__brushOption;
  56710. var range = clone(brushOption.range);
  56711. return {
  56712. brushType: brushOption.brushType,
  56713. panelId: brushOption.panelId,
  56714. range: range
  56715. };
  56716. });
  56717. controller.trigger('brush', {
  56718. areas: areas,
  56719. isEnd: !!opt.isEnd,
  56720. removeOnClick: !!opt.removeOnClick
  56721. });
  56722. }
  56723. function shouldShowCover(controller) {
  56724. var track = controller._track;
  56725. if (!track.length) {
  56726. return false;
  56727. }
  56728. var p2 = track[track.length - 1];
  56729. var p1 = track[0];
  56730. var dx = p2[0] - p1[0];
  56731. var dy = p2[1] - p1[1];
  56732. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  56733. return dist > UNSELECT_THRESHOLD;
  56734. }
  56735. function getTrackEnds(track) {
  56736. var tail = track.length - 1;
  56737. tail < 0 && (tail = 0);
  56738. return [track[0], track[tail]];
  56739. }
  56740. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  56741. var cover = new Group();
  56742. cover.add(new Rect({
  56743. name: 'main',
  56744. style: makeStyle(brushOption),
  56745. silent: true,
  56746. draggable: true,
  56747. cursor: 'move',
  56748. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  56749. ondragend: curry(trigger$1, controller, {
  56750. isEnd: true
  56751. })
  56752. }));
  56753. each(edgeNameSequences, function (nameSequence) {
  56754. cover.add(new Rect({
  56755. name: nameSequence.join(''),
  56756. style: {
  56757. opacity: 0
  56758. },
  56759. draggable: true,
  56760. silent: true,
  56761. invisible: true,
  56762. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  56763. ondragend: curry(trigger$1, controller, {
  56764. isEnd: true
  56765. })
  56766. }));
  56767. });
  56768. return cover;
  56769. }
  56770. function updateBaseRect(controller, cover, localRange, brushOption) {
  56771. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  56772. var handleSize = mathMax$9(lineWidth, MIN_RESIZE_LINE_WIDTH);
  56773. var x = localRange[0][0];
  56774. var y = localRange[1][0];
  56775. var xa = x - lineWidth / 2;
  56776. var ya = y - lineWidth / 2;
  56777. var x2 = localRange[0][1];
  56778. var y2 = localRange[1][1];
  56779. var x2a = x2 - handleSize + lineWidth / 2;
  56780. var y2a = y2 - handleSize + lineWidth / 2;
  56781. var width = x2 - x;
  56782. var height = y2 - y;
  56783. var widtha = width + lineWidth;
  56784. var heighta = height + lineWidth;
  56785. updateRectShape(controller, cover, 'main', x, y, width, height);
  56786. if (brushOption.transformable) {
  56787. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  56788. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  56789. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  56790. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  56791. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  56792. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  56793. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  56794. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  56795. }
  56796. }
  56797. function updateCommon(controller, cover) {
  56798. var brushOption = cover.__brushOption;
  56799. var transformable = brushOption.transformable;
  56800. var mainEl = cover.childAt(0);
  56801. mainEl.useStyle(makeStyle(brushOption));
  56802. mainEl.attr({
  56803. silent: !transformable,
  56804. cursor: transformable ? 'move' : 'default'
  56805. });
  56806. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  56807. var el = cover.childOfName(nameSequence.join(''));
  56808. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  56809. el && el.attr({
  56810. silent: !transformable,
  56811. invisible: !transformable,
  56812. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  56813. });
  56814. });
  56815. }
  56816. function updateRectShape(controller, cover, name, x, y, w, h) {
  56817. var el = cover.childOfName(name);
  56818. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  56819. }
  56820. function makeStyle(brushOption) {
  56821. return defaults({
  56822. strokeNoScale: true
  56823. }, brushOption.brushStyle);
  56824. }
  56825. function formatRectRange(x, y, x2, y2) {
  56826. var min = [mathMin$9(x, x2), mathMin$9(y, y2)];
  56827. var max = [mathMax$9(x, x2), mathMax$9(y, y2)];
  56828. return [[min[0], max[0]], [min[1], max[1]] // y range
  56829. ];
  56830. }
  56831. function getTransform$1(controller) {
  56832. return getTransform(controller.group);
  56833. }
  56834. function getGlobalDirection1(controller, localDirName) {
  56835. var map = {
  56836. w: 'left',
  56837. e: 'right',
  56838. n: 'top',
  56839. s: 'bottom'
  56840. };
  56841. var inverseMap = {
  56842. left: 'w',
  56843. right: 'e',
  56844. top: 'n',
  56845. bottom: 's'
  56846. };
  56847. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  56848. return inverseMap[dir];
  56849. }
  56850. function getGlobalDirection2(controller, localDirNameSeq) {
  56851. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  56852. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  56853. return globalDir.join('');
  56854. }
  56855. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  56856. var brushOption = cover.__brushOption;
  56857. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  56858. var localDelta = toLocalDelta(controller, dx, dy);
  56859. each(dirNameSequence, function (dirName) {
  56860. var ind = DIRECTION_MAP[dirName];
  56861. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  56862. });
  56863. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  56864. updateCoverAfterCreation(controller, cover);
  56865. trigger$1(controller, {
  56866. isEnd: false
  56867. });
  56868. }
  56869. function driftPolygon(controller, cover, dx, dy) {
  56870. var range = cover.__brushOption.range;
  56871. var localDelta = toLocalDelta(controller, dx, dy);
  56872. each(range, function (point) {
  56873. point[0] += localDelta[0];
  56874. point[1] += localDelta[1];
  56875. });
  56876. updateCoverAfterCreation(controller, cover);
  56877. trigger$1(controller, {
  56878. isEnd: false
  56879. });
  56880. }
  56881. function toLocalDelta(controller, dx, dy) {
  56882. var thisGroup = controller.group;
  56883. var localD = thisGroup.transformCoordToLocal(dx, dy);
  56884. var localZero = thisGroup.transformCoordToLocal(0, 0);
  56885. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  56886. }
  56887. function clipByPanel(controller, cover, data) {
  56888. var panel = getPanelByCover(controller, cover);
  56889. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  56890. }
  56891. function pointsToRect(points) {
  56892. var xmin = mathMin$9(points[0][0], points[1][0]);
  56893. var ymin = mathMin$9(points[0][1], points[1][1]);
  56894. var xmax = mathMax$9(points[0][0], points[1][0]);
  56895. var ymax = mathMax$9(points[0][1], points[1][1]);
  56896. return {
  56897. x: xmin,
  56898. y: ymin,
  56899. width: xmax - xmin,
  56900. height: ymax - ymin
  56901. };
  56902. }
  56903. function resetCursor(controller, e, localCursorPoint) {
  56904. if ( // Check active
  56905. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  56906. // but not called when mouse is out of zr area to avoid bad influence
  56907. // if `mousemove`, `mouseup` are triggered from `document` event.
  56908. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  56909. return;
  56910. }
  56911. var zr = controller._zr;
  56912. var covers = controller._covers;
  56913. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  56914. if (!controller._dragging) {
  56915. for (var i = 0; i < covers.length; i++) {
  56916. var brushOption = covers[i].__brushOption;
  56917. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  56918. // Use cursor style set on cover.
  56919. return;
  56920. }
  56921. }
  56922. }
  56923. currPanel && zr.setCursorStyle('crosshair');
  56924. }
  56925. function preventDefault(e) {
  56926. var rawE = e.event;
  56927. rawE.preventDefault && rawE.preventDefault();
  56928. }
  56929. function mainShapeContain(cover, x, y) {
  56930. return cover.childOfName('main').contain(x, y);
  56931. }
  56932. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  56933. var creatingCover = controller._creatingCover;
  56934. var panel = controller._creatingPanel;
  56935. var thisBrushOption = controller._brushOption;
  56936. var eventParams;
  56937. controller._track.push(localCursorPoint.slice());
  56938. if (shouldShowCover(controller) || creatingCover) {
  56939. if (panel && !creatingCover) {
  56940. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  56941. var brushOption = clone(thisBrushOption);
  56942. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  56943. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  56944. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  56945. controller._covers.push(creatingCover);
  56946. }
  56947. if (creatingCover) {
  56948. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  56949. var coverBrushOption = creatingCover.__brushOption;
  56950. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  56951. if (isEnd) {
  56952. endCreating(controller, creatingCover);
  56953. coverRenderer.updateCommon(controller, creatingCover);
  56954. }
  56955. updateCoverShape(controller, creatingCover);
  56956. eventParams = {
  56957. isEnd: isEnd
  56958. };
  56959. }
  56960. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  56961. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  56962. // But a single click do not clear covers, because user may have casual
  56963. // clicks (for example, click on other component and do not expect covers
  56964. // disappear).
  56965. // Only some cover removed, trigger action, but not every click trigger action.
  56966. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  56967. eventParams = {
  56968. isEnd: isEnd,
  56969. removeOnClick: true
  56970. };
  56971. }
  56972. }
  56973. return eventParams;
  56974. }
  56975. function determineBrushType(brushType, panel) {
  56976. if (brushType === 'auto') {
  56977. if ("development" !== 'production') {
  56978. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  56979. }
  56980. return panel.defaultBrushType;
  56981. }
  56982. return brushType;
  56983. }
  56984. var pointerHandlers = {
  56985. mousedown: function (e) {
  56986. if (this._dragging) {
  56987. // In case some browser do not support globalOut,
  56988. // and release mouse out side the browser.
  56989. handleDragEnd(this, e);
  56990. } else if (!e.target || !e.target.draggable) {
  56991. preventDefault(e);
  56992. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  56993. this._creatingCover = null;
  56994. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  56995. if (panel) {
  56996. this._dragging = true;
  56997. this._track = [localCursorPoint.slice()];
  56998. }
  56999. }
  57000. },
  57001. mousemove: function (e) {
  57002. var x = e.offsetX;
  57003. var y = e.offsetY;
  57004. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  57005. resetCursor(this, e, localCursorPoint);
  57006. if (this._dragging) {
  57007. preventDefault(e);
  57008. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  57009. eventParams && trigger$1(this, eventParams);
  57010. }
  57011. },
  57012. mouseup: function (e) {
  57013. handleDragEnd(this, e);
  57014. }
  57015. };
  57016. function handleDragEnd(controller, e) {
  57017. if (controller._dragging) {
  57018. preventDefault(e);
  57019. var x = e.offsetX;
  57020. var y = e.offsetY;
  57021. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  57022. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  57023. controller._dragging = false;
  57024. controller._track = [];
  57025. controller._creatingCover = null; // trigger event should be at final, after procedure will be nested.
  57026. eventParams && trigger$1(controller, eventParams);
  57027. }
  57028. }
  57029. function isOutsideZrArea(controller, x, y) {
  57030. var zr = controller._zr;
  57031. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  57032. }
  57033. /**
  57034. * key: brushType
  57035. */
  57036. var coverRenderers = {
  57037. lineX: getLineRenderer(0),
  57038. lineY: getLineRenderer(1),
  57039. rect: {
  57040. createCover: function (controller, brushOption) {
  57041. function returnInput(range) {
  57042. return range;
  57043. }
  57044. return createBaseRectCover({
  57045. toRectRange: returnInput,
  57046. fromRectRange: returnInput
  57047. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  57048. },
  57049. getCreatingRange: function (localTrack) {
  57050. var ends = getTrackEnds(localTrack);
  57051. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  57052. },
  57053. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57054. updateBaseRect(controller, cover, localRange, brushOption);
  57055. },
  57056. updateCommon: updateCommon,
  57057. contain: mainShapeContain
  57058. },
  57059. polygon: {
  57060. createCover: function (controller, brushOption) {
  57061. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  57062. // border of the shape when drawing, which is a better experience for user.
  57063. cover.add(new Polyline({
  57064. name: 'main',
  57065. style: makeStyle(brushOption),
  57066. silent: true
  57067. }));
  57068. return cover;
  57069. },
  57070. getCreatingRange: function (localTrack) {
  57071. return localTrack;
  57072. },
  57073. endCreating: function (controller, cover) {
  57074. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  57075. cover.add(new Polygon({
  57076. name: 'main',
  57077. draggable: true,
  57078. drift: curry(driftPolygon, controller, cover),
  57079. ondragend: curry(trigger$1, controller, {
  57080. isEnd: true
  57081. })
  57082. }));
  57083. },
  57084. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57085. cover.childAt(0).setShape({
  57086. points: clipByPanel(controller, cover, localRange)
  57087. });
  57088. },
  57089. updateCommon: updateCommon,
  57090. contain: mainShapeContain
  57091. }
  57092. };
  57093. function getLineRenderer(xyIndex) {
  57094. return {
  57095. createCover: function (controller, brushOption) {
  57096. return createBaseRectCover({
  57097. toRectRange: function (range) {
  57098. var rectRange = [range, [0, 100]];
  57099. xyIndex && rectRange.reverse();
  57100. return rectRange;
  57101. },
  57102. fromRectRange: function (rectRange) {
  57103. return rectRange[xyIndex];
  57104. }
  57105. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  57106. },
  57107. getCreatingRange: function (localTrack) {
  57108. var ends = getTrackEnds(localTrack);
  57109. var min = mathMin$9(ends[0][xyIndex], ends[1][xyIndex]);
  57110. var max = mathMax$9(ends[0][xyIndex], ends[1][xyIndex]);
  57111. return [min, max];
  57112. },
  57113. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57114. var otherExtent; // If brushWidth not specified, fit the panel.
  57115. var panel = getPanelByCover(controller, cover);
  57116. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  57117. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  57118. } else {
  57119. var zr = controller._zr;
  57120. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  57121. }
  57122. var rectRange = [localRange, otherExtent];
  57123. xyIndex && rectRange.reverse();
  57124. updateBaseRect(controller, cover, rectRange, brushOption);
  57125. },
  57126. updateCommon: updateCommon,
  57127. contain: mainShapeContain
  57128. };
  57129. }
  57130. function makeRectPanelClipPath(rect) {
  57131. rect = normalizeRect(rect);
  57132. return function (localPoints) {
  57133. return clipPointsByRect(localPoints, rect);
  57134. };
  57135. }
  57136. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  57137. rect = normalizeRect(rect);
  57138. return function (xyIndex) {
  57139. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  57140. var brushWidth = idx ? rect.width : rect.height;
  57141. var base = idx ? rect.x : rect.y;
  57142. return [base, base + (brushWidth || 0)];
  57143. };
  57144. }
  57145. function makeRectIsTargetByCursor(rect, api, targetModel) {
  57146. var boundingRect = normalizeRect(rect);
  57147. return function (e, localCursorPoint) {
  57148. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  57149. };
  57150. } // Consider width/height is negative.
  57151. function normalizeRect(rect) {
  57152. return BoundingRect.create(rect);
  57153. }
  57154. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  57155. var ParallelAxisView =
  57156. /** @class */
  57157. function (_super) {
  57158. __extends(ParallelAxisView, _super);
  57159. function ParallelAxisView() {
  57160. var _this = _super !== null && _super.apply(this, arguments) || this;
  57161. _this.type = ParallelAxisView.type;
  57162. return _this;
  57163. }
  57164. ParallelAxisView.prototype.init = function (ecModel, api) {
  57165. _super.prototype.init.apply(this, arguments);
  57166. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this));
  57167. };
  57168. ParallelAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  57169. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  57170. return;
  57171. }
  57172. this.axisModel = axisModel;
  57173. this.api = api;
  57174. this.group.removeAll();
  57175. var oldAxisGroup = this._axisGroup;
  57176. this._axisGroup = new Group();
  57177. this.group.add(this._axisGroup);
  57178. if (!axisModel.get('show')) {
  57179. return;
  57180. }
  57181. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  57182. var coordSys = coordSysModel.coordinateSystem;
  57183. var areaSelectStyle = axisModel.getAreaSelectStyle();
  57184. var areaWidth = areaSelectStyle.width;
  57185. var dim = axisModel.axis.dim;
  57186. var axisLayout = coordSys.getAxisLayout(dim);
  57187. var builderOpt = extend({
  57188. strokeContainThreshold: areaWidth
  57189. }, axisLayout);
  57190. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  57191. each(elementList, axisBuilder.add, axisBuilder);
  57192. this._axisGroup.add(axisBuilder.getGroup());
  57193. this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api);
  57194. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  57195. }; // /**
  57196. // * @override
  57197. // */
  57198. // updateVisual(axisModel, ecModel, api, payload) {
  57199. // this._brushController && this._brushController
  57200. // .updateCovers(getCoverInfoList(axisModel));
  57201. // }
  57202. ParallelAxisView.prototype._refreshBrushController = function (builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) {
  57203. // After filtering, axis may change, select area needs to be update.
  57204. var extent = axisModel.axis.getExtent();
  57205. var extentLen = extent[1] - extent[0];
  57206. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  57207. // width/height might be negative, which will be
  57208. // normalized in BoundingRect.
  57209. var rect = BoundingRect.create({
  57210. x: extent[0],
  57211. y: -areaWidth / 2,
  57212. width: extentLen,
  57213. height: areaWidth
  57214. });
  57215. rect.x -= extra;
  57216. rect.width += 2 * extra;
  57217. this._brushController.mount({
  57218. enableGlobalPan: true,
  57219. rotation: builderOpt.rotation,
  57220. x: builderOpt.position[0],
  57221. y: builderOpt.position[1]
  57222. }).setPanels([{
  57223. panelId: 'pl',
  57224. clipPath: makeRectPanelClipPath(rect),
  57225. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  57226. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  57227. }]).enableBrush({
  57228. brushType: 'lineX',
  57229. brushStyle: areaSelectStyle,
  57230. removeOnClick: true
  57231. }).updateCovers(getCoverInfoList(axisModel));
  57232. };
  57233. ParallelAxisView.prototype._onBrush = function (eventParam) {
  57234. var coverInfoList = eventParam.areas; // Do not cache these object, because the mey be changed.
  57235. var axisModel = this.axisModel;
  57236. var axis = axisModel.axis;
  57237. var intervals = map(coverInfoList, function (coverInfo) {
  57238. return [axis.coordToData(coverInfo.range[0], true), axis.coordToData(coverInfo.range[1], true)];
  57239. }); // If realtime is true, action is not dispatched on drag end, because
  57240. // the drag end emits the same params with the last drag move event,
  57241. // and may have some delay when using touch pad.
  57242. if (!axisModel.option.realtime === eventParam.isEnd || eventParam.removeOnClick) {
  57243. // jshint ignore:line
  57244. this.api.dispatchAction({
  57245. type: 'axisAreaSelect',
  57246. parallelAxisId: axisModel.id,
  57247. intervals: intervals
  57248. });
  57249. }
  57250. };
  57251. ParallelAxisView.prototype.dispose = function () {
  57252. this._brushController.dispose();
  57253. };
  57254. ParallelAxisView.type = 'parallelAxis';
  57255. return ParallelAxisView;
  57256. }(ComponentView);
  57257. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  57258. return payload && payload.type === 'axisAreaSelect' && ecModel.findComponents({
  57259. mainType: 'parallelAxis',
  57260. query: payload
  57261. })[0] === axisModel;
  57262. }
  57263. function getCoverInfoList(axisModel) {
  57264. var axis = axisModel.axis;
  57265. return map(axisModel.activeIntervals, function (interval) {
  57266. return {
  57267. brushType: 'lineX',
  57268. panelId: 'pl',
  57269. range: [axis.dataToCoord(interval[0], true), axis.dataToCoord(interval[1], true)]
  57270. };
  57271. });
  57272. }
  57273. function getCoordSysModel(axisModel, ecModel) {
  57274. return ecModel.getComponent('parallel', axisModel.get('parallelIndex'));
  57275. }
  57276. /*
  57277. * Licensed to the Apache Software Foundation (ASF) under one
  57278. * or more contributor license agreements. See the NOTICE file
  57279. * distributed with this work for additional information
  57280. * regarding copyright ownership. The ASF licenses this file
  57281. * to you under the Apache License, Version 2.0 (the
  57282. * "License"); you may not use this file except in compliance
  57283. * with the License. You may obtain a copy of the License at
  57284. *
  57285. * http://www.apache.org/licenses/LICENSE-2.0
  57286. *
  57287. * Unless required by applicable law or agreed to in writing,
  57288. * software distributed under the License is distributed on an
  57289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57290. * KIND, either express or implied. See the License for the
  57291. * specific language governing permissions and limitations
  57292. * under the License.
  57293. */
  57294. /**
  57295. * AUTO-GENERATED FILE. DO NOT MODIFY.
  57296. */
  57297. /*
  57298. * Licensed to the Apache Software Foundation (ASF) under one
  57299. * or more contributor license agreements. See the NOTICE file
  57300. * distributed with this work for additional information
  57301. * regarding copyright ownership. The ASF licenses this file
  57302. * to you under the Apache License, Version 2.0 (the
  57303. * "License"); you may not use this file except in compliance
  57304. * with the License. You may obtain a copy of the License at
  57305. *
  57306. * http://www.apache.org/licenses/LICENSE-2.0
  57307. *
  57308. * Unless required by applicable law or agreed to in writing,
  57309. * software distributed under the License is distributed on an
  57310. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57311. * KIND, either express or implied. See the License for the
  57312. * specific language governing permissions and limitations
  57313. * under the License.
  57314. */
  57315. var actionInfo$1 = {
  57316. type: 'axisAreaSelect',
  57317. event: 'axisAreaSelected' // update: 'updateVisual'
  57318. };
  57319. function installParallelActions(registers) {
  57320. registers.registerAction(actionInfo$1, function (payload, ecModel) {
  57321. ecModel.eachComponent({
  57322. mainType: 'parallelAxis',
  57323. query: payload
  57324. }, function (parallelAxisModel) {
  57325. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  57326. });
  57327. });
  57328. /**
  57329. * @payload
  57330. */
  57331. registers.registerAction('parallelAxisExpand', function (payload, ecModel) {
  57332. ecModel.eachComponent({
  57333. mainType: 'parallel',
  57334. query: payload
  57335. }, function (parallelModel) {
  57336. parallelModel.setAxisExpand(payload);
  57337. });
  57338. });
  57339. }
  57340. var defaultAxisOption = {
  57341. type: 'value',
  57342. areaSelectStyle: {
  57343. width: 20,
  57344. borderWidth: 1,
  57345. borderColor: 'rgba(160,197,232)',
  57346. color: 'rgba(160,197,232)',
  57347. opacity: 0.3
  57348. },
  57349. realtime: true,
  57350. z: 10
  57351. };
  57352. function install$g(registers) {
  57353. registers.registerComponentView(ParallelView$1);
  57354. registers.registerComponentModel(ParallelModel);
  57355. registers.registerCoordinateSystem('parallel', parallelCoordSysCreator);
  57356. registers.registerPreprocessor(parallelPreprocessor);
  57357. registers.registerComponentModel(ParallelAxisModel);
  57358. registers.registerComponentView(ParallelAxisView);
  57359. axisModelCreator(registers, 'parallel', ParallelAxisModel, defaultAxisOption);
  57360. installParallelActions(registers);
  57361. }
  57362. function install$h(registers) {
  57363. use(install$g);
  57364. registers.registerChartView(ParallelView);
  57365. registers.registerSeriesModel(ParallelSeriesModel);
  57366. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, parallelVisual);
  57367. }
  57368. var SankeyPathShape =
  57369. /** @class */
  57370. function () {
  57371. function SankeyPathShape() {
  57372. this.x1 = 0;
  57373. this.y1 = 0;
  57374. this.x2 = 0;
  57375. this.y2 = 0;
  57376. this.cpx1 = 0;
  57377. this.cpy1 = 0;
  57378. this.cpx2 = 0;
  57379. this.cpy2 = 0;
  57380. this.extent = 0;
  57381. }
  57382. return SankeyPathShape;
  57383. }();
  57384. var SankeyPath =
  57385. /** @class */
  57386. function (_super) {
  57387. __extends(SankeyPath, _super);
  57388. function SankeyPath(opts) {
  57389. return _super.call(this, opts) || this;
  57390. }
  57391. SankeyPath.prototype.getDefaultShape = function () {
  57392. return new SankeyPathShape();
  57393. };
  57394. SankeyPath.prototype.buildPath = function (ctx, shape) {
  57395. var extent = shape.extent;
  57396. ctx.moveTo(shape.x1, shape.y1);
  57397. ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2);
  57398. if (shape.orient === 'vertical') {
  57399. ctx.lineTo(shape.x2 + extent, shape.y2);
  57400. ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1);
  57401. } else {
  57402. ctx.lineTo(shape.x2, shape.y2 + extent);
  57403. ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent);
  57404. }
  57405. ctx.closePath();
  57406. };
  57407. SankeyPath.prototype.highlight = function () {
  57408. enterEmphasis(this);
  57409. };
  57410. SankeyPath.prototype.downplay = function () {
  57411. leaveEmphasis(this);
  57412. };
  57413. return SankeyPath;
  57414. }(Path);
  57415. var SankeyView =
  57416. /** @class */
  57417. function (_super) {
  57418. __extends(SankeyView, _super);
  57419. function SankeyView() {
  57420. var _this = _super !== null && _super.apply(this, arguments) || this;
  57421. _this.type = SankeyView.type;
  57422. _this._focusAdjacencyDisabled = false;
  57423. return _this;
  57424. }
  57425. SankeyView.prototype.render = function (seriesModel, ecModel, api) {
  57426. var sankeyView = this;
  57427. var graph = seriesModel.getGraph();
  57428. var group = this.group;
  57429. var layoutInfo = seriesModel.layoutInfo; // view width
  57430. var width = layoutInfo.width; // view height
  57431. var height = layoutInfo.height;
  57432. var nodeData = seriesModel.getData();
  57433. var edgeData = seriesModel.getData('edge');
  57434. var orient = seriesModel.get('orient');
  57435. this._model = seriesModel;
  57436. group.removeAll();
  57437. group.x = layoutInfo.x;
  57438. group.y = layoutInfo.y; // generate a bezire Curve for each edge
  57439. graph.eachEdge(function (edge) {
  57440. var curve = new SankeyPath();
  57441. var ecData = getECData(curve);
  57442. ecData.dataIndex = edge.dataIndex;
  57443. ecData.seriesIndex = seriesModel.seriesIndex;
  57444. ecData.dataType = 'edge';
  57445. var edgeModel = edge.getModel();
  57446. var lineStyleModel = edgeModel.getModel('lineStyle');
  57447. var curvature = lineStyleModel.get('curveness');
  57448. var n1Layout = edge.node1.getLayout();
  57449. var node1Model = edge.node1.getModel();
  57450. var dragX1 = node1Model.get('localX');
  57451. var dragY1 = node1Model.get('localY');
  57452. var n2Layout = edge.node2.getLayout();
  57453. var node2Model = edge.node2.getModel();
  57454. var dragX2 = node2Model.get('localX');
  57455. var dragY2 = node2Model.get('localY');
  57456. var edgeLayout = edge.getLayout();
  57457. var x1;
  57458. var y1;
  57459. var x2;
  57460. var y2;
  57461. var cpx1;
  57462. var cpy1;
  57463. var cpx2;
  57464. var cpy2;
  57465. curve.shape.extent = Math.max(1, edgeLayout.dy);
  57466. curve.shape.orient = orient;
  57467. if (orient === 'vertical') {
  57468. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  57469. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  57470. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  57471. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  57472. cpx1 = x1;
  57473. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  57474. cpx2 = x2;
  57475. cpy2 = y1 * curvature + y2 * (1 - curvature);
  57476. } else {
  57477. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  57478. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  57479. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  57480. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  57481. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  57482. cpy1 = y1;
  57483. cpx2 = x1 * curvature + x2 * (1 - curvature);
  57484. cpy2 = y2;
  57485. }
  57486. curve.setShape({
  57487. x1: x1,
  57488. y1: y1,
  57489. x2: x2,
  57490. y2: y2,
  57491. cpx1: cpx1,
  57492. cpy1: cpy1,
  57493. cpx2: cpx2,
  57494. cpy2: cpy2
  57495. });
  57496. curve.useStyle(lineStyleModel.getItemStyle()); // Special color, use source node color or target node color
  57497. switch (curve.style.fill) {
  57498. case 'source':
  57499. curve.style.fill = edge.node1.getVisual('color');
  57500. curve.style.decal = edge.node1.getVisual('style').decal;
  57501. break;
  57502. case 'target':
  57503. curve.style.fill = edge.node2.getVisual('color');
  57504. curve.style.decal = edge.node2.getVisual('style').decal;
  57505. break;
  57506. case 'gradient':
  57507. var sourceColor = edge.node1.getVisual('color');
  57508. var targetColor = edge.node2.getVisual('color');
  57509. if (isString(sourceColor) && isString(targetColor)) {
  57510. curve.style.fill = new LinearGradient(0, 0, +(orient === 'horizontal'), +(orient === 'vertical'), [{
  57511. color: sourceColor,
  57512. offset: 0
  57513. }, {
  57514. color: targetColor,
  57515. offset: 1
  57516. }]);
  57517. }
  57518. }
  57519. setLabelStyle(curve, getLabelStatesModels(edgeModel, 'edgeLabel'), {
  57520. labelFetcher: seriesModel,
  57521. labelDataIndex: edge.dataIndex,
  57522. defaultText: "" + edgeModel.get('value')
  57523. });
  57524. curve.setTextConfig({
  57525. position: 'inside'
  57526. });
  57527. var emphasisModel = edgeModel.getModel('emphasis');
  57528. setStatesStylesFromModel(curve, edgeModel, 'lineStyle', function (model) {
  57529. return model.getItemStyle();
  57530. });
  57531. group.add(curve);
  57532. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  57533. var focus = emphasisModel.get('focus');
  57534. toggleHoverEmphasis(curve, focus === 'adjacency' ? edge.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  57535. getECData(curve).dataType = 'edge';
  57536. }); // Generate a rect for each node
  57537. graph.eachNode(function (node) {
  57538. var layout = node.getLayout();
  57539. var itemModel = node.getModel();
  57540. var dragX = itemModel.get('localX');
  57541. var dragY = itemModel.get('localY');
  57542. var emphasisModel = itemModel.getModel('emphasis');
  57543. var rect = new Rect({
  57544. shape: {
  57545. x: dragX != null ? dragX * width : layout.x,
  57546. y: dragY != null ? dragY * height : layout.y,
  57547. width: layout.dx,
  57548. height: layout.dy
  57549. },
  57550. style: itemModel.getModel('itemStyle').getItemStyle(),
  57551. z2: 10
  57552. });
  57553. setLabelStyle(rect, getLabelStatesModels(itemModel), {
  57554. labelFetcher: seriesModel,
  57555. labelDataIndex: node.dataIndex,
  57556. defaultText: node.id
  57557. });
  57558. rect.disableLabelAnimation = true;
  57559. rect.setStyle('fill', node.getVisual('color'));
  57560. rect.setStyle('decal', node.getVisual('style').decal);
  57561. setStatesStylesFromModel(rect, itemModel);
  57562. group.add(rect);
  57563. nodeData.setItemGraphicEl(node.dataIndex, rect);
  57564. getECData(rect).dataType = 'node';
  57565. var focus = emphasisModel.get('focus');
  57566. toggleHoverEmphasis(rect, focus === 'adjacency' ? node.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  57567. });
  57568. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  57569. var itemModel = nodeData.getItemModel(dataIndex);
  57570. if (itemModel.get('draggable')) {
  57571. el.drift = function (dx, dy) {
  57572. sankeyView._focusAdjacencyDisabled = true;
  57573. this.shape.x += dx;
  57574. this.shape.y += dy;
  57575. this.dirty();
  57576. api.dispatchAction({
  57577. type: 'dragNode',
  57578. seriesId: seriesModel.id,
  57579. dataIndex: nodeData.getRawIndex(dataIndex),
  57580. localX: this.shape.x / width,
  57581. localY: this.shape.y / height
  57582. });
  57583. };
  57584. el.ondragend = function () {
  57585. sankeyView._focusAdjacencyDisabled = false;
  57586. };
  57587. el.draggable = true;
  57588. el.cursor = 'move';
  57589. }
  57590. });
  57591. if (!this._data && seriesModel.isAnimationEnabled()) {
  57592. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  57593. group.removeClipPath();
  57594. }));
  57595. }
  57596. this._data = seriesModel.getData();
  57597. };
  57598. SankeyView.prototype.dispose = function () {};
  57599. SankeyView.type = 'sankey';
  57600. return SankeyView;
  57601. }(ChartView); // Add animation to the view
  57602. function createGridClipShape$1(rect, seriesModel, cb) {
  57603. var rectEl = new Rect({
  57604. shape: {
  57605. x: rect.x - 10,
  57606. y: rect.y - 10,
  57607. width: 0,
  57608. height: rect.height + 20
  57609. }
  57610. });
  57611. initProps(rectEl, {
  57612. shape: {
  57613. width: rect.width + 20
  57614. }
  57615. }, seriesModel, cb);
  57616. return rectEl;
  57617. }
  57618. var SankeySeriesModel =
  57619. /** @class */
  57620. function (_super) {
  57621. __extends(SankeySeriesModel, _super);
  57622. function SankeySeriesModel() {
  57623. var _this = _super !== null && _super.apply(this, arguments) || this;
  57624. _this.type = SankeySeriesModel.type;
  57625. return _this;
  57626. }
  57627. /**
  57628. * Init a graph data structure from data in option series
  57629. */
  57630. SankeySeriesModel.prototype.getInitialData = function (option, ecModel) {
  57631. var links = option.edges || option.links;
  57632. var nodes = option.data || option.nodes;
  57633. var levels = option.levels;
  57634. this.levelModels = [];
  57635. var levelModels = this.levelModels;
  57636. for (var i = 0; i < levels.length; i++) {
  57637. if (levels[i].depth != null && levels[i].depth >= 0) {
  57638. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  57639. } else {
  57640. if ("development" !== 'production') {
  57641. throw new Error('levels[i].depth is mandatory and should be natural number');
  57642. }
  57643. }
  57644. }
  57645. if (nodes && links) {
  57646. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  57647. return graph.data;
  57648. }
  57649. function beforeLink(nodeData, edgeData) {
  57650. nodeData.wrapMethod('getItemModel', function (model, idx) {
  57651. var seriesModel = model.parentModel;
  57652. var layout = seriesModel.getData().getItemLayout(idx);
  57653. if (layout) {
  57654. var nodeDepth = layout.depth;
  57655. var levelModel = seriesModel.levelModels[nodeDepth];
  57656. if (levelModel) {
  57657. model.parentModel = levelModel;
  57658. }
  57659. }
  57660. return model;
  57661. });
  57662. edgeData.wrapMethod('getItemModel', function (model, idx) {
  57663. var seriesModel = model.parentModel;
  57664. var edge = seriesModel.getGraph().getEdgeByIndex(idx);
  57665. var layout = edge.node1.getLayout();
  57666. if (layout) {
  57667. var depth = layout.depth;
  57668. var levelModel = seriesModel.levelModels[depth];
  57669. if (levelModel) {
  57670. model.parentModel = levelModel;
  57671. }
  57672. }
  57673. return model;
  57674. });
  57675. }
  57676. };
  57677. SankeySeriesModel.prototype.setNodePosition = function (dataIndex, localPosition) {
  57678. var nodes = this.option.data || this.option.nodes;
  57679. var dataItem = nodes[dataIndex];
  57680. dataItem.localX = localPosition[0];
  57681. dataItem.localY = localPosition[1];
  57682. };
  57683. /**
  57684. * Return the graphic data structure
  57685. *
  57686. * @return graphic data structure
  57687. */
  57688. SankeySeriesModel.prototype.getGraph = function () {
  57689. return this.getData().graph;
  57690. };
  57691. /**
  57692. * Get edge data of graphic data structure
  57693. *
  57694. * @return data structure of list
  57695. */
  57696. SankeySeriesModel.prototype.getEdgeData = function () {
  57697. return this.getGraph().edgeData;
  57698. };
  57699. SankeySeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  57700. function noValue(val) {
  57701. return isNaN(val) || val == null;
  57702. } // dataType === 'node' or empty do not show tooltip by default
  57703. if (dataType === 'edge') {
  57704. var params = this.getDataParams(dataIndex, dataType);
  57705. var rawDataOpt = params.data;
  57706. var edgeValue = params.value;
  57707. var edgeName = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  57708. return createTooltipMarkup('nameValue', {
  57709. name: edgeName,
  57710. value: edgeValue,
  57711. noValue: noValue(edgeValue)
  57712. });
  57713. } // dataType === 'node'
  57714. else {
  57715. var node = this.getGraph().getNodeByIndex(dataIndex);
  57716. var value = node.getLayout().value;
  57717. var name_1 = this.getDataParams(dataIndex, dataType).data.name;
  57718. return createTooltipMarkup('nameValue', {
  57719. name: name_1 != null ? name_1 + '' : null,
  57720. value: value,
  57721. noValue: noValue(value)
  57722. });
  57723. }
  57724. };
  57725. SankeySeriesModel.prototype.optionUpdated = function () {}; // Override Series.getDataParams()
  57726. SankeySeriesModel.prototype.getDataParams = function (dataIndex, dataType) {
  57727. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  57728. if (params.value == null && dataType === 'node') {
  57729. var node = this.getGraph().getNodeByIndex(dataIndex);
  57730. var nodeValue = node.getLayout().value;
  57731. params.value = nodeValue;
  57732. }
  57733. return params;
  57734. };
  57735. SankeySeriesModel.type = 'series.sankey';
  57736. SankeySeriesModel.defaultOption = {
  57737. // zlevel: 0,
  57738. z: 2,
  57739. coordinateSystem: 'view',
  57740. left: '5%',
  57741. top: '5%',
  57742. right: '20%',
  57743. bottom: '5%',
  57744. orient: 'horizontal',
  57745. nodeWidth: 20,
  57746. nodeGap: 8,
  57747. draggable: true,
  57748. layoutIterations: 32,
  57749. label: {
  57750. show: true,
  57751. position: 'right',
  57752. fontSize: 12
  57753. },
  57754. edgeLabel: {
  57755. show: false,
  57756. fontSize: 12
  57757. },
  57758. levels: [],
  57759. nodeAlign: 'justify',
  57760. lineStyle: {
  57761. color: '#314656',
  57762. opacity: 0.2,
  57763. curveness: 0.5
  57764. },
  57765. emphasis: {
  57766. label: {
  57767. show: true
  57768. },
  57769. lineStyle: {
  57770. opacity: 0.5
  57771. }
  57772. },
  57773. select: {
  57774. itemStyle: {
  57775. borderColor: '#212121'
  57776. }
  57777. },
  57778. animationEasing: 'linear',
  57779. animationDuration: 1000
  57780. };
  57781. return SankeySeriesModel;
  57782. }(SeriesModel);
  57783. function sankeyLayout(ecModel, api) {
  57784. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  57785. var nodeWidth = seriesModel.get('nodeWidth');
  57786. var nodeGap = seriesModel.get('nodeGap');
  57787. var layoutInfo = getViewRect$4(seriesModel, api);
  57788. seriesModel.layoutInfo = layoutInfo;
  57789. var width = layoutInfo.width;
  57790. var height = layoutInfo.height;
  57791. var graph = seriesModel.getGraph();
  57792. var nodes = graph.nodes;
  57793. var edges = graph.edges;
  57794. computeNodeValues(nodes);
  57795. var filteredNodes = filter(nodes, function (node) {
  57796. return node.getLayout().value === 0;
  57797. });
  57798. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  57799. var orient = seriesModel.get('orient');
  57800. var nodeAlign = seriesModel.get('nodeAlign');
  57801. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  57802. });
  57803. }
  57804. /**
  57805. * Get the layout position of the whole view
  57806. */
  57807. function getViewRect$4(seriesModel, api) {
  57808. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  57809. width: api.getWidth(),
  57810. height: api.getHeight()
  57811. });
  57812. }
  57813. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  57814. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  57815. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  57816. computeEdgeDepths(nodes, orient);
  57817. }
  57818. /**
  57819. * Compute the value of each node by summing the associated edge's value
  57820. */
  57821. function computeNodeValues(nodes) {
  57822. each(nodes, function (node) {
  57823. var value1 = sum(node.outEdges, getEdgeValue);
  57824. var value2 = sum(node.inEdges, getEdgeValue);
  57825. var nodeRawValue = node.getValue() || 0;
  57826. var value = Math.max(value1, value2, nodeRawValue);
  57827. node.setLayout({
  57828. value: value
  57829. }, true);
  57830. });
  57831. }
  57832. /**
  57833. * Compute the x-position for each node.
  57834. *
  57835. * Here we use Kahn algorithm to detect cycle when we traverse
  57836. * the node to computer the initial x position.
  57837. */
  57838. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  57839. // Used to mark whether the edge is deleted. if it is deleted,
  57840. // the value is 0, otherwise it is 1.
  57841. var remainEdges = []; // Storage each node's indegree.
  57842. var indegreeArr = []; // Used to storage the node with indegree is equal to 0.
  57843. var zeroIndegrees = [];
  57844. var nextTargetNode = [];
  57845. var x = 0; // let kx = 0;
  57846. for (var i = 0; i < edges.length; i++) {
  57847. remainEdges[i] = 1;
  57848. }
  57849. for (var i = 0; i < nodes.length; i++) {
  57850. indegreeArr[i] = nodes[i].inEdges.length;
  57851. if (indegreeArr[i] === 0) {
  57852. zeroIndegrees.push(nodes[i]);
  57853. }
  57854. }
  57855. var maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the
  57856. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  57857. // position of the nodes.
  57858. while (zeroIndegrees.length) {
  57859. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  57860. var node = zeroIndegrees[idx];
  57861. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  57862. var isItemDepth = item.depth != null && item.depth >= 0;
  57863. if (isItemDepth && item.depth > maxNodeDepth) {
  57864. maxNodeDepth = item.depth;
  57865. }
  57866. node.setLayout({
  57867. depth: isItemDepth ? item.depth : x
  57868. }, true);
  57869. orient === 'vertical' ? node.setLayout({
  57870. dy: nodeWidth
  57871. }, true) : node.setLayout({
  57872. dx: nodeWidth
  57873. }, true);
  57874. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  57875. var edge = node.outEdges[edgeIdx];
  57876. var indexEdge = edges.indexOf(edge);
  57877. remainEdges[indexEdge] = 0;
  57878. var targetNode = edge.node2;
  57879. var nodeIndex = nodes.indexOf(targetNode);
  57880. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  57881. nextTargetNode.push(targetNode);
  57882. }
  57883. }
  57884. }
  57885. ++x;
  57886. zeroIndegrees = nextTargetNode;
  57887. nextTargetNode = [];
  57888. }
  57889. for (var i = 0; i < remainEdges.length; i++) {
  57890. if (remainEdges[i] === 1) {
  57891. throw new Error('Sankey is a DAG, the original data has cycle!');
  57892. }
  57893. }
  57894. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  57895. if (nodeAlign && nodeAlign !== 'left') {
  57896. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  57897. }
  57898. var kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth;
  57899. scaleNodeBreadths(nodes, kx, orient);
  57900. }
  57901. function isNodeDepth(node) {
  57902. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  57903. return item.depth != null && item.depth >= 0;
  57904. }
  57905. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  57906. if (nodeAlign === 'right') {
  57907. var nextSourceNode = [];
  57908. var remainNodes = nodes;
  57909. var nodeHeight = 0;
  57910. while (remainNodes.length) {
  57911. for (var i = 0; i < remainNodes.length; i++) {
  57912. var node = remainNodes[i];
  57913. node.setLayout({
  57914. skNodeHeight: nodeHeight
  57915. }, true);
  57916. for (var j = 0; j < node.inEdges.length; j++) {
  57917. var edge = node.inEdges[j];
  57918. if (nextSourceNode.indexOf(edge.node1) < 0) {
  57919. nextSourceNode.push(edge.node1);
  57920. }
  57921. }
  57922. }
  57923. remainNodes = nextSourceNode;
  57924. nextSourceNode = [];
  57925. ++nodeHeight;
  57926. }
  57927. each(nodes, function (node) {
  57928. if (!isNodeDepth(node)) {
  57929. node.setLayout({
  57930. depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)
  57931. }, true);
  57932. }
  57933. });
  57934. } else if (nodeAlign === 'justify') {
  57935. moveSinksRight(nodes, maxDepth);
  57936. }
  57937. }
  57938. /**
  57939. * All the node without outEgdes are assigned maximum x-position and
  57940. * be aligned in the last column.
  57941. *
  57942. * @param nodes. node of sankey view.
  57943. * @param maxDepth. use to assign to node without outEdges as x-position.
  57944. */
  57945. function moveSinksRight(nodes, maxDepth) {
  57946. each(nodes, function (node) {
  57947. if (!isNodeDepth(node) && !node.outEdges.length) {
  57948. node.setLayout({
  57949. depth: maxDepth
  57950. }, true);
  57951. }
  57952. });
  57953. }
  57954. /**
  57955. * Scale node x-position to the width
  57956. *
  57957. * @param nodes node of sankey view
  57958. * @param kx multiple used to scale nodes
  57959. */
  57960. function scaleNodeBreadths(nodes, kx, orient) {
  57961. each(nodes, function (node) {
  57962. var nodeDepth = node.getLayout().depth * kx;
  57963. orient === 'vertical' ? node.setLayout({
  57964. y: nodeDepth
  57965. }, true) : node.setLayout({
  57966. x: nodeDepth
  57967. }, true);
  57968. });
  57969. }
  57970. /**
  57971. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  57972. *
  57973. * @param nodes node of sankey view
  57974. * @param edges edge of sankey view
  57975. * @param height the whole height of the area to draw the view
  57976. * @param nodeGap the vertical distance between two nodes
  57977. * in the same column.
  57978. * @param iterations the number of iterations for the algorithm
  57979. */
  57980. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  57981. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  57982. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  57983. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  57984. for (var alpha = 1; iterations > 0; iterations--) {
  57985. // 0.99 is a experience parameter, ensure that each iterations of
  57986. // changes as small as possible.
  57987. alpha *= 0.99;
  57988. relaxRightToLeft(nodesByBreadth, alpha, orient);
  57989. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  57990. relaxLeftToRight(nodesByBreadth, alpha, orient);
  57991. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  57992. }
  57993. }
  57994. function prepareNodesByBreadth(nodes, orient) {
  57995. var nodesByBreadth = [];
  57996. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  57997. var groupResult = groupData(nodes, function (node) {
  57998. return node.getLayout()[keyAttr];
  57999. });
  58000. groupResult.keys.sort(function (a, b) {
  58001. return a - b;
  58002. });
  58003. each(groupResult.keys, function (key) {
  58004. nodesByBreadth.push(groupResult.buckets.get(key));
  58005. });
  58006. return nodesByBreadth;
  58007. }
  58008. /**
  58009. * Compute the original y-position for each node
  58010. */
  58011. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  58012. var minKy = Infinity;
  58013. each(nodesByBreadth, function (nodes) {
  58014. var n = nodes.length;
  58015. var sum = 0;
  58016. each(nodes, function (node) {
  58017. sum += node.getLayout().value;
  58018. });
  58019. var ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum;
  58020. if (ky < minKy) {
  58021. minKy = ky;
  58022. }
  58023. });
  58024. each(nodesByBreadth, function (nodes) {
  58025. each(nodes, function (node, i) {
  58026. var nodeDy = node.getLayout().value * minKy;
  58027. if (orient === 'vertical') {
  58028. node.setLayout({
  58029. x: i
  58030. }, true);
  58031. node.setLayout({
  58032. dx: nodeDy
  58033. }, true);
  58034. } else {
  58035. node.setLayout({
  58036. y: i
  58037. }, true);
  58038. node.setLayout({
  58039. dy: nodeDy
  58040. }, true);
  58041. }
  58042. });
  58043. });
  58044. each(edges, function (edge) {
  58045. var edgeDy = +edge.getValue() * minKy;
  58046. edge.setLayout({
  58047. dy: edgeDy
  58048. }, true);
  58049. });
  58050. }
  58051. /**
  58052. * Resolve the collision of initialized depth (y-position)
  58053. */
  58054. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  58055. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  58056. each(nodesByBreadth, function (nodes) {
  58057. nodes.sort(function (a, b) {
  58058. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  58059. });
  58060. var nodeX;
  58061. var node;
  58062. var dy;
  58063. var y0 = 0;
  58064. var n = nodes.length;
  58065. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  58066. for (var i = 0; i < n; i++) {
  58067. node = nodes[i];
  58068. dy = y0 - node.getLayout()[keyAttr];
  58069. if (dy > 0) {
  58070. nodeX = node.getLayout()[keyAttr] + dy;
  58071. orient === 'vertical' ? node.setLayout({
  58072. x: nodeX
  58073. }, true) : node.setLayout({
  58074. y: nodeX
  58075. }, true);
  58076. }
  58077. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  58078. }
  58079. var viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up
  58080. dy = y0 - nodeGap - viewWidth;
  58081. if (dy > 0) {
  58082. nodeX = node.getLayout()[keyAttr] - dy;
  58083. orient === 'vertical' ? node.setLayout({
  58084. x: nodeX
  58085. }, true) : node.setLayout({
  58086. y: nodeX
  58087. }, true);
  58088. y0 = nodeX;
  58089. for (var i = n - 2; i >= 0; --i) {
  58090. node = nodes[i];
  58091. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  58092. if (dy > 0) {
  58093. nodeX = node.getLayout()[keyAttr] - dy;
  58094. orient === 'vertical' ? node.setLayout({
  58095. x: nodeX
  58096. }, true) : node.setLayout({
  58097. y: nodeX
  58098. }, true);
  58099. }
  58100. y0 = node.getLayout()[keyAttr];
  58101. }
  58102. }
  58103. });
  58104. }
  58105. /**
  58106. * Change the y-position of the nodes, except most the right side nodes
  58107. * @param nodesByBreadth
  58108. * @param alpha parameter used to adjust the nodes y-position
  58109. */
  58110. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  58111. each(nodesByBreadth.slice().reverse(), function (nodes) {
  58112. each(nodes, function (node) {
  58113. if (node.outEdges.length) {
  58114. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue);
  58115. if (isNaN(y)) {
  58116. var len = node.outEdges.length;
  58117. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  58118. }
  58119. if (orient === 'vertical') {
  58120. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  58121. node.setLayout({
  58122. x: nodeX
  58123. }, true);
  58124. } else {
  58125. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  58126. node.setLayout({
  58127. y: nodeY
  58128. }, true);
  58129. }
  58130. }
  58131. });
  58132. });
  58133. }
  58134. function weightedTarget(edge, orient) {
  58135. return center$1(edge.node2, orient) * edge.getValue();
  58136. }
  58137. function centerTarget(edge, orient) {
  58138. return center$1(edge.node2, orient);
  58139. }
  58140. function weightedSource(edge, orient) {
  58141. return center$1(edge.node1, orient) * edge.getValue();
  58142. }
  58143. function centerSource(edge, orient) {
  58144. return center$1(edge.node1, orient);
  58145. }
  58146. function center$1(node, orient) {
  58147. return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2;
  58148. }
  58149. function getEdgeValue(edge) {
  58150. return edge.getValue();
  58151. }
  58152. function sum(array, cb, orient) {
  58153. var sum = 0;
  58154. var len = array.length;
  58155. var i = -1;
  58156. while (++i < len) {
  58157. var value = +cb(array[i], orient);
  58158. if (!isNaN(value)) {
  58159. sum += value;
  58160. }
  58161. }
  58162. return sum;
  58163. }
  58164. /**
  58165. * Change the y-position of the nodes, except most the left side nodes
  58166. */
  58167. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  58168. each(nodesByBreadth, function (nodes) {
  58169. each(nodes, function (node) {
  58170. if (node.inEdges.length) {
  58171. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue);
  58172. if (isNaN(y)) {
  58173. var len = node.inEdges.length;
  58174. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  58175. }
  58176. if (orient === 'vertical') {
  58177. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  58178. node.setLayout({
  58179. x: nodeX
  58180. }, true);
  58181. } else {
  58182. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  58183. node.setLayout({
  58184. y: nodeY
  58185. }, true);
  58186. }
  58187. }
  58188. });
  58189. });
  58190. }
  58191. /**
  58192. * Compute the depth(y-position) of each edge
  58193. */
  58194. function computeEdgeDepths(nodes, orient) {
  58195. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  58196. each(nodes, function (node) {
  58197. node.outEdges.sort(function (a, b) {
  58198. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  58199. });
  58200. node.inEdges.sort(function (a, b) {
  58201. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  58202. });
  58203. });
  58204. each(nodes, function (node) {
  58205. var sy = 0;
  58206. var ty = 0;
  58207. each(node.outEdges, function (edge) {
  58208. edge.setLayout({
  58209. sy: sy
  58210. }, true);
  58211. sy += edge.getLayout().dy;
  58212. });
  58213. each(node.inEdges, function (edge) {
  58214. edge.setLayout({
  58215. ty: ty
  58216. }, true);
  58217. ty += edge.getLayout().dy;
  58218. });
  58219. });
  58220. }
  58221. function sankeyVisual(ecModel) {
  58222. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  58223. var graph = seriesModel.getGraph();
  58224. var nodes = graph.nodes;
  58225. var edges = graph.edges;
  58226. if (nodes.length) {
  58227. var minValue_1 = Infinity;
  58228. var maxValue_1 = -Infinity;
  58229. each(nodes, function (node) {
  58230. var nodeValue = node.getLayout().value;
  58231. if (nodeValue < minValue_1) {
  58232. minValue_1 = nodeValue;
  58233. }
  58234. if (nodeValue > maxValue_1) {
  58235. maxValue_1 = nodeValue;
  58236. }
  58237. });
  58238. each(nodes, function (node) {
  58239. var mapping = new VisualMapping({
  58240. type: 'color',
  58241. mappingMethod: 'linear',
  58242. dataExtent: [minValue_1, maxValue_1],
  58243. visual: seriesModel.get('color')
  58244. });
  58245. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  58246. var customColor = node.getModel().get(['itemStyle', 'color']);
  58247. if (customColor != null) {
  58248. node.setVisual('color', customColor);
  58249. node.setVisual('style', {
  58250. fill: customColor
  58251. });
  58252. } else {
  58253. node.setVisual('color', mapValueToColor);
  58254. node.setVisual('style', {
  58255. fill: mapValueToColor
  58256. });
  58257. }
  58258. });
  58259. }
  58260. if (edges.length) {
  58261. each(edges, function (edge) {
  58262. var edgeStyle = edge.getModel().get('lineStyle');
  58263. edge.setVisual('style', edgeStyle);
  58264. });
  58265. }
  58266. });
  58267. }
  58268. function install$i(registers) {
  58269. registers.registerChartView(SankeyView);
  58270. registers.registerSeriesModel(SankeySeriesModel);
  58271. registers.registerLayout(sankeyLayout);
  58272. registers.registerVisual(sankeyVisual);
  58273. registers.registerAction({
  58274. type: 'dragNode',
  58275. event: 'dragnode',
  58276. // here can only use 'update' now, other value is not support in echarts.
  58277. update: 'update'
  58278. }, function (payload, ecModel) {
  58279. ecModel.eachComponent({
  58280. mainType: 'series',
  58281. subType: 'sankey',
  58282. query: payload
  58283. }, function (seriesModel) {
  58284. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  58285. });
  58286. });
  58287. }
  58288. var WhiskerBoxCommonMixin =
  58289. /** @class */
  58290. function () {
  58291. function WhiskerBoxCommonMixin() {}
  58292. /**
  58293. * @override
  58294. */
  58295. WhiskerBoxCommonMixin.prototype.getInitialData = function (option, ecModel) {
  58296. // When both types of xAxis and yAxis are 'value', layout is
  58297. // needed to be specified by user. Otherwise, layout can be
  58298. // judged by which axis is category.
  58299. var ordinalMeta;
  58300. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  58301. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  58302. var xAxisType = xAxisModel.get('type');
  58303. var yAxisType = yAxisModel.get('type');
  58304. var addOrdinal; // FIXME
  58305. // Consider time axis.
  58306. if (xAxisType === 'category') {
  58307. option.layout = 'horizontal';
  58308. ordinalMeta = xAxisModel.getOrdinalMeta();
  58309. addOrdinal = true;
  58310. } else if (yAxisType === 'category') {
  58311. option.layout = 'vertical';
  58312. ordinalMeta = yAxisModel.getOrdinalMeta();
  58313. addOrdinal = true;
  58314. } else {
  58315. option.layout = option.layout || 'horizontal';
  58316. }
  58317. var coordDims = ['x', 'y'];
  58318. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  58319. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  58320. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  58321. var axisModels = [xAxisModel, yAxisModel];
  58322. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  58323. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  58324. var data = option.data; // Clone a new data for next setOption({}) usage.
  58325. // Avoid modifying current data will affect further update.
  58326. if (data && addOrdinal) {
  58327. var newOptionData_1 = [];
  58328. each(data, function (item, index) {
  58329. var newItem;
  58330. if (isArray(item)) {
  58331. newItem = item.slice(); // Modify current using data.
  58332. item.unshift(index);
  58333. } else if (isArray(item.value)) {
  58334. newItem = extend({}, item);
  58335. newItem.value = newItem.value.slice(); // Modify current using data.
  58336. item.value.unshift(index);
  58337. } else {
  58338. newItem = item;
  58339. }
  58340. newOptionData_1.push(newItem);
  58341. });
  58342. option.data = newOptionData_1;
  58343. }
  58344. var defaultValueDimensions = this.defaultValueDimensions;
  58345. var coordDimensions = [{
  58346. name: baseAxisDim,
  58347. type: getDimensionTypeByAxis(baseAxisType),
  58348. ordinalMeta: ordinalMeta,
  58349. otherDims: {
  58350. tooltip: false,
  58351. itemName: 0
  58352. },
  58353. dimsDef: ['base']
  58354. }, {
  58355. name: otherAxisDim,
  58356. type: getDimensionTypeByAxis(otherAxisType),
  58357. dimsDef: defaultValueDimensions.slice()
  58358. }];
  58359. return createSeriesDataSimply(this, {
  58360. coordDimensions: coordDimensions,
  58361. dimensionsCount: defaultValueDimensions.length + 1,
  58362. encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this)
  58363. });
  58364. };
  58365. /**
  58366. * If horizontal, base axis is x, otherwise y.
  58367. * @override
  58368. */
  58369. WhiskerBoxCommonMixin.prototype.getBaseAxis = function () {
  58370. var dim = this._baseAxisDim;
  58371. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  58372. };
  58373. return WhiskerBoxCommonMixin;
  58374. }();
  58375. var BoxplotSeriesModel =
  58376. /** @class */
  58377. function (_super) {
  58378. __extends(BoxplotSeriesModel, _super);
  58379. function BoxplotSeriesModel() {
  58380. var _this = _super !== null && _super.apply(this, arguments) || this;
  58381. _this.type = BoxplotSeriesModel.type; // TODO
  58382. // box width represents group size, so dimension should have 'size'.
  58383. /**
  58384. * @see <https://en.wikipedia.org/wiki/Box_plot>
  58385. * The meanings of 'min' and 'max' depend on user,
  58386. * and echarts do not need to know it.
  58387. * @readOnly
  58388. */
  58389. _this.defaultValueDimensions = [{
  58390. name: 'min',
  58391. defaultTooltip: true
  58392. }, {
  58393. name: 'Q1',
  58394. defaultTooltip: true
  58395. }, {
  58396. name: 'median',
  58397. defaultTooltip: true
  58398. }, {
  58399. name: 'Q3',
  58400. defaultTooltip: true
  58401. }, {
  58402. name: 'max',
  58403. defaultTooltip: true
  58404. }];
  58405. _this.visualDrawType = 'stroke';
  58406. return _this;
  58407. }
  58408. BoxplotSeriesModel.type = 'series.boxplot';
  58409. BoxplotSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  58410. BoxplotSeriesModel.defaultOption = {
  58411. // zlevel: 0,
  58412. z: 2,
  58413. coordinateSystem: 'cartesian2d',
  58414. legendHoverLink: true,
  58415. layout: null,
  58416. boxWidth: [7, 50],
  58417. itemStyle: {
  58418. color: '#fff',
  58419. borderWidth: 1
  58420. },
  58421. emphasis: {
  58422. scale: true,
  58423. itemStyle: {
  58424. borderWidth: 2,
  58425. shadowBlur: 5,
  58426. shadowOffsetX: 1,
  58427. shadowOffsetY: 1,
  58428. shadowColor: 'rgba(0,0,0,0.2)'
  58429. }
  58430. },
  58431. animationDuration: 800
  58432. };
  58433. return BoxplotSeriesModel;
  58434. }(SeriesModel);
  58435. mixin(BoxplotSeriesModel, WhiskerBoxCommonMixin, true);
  58436. var BoxplotView =
  58437. /** @class */
  58438. function (_super) {
  58439. __extends(BoxplotView, _super);
  58440. function BoxplotView() {
  58441. var _this = _super !== null && _super.apply(this, arguments) || this;
  58442. _this.type = BoxplotView.type;
  58443. return _this;
  58444. }
  58445. BoxplotView.prototype.render = function (seriesModel, ecModel, api) {
  58446. var data = seriesModel.getData();
  58447. var group = this.group;
  58448. var oldData = this._data; // There is no old data only when first rendering or switching from
  58449. // stream mode to normal mode, where previous elements should be removed.
  58450. if (!this._data) {
  58451. group.removeAll();
  58452. }
  58453. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  58454. data.diff(oldData).add(function (newIdx) {
  58455. if (data.hasValue(newIdx)) {
  58456. var itemLayout = data.getItemLayout(newIdx);
  58457. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  58458. data.setItemGraphicEl(newIdx, symbolEl);
  58459. group.add(symbolEl);
  58460. }
  58461. }).update(function (newIdx, oldIdx) {
  58462. var symbolEl = oldData.getItemGraphicEl(oldIdx); // Empty data
  58463. if (!data.hasValue(newIdx)) {
  58464. group.remove(symbolEl);
  58465. return;
  58466. }
  58467. var itemLayout = data.getItemLayout(newIdx);
  58468. if (!symbolEl) {
  58469. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  58470. } else {
  58471. saveOldStyle(symbolEl);
  58472. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  58473. }
  58474. group.add(symbolEl);
  58475. data.setItemGraphicEl(newIdx, symbolEl);
  58476. }).remove(function (oldIdx) {
  58477. var el = oldData.getItemGraphicEl(oldIdx);
  58478. el && group.remove(el);
  58479. }).execute();
  58480. this._data = data;
  58481. };
  58482. BoxplotView.prototype.remove = function (ecModel) {
  58483. var group = this.group;
  58484. var data = this._data;
  58485. this._data = null;
  58486. data && data.eachItemGraphicEl(function (el) {
  58487. el && group.remove(el);
  58488. });
  58489. };
  58490. BoxplotView.type = 'boxplot';
  58491. return BoxplotView;
  58492. }(ChartView);
  58493. var BoxPathShape =
  58494. /** @class */
  58495. function () {
  58496. function BoxPathShape() {}
  58497. return BoxPathShape;
  58498. }();
  58499. var BoxPath =
  58500. /** @class */
  58501. function (_super) {
  58502. __extends(BoxPath, _super);
  58503. function BoxPath(opts) {
  58504. var _this = _super.call(this, opts) || this;
  58505. _this.type = 'boxplotBoxPath';
  58506. return _this;
  58507. }
  58508. BoxPath.prototype.getDefaultShape = function () {
  58509. return new BoxPathShape();
  58510. };
  58511. BoxPath.prototype.buildPath = function (ctx, shape) {
  58512. var ends = shape.points;
  58513. var i = 0;
  58514. ctx.moveTo(ends[i][0], ends[i][1]);
  58515. i++;
  58516. for (; i < 4; i++) {
  58517. ctx.lineTo(ends[i][0], ends[i][1]);
  58518. }
  58519. ctx.closePath();
  58520. for (; i < ends.length; i++) {
  58521. ctx.moveTo(ends[i][0], ends[i][1]);
  58522. i++;
  58523. ctx.lineTo(ends[i][0], ends[i][1]);
  58524. }
  58525. };
  58526. return BoxPath;
  58527. }(Path);
  58528. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  58529. var ends = itemLayout.ends;
  58530. var el = new BoxPath({
  58531. shape: {
  58532. points: isInit ? transInit(ends, constDim, itemLayout) : ends
  58533. }
  58534. });
  58535. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  58536. return el;
  58537. }
  58538. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  58539. var seriesModel = data.hostModel;
  58540. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  58541. updateMethod(el, {
  58542. shape: {
  58543. points: itemLayout.ends
  58544. }
  58545. }, seriesModel, dataIndex);
  58546. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  58547. el.style.strokeNoScale = true;
  58548. el.z2 = 100;
  58549. var itemModel = data.getItemModel(dataIndex);
  58550. var emphasisModel = itemModel.getModel('emphasis');
  58551. setStatesStylesFromModel(el, itemModel);
  58552. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  58553. }
  58554. function transInit(points, dim, itemLayout) {
  58555. return map(points, function (point) {
  58556. point = point.slice();
  58557. point[dim] = itemLayout.initBaseline;
  58558. return point;
  58559. });
  58560. }
  58561. var each$6 = each;
  58562. function boxplotLayout(ecModel) {
  58563. var groupResult = groupSeriesByAxis(ecModel);
  58564. each$6(groupResult, function (groupItem) {
  58565. var seriesModels = groupItem.seriesModels;
  58566. if (!seriesModels.length) {
  58567. return;
  58568. }
  58569. calculateBase(groupItem);
  58570. each$6(seriesModels, function (seriesModel, idx) {
  58571. layoutSingleSeries(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]);
  58572. });
  58573. });
  58574. }
  58575. /**
  58576. * Group series by axis.
  58577. */
  58578. function groupSeriesByAxis(ecModel) {
  58579. var result = [];
  58580. var axisList = [];
  58581. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  58582. var baseAxis = seriesModel.getBaseAxis();
  58583. var idx = indexOf(axisList, baseAxis);
  58584. if (idx < 0) {
  58585. idx = axisList.length;
  58586. axisList[idx] = baseAxis;
  58587. result[idx] = {
  58588. axis: baseAxis,
  58589. seriesModels: []
  58590. };
  58591. }
  58592. result[idx].seriesModels.push(seriesModel);
  58593. });
  58594. return result;
  58595. }
  58596. /**
  58597. * Calculate offset and box width for each series.
  58598. */
  58599. function calculateBase(groupItem) {
  58600. var baseAxis = groupItem.axis;
  58601. var seriesModels = groupItem.seriesModels;
  58602. var seriesCount = seriesModels.length;
  58603. var boxWidthList = groupItem.boxWidthList = [];
  58604. var boxOffsetList = groupItem.boxOffsetList = [];
  58605. var boundList = [];
  58606. var bandWidth;
  58607. if (baseAxis.type === 'category') {
  58608. bandWidth = baseAxis.getBandWidth();
  58609. } else {
  58610. var maxDataCount_1 = 0;
  58611. each$6(seriesModels, function (seriesModel) {
  58612. maxDataCount_1 = Math.max(maxDataCount_1, seriesModel.getData().count());
  58613. });
  58614. var extent = baseAxis.getExtent();
  58615. bandWidth = Math.abs(extent[1] - extent[0]) / maxDataCount_1;
  58616. }
  58617. each$6(seriesModels, function (seriesModel) {
  58618. var boxWidthBound = seriesModel.get('boxWidth');
  58619. if (!isArray(boxWidthBound)) {
  58620. boxWidthBound = [boxWidthBound, boxWidthBound];
  58621. }
  58622. boundList.push([parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0]);
  58623. });
  58624. var availableWidth = bandWidth * 0.8 - 2;
  58625. var boxGap = availableWidth / seriesCount * 0.3;
  58626. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  58627. var base = boxWidth / 2 - availableWidth / 2;
  58628. each$6(seriesModels, function (seriesModel, idx) {
  58629. boxOffsetList.push(base);
  58630. base += boxGap + boxWidth;
  58631. boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1]));
  58632. });
  58633. }
  58634. /**
  58635. * Calculate points location for each series.
  58636. */
  58637. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  58638. var coordSys = seriesModel.coordinateSystem;
  58639. var data = seriesModel.getData();
  58640. var halfWidth = boxWidth / 2;
  58641. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  58642. var vDimIdx = 1 - cDimIdx;
  58643. var coordDims = ['x', 'y'];
  58644. var cDim = data.mapDimension(coordDims[cDimIdx]);
  58645. var vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
  58646. if (cDim == null || vDims.length < 5) {
  58647. return;
  58648. }
  58649. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  58650. var axisDimVal = data.get(cDim, dataIndex);
  58651. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  58652. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  58653. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  58654. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  58655. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  58656. var ends = [];
  58657. addBodyEnd(ends, end2, false);
  58658. addBodyEnd(ends, end4, true);
  58659. ends.push(end1, end2, end5, end4);
  58660. layEndLine(ends, end1);
  58661. layEndLine(ends, end5);
  58662. layEndLine(ends, median);
  58663. data.setItemLayout(dataIndex, {
  58664. initBaseline: median[vDimIdx],
  58665. ends: ends
  58666. });
  58667. }
  58668. function getPoint(axisDimVal, dim, dataIndex) {
  58669. var val = data.get(dim, dataIndex);
  58670. var p = [];
  58671. p[cDimIdx] = axisDimVal;
  58672. p[vDimIdx] = val;
  58673. var point;
  58674. if (isNaN(axisDimVal) || isNaN(val)) {
  58675. point = [NaN, NaN];
  58676. } else {
  58677. point = coordSys.dataToPoint(p);
  58678. point[cDimIdx] += offset;
  58679. }
  58680. return point;
  58681. }
  58682. function addBodyEnd(ends, point, start) {
  58683. var point1 = point.slice();
  58684. var point2 = point.slice();
  58685. point1[cDimIdx] += halfWidth;
  58686. point2[cDimIdx] -= halfWidth;
  58687. start ? ends.push(point1, point2) : ends.push(point2, point1);
  58688. }
  58689. function layEndLine(ends, endCenter) {
  58690. var from = endCenter.slice();
  58691. var to = endCenter.slice();
  58692. from[cDimIdx] -= halfWidth;
  58693. to[cDimIdx] += halfWidth;
  58694. ends.push(from, to);
  58695. }
  58696. }
  58697. /**
  58698. * See:
  58699. * <https://en.wikipedia.org/wiki/Box_plot#cite_note-frigge_hoaglin_iglewicz-2>
  58700. * <http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html>
  58701. *
  58702. * Helper method for preparing data.
  58703. *
  58704. * @param rawData like
  58705. * [
  58706. * [12,232,443], (raw data set for the first box)
  58707. * [3843,5545,1232], (raw data set for the second box)
  58708. * ...
  58709. * ]
  58710. * @param opt.boundIQR=1.5 Data less than min bound is outlier.
  58711. * default 1.5, means Q1 - 1.5 * (Q3 - Q1).
  58712. * If 'none'/0 passed, min bound will not be used.
  58713. */
  58714. function prepareBoxplotData(rawData, opt) {
  58715. opt = opt || {};
  58716. var boxData = [];
  58717. var outliers = [];
  58718. var boundIQR = opt.boundIQR;
  58719. var useExtreme = boundIQR === 'none' || boundIQR === 0;
  58720. for (var i = 0; i < rawData.length; i++) {
  58721. var ascList = asc(rawData[i].slice());
  58722. var Q1 = quantile(ascList, 0.25);
  58723. var Q2 = quantile(ascList, 0.5);
  58724. var Q3 = quantile(ascList, 0.75);
  58725. var min = ascList[0];
  58726. var max = ascList[ascList.length - 1];
  58727. var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
  58728. var low = useExtreme ? min : Math.max(min, Q1 - bound);
  58729. var high = useExtreme ? max : Math.min(max, Q3 + bound);
  58730. var itemNameFormatter = opt.itemNameFormatter;
  58731. var itemName = isFunction(itemNameFormatter) ? itemNameFormatter({
  58732. value: i
  58733. }) : isString(itemNameFormatter) ? itemNameFormatter.replace('{value}', i + '') : i + '';
  58734. boxData.push([itemName, low, Q1, Q2, Q3, high]);
  58735. for (var j = 0; j < ascList.length; j++) {
  58736. var dataItem = ascList[j];
  58737. if (dataItem < low || dataItem > high) {
  58738. var outlier = [itemName, dataItem];
  58739. outliers.push(outlier);
  58740. }
  58741. }
  58742. }
  58743. return {
  58744. boxData: boxData,
  58745. outliers: outliers
  58746. };
  58747. }
  58748. var boxplotTransform = {
  58749. type: 'echarts:boxplot',
  58750. transform: function transform(params) {
  58751. var upstream = params.upstream;
  58752. if (upstream.sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS) {
  58753. var errMsg = '';
  58754. if ("development" !== 'production') {
  58755. errMsg = makePrintable('source data is not applicable for this boxplot transform. Expect number[][].');
  58756. }
  58757. throwError(errMsg);
  58758. }
  58759. var result = prepareBoxplotData(upstream.getRawData(), params.config);
  58760. return [{
  58761. dimensions: ['ItemName', 'Low', 'Q1', 'Q2', 'Q3', 'High'],
  58762. data: result.boxData
  58763. }, {
  58764. data: result.outliers
  58765. }];
  58766. }
  58767. };
  58768. function install$j(registers) {
  58769. registers.registerSeriesModel(BoxplotSeriesModel);
  58770. registers.registerChartView(BoxplotView);
  58771. registers.registerLayout(boxplotLayout);
  58772. registers.registerTransform(boxplotTransform);
  58773. }
  58774. var SKIP_PROPS = ['color', 'borderColor'];
  58775. var CandlestickView =
  58776. /** @class */
  58777. function (_super) {
  58778. __extends(CandlestickView, _super);
  58779. function CandlestickView() {
  58780. var _this = _super !== null && _super.apply(this, arguments) || this;
  58781. _this.type = CandlestickView.type;
  58782. return _this;
  58783. }
  58784. CandlestickView.prototype.render = function (seriesModel, ecModel, api) {
  58785. // If there is clipPath created in large mode. Remove it.
  58786. this.group.removeClipPath(); // Clear previously rendered progressive elements.
  58787. this._progressiveEls = null;
  58788. this._updateDrawMode(seriesModel);
  58789. this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel);
  58790. };
  58791. CandlestickView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  58792. this._clear();
  58793. this._updateDrawMode(seriesModel);
  58794. };
  58795. CandlestickView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  58796. this._progressiveEls = [];
  58797. this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel);
  58798. };
  58799. CandlestickView.prototype.eachRendered = function (cb) {
  58800. traverseElements(this._progressiveEls || this.group, cb);
  58801. };
  58802. CandlestickView.prototype._updateDrawMode = function (seriesModel) {
  58803. var isLargeDraw = seriesModel.pipelineContext.large;
  58804. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  58805. this._isLargeDraw = isLargeDraw;
  58806. this._clear();
  58807. }
  58808. };
  58809. CandlestickView.prototype._renderNormal = function (seriesModel) {
  58810. var data = seriesModel.getData();
  58811. var oldData = this._data;
  58812. var group = this.group;
  58813. var isSimpleBox = data.getLayout('isSimpleBox');
  58814. var needsClip = seriesModel.get('clip', true);
  58815. var coord = seriesModel.coordinateSystem;
  58816. var clipArea = coord.getArea && coord.getArea(); // There is no old data only when first rendering or switching from
  58817. // stream mode to normal mode, where previous elements should be removed.
  58818. if (!this._data) {
  58819. group.removeAll();
  58820. }
  58821. data.diff(oldData).add(function (newIdx) {
  58822. if (data.hasValue(newIdx)) {
  58823. var itemLayout = data.getItemLayout(newIdx);
  58824. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  58825. return;
  58826. }
  58827. var el = createNormalBox$1(itemLayout, newIdx, true);
  58828. initProps(el, {
  58829. shape: {
  58830. points: itemLayout.ends
  58831. }
  58832. }, seriesModel, newIdx);
  58833. setBoxCommon(el, data, newIdx, isSimpleBox);
  58834. group.add(el);
  58835. data.setItemGraphicEl(newIdx, el);
  58836. }
  58837. }).update(function (newIdx, oldIdx) {
  58838. var el = oldData.getItemGraphicEl(oldIdx); // Empty data
  58839. if (!data.hasValue(newIdx)) {
  58840. group.remove(el);
  58841. return;
  58842. }
  58843. var itemLayout = data.getItemLayout(newIdx);
  58844. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  58845. group.remove(el);
  58846. return;
  58847. }
  58848. if (!el) {
  58849. el = createNormalBox$1(itemLayout);
  58850. } else {
  58851. updateProps(el, {
  58852. shape: {
  58853. points: itemLayout.ends
  58854. }
  58855. }, seriesModel, newIdx);
  58856. saveOldStyle(el);
  58857. }
  58858. setBoxCommon(el, data, newIdx, isSimpleBox);
  58859. group.add(el);
  58860. data.setItemGraphicEl(newIdx, el);
  58861. }).remove(function (oldIdx) {
  58862. var el = oldData.getItemGraphicEl(oldIdx);
  58863. el && group.remove(el);
  58864. }).execute();
  58865. this._data = data;
  58866. };
  58867. CandlestickView.prototype._renderLarge = function (seriesModel) {
  58868. this._clear();
  58869. createLarge$1(seriesModel, this.group);
  58870. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  58871. if (clipPath) {
  58872. this.group.setClipPath(clipPath);
  58873. } else {
  58874. this.group.removeClipPath();
  58875. }
  58876. };
  58877. CandlestickView.prototype._incrementalRenderNormal = function (params, seriesModel) {
  58878. var data = seriesModel.getData();
  58879. var isSimpleBox = data.getLayout('isSimpleBox');
  58880. var dataIndex;
  58881. while ((dataIndex = params.next()) != null) {
  58882. var itemLayout = data.getItemLayout(dataIndex);
  58883. var el = createNormalBox$1(itemLayout);
  58884. setBoxCommon(el, data, dataIndex, isSimpleBox);
  58885. el.incremental = true;
  58886. this.group.add(el);
  58887. this._progressiveEls.push(el);
  58888. }
  58889. };
  58890. CandlestickView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  58891. createLarge$1(seriesModel, this.group, this._progressiveEls, true);
  58892. };
  58893. CandlestickView.prototype.remove = function (ecModel) {
  58894. this._clear();
  58895. };
  58896. CandlestickView.prototype._clear = function () {
  58897. this.group.removeAll();
  58898. this._data = null;
  58899. };
  58900. CandlestickView.type = 'candlestick';
  58901. return CandlestickView;
  58902. }(ChartView);
  58903. var NormalBoxPathShape =
  58904. /** @class */
  58905. function () {
  58906. function NormalBoxPathShape() {}
  58907. return NormalBoxPathShape;
  58908. }();
  58909. var NormalBoxPath =
  58910. /** @class */
  58911. function (_super) {
  58912. __extends(NormalBoxPath, _super);
  58913. function NormalBoxPath(opts) {
  58914. var _this = _super.call(this, opts) || this;
  58915. _this.type = 'normalCandlestickBox';
  58916. return _this;
  58917. }
  58918. NormalBoxPath.prototype.getDefaultShape = function () {
  58919. return new NormalBoxPathShape();
  58920. };
  58921. NormalBoxPath.prototype.buildPath = function (ctx, shape) {
  58922. var ends = shape.points;
  58923. if (this.__simpleBox) {
  58924. ctx.moveTo(ends[4][0], ends[4][1]);
  58925. ctx.lineTo(ends[6][0], ends[6][1]);
  58926. } else {
  58927. ctx.moveTo(ends[0][0], ends[0][1]);
  58928. ctx.lineTo(ends[1][0], ends[1][1]);
  58929. ctx.lineTo(ends[2][0], ends[2][1]);
  58930. ctx.lineTo(ends[3][0], ends[3][1]);
  58931. ctx.closePath();
  58932. ctx.moveTo(ends[4][0], ends[4][1]);
  58933. ctx.lineTo(ends[5][0], ends[5][1]);
  58934. ctx.moveTo(ends[6][0], ends[6][1]);
  58935. ctx.lineTo(ends[7][0], ends[7][1]);
  58936. }
  58937. };
  58938. return NormalBoxPath;
  58939. }(Path);
  58940. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  58941. var ends = itemLayout.ends;
  58942. return new NormalBoxPath({
  58943. shape: {
  58944. points: isInit ? transInit$1(ends, itemLayout) : ends
  58945. },
  58946. z2: 100
  58947. });
  58948. }
  58949. function isNormalBoxClipped(clipArea, itemLayout) {
  58950. var clipped = true;
  58951. for (var i = 0; i < itemLayout.ends.length; i++) {
  58952. // If any point are in the region.
  58953. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  58954. clipped = false;
  58955. break;
  58956. }
  58957. }
  58958. return clipped;
  58959. }
  58960. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  58961. var itemModel = data.getItemModel(dataIndex);
  58962. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  58963. el.style.strokeNoScale = true;
  58964. el.__simpleBox = isSimpleBox;
  58965. setStatesStylesFromModel(el, itemModel);
  58966. }
  58967. function transInit$1(points, itemLayout) {
  58968. return map(points, function (point) {
  58969. point = point.slice();
  58970. point[1] = itemLayout.initBaseline;
  58971. return point;
  58972. });
  58973. }
  58974. var LargeBoxPathShape =
  58975. /** @class */
  58976. function () {
  58977. function LargeBoxPathShape() {}
  58978. return LargeBoxPathShape;
  58979. }();
  58980. var LargeBoxPath =
  58981. /** @class */
  58982. function (_super) {
  58983. __extends(LargeBoxPath, _super);
  58984. function LargeBoxPath(opts) {
  58985. var _this = _super.call(this, opts) || this;
  58986. _this.type = 'largeCandlestickBox';
  58987. return _this;
  58988. }
  58989. LargeBoxPath.prototype.getDefaultShape = function () {
  58990. return new LargeBoxPathShape();
  58991. };
  58992. LargeBoxPath.prototype.buildPath = function (ctx, shape) {
  58993. // Drawing lines is more efficient than drawing
  58994. // a whole line or drawing rects.
  58995. var points = shape.points;
  58996. for (var i = 0; i < points.length;) {
  58997. if (this.__sign === points[i++]) {
  58998. var x = points[i++];
  58999. ctx.moveTo(x, points[i++]);
  59000. ctx.lineTo(x, points[i++]);
  59001. } else {
  59002. i += 3;
  59003. }
  59004. }
  59005. };
  59006. return LargeBoxPath;
  59007. }(Path);
  59008. function createLarge$1(seriesModel, group, progressiveEls, incremental) {
  59009. var data = seriesModel.getData();
  59010. var largePoints = data.getLayout('largePoints');
  59011. var elP = new LargeBoxPath({
  59012. shape: {
  59013. points: largePoints
  59014. },
  59015. __sign: 1,
  59016. ignoreCoarsePointer: true
  59017. });
  59018. group.add(elP);
  59019. var elN = new LargeBoxPath({
  59020. shape: {
  59021. points: largePoints
  59022. },
  59023. __sign: -1,
  59024. ignoreCoarsePointer: true
  59025. });
  59026. group.add(elN);
  59027. var elDoji = new LargeBoxPath({
  59028. shape: {
  59029. points: largePoints
  59030. },
  59031. __sign: 0,
  59032. ignoreCoarsePointer: true
  59033. });
  59034. group.add(elDoji);
  59035. setLargeStyle(1, elP, seriesModel);
  59036. setLargeStyle(-1, elN, seriesModel);
  59037. setLargeStyle(0, elDoji, seriesModel);
  59038. if (incremental) {
  59039. elP.incremental = true;
  59040. elN.incremental = true;
  59041. }
  59042. if (progressiveEls) {
  59043. progressiveEls.push(elP, elN);
  59044. }
  59045. }
  59046. function setLargeStyle(sign, el, seriesModel, data) {
  59047. // TODO put in visual?
  59048. var borderColor = seriesModel.get(['itemStyle', sign > 0 ? 'borderColor' : 'borderColor0']) // Use color for border color by default.
  59049. || seriesModel.get(['itemStyle', sign > 0 ? 'color' : 'color0']);
  59050. if (sign === 0) {
  59051. borderColor = seriesModel.get(['itemStyle', 'borderColorDoji']);
  59052. } // Color must be excluded.
  59053. // Because symbol provide setColor individually to set fill and stroke
  59054. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(SKIP_PROPS);
  59055. el.useStyle(itemStyle);
  59056. el.style.fill = null;
  59057. el.style.stroke = borderColor;
  59058. }
  59059. var CandlestickSeriesModel =
  59060. /** @class */
  59061. function (_super) {
  59062. __extends(CandlestickSeriesModel, _super);
  59063. function CandlestickSeriesModel() {
  59064. var _this = _super !== null && _super.apply(this, arguments) || this;
  59065. _this.type = CandlestickSeriesModel.type;
  59066. _this.defaultValueDimensions = [{
  59067. name: 'open',
  59068. defaultTooltip: true
  59069. }, {
  59070. name: 'close',
  59071. defaultTooltip: true
  59072. }, {
  59073. name: 'lowest',
  59074. defaultTooltip: true
  59075. }, {
  59076. name: 'highest',
  59077. defaultTooltip: true
  59078. }];
  59079. return _this;
  59080. }
  59081. /**
  59082. * Get dimension for shadow in dataZoom
  59083. * @return dimension name
  59084. */
  59085. CandlestickSeriesModel.prototype.getShadowDim = function () {
  59086. return 'open';
  59087. };
  59088. CandlestickSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  59089. var itemLayout = data.getItemLayout(dataIndex);
  59090. return itemLayout && selectors.rect(itemLayout.brushRect);
  59091. };
  59092. CandlestickSeriesModel.type = 'series.candlestick';
  59093. CandlestickSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  59094. CandlestickSeriesModel.defaultOption = {
  59095. // zlevel: 0,
  59096. z: 2,
  59097. coordinateSystem: 'cartesian2d',
  59098. legendHoverLink: true,
  59099. // xAxisIndex: 0,
  59100. // yAxisIndex: 0,
  59101. layout: null,
  59102. clip: true,
  59103. itemStyle: {
  59104. color: '#eb5454',
  59105. color0: '#47b262',
  59106. borderColor: '#eb5454',
  59107. borderColor0: '#47b262',
  59108. borderColorDoji: null,
  59109. // borderColor: '#d24040',
  59110. // borderColor0: '#398f4f',
  59111. borderWidth: 1
  59112. },
  59113. emphasis: {
  59114. scale: true,
  59115. itemStyle: {
  59116. borderWidth: 2
  59117. }
  59118. },
  59119. barMaxWidth: null,
  59120. barMinWidth: null,
  59121. barWidth: null,
  59122. large: true,
  59123. largeThreshold: 600,
  59124. progressive: 3e3,
  59125. progressiveThreshold: 1e4,
  59126. progressiveChunkMode: 'mod',
  59127. animationEasing: 'linear',
  59128. animationDuration: 300
  59129. };
  59130. return CandlestickSeriesModel;
  59131. }(SeriesModel);
  59132. mixin(CandlestickSeriesModel, WhiskerBoxCommonMixin, true);
  59133. function candlestickPreprocessor(option) {
  59134. if (!option || !isArray(option.series)) {
  59135. return;
  59136. } // Translate 'k' to 'candlestick'.
  59137. each(option.series, function (seriesItem) {
  59138. if (isObject(seriesItem) && seriesItem.type === 'k') {
  59139. seriesItem.type = 'candlestick';
  59140. }
  59141. });
  59142. }
  59143. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  59144. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  59145. var dojiBorderColorQuery = ['itemStyle', 'borderColorDoji'];
  59146. var positiveColorQuery = ['itemStyle', 'color'];
  59147. var negativeColorQuery = ['itemStyle', 'color0'];
  59148. var candlestickVisual = {
  59149. seriesType: 'candlestick',
  59150. plan: createRenderPlanner(),
  59151. // For legend.
  59152. performRawSeries: true,
  59153. reset: function (seriesModel, ecModel) {
  59154. function getColor(sign, model) {
  59155. return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
  59156. }
  59157. function getBorderColor(sign, model) {
  59158. return model.get(sign === 0 ? dojiBorderColorQuery : sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
  59159. } // Only visible series has each data be visual encoded
  59160. if (ecModel.isSeriesFiltered(seriesModel)) {
  59161. return;
  59162. }
  59163. var isLargeRender = seriesModel.pipelineContext.large;
  59164. return !isLargeRender && {
  59165. progress: function (params, data) {
  59166. var dataIndex;
  59167. while ((dataIndex = params.next()) != null) {
  59168. var itemModel = data.getItemModel(dataIndex);
  59169. var sign = data.getItemLayout(dataIndex).sign;
  59170. var style = itemModel.getItemStyle();
  59171. style.fill = getColor(sign, itemModel);
  59172. style.stroke = getBorderColor(sign, itemModel) || style.fill;
  59173. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  59174. extend(existsStyle, style);
  59175. }
  59176. }
  59177. };
  59178. }
  59179. };
  59180. var candlestickLayout = {
  59181. seriesType: 'candlestick',
  59182. plan: createRenderPlanner(),
  59183. reset: function (seriesModel) {
  59184. var coordSys = seriesModel.coordinateSystem;
  59185. var data = seriesModel.getData();
  59186. var candleWidth = calculateCandleWidth(seriesModel, data);
  59187. var cDimIdx = 0;
  59188. var vDimIdx = 1;
  59189. var coordDims = ['x', 'y'];
  59190. var cDimI = data.getDimensionIndex(data.mapDimension(coordDims[cDimIdx]));
  59191. var vDimsI = map(data.mapDimensionsAll(coordDims[vDimIdx]), data.getDimensionIndex, data);
  59192. var openDimI = vDimsI[0];
  59193. var closeDimI = vDimsI[1];
  59194. var lowestDimI = vDimsI[2];
  59195. var highestDimI = vDimsI[3];
  59196. data.setLayout({
  59197. candleWidth: candleWidth,
  59198. // The value is experimented visually.
  59199. isSimpleBox: candleWidth <= 1.3
  59200. });
  59201. if (cDimI < 0 || vDimsI.length < 4) {
  59202. return;
  59203. }
  59204. return {
  59205. progress: seriesModel.pipelineContext.large ? largeProgress : normalProgress
  59206. };
  59207. function normalProgress(params, data) {
  59208. var dataIndex;
  59209. var store = data.getStore();
  59210. while ((dataIndex = params.next()) != null) {
  59211. var axisDimVal = store.get(cDimI, dataIndex);
  59212. var openVal = store.get(openDimI, dataIndex);
  59213. var closeVal = store.get(closeDimI, dataIndex);
  59214. var lowestVal = store.get(lowestDimI, dataIndex);
  59215. var highestVal = store.get(highestDimI, dataIndex);
  59216. var ocLow = Math.min(openVal, closeVal);
  59217. var ocHigh = Math.max(openVal, closeVal);
  59218. var ocLowPoint = getPoint(ocLow, axisDimVal);
  59219. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  59220. var lowestPoint = getPoint(lowestVal, axisDimVal);
  59221. var highestPoint = getPoint(highestVal, axisDimVal);
  59222. var ends = [];
  59223. addBodyEnd(ends, ocHighPoint, 0);
  59224. addBodyEnd(ends, ocLowPoint, 1);
  59225. ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint));
  59226. var itemModel = data.getItemModel(dataIndex);
  59227. var hasDojiColor = !!itemModel.get(['itemStyle', 'borderColorDoji']);
  59228. data.setItemLayout(dataIndex, {
  59229. sign: getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor),
  59230. initBaseline: openVal > closeVal ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx],
  59231. ends: ends,
  59232. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  59233. });
  59234. }
  59235. function getPoint(val, axisDimVal) {
  59236. var p = [];
  59237. p[cDimIdx] = axisDimVal;
  59238. p[vDimIdx] = val;
  59239. return isNaN(axisDimVal) || isNaN(val) ? [NaN, NaN] : coordSys.dataToPoint(p);
  59240. }
  59241. function addBodyEnd(ends, point, start) {
  59242. var point1 = point.slice();
  59243. var point2 = point.slice();
  59244. point1[cDimIdx] = subPixelOptimize$1(point1[cDimIdx] + candleWidth / 2, 1, false);
  59245. point2[cDimIdx] = subPixelOptimize$1(point2[cDimIdx] - candleWidth / 2, 1, true);
  59246. start ? ends.push(point1, point2) : ends.push(point2, point1);
  59247. }
  59248. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  59249. var pmin = getPoint(lowestVal, axisDimVal);
  59250. var pmax = getPoint(highestVal, axisDimVal);
  59251. pmin[cDimIdx] -= candleWidth / 2;
  59252. pmax[cDimIdx] -= candleWidth / 2;
  59253. return {
  59254. x: pmin[0],
  59255. y: pmin[1],
  59256. width: candleWidth ,
  59257. height: pmax[1] - pmin[1]
  59258. };
  59259. }
  59260. function subPixelOptimizePoint(point) {
  59261. point[cDimIdx] = subPixelOptimize$1(point[cDimIdx], 1);
  59262. return point;
  59263. }
  59264. }
  59265. function largeProgress(params, data) {
  59266. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  59267. var points = createFloat32Array(params.count * 4);
  59268. var offset = 0;
  59269. var point;
  59270. var tmpIn = [];
  59271. var tmpOut = [];
  59272. var dataIndex;
  59273. var store = data.getStore();
  59274. var hasDojiColor = !!seriesModel.get(['itemStyle', 'borderColorDoji']);
  59275. while ((dataIndex = params.next()) != null) {
  59276. var axisDimVal = store.get(cDimI, dataIndex);
  59277. var openVal = store.get(openDimI, dataIndex);
  59278. var closeVal = store.get(closeDimI, dataIndex);
  59279. var lowestVal = store.get(lowestDimI, dataIndex);
  59280. var highestVal = store.get(highestDimI, dataIndex);
  59281. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  59282. points[offset++] = NaN;
  59283. offset += 3;
  59284. continue;
  59285. }
  59286. points[offset++] = getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor);
  59287. tmpIn[cDimIdx] = axisDimVal;
  59288. tmpIn[vDimIdx] = lowestVal;
  59289. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  59290. points[offset++] = point ? point[0] : NaN;
  59291. points[offset++] = point ? point[1] : NaN;
  59292. tmpIn[vDimIdx] = highestVal;
  59293. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  59294. points[offset++] = point ? point[1] : NaN;
  59295. }
  59296. data.setLayout('largePoints', points);
  59297. }
  59298. }
  59299. };
  59300. /**
  59301. * Get the sign of a single data.
  59302. *
  59303. * @returns 0 for doji with hasDojiColor: true,
  59304. * 1 for positive,
  59305. * -1 for negative.
  59306. */
  59307. function getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor) {
  59308. var sign;
  59309. if (openVal > closeVal) {
  59310. sign = -1;
  59311. } else if (openVal < closeVal) {
  59312. sign = 1;
  59313. } else {
  59314. sign = hasDojiColor // When doji color is set, use it instead of color/color0.
  59315. ? 0 : dataIndex > 0 // If close === open, compare with close of last record
  59316. ? store.get(closeDimI, dataIndex - 1) <= closeVal ? 1 : -1 : // No record of previous, set to be positive
  59317. 1;
  59318. }
  59319. return sign;
  59320. }
  59321. function calculateCandleWidth(seriesModel, data) {
  59322. var baseAxis = seriesModel.getBaseAxis();
  59323. var extent;
  59324. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  59325. var barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth);
  59326. var barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth);
  59327. var barWidth = seriesModel.get('barWidth');
  59328. return barWidth != null ? parsePercent$1(barWidth, bandWidth) // Put max outer to ensure bar visible in spite of overlap.
  59329. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  59330. }
  59331. function install$k(registers) {
  59332. registers.registerChartView(CandlestickView);
  59333. registers.registerSeriesModel(CandlestickSeriesModel);
  59334. registers.registerPreprocessor(candlestickPreprocessor);
  59335. registers.registerVisual(candlestickVisual);
  59336. registers.registerLayout(candlestickLayout);
  59337. }
  59338. function updateRipplePath(rippleGroup, effectCfg) {
  59339. var color = effectCfg.rippleEffectColor || effectCfg.color;
  59340. rippleGroup.eachChild(function (ripplePath) {
  59341. ripplePath.attr({
  59342. z: effectCfg.z,
  59343. zlevel: effectCfg.zlevel,
  59344. style: {
  59345. stroke: effectCfg.brushType === 'stroke' ? color : null,
  59346. fill: effectCfg.brushType === 'fill' ? color : null
  59347. }
  59348. });
  59349. });
  59350. }
  59351. var EffectSymbol =
  59352. /** @class */
  59353. function (_super) {
  59354. __extends(EffectSymbol, _super);
  59355. function EffectSymbol(data, idx) {
  59356. var _this = _super.call(this) || this;
  59357. var symbol = new Symbol(data, idx);
  59358. var rippleGroup = new Group();
  59359. _this.add(symbol);
  59360. _this.add(rippleGroup);
  59361. _this.updateData(data, idx);
  59362. return _this;
  59363. }
  59364. EffectSymbol.prototype.stopEffectAnimation = function () {
  59365. this.childAt(1).removeAll();
  59366. };
  59367. EffectSymbol.prototype.startEffectAnimation = function (effectCfg) {
  59368. var symbolType = effectCfg.symbolType;
  59369. var color = effectCfg.color;
  59370. var rippleNumber = effectCfg.rippleNumber;
  59371. var rippleGroup = this.childAt(1);
  59372. for (var i = 0; i < rippleNumber; i++) {
  59373. // If width/height are set too small (e.g., set to 1) on ios10
  59374. // and macOS Sierra, a circle stroke become a rect, no matter what
  59375. // the scale is set. So we set width/height as 2. See #4136.
  59376. var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color);
  59377. ripplePath.attr({
  59378. style: {
  59379. strokeNoScale: true
  59380. },
  59381. z2: 99,
  59382. silent: true,
  59383. scaleX: 0.5,
  59384. scaleY: 0.5
  59385. });
  59386. var delay = -i / rippleNumber * effectCfg.period + effectCfg.effectOffset;
  59387. ripplePath.animate('', true).when(effectCfg.period, {
  59388. scaleX: effectCfg.rippleScale / 2,
  59389. scaleY: effectCfg.rippleScale / 2
  59390. }).delay(delay).start();
  59391. ripplePath.animateStyle(true).when(effectCfg.period, {
  59392. opacity: 0
  59393. }).delay(delay).start();
  59394. rippleGroup.add(ripplePath);
  59395. }
  59396. updateRipplePath(rippleGroup, effectCfg);
  59397. };
  59398. /**
  59399. * Update effect symbol
  59400. */
  59401. EffectSymbol.prototype.updateEffectAnimation = function (effectCfg) {
  59402. var oldEffectCfg = this._effectCfg;
  59403. var rippleGroup = this.childAt(1); // Must reinitialize effect if following configuration changed
  59404. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale', 'rippleNumber'];
  59405. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  59406. var propName = DIFFICULT_PROPS[i];
  59407. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  59408. this.stopEffectAnimation();
  59409. this.startEffectAnimation(effectCfg);
  59410. return;
  59411. }
  59412. }
  59413. updateRipplePath(rippleGroup, effectCfg);
  59414. };
  59415. /**
  59416. * Highlight symbol
  59417. */
  59418. EffectSymbol.prototype.highlight = function () {
  59419. enterEmphasis(this);
  59420. };
  59421. /**
  59422. * Downplay symbol
  59423. */
  59424. EffectSymbol.prototype.downplay = function () {
  59425. leaveEmphasis(this);
  59426. };
  59427. EffectSymbol.prototype.getSymbolType = function () {
  59428. var symbol = this.childAt(0);
  59429. return symbol && symbol.getSymbolType();
  59430. };
  59431. /**
  59432. * Update symbol properties
  59433. */
  59434. EffectSymbol.prototype.updateData = function (data, idx) {
  59435. var _this = this;
  59436. var seriesModel = data.hostModel;
  59437. this.childAt(0).updateData(data, idx);
  59438. var rippleGroup = this.childAt(1);
  59439. var itemModel = data.getItemModel(idx);
  59440. var symbolType = data.getItemVisual(idx, 'symbol');
  59441. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  59442. var symbolStyle = data.getItemVisual(idx, 'style');
  59443. var color = symbolStyle && symbolStyle.fill;
  59444. var emphasisModel = itemModel.getModel('emphasis');
  59445. rippleGroup.setScale(symbolSize);
  59446. rippleGroup.traverse(function (ripplePath) {
  59447. ripplePath.setStyle('fill', color);
  59448. });
  59449. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  59450. if (symbolOffset) {
  59451. rippleGroup.x = symbolOffset[0];
  59452. rippleGroup.y = symbolOffset[1];
  59453. }
  59454. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  59455. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  59456. var effectCfg = {};
  59457. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  59458. effectCfg.rippleScale = itemModel.get(['rippleEffect', 'scale']);
  59459. effectCfg.brushType = itemModel.get(['rippleEffect', 'brushType']);
  59460. effectCfg.period = itemModel.get(['rippleEffect', 'period']) * 1000;
  59461. effectCfg.effectOffset = idx / data.count();
  59462. effectCfg.z = seriesModel.getShallow('z') || 0;
  59463. effectCfg.zlevel = seriesModel.getShallow('zlevel') || 0;
  59464. effectCfg.symbolType = symbolType;
  59465. effectCfg.color = color;
  59466. effectCfg.rippleEffectColor = itemModel.get(['rippleEffect', 'color']);
  59467. effectCfg.rippleNumber = itemModel.get(['rippleEffect', 'number']);
  59468. if (effectCfg.showEffectOn === 'render') {
  59469. this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg);
  59470. this._effectCfg = effectCfg;
  59471. } else {
  59472. // Not keep old effect config
  59473. this._effectCfg = null;
  59474. this.stopEffectAnimation();
  59475. this.onHoverStateChange = function (toState) {
  59476. if (toState === 'emphasis') {
  59477. if (effectCfg.showEffectOn !== 'render') {
  59478. _this.startEffectAnimation(effectCfg);
  59479. }
  59480. } else if (toState === 'normal') {
  59481. if (effectCfg.showEffectOn !== 'render') {
  59482. _this.stopEffectAnimation();
  59483. }
  59484. }
  59485. };
  59486. }
  59487. this._effectCfg = effectCfg;
  59488. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  59489. };
  59490. EffectSymbol.prototype.fadeOut = function (cb) {
  59491. cb && cb();
  59492. };
  59493. return EffectSymbol;
  59494. }(Group);
  59495. var EffectScatterView =
  59496. /** @class */
  59497. function (_super) {
  59498. __extends(EffectScatterView, _super);
  59499. function EffectScatterView() {
  59500. var _this = _super !== null && _super.apply(this, arguments) || this;
  59501. _this.type = EffectScatterView.type;
  59502. return _this;
  59503. }
  59504. EffectScatterView.prototype.init = function () {
  59505. this._symbolDraw = new SymbolDraw(EffectSymbol);
  59506. };
  59507. EffectScatterView.prototype.render = function (seriesModel, ecModel, api) {
  59508. var data = seriesModel.getData();
  59509. var effectSymbolDraw = this._symbolDraw;
  59510. effectSymbolDraw.updateData(data, {
  59511. clipShape: this._getClipShape(seriesModel)
  59512. });
  59513. this.group.add(effectSymbolDraw.group);
  59514. };
  59515. EffectScatterView.prototype._getClipShape = function (seriesModel) {
  59516. var coordSys = seriesModel.coordinateSystem;
  59517. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  59518. return seriesModel.get('clip', true) ? clipArea : null;
  59519. };
  59520. EffectScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  59521. var data = seriesModel.getData();
  59522. this.group.dirty();
  59523. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  59524. if (res.progress) {
  59525. res.progress({
  59526. start: 0,
  59527. end: data.count(),
  59528. count: data.count()
  59529. }, data);
  59530. }
  59531. this._symbolDraw.updateLayout();
  59532. };
  59533. EffectScatterView.prototype._updateGroupTransform = function (seriesModel) {
  59534. var coordSys = seriesModel.coordinateSystem;
  59535. if (coordSys && coordSys.getRoamTransform) {
  59536. this.group.transform = clone$2(coordSys.getRoamTransform());
  59537. this.group.decomposeTransform();
  59538. }
  59539. };
  59540. EffectScatterView.prototype.remove = function (ecModel, api) {
  59541. this._symbolDraw && this._symbolDraw.remove(true);
  59542. };
  59543. EffectScatterView.type = 'effectScatter';
  59544. return EffectScatterView;
  59545. }(ChartView);
  59546. var EffectScatterSeriesModel =
  59547. /** @class */
  59548. function (_super) {
  59549. __extends(EffectScatterSeriesModel, _super);
  59550. function EffectScatterSeriesModel() {
  59551. var _this = _super !== null && _super.apply(this, arguments) || this;
  59552. _this.type = EffectScatterSeriesModel.type;
  59553. _this.hasSymbolVisual = true;
  59554. return _this;
  59555. }
  59556. EffectScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  59557. return createSeriesData(null, this, {
  59558. useEncodeDefaulter: true
  59559. });
  59560. };
  59561. EffectScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  59562. return selectors.point(data.getItemLayout(dataIndex));
  59563. };
  59564. EffectScatterSeriesModel.type = 'series.effectScatter';
  59565. EffectScatterSeriesModel.dependencies = ['grid', 'polar'];
  59566. EffectScatterSeriesModel.defaultOption = {
  59567. coordinateSystem: 'cartesian2d',
  59568. // zlevel: 0,
  59569. z: 2,
  59570. legendHoverLink: true,
  59571. effectType: 'ripple',
  59572. progressive: 0,
  59573. // When to show the effect, option: 'render'|'emphasis'
  59574. showEffectOn: 'render',
  59575. clip: true,
  59576. // Ripple effect config
  59577. rippleEffect: {
  59578. period: 4,
  59579. // Scale of ripple
  59580. scale: 2.5,
  59581. // Brush type can be fill or stroke
  59582. brushType: 'fill',
  59583. // Ripple number
  59584. number: 3
  59585. },
  59586. universalTransition: {
  59587. divideShape: 'clone'
  59588. },
  59589. // Cartesian coordinate system
  59590. // xAxisIndex: 0,
  59591. // yAxisIndex: 0,
  59592. // Polar coordinate system
  59593. // polarIndex: 0,
  59594. // Geo coordinate system
  59595. // geoIndex: 0,
  59596. // symbol: null, // 图形类型
  59597. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  59598. // symbolRotate: null, // 图形旋转控制
  59599. // itemStyle: {
  59600. // opacity: 1
  59601. // }
  59602. };
  59603. return EffectScatterSeriesModel;
  59604. }(SeriesModel);
  59605. function install$l(registers) {
  59606. registers.registerChartView(EffectScatterView);
  59607. registers.registerSeriesModel(EffectScatterSeriesModel);
  59608. registers.registerLayout(pointsLayout('effectScatter'));
  59609. }
  59610. var EffectLine =
  59611. /** @class */
  59612. function (_super) {
  59613. __extends(EffectLine, _super);
  59614. function EffectLine(lineData, idx, seriesScope) {
  59615. var _this = _super.call(this) || this;
  59616. _this.add(_this.createLine(lineData, idx, seriesScope));
  59617. _this._updateEffectSymbol(lineData, idx);
  59618. return _this;
  59619. }
  59620. EffectLine.prototype.createLine = function (lineData, idx, seriesScope) {
  59621. return new Line$1(lineData, idx, seriesScope);
  59622. };
  59623. EffectLine.prototype._updateEffectSymbol = function (lineData, idx) {
  59624. var itemModel = lineData.getItemModel(idx);
  59625. var effectModel = itemModel.getModel('effect');
  59626. var size = effectModel.get('symbolSize');
  59627. var symbolType = effectModel.get('symbol');
  59628. if (!isArray(size)) {
  59629. size = [size, size];
  59630. }
  59631. var lineStyle = lineData.getItemVisual(idx, 'style');
  59632. var color = effectModel.get('color') || lineStyle && lineStyle.stroke;
  59633. var symbol = this.childAt(1);
  59634. if (this._symbolType !== symbolType) {
  59635. // Remove previous
  59636. this.remove(symbol);
  59637. symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color);
  59638. symbol.z2 = 100;
  59639. symbol.culling = true;
  59640. this.add(symbol);
  59641. } // Symbol may be removed if loop is false
  59642. if (!symbol) {
  59643. return;
  59644. } // Shadow color is same with color in default
  59645. symbol.setStyle('shadowColor', color);
  59646. symbol.setStyle(effectModel.getItemStyle(['color']));
  59647. symbol.scaleX = size[0];
  59648. symbol.scaleY = size[1];
  59649. symbol.setColor(color);
  59650. this._symbolType = symbolType;
  59651. this._symbolScale = size;
  59652. this._updateEffectAnimation(lineData, effectModel, idx);
  59653. };
  59654. EffectLine.prototype._updateEffectAnimation = function (lineData, effectModel, idx) {
  59655. var symbol = this.childAt(1);
  59656. if (!symbol) {
  59657. return;
  59658. }
  59659. var points = lineData.getItemLayout(idx);
  59660. var period = effectModel.get('period') * 1000;
  59661. var loop = effectModel.get('loop');
  59662. var roundTrip = effectModel.get('roundTrip');
  59663. var constantSpeed = effectModel.get('constantSpeed');
  59664. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  59665. return idx / lineData.count() * period / 3;
  59666. }); // Ignore when updating
  59667. symbol.ignore = true;
  59668. this._updateAnimationPoints(symbol, points);
  59669. if (constantSpeed > 0) {
  59670. period = this._getLineLength(symbol) / constantSpeed * 1000;
  59671. }
  59672. if (period !== this._period || loop !== this._loop || roundTrip !== this._roundTrip) {
  59673. symbol.stopAnimation();
  59674. var delayNum = void 0;
  59675. if (isFunction(delayExpr)) {
  59676. delayNum = delayExpr(idx);
  59677. } else {
  59678. delayNum = delayExpr;
  59679. }
  59680. if (symbol.__t > 0) {
  59681. delayNum = -period * symbol.__t;
  59682. }
  59683. this._animateSymbol(symbol, period, delayNum, loop, roundTrip);
  59684. }
  59685. this._period = period;
  59686. this._loop = loop;
  59687. this._roundTrip = roundTrip;
  59688. };
  59689. EffectLine.prototype._animateSymbol = function (symbol, period, delayNum, loop, roundTrip) {
  59690. if (period > 0) {
  59691. symbol.__t = 0;
  59692. var self_1 = this;
  59693. var animator = symbol.animate('', loop).when(roundTrip ? period * 2 : period, {
  59694. __t: roundTrip ? 2 : 1
  59695. }).delay(delayNum).during(function () {
  59696. self_1._updateSymbolPosition(symbol);
  59697. });
  59698. if (!loop) {
  59699. animator.done(function () {
  59700. self_1.remove(symbol);
  59701. });
  59702. }
  59703. animator.start();
  59704. }
  59705. };
  59706. EffectLine.prototype._getLineLength = function (symbol) {
  59707. // Not so accurate
  59708. return dist(symbol.__p1, symbol.__cp1) + dist(symbol.__cp1, symbol.__p2);
  59709. };
  59710. EffectLine.prototype._updateAnimationPoints = function (symbol, points) {
  59711. symbol.__p1 = points[0];
  59712. symbol.__p2 = points[1];
  59713. symbol.__cp1 = points[2] || [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
  59714. };
  59715. EffectLine.prototype.updateData = function (lineData, idx, seriesScope) {
  59716. this.childAt(0).updateData(lineData, idx, seriesScope);
  59717. this._updateEffectSymbol(lineData, idx);
  59718. };
  59719. EffectLine.prototype._updateSymbolPosition = function (symbol) {
  59720. var p1 = symbol.__p1;
  59721. var p2 = symbol.__p2;
  59722. var cp1 = symbol.__cp1;
  59723. var t = symbol.__t < 1 ? symbol.__t : 2 - symbol.__t;
  59724. var pos = [symbol.x, symbol.y];
  59725. var lastPos = pos.slice();
  59726. var quadraticAt$1 = quadraticAt;
  59727. var quadraticDerivativeAt$1 = quadraticDerivativeAt;
  59728. pos[0] = quadraticAt$1(p1[0], cp1[0], p2[0], t);
  59729. pos[1] = quadraticAt$1(p1[1], cp1[1], p2[1], t); // Tangent
  59730. var tx = symbol.__t < 1 ? quadraticDerivativeAt$1(p1[0], cp1[0], p2[0], t) : quadraticDerivativeAt$1(p2[0], cp1[0], p1[0], 1 - t);
  59731. var ty = symbol.__t < 1 ? quadraticDerivativeAt$1(p1[1], cp1[1], p2[1], t) : quadraticDerivativeAt$1(p2[1], cp1[1], p1[1], 1 - t);
  59732. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2; // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  59733. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  59734. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  59735. symbol.scaleY = dist(lastPos, pos) * 1.05; // make sure the last segment render within endPoint
  59736. if (t === 1) {
  59737. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  59738. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  59739. }
  59740. } else if (symbol.__lastT === 1) {
  59741. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  59742. symbol.scaleY = 2 * dist(p1, pos);
  59743. } else {
  59744. symbol.scaleY = this._symbolScale[1];
  59745. }
  59746. }
  59747. symbol.__lastT = symbol.__t;
  59748. symbol.ignore = false;
  59749. symbol.x = pos[0];
  59750. symbol.y = pos[1];
  59751. };
  59752. EffectLine.prototype.updateLayout = function (lineData, idx) {
  59753. this.childAt(0).updateLayout(lineData, idx);
  59754. var effectModel = lineData.getItemModel(idx).getModel('effect');
  59755. this._updateEffectAnimation(lineData, effectModel, idx);
  59756. };
  59757. return EffectLine;
  59758. }(Group);
  59759. var Polyline$1 =
  59760. /** @class */
  59761. function (_super) {
  59762. __extends(Polyline$1, _super);
  59763. function Polyline$1(lineData, idx, seriesScope) {
  59764. var _this = _super.call(this) || this;
  59765. _this._createPolyline(lineData, idx, seriesScope);
  59766. return _this;
  59767. }
  59768. Polyline$1.prototype._createPolyline = function (lineData, idx, seriesScope) {
  59769. // let seriesModel = lineData.hostModel;
  59770. var points = lineData.getItemLayout(idx);
  59771. var line = new Polyline({
  59772. shape: {
  59773. points: points
  59774. }
  59775. });
  59776. this.add(line);
  59777. this._updateCommonStl(lineData, idx, seriesScope);
  59778. };
  59779. Polyline$1.prototype.updateData = function (lineData, idx, seriesScope) {
  59780. var seriesModel = lineData.hostModel;
  59781. var line = this.childAt(0);
  59782. var target = {
  59783. shape: {
  59784. points: lineData.getItemLayout(idx)
  59785. }
  59786. };
  59787. updateProps(line, target, seriesModel, idx);
  59788. this._updateCommonStl(lineData, idx, seriesScope);
  59789. };
  59790. Polyline$1.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  59791. var line = this.childAt(0);
  59792. var itemModel = lineData.getItemModel(idx);
  59793. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  59794. var focus = seriesScope && seriesScope.focus;
  59795. var blurScope = seriesScope && seriesScope.blurScope;
  59796. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  59797. if (!seriesScope || lineData.hasItemOption) {
  59798. var emphasisModel = itemModel.getModel('emphasis');
  59799. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  59800. emphasisDisabled = emphasisModel.get('disabled');
  59801. focus = emphasisModel.get('focus');
  59802. blurScope = emphasisModel.get('blurScope');
  59803. }
  59804. line.useStyle(lineData.getItemVisual(idx, 'style'));
  59805. line.style.fill = null;
  59806. line.style.strokeNoScale = true;
  59807. var lineEmphasisState = line.ensureState('emphasis');
  59808. lineEmphasisState.style = emphasisLineStyle;
  59809. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  59810. };
  59811. Polyline$1.prototype.updateLayout = function (lineData, idx) {
  59812. var polyline = this.childAt(0);
  59813. polyline.setShape('points', lineData.getItemLayout(idx));
  59814. };
  59815. return Polyline$1;
  59816. }(Group);
  59817. var EffectPolyline =
  59818. /** @class */
  59819. function (_super) {
  59820. __extends(EffectPolyline, _super);
  59821. function EffectPolyline() {
  59822. var _this = _super !== null && _super.apply(this, arguments) || this;
  59823. _this._lastFrame = 0;
  59824. _this._lastFramePercent = 0;
  59825. return _this;
  59826. } // Override
  59827. EffectPolyline.prototype.createLine = function (lineData, idx, seriesScope) {
  59828. return new Polyline$1(lineData, idx, seriesScope);
  59829. };
  59830. EffectPolyline.prototype._updateAnimationPoints = function (symbol, points) {
  59831. this._points = points;
  59832. var accLenArr = [0];
  59833. var len = 0;
  59834. for (var i = 1; i < points.length; i++) {
  59835. var p1 = points[i - 1];
  59836. var p2 = points[i];
  59837. len += dist(p1, p2);
  59838. accLenArr.push(len);
  59839. }
  59840. if (len === 0) {
  59841. this._length = 0;
  59842. return;
  59843. }
  59844. for (var i = 0; i < accLenArr.length; i++) {
  59845. accLenArr[i] /= len;
  59846. }
  59847. this._offsets = accLenArr;
  59848. this._length = len;
  59849. };
  59850. EffectPolyline.prototype._getLineLength = function () {
  59851. return this._length;
  59852. };
  59853. EffectPolyline.prototype._updateSymbolPosition = function (symbol) {
  59854. var t = symbol.__t < 1 ? symbol.__t : 2 - symbol.__t;
  59855. var points = this._points;
  59856. var offsets = this._offsets;
  59857. var len = points.length;
  59858. if (!offsets) {
  59859. // Has length 0
  59860. return;
  59861. }
  59862. var lastFrame = this._lastFrame;
  59863. var frame;
  59864. if (t < this._lastFramePercent) {
  59865. // Start from the next frame
  59866. // PENDING start from lastFrame ?
  59867. var start = Math.min(lastFrame + 1, len - 1);
  59868. for (frame = start; frame >= 0; frame--) {
  59869. if (offsets[frame] <= t) {
  59870. break;
  59871. }
  59872. } // PENDING really need to do this ?
  59873. frame = Math.min(frame, len - 2);
  59874. } else {
  59875. for (frame = lastFrame; frame < len; frame++) {
  59876. if (offsets[frame] > t) {
  59877. break;
  59878. }
  59879. }
  59880. frame = Math.min(frame - 1, len - 2);
  59881. }
  59882. var p = (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]);
  59883. var p0 = points[frame];
  59884. var p1 = points[frame + 1];
  59885. symbol.x = p0[0] * (1 - p) + p * p1[0];
  59886. symbol.y = p0[1] * (1 - p) + p * p1[1];
  59887. var tx = symbol.__t < 1 ? p1[0] - p0[0] : p0[0] - p1[0];
  59888. var ty = symbol.__t < 1 ? p1[1] - p0[1] : p0[1] - p1[1];
  59889. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  59890. this._lastFrame = frame;
  59891. this._lastFramePercent = t;
  59892. symbol.ignore = false;
  59893. };
  59894. return EffectPolyline;
  59895. }(EffectLine);
  59896. var LargeLinesPathShape =
  59897. /** @class */
  59898. function () {
  59899. function LargeLinesPathShape() {
  59900. this.polyline = false;
  59901. this.curveness = 0;
  59902. this.segs = [];
  59903. }
  59904. return LargeLinesPathShape;
  59905. }();
  59906. var LargeLinesPath =
  59907. /** @class */
  59908. function (_super) {
  59909. __extends(LargeLinesPath, _super);
  59910. function LargeLinesPath(opts) {
  59911. var _this = _super.call(this, opts) || this;
  59912. _this._off = 0;
  59913. _this.hoverDataIdx = -1;
  59914. return _this;
  59915. }
  59916. LargeLinesPath.prototype.reset = function () {
  59917. this.notClear = false;
  59918. this._off = 0;
  59919. };
  59920. LargeLinesPath.prototype.getDefaultStyle = function () {
  59921. return {
  59922. stroke: '#000',
  59923. fill: null
  59924. };
  59925. };
  59926. LargeLinesPath.prototype.getDefaultShape = function () {
  59927. return new LargeLinesPathShape();
  59928. };
  59929. LargeLinesPath.prototype.buildPath = function (ctx, shape) {
  59930. var segs = shape.segs;
  59931. var curveness = shape.curveness;
  59932. var i;
  59933. if (shape.polyline) {
  59934. for (i = this._off; i < segs.length;) {
  59935. var count = segs[i++];
  59936. if (count > 0) {
  59937. ctx.moveTo(segs[i++], segs[i++]);
  59938. for (var k = 1; k < count; k++) {
  59939. ctx.lineTo(segs[i++], segs[i++]);
  59940. }
  59941. }
  59942. }
  59943. } else {
  59944. for (i = this._off; i < segs.length;) {
  59945. var x0 = segs[i++];
  59946. var y0 = segs[i++];
  59947. var x1 = segs[i++];
  59948. var y1 = segs[i++];
  59949. ctx.moveTo(x0, y0);
  59950. if (curveness > 0) {
  59951. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  59952. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  59953. ctx.quadraticCurveTo(x2, y2, x1, y1);
  59954. } else {
  59955. ctx.lineTo(x1, y1);
  59956. }
  59957. }
  59958. }
  59959. if (this.incremental) {
  59960. this._off = i;
  59961. this.notClear = true;
  59962. }
  59963. };
  59964. LargeLinesPath.prototype.findDataIndex = function (x, y) {
  59965. var shape = this.shape;
  59966. var segs = shape.segs;
  59967. var curveness = shape.curveness;
  59968. var lineWidth = this.style.lineWidth;
  59969. if (shape.polyline) {
  59970. var dataIndex = 0;
  59971. for (var i = 0; i < segs.length;) {
  59972. var count = segs[i++];
  59973. if (count > 0) {
  59974. var x0 = segs[i++];
  59975. var y0 = segs[i++];
  59976. for (var k = 1; k < count; k++) {
  59977. var x1 = segs[i++];
  59978. var y1 = segs[i++];
  59979. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  59980. return dataIndex;
  59981. }
  59982. }
  59983. }
  59984. dataIndex++;
  59985. }
  59986. } else {
  59987. var dataIndex = 0;
  59988. for (var i = 0; i < segs.length;) {
  59989. var x0 = segs[i++];
  59990. var y0 = segs[i++];
  59991. var x1 = segs[i++];
  59992. var y1 = segs[i++];
  59993. if (curveness > 0) {
  59994. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  59995. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  59996. if (containStroke$2(x0, y0, x2, y2, x1, y1, lineWidth, x, y)) {
  59997. return dataIndex;
  59998. }
  59999. } else {
  60000. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  60001. return dataIndex;
  60002. }
  60003. }
  60004. dataIndex++;
  60005. }
  60006. }
  60007. return -1;
  60008. };
  60009. LargeLinesPath.prototype.contain = function (x, y) {
  60010. var localPos = this.transformCoordToLocal(x, y);
  60011. var rect = this.getBoundingRect();
  60012. x = localPos[0];
  60013. y = localPos[1];
  60014. if (rect.contain(x, y)) {
  60015. // Cache found data index.
  60016. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  60017. return dataIdx >= 0;
  60018. }
  60019. this.hoverDataIdx = -1;
  60020. return false;
  60021. };
  60022. LargeLinesPath.prototype.getBoundingRect = function () {
  60023. // Ignore stroke for large symbol draw.
  60024. var rect = this._rect;
  60025. if (!rect) {
  60026. var shape = this.shape;
  60027. var points = shape.segs;
  60028. var minX = Infinity;
  60029. var minY = Infinity;
  60030. var maxX = -Infinity;
  60031. var maxY = -Infinity;
  60032. for (var i = 0; i < points.length;) {
  60033. var x = points[i++];
  60034. var y = points[i++];
  60035. minX = Math.min(x, minX);
  60036. maxX = Math.max(x, maxX);
  60037. minY = Math.min(y, minY);
  60038. maxY = Math.max(y, maxY);
  60039. }
  60040. rect = this._rect = new BoundingRect(minX, minY, maxX, maxY);
  60041. }
  60042. return rect;
  60043. };
  60044. return LargeLinesPath;
  60045. }(Path);
  60046. var LargeLineDraw =
  60047. /** @class */
  60048. function () {
  60049. function LargeLineDraw() {
  60050. this.group = new Group();
  60051. }
  60052. /**
  60053. * Update symbols draw by new data
  60054. */
  60055. LargeLineDraw.prototype.updateData = function (data) {
  60056. this._clear();
  60057. var lineEl = this._create();
  60058. lineEl.setShape({
  60059. segs: data.getLayout('linesPoints')
  60060. });
  60061. this._setCommon(lineEl, data);
  60062. };
  60063. /**
  60064. * @override
  60065. */
  60066. LargeLineDraw.prototype.incrementalPrepareUpdate = function (data) {
  60067. this.group.removeAll();
  60068. this._clear();
  60069. };
  60070. /**
  60071. * @override
  60072. */
  60073. LargeLineDraw.prototype.incrementalUpdate = function (taskParams, data) {
  60074. var lastAdded = this._newAdded[0];
  60075. var linePoints = data.getLayout('linesPoints');
  60076. var oldSegs = lastAdded && lastAdded.shape.segs; // Merging the exists. Each element has 1e4 points.
  60077. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  60078. if (oldSegs && oldSegs.length < 2e4) {
  60079. var oldLen = oldSegs.length;
  60080. var newSegs = new Float32Array(oldLen + linePoints.length); // Concat two array
  60081. newSegs.set(oldSegs);
  60082. newSegs.set(linePoints, oldLen);
  60083. lastAdded.setShape({
  60084. segs: newSegs
  60085. });
  60086. } else {
  60087. // Clear
  60088. this._newAdded = [];
  60089. var lineEl = this._create();
  60090. lineEl.incremental = true;
  60091. lineEl.setShape({
  60092. segs: linePoints
  60093. });
  60094. this._setCommon(lineEl, data);
  60095. lineEl.__startIndex = taskParams.start;
  60096. }
  60097. };
  60098. /**
  60099. * @override
  60100. */
  60101. LargeLineDraw.prototype.remove = function () {
  60102. this._clear();
  60103. };
  60104. LargeLineDraw.prototype.eachRendered = function (cb) {
  60105. this._newAdded[0] && cb(this._newAdded[0]);
  60106. };
  60107. LargeLineDraw.prototype._create = function () {
  60108. var lineEl = new LargeLinesPath({
  60109. cursor: 'default',
  60110. ignoreCoarsePointer: true
  60111. });
  60112. this._newAdded.push(lineEl);
  60113. this.group.add(lineEl);
  60114. return lineEl;
  60115. };
  60116. LargeLineDraw.prototype._setCommon = function (lineEl, data, isIncremental) {
  60117. var hostModel = data.hostModel;
  60118. lineEl.setShape({
  60119. polyline: hostModel.get('polyline'),
  60120. curveness: hostModel.get(['lineStyle', 'curveness'])
  60121. });
  60122. lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle());
  60123. lineEl.style.strokeNoScale = true;
  60124. var style = data.getVisual('style');
  60125. if (style && style.stroke) {
  60126. lineEl.setStyle('stroke', style.stroke);
  60127. }
  60128. lineEl.setStyle('fill', null);
  60129. var ecData = getECData(lineEl); // Enable tooltip
  60130. // PENDING May have performance issue when path is extremely large
  60131. ecData.seriesIndex = hostModel.seriesIndex;
  60132. lineEl.on('mousemove', function (e) {
  60133. ecData.dataIndex = null;
  60134. var dataIndex = lineEl.hoverDataIdx;
  60135. if (dataIndex > 0) {
  60136. // Provide dataIndex for tooltip
  60137. ecData.dataIndex = dataIndex + lineEl.__startIndex;
  60138. }
  60139. });
  60140. };
  60141. LargeLineDraw.prototype._clear = function () {
  60142. this._newAdded = [];
  60143. this.group.removeAll();
  60144. };
  60145. return LargeLineDraw;
  60146. }();
  60147. var linesLayout = {
  60148. seriesType: 'lines',
  60149. plan: createRenderPlanner(),
  60150. reset: function (seriesModel) {
  60151. var coordSys = seriesModel.coordinateSystem;
  60152. if (!coordSys) {
  60153. if ("development" !== 'production') {
  60154. error('The lines series must have a coordinate system.');
  60155. }
  60156. return;
  60157. }
  60158. var isPolyline = seriesModel.get('polyline');
  60159. var isLarge = seriesModel.pipelineContext.large;
  60160. return {
  60161. progress: function (params, lineData) {
  60162. var lineCoords = [];
  60163. if (isLarge) {
  60164. var points = void 0;
  60165. var segCount = params.end - params.start;
  60166. if (isPolyline) {
  60167. var totalCoordsCount = 0;
  60168. for (var i = params.start; i < params.end; i++) {
  60169. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  60170. }
  60171. points = new Float32Array(segCount + totalCoordsCount * 2);
  60172. } else {
  60173. points = new Float32Array(segCount * 4);
  60174. }
  60175. var offset = 0;
  60176. var pt = [];
  60177. for (var i = params.start; i < params.end; i++) {
  60178. var len = seriesModel.getLineCoords(i, lineCoords);
  60179. if (isPolyline) {
  60180. points[offset++] = len;
  60181. }
  60182. for (var k = 0; k < len; k++) {
  60183. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  60184. points[offset++] = pt[0];
  60185. points[offset++] = pt[1];
  60186. }
  60187. }
  60188. lineData.setLayout('linesPoints', points);
  60189. } else {
  60190. for (var i = params.start; i < params.end; i++) {
  60191. var itemModel = lineData.getItemModel(i);
  60192. var len = seriesModel.getLineCoords(i, lineCoords);
  60193. var pts = [];
  60194. if (isPolyline) {
  60195. for (var j = 0; j < len; j++) {
  60196. pts.push(coordSys.dataToPoint(lineCoords[j]));
  60197. }
  60198. } else {
  60199. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  60200. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  60201. var curveness = itemModel.get(['lineStyle', 'curveness']);
  60202. if (+curveness) {
  60203. pts[2] = [(pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness, (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness];
  60204. }
  60205. }
  60206. lineData.setItemLayout(i, pts);
  60207. }
  60208. }
  60209. }
  60210. };
  60211. }
  60212. };
  60213. var LinesView =
  60214. /** @class */
  60215. function (_super) {
  60216. __extends(LinesView, _super);
  60217. function LinesView() {
  60218. var _this = _super !== null && _super.apply(this, arguments) || this;
  60219. _this.type = LinesView.type;
  60220. return _this;
  60221. }
  60222. LinesView.prototype.render = function (seriesModel, ecModel, api) {
  60223. var data = seriesModel.getData();
  60224. var lineDraw = this._updateLineDraw(data, seriesModel);
  60225. var zlevel = seriesModel.get('zlevel');
  60226. var trailLength = seriesModel.get(['effect', 'trailLength']);
  60227. var zr = api.getZr(); // Avoid the drag cause ghost shadow
  60228. // FIXME Better way ?
  60229. // SVG doesn't support
  60230. var isSvg = zr.painter.getType() === 'svg';
  60231. if (!isSvg) {
  60232. zr.painter.getLayer(zlevel).clear(true);
  60233. } // Config layer with motion blur
  60234. if (this._lastZlevel != null && !isSvg) {
  60235. zr.configLayer(this._lastZlevel, {
  60236. motionBlur: false
  60237. });
  60238. }
  60239. if (this._showEffect(seriesModel) && trailLength > 0) {
  60240. if (!isSvg) {
  60241. zr.configLayer(zlevel, {
  60242. motionBlur: true,
  60243. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  60244. });
  60245. } else if ("development" !== 'production') {
  60246. console.warn('SVG render mode doesn\'t support lines with trail effect');
  60247. }
  60248. }
  60249. lineDraw.updateData(data);
  60250. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  60251. if (clipPath) {
  60252. this.group.setClipPath(clipPath);
  60253. } else {
  60254. this.group.removeClipPath();
  60255. }
  60256. this._lastZlevel = zlevel;
  60257. this._finished = true;
  60258. };
  60259. LinesView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  60260. var data = seriesModel.getData();
  60261. var lineDraw = this._updateLineDraw(data, seriesModel);
  60262. lineDraw.incrementalPrepareUpdate(data);
  60263. this._clearLayer(api);
  60264. this._finished = false;
  60265. };
  60266. LinesView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  60267. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  60268. this._finished = taskParams.end === seriesModel.getData().count();
  60269. };
  60270. LinesView.prototype.eachRendered = function (cb) {
  60271. this._lineDraw && this._lineDraw.eachRendered(cb);
  60272. };
  60273. LinesView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  60274. var data = seriesModel.getData();
  60275. var pipelineContext = seriesModel.pipelineContext;
  60276. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  60277. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  60278. return {
  60279. update: true
  60280. };
  60281. } else {
  60282. // TODO Use same logic with ScatterView.
  60283. // Manually update layout
  60284. var res = linesLayout.reset(seriesModel, ecModel, api);
  60285. if (res.progress) {
  60286. res.progress({
  60287. start: 0,
  60288. end: data.count(),
  60289. count: data.count()
  60290. }, data);
  60291. } // Not in large mode
  60292. this._lineDraw.updateLayout();
  60293. this._clearLayer(api);
  60294. }
  60295. };
  60296. LinesView.prototype._updateLineDraw = function (data, seriesModel) {
  60297. var lineDraw = this._lineDraw;
  60298. var hasEffect = this._showEffect(seriesModel);
  60299. var isPolyline = !!seriesModel.get('polyline');
  60300. var pipelineContext = seriesModel.pipelineContext;
  60301. var isLargeDraw = pipelineContext.large;
  60302. if ("development" !== 'production') {
  60303. if (hasEffect && isLargeDraw) {
  60304. console.warn('Large lines not support effect');
  60305. }
  60306. }
  60307. if (!lineDraw || hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLargeDraw !== this._isLargeDraw) {
  60308. if (lineDraw) {
  60309. lineDraw.remove();
  60310. }
  60311. lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$1 : hasEffect ? EffectLine : Line$1);
  60312. this._hasEffet = hasEffect;
  60313. this._isPolyline = isPolyline;
  60314. this._isLargeDraw = isLargeDraw;
  60315. }
  60316. this.group.add(lineDraw.group);
  60317. return lineDraw;
  60318. };
  60319. LinesView.prototype._showEffect = function (seriesModel) {
  60320. return !!seriesModel.get(['effect', 'show']);
  60321. };
  60322. LinesView.prototype._clearLayer = function (api) {
  60323. // Not use motion when dragging or zooming
  60324. var zr = api.getZr();
  60325. var isSvg = zr.painter.getType() === 'svg';
  60326. if (!isSvg && this._lastZlevel != null) {
  60327. zr.painter.getLayer(this._lastZlevel).clear(true);
  60328. }
  60329. };
  60330. LinesView.prototype.remove = function (ecModel, api) {
  60331. this._lineDraw && this._lineDraw.remove();
  60332. this._lineDraw = null; // Clear motion when lineDraw is removed
  60333. this._clearLayer(api);
  60334. };
  60335. LinesView.prototype.dispose = function (ecModel, api) {
  60336. this.remove(ecModel, api);
  60337. };
  60338. LinesView.type = 'lines';
  60339. return LinesView;
  60340. }(ChartView);
  60341. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  60342. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  60343. function compatEc2(seriesOpt) {
  60344. var data = seriesOpt.data;
  60345. if (data && data[0] && data[0][0] && data[0][0].coord) {
  60346. if ("development" !== 'production') {
  60347. console.warn('Lines data configuration has been changed to' + ' { coords:[[1,2],[2,3]] }');
  60348. }
  60349. seriesOpt.data = map(data, function (itemOpt) {
  60350. var coords = [itemOpt[0].coord, itemOpt[1].coord];
  60351. var target = {
  60352. coords: coords
  60353. };
  60354. if (itemOpt[0].name) {
  60355. target.fromName = itemOpt[0].name;
  60356. }
  60357. if (itemOpt[1].name) {
  60358. target.toName = itemOpt[1].name;
  60359. }
  60360. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  60361. });
  60362. }
  60363. }
  60364. var LinesSeriesModel =
  60365. /** @class */
  60366. function (_super) {
  60367. __extends(LinesSeriesModel, _super);
  60368. function LinesSeriesModel() {
  60369. var _this = _super !== null && _super.apply(this, arguments) || this;
  60370. _this.type = LinesSeriesModel.type;
  60371. _this.visualStyleAccessPath = 'lineStyle';
  60372. _this.visualDrawType = 'stroke';
  60373. return _this;
  60374. }
  60375. LinesSeriesModel.prototype.init = function (option) {
  60376. // The input data may be null/undefined.
  60377. option.data = option.data || []; // Not using preprocessor because mergeOption may not have series.type
  60378. compatEc2(option);
  60379. var result = this._processFlatCoordsArray(option.data);
  60380. this._flatCoords = result.flatCoords;
  60381. this._flatCoordsOffset = result.flatCoordsOffset;
  60382. if (result.flatCoords) {
  60383. option.data = new Float32Array(result.count);
  60384. }
  60385. _super.prototype.init.apply(this, arguments);
  60386. };
  60387. LinesSeriesModel.prototype.mergeOption = function (option) {
  60388. compatEc2(option);
  60389. if (option.data) {
  60390. // Only update when have option data to merge.
  60391. var result = this._processFlatCoordsArray(option.data);
  60392. this._flatCoords = result.flatCoords;
  60393. this._flatCoordsOffset = result.flatCoordsOffset;
  60394. if (result.flatCoords) {
  60395. option.data = new Float32Array(result.count);
  60396. }
  60397. }
  60398. _super.prototype.mergeOption.apply(this, arguments);
  60399. };
  60400. LinesSeriesModel.prototype.appendData = function (params) {
  60401. var result = this._processFlatCoordsArray(params.data);
  60402. if (result.flatCoords) {
  60403. if (!this._flatCoords) {
  60404. this._flatCoords = result.flatCoords;
  60405. this._flatCoordsOffset = result.flatCoordsOffset;
  60406. } else {
  60407. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  60408. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  60409. }
  60410. params.data = new Float32Array(result.count);
  60411. }
  60412. this.getRawData().appendData(params.data);
  60413. };
  60414. LinesSeriesModel.prototype._getCoordsFromItemModel = function (idx) {
  60415. var itemModel = this.getData().getItemModel(idx);
  60416. var coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords');
  60417. if ("development" !== 'production') {
  60418. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  60419. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  60420. }
  60421. }
  60422. return coords;
  60423. };
  60424. LinesSeriesModel.prototype.getLineCoordsCount = function (idx) {
  60425. if (this._flatCoordsOffset) {
  60426. return this._flatCoordsOffset[idx * 2 + 1];
  60427. } else {
  60428. return this._getCoordsFromItemModel(idx).length;
  60429. }
  60430. };
  60431. LinesSeriesModel.prototype.getLineCoords = function (idx, out) {
  60432. if (this._flatCoordsOffset) {
  60433. var offset = this._flatCoordsOffset[idx * 2];
  60434. var len = this._flatCoordsOffset[idx * 2 + 1];
  60435. for (var i = 0; i < len; i++) {
  60436. out[i] = out[i] || [];
  60437. out[i][0] = this._flatCoords[offset + i * 2];
  60438. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  60439. }
  60440. return len;
  60441. } else {
  60442. var coords = this._getCoordsFromItemModel(idx);
  60443. for (var i = 0; i < coords.length; i++) {
  60444. out[i] = out[i] || [];
  60445. out[i][0] = coords[i][0];
  60446. out[i][1] = coords[i][1];
  60447. }
  60448. return coords.length;
  60449. }
  60450. };
  60451. LinesSeriesModel.prototype._processFlatCoordsArray = function (data) {
  60452. var startOffset = 0;
  60453. if (this._flatCoords) {
  60454. startOffset = this._flatCoords.length;
  60455. } // Stored as a typed array. In format
  60456. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  60457. if (isNumber(data[0])) {
  60458. var len = data.length; // Store offset and len of each segment
  60459. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  60460. var coordsStorage = new Float64Arr(len);
  60461. var coordsCursor = 0;
  60462. var offsetCursor = 0;
  60463. var dataCount = 0;
  60464. for (var i = 0; i < len;) {
  60465. dataCount++;
  60466. var count = data[i++]; // Offset
  60467. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset; // Len
  60468. coordsOffsetAndLenStorage[offsetCursor++] = count;
  60469. for (var k = 0; k < count; k++) {
  60470. var x = data[i++];
  60471. var y = data[i++];
  60472. coordsStorage[coordsCursor++] = x;
  60473. coordsStorage[coordsCursor++] = y;
  60474. if (i > len) {
  60475. if ("development" !== 'production') {
  60476. throw new Error('Invalid data format.');
  60477. }
  60478. }
  60479. }
  60480. }
  60481. return {
  60482. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  60483. flatCoords: coordsStorage,
  60484. count: dataCount
  60485. };
  60486. }
  60487. return {
  60488. flatCoordsOffset: null,
  60489. flatCoords: null,
  60490. count: data.length
  60491. };
  60492. };
  60493. LinesSeriesModel.prototype.getInitialData = function (option, ecModel) {
  60494. if ("development" !== 'production') {
  60495. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  60496. if (!CoordSys) {
  60497. throw new Error('Unknown coordinate system ' + option.coordinateSystem);
  60498. }
  60499. }
  60500. var lineData = new SeriesData(['value'], this);
  60501. lineData.hasItemOption = false;
  60502. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  60503. // dataItem is simply coords
  60504. if (dataItem instanceof Array) {
  60505. return NaN;
  60506. } else {
  60507. lineData.hasItemOption = true;
  60508. var value = dataItem.value;
  60509. if (value != null) {
  60510. return value instanceof Array ? value[dimIndex] : value;
  60511. }
  60512. }
  60513. });
  60514. return lineData;
  60515. };
  60516. LinesSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  60517. var data = this.getData();
  60518. var itemModel = data.getItemModel(dataIndex);
  60519. var name = itemModel.get('name');
  60520. if (name) {
  60521. return name;
  60522. }
  60523. var fromName = itemModel.get('fromName');
  60524. var toName = itemModel.get('toName');
  60525. var nameArr = [];
  60526. fromName != null && nameArr.push(fromName);
  60527. toName != null && nameArr.push(toName);
  60528. return createTooltipMarkup('nameValue', {
  60529. name: nameArr.join(' > ')
  60530. });
  60531. };
  60532. LinesSeriesModel.prototype.preventIncremental = function () {
  60533. return !!this.get(['effect', 'show']);
  60534. };
  60535. LinesSeriesModel.prototype.getProgressive = function () {
  60536. var progressive = this.option.progressive;
  60537. if (progressive == null) {
  60538. return this.option.large ? 1e4 : this.get('progressive');
  60539. }
  60540. return progressive;
  60541. };
  60542. LinesSeriesModel.prototype.getProgressiveThreshold = function () {
  60543. var progressiveThreshold = this.option.progressiveThreshold;
  60544. if (progressiveThreshold == null) {
  60545. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  60546. }
  60547. return progressiveThreshold;
  60548. };
  60549. LinesSeriesModel.prototype.getZLevelKey = function () {
  60550. var effectModel = this.getModel('effect');
  60551. var trailLength = effectModel.get('trailLength');
  60552. return this.getData().count() > this.getProgressiveThreshold() // Each progressive series has individual key.
  60553. ? this.id : effectModel.get('show') && trailLength > 0 ? trailLength + '' : '';
  60554. };
  60555. LinesSeriesModel.type = 'series.lines';
  60556. LinesSeriesModel.dependencies = ['grid', 'polar', 'geo', 'calendar'];
  60557. LinesSeriesModel.defaultOption = {
  60558. coordinateSystem: 'geo',
  60559. // zlevel: 0,
  60560. z: 2,
  60561. legendHoverLink: true,
  60562. // Cartesian coordinate system
  60563. xAxisIndex: 0,
  60564. yAxisIndex: 0,
  60565. symbol: ['none', 'none'],
  60566. symbolSize: [10, 10],
  60567. // Geo coordinate system
  60568. geoIndex: 0,
  60569. effect: {
  60570. show: false,
  60571. period: 4,
  60572. constantSpeed: 0,
  60573. symbol: 'circle',
  60574. symbolSize: 3,
  60575. loop: true,
  60576. trailLength: 0.2
  60577. },
  60578. large: false,
  60579. // Available when large is true
  60580. largeThreshold: 2000,
  60581. polyline: false,
  60582. clip: true,
  60583. label: {
  60584. show: false,
  60585. position: 'end' // distance: 5,
  60586. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  60587. },
  60588. lineStyle: {
  60589. opacity: 0.5
  60590. }
  60591. };
  60592. return LinesSeriesModel;
  60593. }(SeriesModel);
  60594. /*
  60595. * Licensed to the Apache Software Foundation (ASF) under one
  60596. * or more contributor license agreements. See the NOTICE file
  60597. * distributed with this work for additional information
  60598. * regarding copyright ownership. The ASF licenses this file
  60599. * to you under the Apache License, Version 2.0 (the
  60600. * "License"); you may not use this file except in compliance
  60601. * with the License. You may obtain a copy of the License at
  60602. *
  60603. * http://www.apache.org/licenses/LICENSE-2.0
  60604. *
  60605. * Unless required by applicable law or agreed to in writing,
  60606. * software distributed under the License is distributed on an
  60607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60608. * KIND, either express or implied. See the License for the
  60609. * specific language governing permissions and limitations
  60610. * under the License.
  60611. */
  60612. /**
  60613. * AUTO-GENERATED FILE. DO NOT MODIFY.
  60614. */
  60615. /*
  60616. * Licensed to the Apache Software Foundation (ASF) under one
  60617. * or more contributor license agreements. See the NOTICE file
  60618. * distributed with this work for additional information
  60619. * regarding copyright ownership. The ASF licenses this file
  60620. * to you under the Apache License, Version 2.0 (the
  60621. * "License"); you may not use this file except in compliance
  60622. * with the License. You may obtain a copy of the License at
  60623. *
  60624. * http://www.apache.org/licenses/LICENSE-2.0
  60625. *
  60626. * Unless required by applicable law or agreed to in writing,
  60627. * software distributed under the License is distributed on an
  60628. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60629. * KIND, either express or implied. See the License for the
  60630. * specific language governing permissions and limitations
  60631. * under the License.
  60632. */
  60633. function normalize$3(a) {
  60634. if (!(a instanceof Array)) {
  60635. a = [a, a];
  60636. }
  60637. return a;
  60638. }
  60639. var linesVisual = {
  60640. seriesType: 'lines',
  60641. reset: function (seriesModel) {
  60642. var symbolType = normalize$3(seriesModel.get('symbol'));
  60643. var symbolSize = normalize$3(seriesModel.get('symbolSize'));
  60644. var data = seriesModel.getData();
  60645. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  60646. data.setVisual('toSymbol', symbolType && symbolType[1]);
  60647. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  60648. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  60649. function dataEach(data, idx) {
  60650. var itemModel = data.getItemModel(idx);
  60651. var symbolType = normalize$3(itemModel.getShallow('symbol', true));
  60652. var symbolSize = normalize$3(itemModel.getShallow('symbolSize', true));
  60653. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  60654. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  60655. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  60656. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  60657. }
  60658. return {
  60659. dataEach: data.hasItemOption ? dataEach : null
  60660. };
  60661. }
  60662. };
  60663. function install$m(registers) {
  60664. registers.registerChartView(LinesView);
  60665. registers.registerSeriesModel(LinesSeriesModel);
  60666. registers.registerLayout(linesLayout);
  60667. registers.registerVisual(linesVisual);
  60668. }
  60669. var GRADIENT_LEVELS = 256;
  60670. var HeatmapLayer =
  60671. /** @class */
  60672. function () {
  60673. function HeatmapLayer() {
  60674. this.blurSize = 30;
  60675. this.pointSize = 20;
  60676. this.maxOpacity = 1;
  60677. this.minOpacity = 0;
  60678. this._gradientPixels = {
  60679. inRange: null,
  60680. outOfRange: null
  60681. };
  60682. var canvas = platformApi.createCanvas();
  60683. this.canvas = canvas;
  60684. }
  60685. /**
  60686. * Renders Heatmap and returns the rendered canvas
  60687. * @param data array of data, each has x, y, value
  60688. * @param width canvas width
  60689. * @param height canvas height
  60690. */
  60691. HeatmapLayer.prototype.update = function (data, width, height, normalize, colorFunc, isInRange) {
  60692. var brush = this._getBrush();
  60693. var gradientInRange = this._getGradient(colorFunc, 'inRange');
  60694. var gradientOutOfRange = this._getGradient(colorFunc, 'outOfRange');
  60695. var r = this.pointSize + this.blurSize;
  60696. var canvas = this.canvas;
  60697. var ctx = canvas.getContext('2d');
  60698. var len = data.length;
  60699. canvas.width = width;
  60700. canvas.height = height;
  60701. for (var i = 0; i < len; ++i) {
  60702. var p = data[i];
  60703. var x = p[0];
  60704. var y = p[1];
  60705. var value = p[2]; // calculate alpha using value
  60706. var alpha = normalize(value); // draw with the circle brush with alpha
  60707. ctx.globalAlpha = alpha;
  60708. ctx.drawImage(brush, x - r, y - r);
  60709. }
  60710. if (!canvas.width || !canvas.height) {
  60711. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  60712. // 'CanvasRenderingContext2D': The source height is 0."
  60713. return canvas;
  60714. } // colorize the canvas using alpha value and set with gradient
  60715. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  60716. var pixels = imageData.data;
  60717. var offset = 0;
  60718. var pixelLen = pixels.length;
  60719. var minOpacity = this.minOpacity;
  60720. var maxOpacity = this.maxOpacity;
  60721. var diffOpacity = maxOpacity - minOpacity;
  60722. while (offset < pixelLen) {
  60723. var alpha = pixels[offset + 3] / 256;
  60724. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4; // Simple optimize to ignore the empty data
  60725. if (alpha > 0) {
  60726. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  60727. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  60728. pixels[offset++] = gradient[gradientOffset];
  60729. pixels[offset++] = gradient[gradientOffset + 1];
  60730. pixels[offset++] = gradient[gradientOffset + 2];
  60731. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  60732. } else {
  60733. offset += 4;
  60734. }
  60735. }
  60736. ctx.putImageData(imageData, 0, 0);
  60737. return canvas;
  60738. };
  60739. /**
  60740. * get canvas of a black circle brush used for canvas to draw later
  60741. */
  60742. HeatmapLayer.prototype._getBrush = function () {
  60743. var brushCanvas = this._brushCanvas || (this._brushCanvas = platformApi.createCanvas()); // set brush size
  60744. var r = this.pointSize + this.blurSize;
  60745. var d = r * 2;
  60746. brushCanvas.width = d;
  60747. brushCanvas.height = d;
  60748. var ctx = brushCanvas.getContext('2d');
  60749. ctx.clearRect(0, 0, d, d); // in order to render shadow without the distinct circle,
  60750. // draw the distinct circle in an invisible place,
  60751. // and use shadowOffset to draw shadow in the center of the canvas
  60752. ctx.shadowOffsetX = d;
  60753. ctx.shadowBlur = this.blurSize; // draw the shadow in black, and use alpha and shadow blur to generate
  60754. // color in color map
  60755. ctx.shadowColor = '#000'; // draw circle in the left to the canvas
  60756. ctx.beginPath();
  60757. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  60758. ctx.closePath();
  60759. ctx.fill();
  60760. return brushCanvas;
  60761. };
  60762. /**
  60763. * get gradient color map
  60764. * @private
  60765. */
  60766. HeatmapLayer.prototype._getGradient = function (colorFunc, state) {
  60767. var gradientPixels = this._gradientPixels;
  60768. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  60769. var color = [0, 0, 0, 0];
  60770. var off = 0;
  60771. for (var i = 0; i < 256; i++) {
  60772. colorFunc[state](i / 255, true, color);
  60773. pixelsSingleState[off++] = color[0];
  60774. pixelsSingleState[off++] = color[1];
  60775. pixelsSingleState[off++] = color[2];
  60776. pixelsSingleState[off++] = color[3];
  60777. }
  60778. return pixelsSingleState;
  60779. };
  60780. return HeatmapLayer;
  60781. }();
  60782. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  60783. var dataSpan = dataExtent[1] - dataExtent[0];
  60784. pieceList = map(pieceList, function (piece) {
  60785. return {
  60786. interval: [(piece.interval[0] - dataExtent[0]) / dataSpan, (piece.interval[1] - dataExtent[0]) / dataSpan]
  60787. };
  60788. });
  60789. var len = pieceList.length;
  60790. var lastIndex = 0;
  60791. return function (val) {
  60792. var i; // Try to find in the location of the last found
  60793. for (i = lastIndex; i < len; i++) {
  60794. var interval = pieceList[i].interval;
  60795. if (interval[0] <= val && val <= interval[1]) {
  60796. lastIndex = i;
  60797. break;
  60798. }
  60799. }
  60800. if (i === len) {
  60801. // Not found, back interation
  60802. for (i = lastIndex - 1; i >= 0; i--) {
  60803. var interval = pieceList[i].interval;
  60804. if (interval[0] <= val && val <= interval[1]) {
  60805. lastIndex = i;
  60806. break;
  60807. }
  60808. }
  60809. }
  60810. return i >= 0 && i < len && selected[i];
  60811. };
  60812. }
  60813. function getIsInContinuousRange(dataExtent, range) {
  60814. var dataSpan = dataExtent[1] - dataExtent[0];
  60815. range = [(range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan];
  60816. return function (val) {
  60817. return val >= range[0] && val <= range[1];
  60818. };
  60819. }
  60820. function isGeoCoordSys(coordSys) {
  60821. var dimensions = coordSys.dimensions; // Not use coordSys.type === 'geo' because coordSys maybe extended
  60822. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  60823. }
  60824. var HeatmapView =
  60825. /** @class */
  60826. function (_super) {
  60827. __extends(HeatmapView, _super);
  60828. function HeatmapView() {
  60829. var _this = _super !== null && _super.apply(this, arguments) || this;
  60830. _this.type = HeatmapView.type;
  60831. return _this;
  60832. }
  60833. HeatmapView.prototype.render = function (seriesModel, ecModel, api) {
  60834. var visualMapOfThisSeries;
  60835. ecModel.eachComponent('visualMap', function (visualMap) {
  60836. visualMap.eachTargetSeries(function (targetSeries) {
  60837. if (targetSeries === seriesModel) {
  60838. visualMapOfThisSeries = visualMap;
  60839. }
  60840. });
  60841. });
  60842. if ("development" !== 'production') {
  60843. if (!visualMapOfThisSeries) {
  60844. throw new Error('Heatmap must use with visualMap');
  60845. }
  60846. } // Clear previously rendered progressive elements.
  60847. this._progressiveEls = null;
  60848. this.group.removeAll();
  60849. var coordSys = seriesModel.coordinateSystem;
  60850. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  60851. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  60852. } else if (isGeoCoordSys(coordSys)) {
  60853. this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api);
  60854. }
  60855. };
  60856. HeatmapView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  60857. this.group.removeAll();
  60858. };
  60859. HeatmapView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  60860. var coordSys = seriesModel.coordinateSystem;
  60861. if (coordSys) {
  60862. // geo does not support incremental rendering?
  60863. if (isGeoCoordSys(coordSys)) {
  60864. this.render(seriesModel, ecModel, api);
  60865. } else {
  60866. this._progressiveEls = [];
  60867. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  60868. }
  60869. }
  60870. };
  60871. HeatmapView.prototype.eachRendered = function (cb) {
  60872. traverseElements(this._progressiveEls || this.group, cb);
  60873. };
  60874. HeatmapView.prototype._renderOnCartesianAndCalendar = function (seriesModel, api, start, end, incremental) {
  60875. var coordSys = seriesModel.coordinateSystem;
  60876. var isCartesian2d = isCoordinateSystemType(coordSys, 'cartesian2d');
  60877. var width;
  60878. var height;
  60879. var xAxisExtent;
  60880. var yAxisExtent;
  60881. if (isCartesian2d) {
  60882. var xAxis = coordSys.getAxis('x');
  60883. var yAxis = coordSys.getAxis('y');
  60884. if ("development" !== 'production') {
  60885. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  60886. throw new Error('Heatmap on cartesian must have two category axes');
  60887. }
  60888. if (!(xAxis.onBand && yAxis.onBand)) {
  60889. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  60890. }
  60891. } // add 0.5px to avoid the gaps
  60892. width = xAxis.getBandWidth() + .5;
  60893. height = yAxis.getBandWidth() + .5;
  60894. xAxisExtent = xAxis.scale.getExtent();
  60895. yAxisExtent = yAxis.scale.getExtent();
  60896. }
  60897. var group = this.group;
  60898. var data = seriesModel.getData();
  60899. var emphasisStyle = seriesModel.getModel(['emphasis', 'itemStyle']).getItemStyle();
  60900. var blurStyle = seriesModel.getModel(['blur', 'itemStyle']).getItemStyle();
  60901. var selectStyle = seriesModel.getModel(['select', 'itemStyle']).getItemStyle();
  60902. var borderRadius = seriesModel.get(['itemStyle', 'borderRadius']);
  60903. var labelStatesModels = getLabelStatesModels(seriesModel);
  60904. var emphasisModel = seriesModel.getModel('emphasis');
  60905. var focus = emphasisModel.get('focus');
  60906. var blurScope = emphasisModel.get('blurScope');
  60907. var emphasisDisabled = emphasisModel.get('disabled');
  60908. var dataDims = isCartesian2d ? [data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value')] : [data.mapDimension('time'), data.mapDimension('value')];
  60909. for (var idx = start; idx < end; idx++) {
  60910. var rect = void 0;
  60911. var style = data.getItemVisual(idx, 'style');
  60912. if (isCartesian2d) {
  60913. var dataDimX = data.get(dataDims[0], idx);
  60914. var dataDimY = data.get(dataDims[1], idx); // Ignore empty data and out of extent data
  60915. if (isNaN(data.get(dataDims[2], idx)) || isNaN(dataDimX) || isNaN(dataDimY) || dataDimX < xAxisExtent[0] || dataDimX > xAxisExtent[1] || dataDimY < yAxisExtent[0] || dataDimY > yAxisExtent[1]) {
  60916. continue;
  60917. }
  60918. var point = coordSys.dataToPoint([dataDimX, dataDimY]);
  60919. rect = new Rect({
  60920. shape: {
  60921. x: point[0] - width / 2,
  60922. y: point[1] - height / 2,
  60923. width: width,
  60924. height: height
  60925. },
  60926. style: style
  60927. });
  60928. } else {
  60929. // Ignore empty data
  60930. if (isNaN(data.get(dataDims[1], idx))) {
  60931. continue;
  60932. }
  60933. rect = new Rect({
  60934. z2: 1,
  60935. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  60936. style: style
  60937. });
  60938. } // Optimization for large dataset
  60939. if (data.hasItemOption) {
  60940. var itemModel = data.getItemModel(idx);
  60941. var emphasisModel_1 = itemModel.getModel('emphasis');
  60942. emphasisStyle = emphasisModel_1.getModel('itemStyle').getItemStyle();
  60943. blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  60944. selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle(); // Each item value struct in the data would be firstly
  60945. // {
  60946. // itemStyle: { borderRadius: [30, 30] },
  60947. // value: [2022, 02, 22]
  60948. // }
  60949. borderRadius = itemModel.get(['itemStyle', 'borderRadius']);
  60950. focus = emphasisModel_1.get('focus');
  60951. blurScope = emphasisModel_1.get('blurScope');
  60952. emphasisDisabled = emphasisModel_1.get('disabled');
  60953. labelStatesModels = getLabelStatesModels(itemModel);
  60954. }
  60955. rect.shape.r = borderRadius;
  60956. var rawValue = seriesModel.getRawValue(idx);
  60957. var defaultText = '-';
  60958. if (rawValue && rawValue[2] != null) {
  60959. defaultText = rawValue[2] + '';
  60960. }
  60961. setLabelStyle(rect, labelStatesModels, {
  60962. labelFetcher: seriesModel,
  60963. labelDataIndex: idx,
  60964. defaultOpacity: style.opacity,
  60965. defaultText: defaultText
  60966. });
  60967. rect.ensureState('emphasis').style = emphasisStyle;
  60968. rect.ensureState('blur').style = blurStyle;
  60969. rect.ensureState('select').style = selectStyle;
  60970. toggleHoverEmphasis(rect, focus, blurScope, emphasisDisabled);
  60971. rect.incremental = incremental; // PENDING
  60972. if (incremental) {
  60973. // Rect must use hover layer if it's incremental.
  60974. rect.states.emphasis.hoverLayer = true;
  60975. }
  60976. group.add(rect);
  60977. data.setItemGraphicEl(idx, rect);
  60978. if (this._progressiveEls) {
  60979. this._progressiveEls.push(rect);
  60980. }
  60981. }
  60982. };
  60983. HeatmapView.prototype._renderOnGeo = function (geo, seriesModel, visualMapModel, api) {
  60984. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  60985. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange; // if (!visualMapping) {
  60986. // throw new Error('Data range must have color visuals');
  60987. // }
  60988. var data = seriesModel.getData();
  60989. var hmLayer = this._hmLayer || this._hmLayer || new HeatmapLayer();
  60990. hmLayer.blurSize = seriesModel.get('blurSize');
  60991. hmLayer.pointSize = seriesModel.get('pointSize');
  60992. hmLayer.minOpacity = seriesModel.get('minOpacity');
  60993. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  60994. var rect = geo.getViewRect().clone();
  60995. var roamTransform = geo.getRoamTransform();
  60996. rect.applyTransform(roamTransform); // Clamp on viewport
  60997. var x = Math.max(rect.x, 0);
  60998. var y = Math.max(rect.y, 0);
  60999. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  61000. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  61001. var width = x2 - x;
  61002. var height = y2 - y;
  61003. var dims = [data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value')];
  61004. var points = data.mapArray(dims, function (lng, lat, value) {
  61005. var pt = geo.dataToPoint([lng, lat]);
  61006. pt[0] -= x;
  61007. pt[1] -= y;
  61008. pt.push(value);
  61009. return pt;
  61010. });
  61011. var dataExtent = visualMapModel.getExtent();
  61012. var isInRange = visualMapModel.type === 'visualMap.continuous' ? getIsInContinuousRange(dataExtent, visualMapModel.option.range) : getIsInPiecewiseRange(dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected);
  61013. hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), {
  61014. inRange: inRangeVisuals.color.getColorMapper(),
  61015. outOfRange: outOfRangeVisuals.color.getColorMapper()
  61016. }, isInRange);
  61017. var img = new ZRImage({
  61018. style: {
  61019. width: width,
  61020. height: height,
  61021. x: x,
  61022. y: y,
  61023. image: hmLayer.canvas
  61024. },
  61025. silent: true
  61026. });
  61027. this.group.add(img);
  61028. };
  61029. HeatmapView.type = 'heatmap';
  61030. return HeatmapView;
  61031. }(ChartView);
  61032. var HeatmapSeriesModel =
  61033. /** @class */
  61034. function (_super) {
  61035. __extends(HeatmapSeriesModel, _super);
  61036. function HeatmapSeriesModel() {
  61037. var _this = _super !== null && _super.apply(this, arguments) || this;
  61038. _this.type = HeatmapSeriesModel.type;
  61039. return _this;
  61040. }
  61041. HeatmapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61042. return createSeriesData(null, this, {
  61043. generateCoord: 'value'
  61044. });
  61045. };
  61046. HeatmapSeriesModel.prototype.preventIncremental = function () {
  61047. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  61048. if (coordSysCreator && coordSysCreator.dimensions) {
  61049. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  61050. }
  61051. };
  61052. HeatmapSeriesModel.type = 'series.heatmap';
  61053. HeatmapSeriesModel.dependencies = ['grid', 'geo', 'calendar'];
  61054. HeatmapSeriesModel.defaultOption = {
  61055. coordinateSystem: 'cartesian2d',
  61056. // zlevel: 0,
  61057. z: 2,
  61058. // Cartesian coordinate system
  61059. // xAxisIndex: 0,
  61060. // yAxisIndex: 0,
  61061. // Geo coordinate system
  61062. geoIndex: 0,
  61063. blurSize: 30,
  61064. pointSize: 20,
  61065. maxOpacity: 1,
  61066. minOpacity: 0,
  61067. select: {
  61068. itemStyle: {
  61069. borderColor: '#212121'
  61070. }
  61071. }
  61072. };
  61073. return HeatmapSeriesModel;
  61074. }(SeriesModel);
  61075. function install$n(registers) {
  61076. registers.registerChartView(HeatmapView);
  61077. registers.registerSeriesModel(HeatmapSeriesModel);
  61078. }
  61079. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth']; // index: +isHorizontal
  61080. var LAYOUT_ATTRS = [{
  61081. xy: 'x',
  61082. wh: 'width',
  61083. index: 0,
  61084. posDesc: ['left', 'right']
  61085. }, {
  61086. xy: 'y',
  61087. wh: 'height',
  61088. index: 1,
  61089. posDesc: ['top', 'bottom']
  61090. }];
  61091. var pathForLineWidth = new Circle();
  61092. var PictorialBarView =
  61093. /** @class */
  61094. function (_super) {
  61095. __extends(PictorialBarView, _super);
  61096. function PictorialBarView() {
  61097. var _this = _super !== null && _super.apply(this, arguments) || this;
  61098. _this.type = PictorialBarView.type;
  61099. return _this;
  61100. }
  61101. PictorialBarView.prototype.render = function (seriesModel, ecModel, api) {
  61102. var group = this.group;
  61103. var data = seriesModel.getData();
  61104. var oldData = this._data;
  61105. var cartesian = seriesModel.coordinateSystem;
  61106. var baseAxis = cartesian.getBaseAxis();
  61107. var isHorizontal = baseAxis.isHorizontal();
  61108. var coordSysRect = cartesian.master.getRect();
  61109. var opt = {
  61110. ecSize: {
  61111. width: api.getWidth(),
  61112. height: api.getHeight()
  61113. },
  61114. seriesModel: seriesModel,
  61115. coordSys: cartesian,
  61116. coordSysExtent: [[coordSysRect.x, coordSysRect.x + coordSysRect.width], [coordSysRect.y, coordSysRect.y + coordSysRect.height]],
  61117. isHorizontal: isHorizontal,
  61118. valueDim: LAYOUT_ATTRS[+isHorizontal],
  61119. categoryDim: LAYOUT_ATTRS[1 - +isHorizontal]
  61120. };
  61121. data.diff(oldData).add(function (dataIndex) {
  61122. if (!data.hasValue(dataIndex)) {
  61123. return;
  61124. }
  61125. var itemModel = getItemModel(data, dataIndex);
  61126. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  61127. var bar = createBar(data, opt, symbolMeta);
  61128. data.setItemGraphicEl(dataIndex, bar);
  61129. group.add(bar);
  61130. updateCommon$1(bar, opt, symbolMeta);
  61131. }).update(function (newIndex, oldIndex) {
  61132. var bar = oldData.getItemGraphicEl(oldIndex);
  61133. if (!data.hasValue(newIndex)) {
  61134. group.remove(bar);
  61135. return;
  61136. }
  61137. var itemModel = getItemModel(data, newIndex);
  61138. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  61139. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  61140. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  61141. group.remove(bar);
  61142. data.setItemGraphicEl(newIndex, null);
  61143. bar = null;
  61144. }
  61145. if (bar) {
  61146. updateBar(bar, opt, symbolMeta);
  61147. } else {
  61148. bar = createBar(data, opt, symbolMeta, true);
  61149. }
  61150. data.setItemGraphicEl(newIndex, bar);
  61151. bar.__pictorialSymbolMeta = symbolMeta; // Add back
  61152. group.add(bar);
  61153. updateCommon$1(bar, opt, symbolMeta);
  61154. }).remove(function (dataIndex) {
  61155. var bar = oldData.getItemGraphicEl(dataIndex);
  61156. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  61157. }).execute();
  61158. this._data = data;
  61159. return this.group;
  61160. };
  61161. PictorialBarView.prototype.remove = function (ecModel, api) {
  61162. var group = this.group;
  61163. var data = this._data;
  61164. if (ecModel.get('animation')) {
  61165. if (data) {
  61166. data.eachItemGraphicEl(function (bar) {
  61167. removeBar(data, getECData(bar).dataIndex, ecModel, bar);
  61168. });
  61169. }
  61170. } else {
  61171. group.removeAll();
  61172. }
  61173. };
  61174. PictorialBarView.type = 'pictorialBar';
  61175. return PictorialBarView;
  61176. }(ChartView); // Set or calculate default value about symbol, and calculate layout info.
  61177. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  61178. var layout = data.getItemLayout(dataIndex);
  61179. var symbolRepeat = itemModel.get('symbolRepeat');
  61180. var symbolClip = itemModel.get('symbolClip');
  61181. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  61182. var symbolRotate = itemModel.get('symbolRotate');
  61183. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  61184. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  61185. var isAnimationEnabled = itemModel.isAnimationEnabled();
  61186. var symbolMeta = {
  61187. dataIndex: dataIndex,
  61188. layout: layout,
  61189. itemModel: itemModel,
  61190. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  61191. style: data.getItemVisual(dataIndex, 'style'),
  61192. symbolClip: symbolClip,
  61193. symbolRepeat: symbolRepeat,
  61194. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  61195. symbolPatternSize: symbolPatternSize,
  61196. rotation: rotation,
  61197. animationModel: isAnimationEnabled ? itemModel : null,
  61198. hoverScale: isAnimationEnabled && itemModel.get(['emphasis', 'scale']),
  61199. z2: itemModel.getShallow('z', true) || 0
  61200. };
  61201. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  61202. prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength, symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta);
  61203. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  61204. var symbolSize = symbolMeta.symbolSize;
  61205. var symbolOffset = normalizeSymbolOffset(itemModel.get('symbolOffset'), symbolSize);
  61206. prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta);
  61207. return symbolMeta;
  61208. } // bar length can be negative.
  61209. function prepareBarLength(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) {
  61210. var valueDim = opt.valueDim;
  61211. var symbolBoundingData = itemModel.get('symbolBoundingData');
  61212. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  61213. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  61214. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  61215. var boundingLength;
  61216. if (isArray(symbolBoundingData)) {
  61217. var symbolBoundingExtent = [convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx];
  61218. symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse();
  61219. boundingLength = symbolBoundingExtent[pxSignIdx];
  61220. } else if (symbolBoundingData != null) {
  61221. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  61222. } else if (symbolRepeat) {
  61223. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  61224. } else {
  61225. boundingLength = layout[valueDim.wh];
  61226. }
  61227. outputSymbolMeta.boundingLength = boundingLength;
  61228. if (symbolRepeat) {
  61229. outputSymbolMeta.repeatCutLength = layout[valueDim.wh];
  61230. } // if 'pxSign' means sign of pixel, it can't be zero, or symbolScale will be zero
  61231. // and when borderWidth be settled, the actual linewidth will be NaN
  61232. outputSymbolMeta.pxSign = boundingLength > 0 ? 1 : -1;
  61233. }
  61234. function convertToCoordOnAxis(axis, value) {
  61235. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  61236. } // Support ['100%', '100%']
  61237. function prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength, pxSign, symbolPatternSize, opt, outputSymbolMeta) {
  61238. var valueDim = opt.valueDim;
  61239. var categoryDim = opt.categoryDim;
  61240. var categorySize = Math.abs(layout[categoryDim.wh]);
  61241. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  61242. var parsedSymbolSize;
  61243. if (isArray(symbolSize)) {
  61244. parsedSymbolSize = symbolSize.slice();
  61245. } else {
  61246. if (symbolSize == null) {
  61247. // will parse to number below
  61248. parsedSymbolSize = ['100%', '100%'];
  61249. } else {
  61250. parsedSymbolSize = [symbolSize, symbolSize];
  61251. }
  61252. } // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  61253. // to complicated to calculate real percent value if considering scaled lineWidth.
  61254. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  61255. // which can be tolerated in pictorial chart.
  61256. parsedSymbolSize[categoryDim.index] = parsePercent$1(parsedSymbolSize[categoryDim.index], categorySize);
  61257. parsedSymbolSize[valueDim.index] = parsePercent$1(parsedSymbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength));
  61258. outputSymbolMeta.symbolSize = parsedSymbolSize; // If x or y is less than zero, show reversed shape.
  61259. var symbolScale = outputSymbolMeta.symbolScale = [parsedSymbolSize[0] / symbolPatternSize, parsedSymbolSize[1] / symbolPatternSize]; // Follow convention, 'right' and 'top' is the normal scale.
  61260. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  61261. }
  61262. function prepareLineWidth(itemModel, symbolScale, rotation, opt, outputSymbolMeta) {
  61263. // In symbols are drawn with scale, so do not need to care about the case that width
  61264. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  61265. // be calculated.
  61266. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  61267. if (valueLineWidth) {
  61268. pathForLineWidth.attr({
  61269. scaleX: symbolScale[0],
  61270. scaleY: symbolScale[1],
  61271. rotation: rotation
  61272. });
  61273. pathForLineWidth.updateTransform();
  61274. valueLineWidth /= pathForLineWidth.getLineScale();
  61275. valueLineWidth *= symbolScale[opt.valueDim.index];
  61276. }
  61277. outputSymbolMeta.valueLineWidth = valueLineWidth || 0;
  61278. }
  61279. function prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, outputSymbolMeta) {
  61280. var categoryDim = opt.categoryDim;
  61281. var valueDim = opt.valueDim;
  61282. var pxSign = outputSymbolMeta.pxSign;
  61283. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  61284. var pathLen = unitLength; // Note: rotation will not effect the layout of symbols, because user may
  61285. // want symbols to rotate on its center, which should not be translated
  61286. // when rotating.
  61287. if (symbolRepeat) {
  61288. var absBoundingLength = Math.abs(boundingLength);
  61289. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  61290. var hasEndGap = false;
  61291. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  61292. hasEndGap = true;
  61293. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  61294. }
  61295. var symbolMarginNumeric = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  61296. var uLenWithMargin = Math.max(unitLength + symbolMarginNumeric * 2, 0); // When symbol margin is less than 0, margin at both ends will be subtracted
  61297. // to ensure that all of the symbols will not be overflow the given area.
  61298. var endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Both final repeatTimes and final symbolMarginNumeric area calculated based on
  61299. // boundingLength.
  61300. var repeatSpecified = isNumeric(symbolRepeat);
  61301. var repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); // Adjust calculate margin, to ensure each symbol is displayed
  61302. // entirely in the given layout area.
  61303. var mDiff = absBoundingLength - repeatTimes * unitLength;
  61304. symbolMarginNumeric = mDiff / 2 / (hasEndGap ? repeatTimes : Math.max(repeatTimes - 1, 1));
  61305. uLenWithMargin = unitLength + symbolMarginNumeric * 2;
  61306. endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Update repeatTimes when not all symbol will be shown.
  61307. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  61308. repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0;
  61309. }
  61310. pathLen = repeatTimes * uLenWithMargin - endFix;
  61311. outputSymbolMeta.repeatTimes = repeatTimes;
  61312. outputSymbolMeta.symbolMargin = symbolMarginNumeric;
  61313. }
  61314. var sizeFix = pxSign * (pathLen / 2);
  61315. var pathPosition = outputSymbolMeta.pathPosition = [];
  61316. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  61317. pathPosition[valueDim.index] = symbolPosition === 'start' ? sizeFix : symbolPosition === 'end' ? boundingLength - sizeFix : boundingLength / 2; // 'center'
  61318. if (symbolOffset) {
  61319. pathPosition[0] += symbolOffset[0];
  61320. pathPosition[1] += symbolOffset[1];
  61321. }
  61322. var bundlePosition = outputSymbolMeta.bundlePosition = [];
  61323. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  61324. bundlePosition[valueDim.index] = layout[valueDim.xy];
  61325. var barRectShape = outputSymbolMeta.barRectShape = extend({}, layout);
  61326. barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix));
  61327. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  61328. var clipShape = outputSymbolMeta.clipShape = {}; // Consider that symbol may be overflow layout rect.
  61329. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  61330. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  61331. clipShape[valueDim.xy] = 0;
  61332. clipShape[valueDim.wh] = layout[valueDim.wh];
  61333. }
  61334. function createPath(symbolMeta) {
  61335. var symbolPatternSize = symbolMeta.symbolPatternSize;
  61336. var path = createSymbol( // Consider texture img, make a big size.
  61337. symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize);
  61338. path.attr({
  61339. culling: true
  61340. });
  61341. path.type !== 'image' && path.setStyle({
  61342. strokeNoScale: true
  61343. });
  61344. return path;
  61345. }
  61346. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  61347. var bundle = bar.__pictorialBundle;
  61348. var symbolSize = symbolMeta.symbolSize;
  61349. var valueLineWidth = symbolMeta.valueLineWidth;
  61350. var pathPosition = symbolMeta.pathPosition;
  61351. var valueDim = opt.valueDim;
  61352. var repeatTimes = symbolMeta.repeatTimes || 0;
  61353. var index = 0;
  61354. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  61355. eachPath(bar, function (path) {
  61356. path.__pictorialAnimationIndex = index;
  61357. path.__pictorialRepeatTimes = repeatTimes;
  61358. if (index < repeatTimes) {
  61359. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  61360. } else {
  61361. updateAttr(path, null, {
  61362. scaleX: 0,
  61363. scaleY: 0
  61364. }, symbolMeta, isUpdate, function () {
  61365. bundle.remove(path);
  61366. });
  61367. } // updateHoverAnimation(path, symbolMeta);
  61368. index++;
  61369. });
  61370. for (; index < repeatTimes; index++) {
  61371. var path = createPath(symbolMeta);
  61372. path.__pictorialAnimationIndex = index;
  61373. path.__pictorialRepeatTimes = repeatTimes;
  61374. bundle.add(path);
  61375. var target = makeTarget(index);
  61376. updateAttr(path, {
  61377. x: target.x,
  61378. y: target.y,
  61379. scaleX: 0,
  61380. scaleY: 0
  61381. }, {
  61382. scaleX: target.scaleX,
  61383. scaleY: target.scaleY,
  61384. rotation: target.rotation
  61385. }, symbolMeta, isUpdate);
  61386. }
  61387. function makeTarget(index) {
  61388. var position = pathPosition.slice(); // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  61389. // Otherwise: i = index;
  61390. var pxSign = symbolMeta.pxSign;
  61391. var i = index;
  61392. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  61393. i = repeatTimes - 1 - index;
  61394. }
  61395. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  61396. return {
  61397. x: position[0],
  61398. y: position[1],
  61399. scaleX: symbolMeta.symbolScale[0],
  61400. scaleY: symbolMeta.symbolScale[1],
  61401. rotation: symbolMeta.rotation
  61402. };
  61403. }
  61404. }
  61405. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  61406. var bundle = bar.__pictorialBundle;
  61407. var mainPath = bar.__pictorialMainPath;
  61408. if (!mainPath) {
  61409. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  61410. bundle.add(mainPath);
  61411. updateAttr(mainPath, {
  61412. x: symbolMeta.pathPosition[0],
  61413. y: symbolMeta.pathPosition[1],
  61414. scaleX: 0,
  61415. scaleY: 0,
  61416. rotation: symbolMeta.rotation
  61417. }, {
  61418. scaleX: symbolMeta.symbolScale[0],
  61419. scaleY: symbolMeta.symbolScale[1]
  61420. }, symbolMeta, isUpdate);
  61421. } else {
  61422. updateAttr(mainPath, null, {
  61423. x: symbolMeta.pathPosition[0],
  61424. y: symbolMeta.pathPosition[1],
  61425. scaleX: symbolMeta.symbolScale[0],
  61426. scaleY: symbolMeta.symbolScale[1],
  61427. rotation: symbolMeta.rotation
  61428. }, symbolMeta, isUpdate);
  61429. }
  61430. } // bar rect is used for label.
  61431. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  61432. var rectShape = extend({}, symbolMeta.barRectShape);
  61433. var barRect = bar.__pictorialBarRect;
  61434. if (!barRect) {
  61435. barRect = bar.__pictorialBarRect = new Rect({
  61436. z2: 2,
  61437. shape: rectShape,
  61438. silent: true,
  61439. style: {
  61440. stroke: 'transparent',
  61441. fill: 'transparent',
  61442. lineWidth: 0
  61443. }
  61444. });
  61445. barRect.disableMorphing = true;
  61446. bar.add(barRect);
  61447. } else {
  61448. updateAttr(barRect, null, {
  61449. shape: rectShape
  61450. }, symbolMeta, isUpdate);
  61451. }
  61452. }
  61453. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  61454. // If not clip, symbol will be remove and rebuilt.
  61455. if (symbolMeta.symbolClip) {
  61456. var clipPath = bar.__pictorialClipPath;
  61457. var clipShape = extend({}, symbolMeta.clipShape);
  61458. var valueDim = opt.valueDim;
  61459. var animationModel = symbolMeta.animationModel;
  61460. var dataIndex = symbolMeta.dataIndex;
  61461. if (clipPath) {
  61462. updateProps(clipPath, {
  61463. shape: clipShape
  61464. }, animationModel, dataIndex);
  61465. } else {
  61466. clipShape[valueDim.wh] = 0;
  61467. clipPath = new Rect({
  61468. shape: clipShape
  61469. });
  61470. bar.__pictorialBundle.setClipPath(clipPath);
  61471. bar.__pictorialClipPath = clipPath;
  61472. var target = {};
  61473. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  61474. graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, {
  61475. shape: target
  61476. }, animationModel, dataIndex);
  61477. }
  61478. }
  61479. }
  61480. function getItemModel(data, dataIndex) {
  61481. var itemModel = data.getItemModel(dataIndex);
  61482. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  61483. itemModel.isAnimationEnabled = isAnimationEnabled;
  61484. return itemModel;
  61485. }
  61486. function getAnimationDelayParams(path) {
  61487. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  61488. return {
  61489. index: path.__pictorialAnimationIndex,
  61490. count: path.__pictorialRepeatTimes
  61491. };
  61492. }
  61493. function isAnimationEnabled() {
  61494. // `animation` prop can be set on itemModel in pictorial bar chart.
  61495. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  61496. }
  61497. function createBar(data, opt, symbolMeta, isUpdate) {
  61498. // bar is the main element for each data.
  61499. var bar = new Group(); // bundle is used for location and clip.
  61500. var bundle = new Group();
  61501. bar.add(bundle);
  61502. bar.__pictorialBundle = bundle;
  61503. bundle.x = symbolMeta.bundlePosition[0];
  61504. bundle.y = symbolMeta.bundlePosition[1];
  61505. if (symbolMeta.symbolRepeat) {
  61506. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  61507. } else {
  61508. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  61509. }
  61510. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  61511. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  61512. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  61513. bar.__pictorialSymbolMeta = symbolMeta;
  61514. return bar;
  61515. }
  61516. function updateBar(bar, opt, symbolMeta) {
  61517. var animationModel = symbolMeta.animationModel;
  61518. var dataIndex = symbolMeta.dataIndex;
  61519. var bundle = bar.__pictorialBundle;
  61520. updateProps(bundle, {
  61521. x: symbolMeta.bundlePosition[0],
  61522. y: symbolMeta.bundlePosition[1]
  61523. }, animationModel, dataIndex);
  61524. if (symbolMeta.symbolRepeat) {
  61525. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  61526. } else {
  61527. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  61528. }
  61529. createOrUpdateBarRect(bar, symbolMeta, true);
  61530. createOrUpdateClip(bar, opt, symbolMeta, true);
  61531. }
  61532. function removeBar(data, dataIndex, animationModel, bar) {
  61533. // Not show text when animating
  61534. var labelRect = bar.__pictorialBarRect;
  61535. labelRect && labelRect.removeTextContent();
  61536. var paths = [];
  61537. eachPath(bar, function (path) {
  61538. paths.push(path);
  61539. });
  61540. bar.__pictorialMainPath && paths.push(bar.__pictorialMainPath); // I do not find proper remove animation for clip yet.
  61541. bar.__pictorialClipPath && (animationModel = null);
  61542. each(paths, function (path) {
  61543. removeElement(path, {
  61544. scaleX: 0,
  61545. scaleY: 0
  61546. }, animationModel, dataIndex, function () {
  61547. bar.parent && bar.parent.remove(bar);
  61548. });
  61549. });
  61550. data.setItemGraphicEl(dataIndex, null);
  61551. }
  61552. function getShapeStr(data, symbolMeta) {
  61553. return [data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip].join(':');
  61554. }
  61555. function eachPath(bar, cb, context) {
  61556. // Do not use Group#eachChild, because it do not support remove.
  61557. each(bar.__pictorialBundle.children(), function (el) {
  61558. el !== bar.__pictorialBarRect && cb.call(context, el);
  61559. });
  61560. }
  61561. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  61562. immediateAttrs && el.attr(immediateAttrs); // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  61563. if (symbolMeta.symbolClip && !isUpdate) {
  61564. animationAttrs && el.attr(animationAttrs);
  61565. } else {
  61566. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb);
  61567. }
  61568. }
  61569. function updateCommon$1(bar, opt, symbolMeta) {
  61570. var dataIndex = symbolMeta.dataIndex;
  61571. var itemModel = symbolMeta.itemModel; // Color must be excluded.
  61572. // Because symbol provide setColor individually to set fill and stroke
  61573. var emphasisModel = itemModel.getModel('emphasis');
  61574. var emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  61575. var blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  61576. var selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  61577. var cursorStyle = itemModel.getShallow('cursor');
  61578. var focus = emphasisModel.get('focus');
  61579. var blurScope = emphasisModel.get('blurScope');
  61580. var hoverScale = emphasisModel.get('scale');
  61581. eachPath(bar, function (path) {
  61582. if (path instanceof ZRImage) {
  61583. var pathStyle = path.style;
  61584. path.useStyle(extend({
  61585. // TODO other properties like dx, dy ?
  61586. image: pathStyle.image,
  61587. x: pathStyle.x,
  61588. y: pathStyle.y,
  61589. width: pathStyle.width,
  61590. height: pathStyle.height
  61591. }, symbolMeta.style));
  61592. } else {
  61593. path.useStyle(symbolMeta.style);
  61594. }
  61595. var emphasisState = path.ensureState('emphasis');
  61596. emphasisState.style = emphasisStyle;
  61597. if (hoverScale) {
  61598. // NOTE: Must after scale is set after updateAttr
  61599. emphasisState.scaleX = path.scaleX * 1.1;
  61600. emphasisState.scaleY = path.scaleY * 1.1;
  61601. }
  61602. path.ensureState('blur').style = blurStyle;
  61603. path.ensureState('select').style = selectStyle;
  61604. cursorStyle && (path.cursor = cursorStyle);
  61605. path.z2 = symbolMeta.z2;
  61606. });
  61607. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  61608. var barRect = bar.__pictorialBarRect;
  61609. setLabelStyle(barRect, getLabelStatesModels(itemModel), {
  61610. labelFetcher: opt.seriesModel,
  61611. labelDataIndex: dataIndex,
  61612. defaultText: getDefaultLabel(opt.seriesModel.getData(), dataIndex),
  61613. inheritColor: symbolMeta.style.fill,
  61614. defaultOpacity: symbolMeta.style.opacity,
  61615. defaultOutsidePosition: barPositionOutside
  61616. });
  61617. toggleHoverEmphasis(bar, focus, blurScope, emphasisModel.get('disabled'));
  61618. }
  61619. function toIntTimes(times) {
  61620. var roundedTimes = Math.round(times); // Escapse accurate error
  61621. return Math.abs(times - roundedTimes) < 1e-4 ? roundedTimes : Math.ceil(times);
  61622. }
  61623. var PictorialBarSeriesModel =
  61624. /** @class */
  61625. function (_super) {
  61626. __extends(PictorialBarSeriesModel, _super);
  61627. function PictorialBarSeriesModel() {
  61628. var _this = _super !== null && _super.apply(this, arguments) || this;
  61629. _this.type = PictorialBarSeriesModel.type;
  61630. _this.hasSymbolVisual = true;
  61631. _this.defaultSymbol = 'roundRect';
  61632. return _this;
  61633. }
  61634. PictorialBarSeriesModel.prototype.getInitialData = function (option) {
  61635. // Disable stack.
  61636. option.stack = null;
  61637. return _super.prototype.getInitialData.apply(this, arguments);
  61638. };
  61639. PictorialBarSeriesModel.type = 'series.pictorialBar';
  61640. PictorialBarSeriesModel.dependencies = ['grid'];
  61641. PictorialBarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  61642. symbol: 'circle',
  61643. symbolSize: null,
  61644. symbolRotate: null,
  61645. symbolPosition: null,
  61646. symbolOffset: null,
  61647. symbolMargin: null,
  61648. symbolRepeat: false,
  61649. symbolRepeatDirection: 'end',
  61650. symbolClip: false,
  61651. symbolBoundingData: null,
  61652. symbolPatternSize: 400,
  61653. barGap: '-100%',
  61654. // z can be set in data item, which is z2 actually.
  61655. // Disable progressive
  61656. progressive: 0,
  61657. emphasis: {
  61658. // By default pictorialBar do not hover scale. Hover scale is not suitable
  61659. // for the case that both has foreground and background.
  61660. scale: false
  61661. },
  61662. select: {
  61663. itemStyle: {
  61664. borderColor: '#212121'
  61665. }
  61666. }
  61667. });
  61668. return PictorialBarSeriesModel;
  61669. }(BaseBarSeriesModel);
  61670. function install$o(registers) {
  61671. registers.registerChartView(PictorialBarView);
  61672. registers.registerSeriesModel(PictorialBarSeriesModel);
  61673. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'pictorialBar')); // Do layout after other overall layout, which can prepare some information.
  61674. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('pictorialBar'));
  61675. }
  61676. var ThemeRiverView =
  61677. /** @class */
  61678. function (_super) {
  61679. __extends(ThemeRiverView, _super);
  61680. function ThemeRiverView() {
  61681. var _this = _super !== null && _super.apply(this, arguments) || this;
  61682. _this.type = ThemeRiverView.type;
  61683. _this._layers = [];
  61684. return _this;
  61685. }
  61686. ThemeRiverView.prototype.render = function (seriesModel, ecModel, api) {
  61687. var data = seriesModel.getData();
  61688. var self = this;
  61689. var group = this.group;
  61690. var layersSeries = seriesModel.getLayerSeries();
  61691. var layoutInfo = data.getLayout('layoutInfo');
  61692. var rect = layoutInfo.rect;
  61693. var boundaryGap = layoutInfo.boundaryGap;
  61694. group.x = 0;
  61695. group.y = rect.y + boundaryGap[0];
  61696. function keyGetter(item) {
  61697. return item.name;
  61698. }
  61699. var dataDiffer = new DataDiffer(this._layersSeries || [], layersSeries, keyGetter, keyGetter);
  61700. var newLayersGroups = [];
  61701. dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute();
  61702. function process(status, idx, oldIdx) {
  61703. var oldLayersGroups = self._layers;
  61704. if (status === 'remove') {
  61705. group.remove(oldLayersGroups[idx]);
  61706. return;
  61707. }
  61708. var points0 = [];
  61709. var points1 = [];
  61710. var style;
  61711. var indices = layersSeries[idx].indices;
  61712. var j = 0;
  61713. for (; j < indices.length; j++) {
  61714. var layout = data.getItemLayout(indices[j]);
  61715. var x = layout.x;
  61716. var y0 = layout.y0;
  61717. var y = layout.y;
  61718. points0.push(x, y0);
  61719. points1.push(x, y0 + y);
  61720. style = data.getItemVisual(indices[j], 'style');
  61721. }
  61722. var polygon;
  61723. var textLayout = data.getItemLayout(indices[0]);
  61724. var labelModel = seriesModel.getModel('label');
  61725. var margin = labelModel.get('margin');
  61726. var emphasisModel = seriesModel.getModel('emphasis');
  61727. if (status === 'add') {
  61728. var layerGroup = newLayersGroups[idx] = new Group();
  61729. polygon = new ECPolygon({
  61730. shape: {
  61731. points: points0,
  61732. stackedOnPoints: points1,
  61733. smooth: 0.4,
  61734. stackedOnSmooth: 0.4,
  61735. smoothConstraint: false
  61736. },
  61737. z2: 0
  61738. });
  61739. layerGroup.add(polygon);
  61740. group.add(layerGroup);
  61741. if (seriesModel.isAnimationEnabled()) {
  61742. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  61743. polygon.removeClipPath();
  61744. }));
  61745. }
  61746. } else {
  61747. var layerGroup = oldLayersGroups[oldIdx];
  61748. polygon = layerGroup.childAt(0);
  61749. group.add(layerGroup);
  61750. newLayersGroups[idx] = layerGroup;
  61751. updateProps(polygon, {
  61752. shape: {
  61753. points: points0,
  61754. stackedOnPoints: points1
  61755. }
  61756. }, seriesModel);
  61757. saveOldStyle(polygon);
  61758. }
  61759. setLabelStyle(polygon, getLabelStatesModels(seriesModel), {
  61760. labelDataIndex: indices[j - 1],
  61761. defaultText: data.getName(indices[j - 1]),
  61762. inheritColor: style.fill
  61763. }, {
  61764. normal: {
  61765. verticalAlign: 'middle' // align: 'right'
  61766. }
  61767. });
  61768. polygon.setTextConfig({
  61769. position: null,
  61770. local: true
  61771. });
  61772. var labelEl = polygon.getTextContent(); // TODO More label position options.
  61773. if (labelEl) {
  61774. labelEl.x = textLayout.x - margin;
  61775. labelEl.y = textLayout.y0 + textLayout.y / 2;
  61776. }
  61777. polygon.useStyle(style);
  61778. data.setItemGraphicEl(idx, polygon);
  61779. setStatesStylesFromModel(polygon, seriesModel);
  61780. toggleHoverEmphasis(polygon, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  61781. }
  61782. this._layersSeries = layersSeries;
  61783. this._layers = newLayersGroups;
  61784. };
  61785. ThemeRiverView.type = 'themeRiver';
  61786. return ThemeRiverView;
  61787. }(ChartView);
  61788. function createGridClipShape$2(rect, seriesModel, cb) {
  61789. var rectEl = new Rect({
  61790. shape: {
  61791. x: rect.x - 10,
  61792. y: rect.y - 10,
  61793. width: 0,
  61794. height: rect.height + 20
  61795. }
  61796. });
  61797. initProps(rectEl, {
  61798. shape: {
  61799. x: rect.x - 50,
  61800. width: rect.width + 100,
  61801. height: rect.height + 20
  61802. }
  61803. }, seriesModel, cb);
  61804. return rectEl;
  61805. }
  61806. var DATA_NAME_INDEX = 2;
  61807. var ThemeRiverSeriesModel =
  61808. /** @class */
  61809. function (_super) {
  61810. __extends(ThemeRiverSeriesModel, _super);
  61811. function ThemeRiverSeriesModel() {
  61812. var _this = _super !== null && _super.apply(this, arguments) || this;
  61813. _this.type = ThemeRiverSeriesModel.type;
  61814. return _this;
  61815. }
  61816. /**
  61817. * @override
  61818. */
  61819. ThemeRiverSeriesModel.prototype.init = function (option) {
  61820. // eslint-disable-next-line
  61821. _super.prototype.init.apply(this, arguments); // Put this function here is for the sake of consistency of code style.
  61822. // Enable legend selection for each data item
  61823. // Use a function instead of direct access because data reference may changed
  61824. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  61825. };
  61826. /**
  61827. * If there is no value of a certain point in the time for some event,set it value to 0.
  61828. *
  61829. * @param {Array} data initial data in the option
  61830. * @return {Array}
  61831. */
  61832. ThemeRiverSeriesModel.prototype.fixData = function (data) {
  61833. var rawDataLength = data.length;
  61834. /**
  61835. * Make sure every layer data get the same keys.
  61836. * The value index tells which layer has visited.
  61837. * {
  61838. * 2014/01/01: -1
  61839. * }
  61840. */
  61841. var timeValueKeys = {}; // grouped data by name
  61842. var groupResult = groupData(data, function (item) {
  61843. if (!timeValueKeys.hasOwnProperty(item[0] + '')) {
  61844. timeValueKeys[item[0] + ''] = -1;
  61845. }
  61846. return item[2];
  61847. });
  61848. var layerData = [];
  61849. groupResult.buckets.each(function (items, key) {
  61850. layerData.push({
  61851. name: key,
  61852. dataList: items
  61853. });
  61854. });
  61855. var layerNum = layerData.length;
  61856. for (var k = 0; k < layerNum; ++k) {
  61857. var name_1 = layerData[k].name;
  61858. for (var j = 0; j < layerData[k].dataList.length; ++j) {
  61859. var timeValue = layerData[k].dataList[j][0] + '';
  61860. timeValueKeys[timeValue] = k;
  61861. }
  61862. for (var timeValue in timeValueKeys) {
  61863. if (timeValueKeys.hasOwnProperty(timeValue) && timeValueKeys[timeValue] !== k) {
  61864. timeValueKeys[timeValue] = k;
  61865. data[rawDataLength] = [timeValue, 0, name_1];
  61866. rawDataLength++;
  61867. }
  61868. }
  61869. }
  61870. return data;
  61871. };
  61872. /**
  61873. * @override
  61874. * @param option the initial option that user gave
  61875. * @param ecModel the model object for themeRiver option
  61876. */
  61877. ThemeRiverSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61878. var singleAxisModel = this.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  61879. var axisType = singleAxisModel.get('type'); // filter the data item with the value of label is undefined
  61880. var filterData = filter(option.data, function (dataItem) {
  61881. return dataItem[2] !== undefined;
  61882. }); // ??? TODO design a stage to transfer data for themeRiver and lines?
  61883. var data = this.fixData(filterData || []);
  61884. var nameList = [];
  61885. var nameMap = this.nameMap = createHashMap();
  61886. var count = 0;
  61887. for (var i = 0; i < data.length; ++i) {
  61888. nameList.push(data[i][DATA_NAME_INDEX]);
  61889. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  61890. nameMap.set(data[i][DATA_NAME_INDEX], count);
  61891. count++;
  61892. }
  61893. }
  61894. var dimensions = prepareSeriesDataSchema(data, {
  61895. coordDimensions: ['single'],
  61896. dimensionsDefine: [{
  61897. name: 'time',
  61898. type: getDimensionTypeByAxis(axisType)
  61899. }, {
  61900. name: 'value',
  61901. type: 'float'
  61902. }, {
  61903. name: 'name',
  61904. type: 'ordinal'
  61905. }],
  61906. encodeDefine: {
  61907. single: 0,
  61908. value: 1,
  61909. itemName: 2
  61910. }
  61911. }).dimensions;
  61912. var list = new SeriesData(dimensions, this);
  61913. list.initData(data);
  61914. return list;
  61915. };
  61916. /**
  61917. * The raw data is divided into multiple layers and each layer
  61918. * has same name.
  61919. */
  61920. ThemeRiverSeriesModel.prototype.getLayerSeries = function () {
  61921. var data = this.getData();
  61922. var lenCount = data.count();
  61923. var indexArr = [];
  61924. for (var i = 0; i < lenCount; ++i) {
  61925. indexArr[i] = i;
  61926. }
  61927. var timeDim = data.mapDimension('single'); // data group by name
  61928. var groupResult = groupData(indexArr, function (index) {
  61929. return data.get('name', index);
  61930. });
  61931. var layerSeries = [];
  61932. groupResult.buckets.each(function (items, key) {
  61933. items.sort(function (index1, index2) {
  61934. return data.get(timeDim, index1) - data.get(timeDim, index2);
  61935. });
  61936. layerSeries.push({
  61937. name: key,
  61938. indices: items
  61939. });
  61940. });
  61941. return layerSeries;
  61942. };
  61943. /**
  61944. * Get data indices for show tooltip content
  61945. */
  61946. ThemeRiverSeriesModel.prototype.getAxisTooltipData = function (dim, value, baseAxis) {
  61947. if (!isArray(dim)) {
  61948. dim = dim ? [dim] : [];
  61949. }
  61950. var data = this.getData();
  61951. var layerSeries = this.getLayerSeries();
  61952. var indices = [];
  61953. var layerNum = layerSeries.length;
  61954. var nestestValue;
  61955. for (var i = 0; i < layerNum; ++i) {
  61956. var minDist = Number.MAX_VALUE;
  61957. var nearestIdx = -1;
  61958. var pointNum = layerSeries[i].indices.length;
  61959. for (var j = 0; j < pointNum; ++j) {
  61960. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  61961. var dist = Math.abs(theValue - value);
  61962. if (dist <= minDist) {
  61963. nestestValue = theValue;
  61964. minDist = dist;
  61965. nearestIdx = layerSeries[i].indices[j];
  61966. }
  61967. }
  61968. indices.push(nearestIdx);
  61969. }
  61970. return {
  61971. dataIndices: indices,
  61972. nestestValue: nestestValue
  61973. };
  61974. };
  61975. ThemeRiverSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  61976. var data = this.getData();
  61977. var name = data.getName(dataIndex);
  61978. var value = data.get(data.mapDimension('value'), dataIndex);
  61979. return createTooltipMarkup('nameValue', {
  61980. name: name,
  61981. value: value
  61982. });
  61983. };
  61984. ThemeRiverSeriesModel.type = 'series.themeRiver';
  61985. ThemeRiverSeriesModel.dependencies = ['singleAxis'];
  61986. ThemeRiverSeriesModel.defaultOption = {
  61987. // zlevel: 0,
  61988. z: 2,
  61989. colorBy: 'data',
  61990. coordinateSystem: 'singleAxis',
  61991. // gap in axis's orthogonal orientation
  61992. boundaryGap: ['10%', '10%'],
  61993. // legendHoverLink: true,
  61994. singleAxisIndex: 0,
  61995. animationEasing: 'linear',
  61996. label: {
  61997. margin: 4,
  61998. show: true,
  61999. position: 'left',
  62000. fontSize: 11
  62001. },
  62002. emphasis: {
  62003. label: {
  62004. show: true
  62005. }
  62006. }
  62007. };
  62008. return ThemeRiverSeriesModel;
  62009. }(SeriesModel);
  62010. function themeRiverLayout(ecModel, api) {
  62011. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62012. var data = seriesModel.getData();
  62013. var single = seriesModel.coordinateSystem;
  62014. var layoutInfo = {}; // use the axis boundingRect for view
  62015. var rect = single.getRect();
  62016. layoutInfo.rect = rect;
  62017. var boundaryGap = seriesModel.get('boundaryGap');
  62018. var axis = single.getAxis();
  62019. layoutInfo.boundaryGap = boundaryGap;
  62020. if (axis.orient === 'horizontal') {
  62021. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  62022. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  62023. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  62024. doThemeRiverLayout(data, seriesModel, height);
  62025. } else {
  62026. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  62027. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  62028. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  62029. doThemeRiverLayout(data, seriesModel, width);
  62030. }
  62031. data.setLayout('layoutInfo', layoutInfo);
  62032. });
  62033. }
  62034. /**
  62035. * The layout information about themeriver
  62036. *
  62037. * @param data data in the series
  62038. * @param seriesModel the model object of themeRiver series
  62039. * @param height value used to compute every series height
  62040. */
  62041. function doThemeRiverLayout(data, seriesModel, height) {
  62042. if (!data.count()) {
  62043. return;
  62044. }
  62045. var coordSys = seriesModel.coordinateSystem; // the data in each layer are organized into a series.
  62046. var layerSeries = seriesModel.getLayerSeries(); // the points in each layer.
  62047. var timeDim = data.mapDimension('single');
  62048. var valueDim = data.mapDimension('value');
  62049. var layerPoints = map(layerSeries, function (singleLayer) {
  62050. return map(singleLayer.indices, function (idx) {
  62051. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  62052. pt[1] = data.get(valueDim, idx);
  62053. return pt;
  62054. });
  62055. });
  62056. var base = computeBaseline(layerPoints);
  62057. var baseLine = base.y0;
  62058. var ky = height / base.max; // set layout information for each item.
  62059. var n = layerSeries.length;
  62060. var m = layerSeries[0].indices.length;
  62061. var baseY0;
  62062. for (var j = 0; j < m; ++j) {
  62063. baseY0 = baseLine[j] * ky;
  62064. data.setItemLayout(layerSeries[0].indices[j], {
  62065. layerIndex: 0,
  62066. x: layerPoints[0][j][0],
  62067. y0: baseY0,
  62068. y: layerPoints[0][j][1] * ky
  62069. });
  62070. for (var i = 1; i < n; ++i) {
  62071. baseY0 += layerPoints[i - 1][j][1] * ky;
  62072. data.setItemLayout(layerSeries[i].indices[j], {
  62073. layerIndex: i,
  62074. x: layerPoints[i][j][0],
  62075. y0: baseY0,
  62076. y: layerPoints[i][j][1] * ky
  62077. });
  62078. }
  62079. }
  62080. }
  62081. /**
  62082. * Compute the baseLine of the rawdata
  62083. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  62084. *
  62085. * @param data the points in each layer
  62086. */
  62087. function computeBaseline(data) {
  62088. var layerNum = data.length;
  62089. var pointNum = data[0].length;
  62090. var sums = [];
  62091. var y0 = [];
  62092. var max = 0;
  62093. for (var i = 0; i < pointNum; ++i) {
  62094. var temp = 0;
  62095. for (var j = 0; j < layerNum; ++j) {
  62096. temp += data[j][i][1];
  62097. }
  62098. if (temp > max) {
  62099. max = temp;
  62100. }
  62101. sums.push(temp);
  62102. }
  62103. for (var k = 0; k < pointNum; ++k) {
  62104. y0[k] = (max - sums[k]) / 2;
  62105. }
  62106. max = 0;
  62107. for (var l = 0; l < pointNum; ++l) {
  62108. var sum = sums[l] + y0[l];
  62109. if (sum > max) {
  62110. max = sum;
  62111. }
  62112. }
  62113. return {
  62114. y0: y0,
  62115. max: max
  62116. };
  62117. }
  62118. function install$p(registers) {
  62119. registers.registerChartView(ThemeRiverView);
  62120. registers.registerSeriesModel(ThemeRiverSeriesModel);
  62121. registers.registerLayout(themeRiverLayout);
  62122. registers.registerProcessor(dataFilter('themeRiver'));
  62123. }
  62124. var DEFAULT_SECTOR_Z = 2;
  62125. var DEFAULT_TEXT_Z = 4;
  62126. /**
  62127. * Sunburstce of Sunburst including Sector, Label, LabelLine
  62128. */
  62129. var SunburstPiece =
  62130. /** @class */
  62131. function (_super) {
  62132. __extends(SunburstPiece, _super);
  62133. function SunburstPiece(node, seriesModel, ecModel, api) {
  62134. var _this = _super.call(this) || this;
  62135. _this.z2 = DEFAULT_SECTOR_Z;
  62136. _this.textConfig = {
  62137. inside: true
  62138. };
  62139. getECData(_this).seriesIndex = seriesModel.seriesIndex;
  62140. var text = new ZRText({
  62141. z2: DEFAULT_TEXT_Z,
  62142. silent: node.getModel().get(['label', 'silent'])
  62143. });
  62144. _this.setTextContent(text);
  62145. _this.updateData(true, node, seriesModel, ecModel, api);
  62146. return _this;
  62147. }
  62148. SunburstPiece.prototype.updateData = function (firstCreate, node, // state: 'emphasis' | 'normal' | 'highlight' | 'downplay',
  62149. seriesModel, ecModel, api) {
  62150. this.node = node;
  62151. node.piece = this;
  62152. seriesModel = seriesModel || this._seriesModel;
  62153. ecModel = ecModel || this._ecModel;
  62154. var sector = this;
  62155. getECData(sector).dataIndex = node.dataIndex;
  62156. var itemModel = node.getModel();
  62157. var emphasisModel = itemModel.getModel('emphasis');
  62158. var layout = node.getLayout();
  62159. var sectorShape = extend({}, layout);
  62160. sectorShape.label = null;
  62161. var normalStyle = node.getVisual('style');
  62162. normalStyle.lineJoin = 'bevel';
  62163. var decal = node.getVisual('decal');
  62164. if (decal) {
  62165. normalStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  62166. }
  62167. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  62168. extend(sectorShape, cornerRadius);
  62169. each(SPECIAL_STATES, function (stateName) {
  62170. var state = sector.ensureState(stateName);
  62171. var itemStyleModel = itemModel.getModel([stateName, 'itemStyle']);
  62172. state.style = itemStyleModel.getItemStyle(); // border radius
  62173. var cornerRadius = getSectorCornerRadius(itemStyleModel, sectorShape);
  62174. if (cornerRadius) {
  62175. state.shape = cornerRadius;
  62176. }
  62177. });
  62178. if (firstCreate) {
  62179. sector.setShape(sectorShape);
  62180. sector.shape.r = layout.r0;
  62181. initProps(sector, {
  62182. shape: {
  62183. r: layout.r
  62184. }
  62185. }, seriesModel, node.dataIndex);
  62186. } else {
  62187. // Disable animation for gradient since no interpolation method
  62188. // is supported for gradient
  62189. updateProps(sector, {
  62190. shape: sectorShape
  62191. }, seriesModel);
  62192. saveOldStyle(sector);
  62193. }
  62194. sector.useStyle(normalStyle);
  62195. this._updateLabel(seriesModel);
  62196. var cursorStyle = itemModel.getShallow('cursor');
  62197. cursorStyle && sector.attr('cursor', cursorStyle);
  62198. this._seriesModel = seriesModel || this._seriesModel;
  62199. this._ecModel = ecModel || this._ecModel;
  62200. var focus = emphasisModel.get('focus');
  62201. var focusOrIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : focus;
  62202. toggleHoverEmphasis(this, focusOrIndices, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  62203. };
  62204. SunburstPiece.prototype._updateLabel = function (seriesModel) {
  62205. var _this = this;
  62206. var itemModel = this.node.getModel();
  62207. var normalLabelModel = itemModel.getModel('label');
  62208. var layout = this.node.getLayout();
  62209. var angle = layout.endAngle - layout.startAngle;
  62210. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  62211. var dx = Math.cos(midAngle);
  62212. var dy = Math.sin(midAngle);
  62213. var sector = this;
  62214. var label = sector.getTextContent();
  62215. var dataIndex = this.node.dataIndex;
  62216. var labelMinAngle = normalLabelModel.get('minAngle') / 180 * Math.PI;
  62217. var isNormalShown = normalLabelModel.get('show') && !(labelMinAngle != null && Math.abs(angle) < labelMinAngle);
  62218. label.ignore = !isNormalShown; // TODO use setLabelStyle
  62219. each(DISPLAY_STATES, function (stateName) {
  62220. var labelStateModel = stateName === 'normal' ? itemModel.getModel('label') : itemModel.getModel([stateName, 'label']);
  62221. var isNormal = stateName === 'normal';
  62222. var state = isNormal ? label : label.ensureState(stateName);
  62223. var text = seriesModel.getFormattedLabel(dataIndex, stateName);
  62224. if (isNormal) {
  62225. text = text || _this.node.name;
  62226. }
  62227. state.style = createTextStyle(labelStateModel, {}, null, stateName !== 'normal', true);
  62228. if (text) {
  62229. state.style.text = text;
  62230. } // Not displaying text when angle is too small
  62231. var isShown = labelStateModel.get('show');
  62232. if (isShown != null && !isNormal) {
  62233. state.ignore = !isShown;
  62234. }
  62235. var labelPosition = getLabelAttr(labelStateModel, 'position');
  62236. var sectorState = isNormal ? sector : sector.states[stateName];
  62237. var labelColor = sectorState.style.fill;
  62238. sectorState.textConfig = {
  62239. outsideFill: labelStateModel.get('color') === 'inherit' ? labelColor : null,
  62240. inside: labelPosition !== 'outside'
  62241. };
  62242. var r;
  62243. var labelPadding = getLabelAttr(labelStateModel, 'distance') || 0;
  62244. var textAlign = getLabelAttr(labelStateModel, 'align');
  62245. if (labelPosition === 'outside') {
  62246. r = layout.r + labelPadding;
  62247. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  62248. } else {
  62249. if (!textAlign || textAlign === 'center') {
  62250. // Put label in the center if it's a circle
  62251. if (angle === 2 * Math.PI && layout.r0 === 0) {
  62252. r = 0;
  62253. } else {
  62254. r = (layout.r + layout.r0) / 2;
  62255. }
  62256. textAlign = 'center';
  62257. } else if (textAlign === 'left') {
  62258. r = layout.r0 + labelPadding;
  62259. if (midAngle > Math.PI / 2) {
  62260. textAlign = 'right';
  62261. }
  62262. } else if (textAlign === 'right') {
  62263. r = layout.r - labelPadding;
  62264. if (midAngle > Math.PI / 2) {
  62265. textAlign = 'left';
  62266. }
  62267. }
  62268. }
  62269. state.style.align = textAlign;
  62270. state.style.verticalAlign = getLabelAttr(labelStateModel, 'verticalAlign') || 'middle';
  62271. state.x = r * dx + layout.cx;
  62272. state.y = r * dy + layout.cy;
  62273. var rotateType = getLabelAttr(labelStateModel, 'rotate');
  62274. var rotate = 0;
  62275. if (rotateType === 'radial') {
  62276. rotate = normalizeRadian(-midAngle);
  62277. if (rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  62278. rotate += Math.PI;
  62279. }
  62280. } else if (rotateType === 'tangential') {
  62281. rotate = Math.PI / 2 - midAngle;
  62282. if (rotate > Math.PI / 2) {
  62283. rotate -= Math.PI;
  62284. } else if (rotate < -Math.PI / 2) {
  62285. rotate += Math.PI;
  62286. }
  62287. } else if (isNumber(rotateType)) {
  62288. rotate = rotateType * Math.PI / 180;
  62289. }
  62290. state.rotation = rotate;
  62291. });
  62292. function getLabelAttr(model, name) {
  62293. var stateAttr = model.get(name);
  62294. if (stateAttr == null) {
  62295. return normalLabelModel.get(name);
  62296. }
  62297. return stateAttr;
  62298. }
  62299. label.dirtyStyle();
  62300. };
  62301. return SunburstPiece;
  62302. }(Sector);
  62303. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  62304. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  62305. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  62306. function installSunburstAction(registers) {
  62307. registers.registerAction({
  62308. type: ROOT_TO_NODE_ACTION,
  62309. update: 'updateView'
  62310. }, function (payload, ecModel) {
  62311. ecModel.eachComponent({
  62312. mainType: 'series',
  62313. subType: 'sunburst',
  62314. query: payload
  62315. }, handleRootToNode);
  62316. function handleRootToNode(model, index) {
  62317. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION], model);
  62318. if (targetInfo) {
  62319. var originViewRoot = model.getViewRoot();
  62320. if (originViewRoot) {
  62321. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  62322. }
  62323. model.resetViewRoot(targetInfo.node);
  62324. }
  62325. }
  62326. });
  62327. registers.registerAction({
  62328. type: HIGHLIGHT_ACTION,
  62329. update: 'none'
  62330. }, function (payload, ecModel, api) {
  62331. // Clone
  62332. payload = extend({}, payload);
  62333. ecModel.eachComponent({
  62334. mainType: 'series',
  62335. subType: 'sunburst',
  62336. query: payload
  62337. }, handleHighlight);
  62338. function handleHighlight(model) {
  62339. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  62340. if (targetInfo) {
  62341. payload.dataIndex = targetInfo.node.dataIndex;
  62342. }
  62343. }
  62344. if ("development" !== 'production') {
  62345. deprecateReplaceLog('sunburstHighlight', 'highlight');
  62346. } // Fast forward action
  62347. api.dispatchAction(extend(payload, {
  62348. type: 'highlight'
  62349. }));
  62350. });
  62351. registers.registerAction({
  62352. type: UNHIGHLIGHT_ACTION,
  62353. update: 'updateView'
  62354. }, function (payload, ecModel, api) {
  62355. payload = extend({}, payload);
  62356. if ("development" !== 'production') {
  62357. deprecateReplaceLog('sunburstUnhighlight', 'downplay');
  62358. }
  62359. api.dispatchAction(extend(payload, {
  62360. type: 'downplay'
  62361. }));
  62362. });
  62363. }
  62364. var SunburstView =
  62365. /** @class */
  62366. function (_super) {
  62367. __extends(SunburstView, _super);
  62368. function SunburstView() {
  62369. var _this = _super !== null && _super.apply(this, arguments) || this;
  62370. _this.type = SunburstView.type;
  62371. return _this;
  62372. }
  62373. SunburstView.prototype.render = function (seriesModel, ecModel, api, // @ts-ignore
  62374. payload) {
  62375. var self = this;
  62376. this.seriesModel = seriesModel;
  62377. this.api = api;
  62378. this.ecModel = ecModel;
  62379. var data = seriesModel.getData();
  62380. var virtualRoot = data.tree.root;
  62381. var newRoot = seriesModel.getViewRoot();
  62382. var group = this.group;
  62383. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  62384. var newChildren = [];
  62385. newRoot.eachNode(function (node) {
  62386. newChildren.push(node);
  62387. });
  62388. var oldChildren = this._oldChildren || [];
  62389. dualTravel(newChildren, oldChildren);
  62390. renderRollUp(virtualRoot, newRoot);
  62391. this._initEvents();
  62392. this._oldChildren = newChildren;
  62393. function dualTravel(newChildren, oldChildren) {
  62394. if (newChildren.length === 0 && oldChildren.length === 0) {
  62395. return;
  62396. }
  62397. new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  62398. function getKey(node) {
  62399. return node.getId();
  62400. }
  62401. function processNode(newIdx, oldIdx) {
  62402. var newNode = newIdx == null ? null : newChildren[newIdx];
  62403. var oldNode = oldIdx == null ? null : oldChildren[oldIdx];
  62404. doRenderNode(newNode, oldNode);
  62405. }
  62406. }
  62407. function doRenderNode(newNode, oldNode) {
  62408. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  62409. // Not render data with value 0
  62410. newNode = null;
  62411. }
  62412. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  62413. if (oldNode && oldNode.piece) {
  62414. if (newNode) {
  62415. // Update
  62416. oldNode.piece.updateData(false, newNode, seriesModel, ecModel, api); // For tooltip
  62417. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  62418. } else {
  62419. // Remove
  62420. removeNode(oldNode);
  62421. }
  62422. } else if (newNode) {
  62423. // Add
  62424. var piece = new SunburstPiece(newNode, seriesModel, ecModel, api);
  62425. group.add(piece); // For tooltip
  62426. data.setItemGraphicEl(newNode.dataIndex, piece);
  62427. }
  62428. }
  62429. }
  62430. function removeNode(node) {
  62431. if (!node) {
  62432. return;
  62433. }
  62434. if (node.piece) {
  62435. group.remove(node.piece);
  62436. node.piece = null;
  62437. }
  62438. }
  62439. function renderRollUp(virtualRoot, viewRoot) {
  62440. if (viewRoot.depth > 0) {
  62441. // Render
  62442. if (self.virtualPiece) {
  62443. // Update
  62444. self.virtualPiece.updateData(false, virtualRoot, seriesModel, ecModel, api);
  62445. } else {
  62446. // Add
  62447. self.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel, api);
  62448. group.add(self.virtualPiece);
  62449. } // TODO event scope
  62450. viewRoot.piece.off('click');
  62451. self.virtualPiece.on('click', function (e) {
  62452. self._rootToNode(viewRoot.parentNode);
  62453. });
  62454. } else if (self.virtualPiece) {
  62455. // Remove
  62456. group.remove(self.virtualPiece);
  62457. self.virtualPiece = null;
  62458. }
  62459. }
  62460. };
  62461. /**
  62462. * @private
  62463. */
  62464. SunburstView.prototype._initEvents = function () {
  62465. var _this = this;
  62466. this.group.off('click');
  62467. this.group.on('click', function (e) {
  62468. var targetFound = false;
  62469. var viewRoot = _this.seriesModel.getViewRoot();
  62470. viewRoot.eachNode(function (node) {
  62471. if (!targetFound && node.piece && node.piece === e.target) {
  62472. var nodeClick = node.getModel().get('nodeClick');
  62473. if (nodeClick === 'rootToNode') {
  62474. _this._rootToNode(node);
  62475. } else if (nodeClick === 'link') {
  62476. var itemModel = node.getModel();
  62477. var link = itemModel.get('link');
  62478. if (link) {
  62479. var linkTarget = itemModel.get('target', true) || '_blank';
  62480. windowOpen(link, linkTarget);
  62481. }
  62482. }
  62483. targetFound = true;
  62484. }
  62485. });
  62486. });
  62487. };
  62488. /**
  62489. * @private
  62490. */
  62491. SunburstView.prototype._rootToNode = function (node) {
  62492. if (node !== this.seriesModel.getViewRoot()) {
  62493. this.api.dispatchAction({
  62494. type: ROOT_TO_NODE_ACTION,
  62495. from: this.uid,
  62496. seriesId: this.seriesModel.id,
  62497. targetNode: node
  62498. });
  62499. }
  62500. };
  62501. /**
  62502. * @implement
  62503. */
  62504. SunburstView.prototype.containPoint = function (point, seriesModel) {
  62505. var treeRoot = seriesModel.getData();
  62506. var itemLayout = treeRoot.getItemLayout(0);
  62507. if (itemLayout) {
  62508. var dx = point[0] - itemLayout.cx;
  62509. var dy = point[1] - itemLayout.cy;
  62510. var radius = Math.sqrt(dx * dx + dy * dy);
  62511. return radius <= itemLayout.r && radius >= itemLayout.r0;
  62512. }
  62513. };
  62514. SunburstView.type = 'sunburst';
  62515. return SunburstView;
  62516. }(ChartView);
  62517. var SunburstSeriesModel =
  62518. /** @class */
  62519. function (_super) {
  62520. __extends(SunburstSeriesModel, _super);
  62521. function SunburstSeriesModel() {
  62522. var _this = _super !== null && _super.apply(this, arguments) || this;
  62523. _this.type = SunburstSeriesModel.type;
  62524. _this.ignoreStyleOnData = true;
  62525. return _this;
  62526. }
  62527. SunburstSeriesModel.prototype.getInitialData = function (option, ecModel) {
  62528. // Create a virtual root.
  62529. var root = {
  62530. name: option.name,
  62531. children: option.data
  62532. };
  62533. completeTreeValue$1(root);
  62534. var levelModels = this._levelModels = map(option.levels || [], function (levelDefine) {
  62535. return new Model(levelDefine, this, ecModel);
  62536. }, this); // Make sure always a new tree is created when setOption,
  62537. // in TreemapView, we check whether oldTree === newTree
  62538. // to choose mappings approach among old shapes and new shapes.
  62539. var tree = Tree.createTree(root, this, beforeLink);
  62540. function beforeLink(nodeData) {
  62541. nodeData.wrapMethod('getItemModel', function (model, idx) {
  62542. var node = tree.getNodeByDataIndex(idx);
  62543. var levelModel = levelModels[node.depth];
  62544. levelModel && (model.parentModel = levelModel);
  62545. return model;
  62546. });
  62547. }
  62548. return tree.data;
  62549. };
  62550. SunburstSeriesModel.prototype.optionUpdated = function () {
  62551. this.resetViewRoot();
  62552. };
  62553. /*
  62554. * @override
  62555. */
  62556. SunburstSeriesModel.prototype.getDataParams = function (dataIndex) {
  62557. var params = _super.prototype.getDataParams.apply(this, arguments);
  62558. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  62559. params.treePathInfo = wrapTreePathInfo(node, this);
  62560. return params;
  62561. };
  62562. SunburstSeriesModel.prototype.getLevelModel = function (node) {
  62563. return this._levelModels && this._levelModels[node.depth];
  62564. };
  62565. SunburstSeriesModel.prototype.getViewRoot = function () {
  62566. return this._viewRoot;
  62567. };
  62568. SunburstSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  62569. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  62570. var root = this.getRawData().tree.root;
  62571. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  62572. this._viewRoot = root;
  62573. }
  62574. };
  62575. SunburstSeriesModel.prototype.enableAriaDecal = function () {
  62576. enableAriaDecalForTree(this);
  62577. };
  62578. SunburstSeriesModel.type = 'series.sunburst';
  62579. SunburstSeriesModel.defaultOption = {
  62580. // zlevel: 0,
  62581. z: 2,
  62582. // 默认全局居中
  62583. center: ['50%', '50%'],
  62584. radius: [0, '75%'],
  62585. // 默认顺时针
  62586. clockwise: true,
  62587. startAngle: 90,
  62588. // 最小角度改为0
  62589. minAngle: 0,
  62590. // If still show when all data zero.
  62591. stillShowZeroSum: true,
  62592. // 'rootToNode', 'link', or false
  62593. nodeClick: 'rootToNode',
  62594. renderLabelForZeroData: false,
  62595. label: {
  62596. // could be: 'radial', 'tangential', or 'none'
  62597. rotate: 'radial',
  62598. show: true,
  62599. opacity: 1,
  62600. // 'left' is for inner side of inside, and 'right' is for outer
  62601. // side for inside
  62602. align: 'center',
  62603. position: 'inside',
  62604. distance: 5,
  62605. silent: true
  62606. },
  62607. itemStyle: {
  62608. borderWidth: 1,
  62609. borderColor: 'white',
  62610. borderType: 'solid',
  62611. shadowBlur: 0,
  62612. shadowColor: 'rgba(0, 0, 0, 0.2)',
  62613. shadowOffsetX: 0,
  62614. shadowOffsetY: 0,
  62615. opacity: 1
  62616. },
  62617. emphasis: {
  62618. focus: 'descendant'
  62619. },
  62620. blur: {
  62621. itemStyle: {
  62622. opacity: 0.2
  62623. },
  62624. label: {
  62625. opacity: 0.1
  62626. }
  62627. },
  62628. // Animation type can be expansion, scale.
  62629. animationType: 'expansion',
  62630. animationDuration: 1000,
  62631. animationDurationUpdate: 500,
  62632. data: [],
  62633. /**
  62634. * Sort order.
  62635. *
  62636. * Valid values: 'desc', 'asc', null, or callback function.
  62637. * 'desc' and 'asc' for descend and ascendant order;
  62638. * null for not sorting;
  62639. * example of callback function:
  62640. * function(nodeA, nodeB) {
  62641. * return nodeA.getValue() - nodeB.getValue();
  62642. * }
  62643. */
  62644. sort: 'desc'
  62645. };
  62646. return SunburstSeriesModel;
  62647. }(SeriesModel);
  62648. function completeTreeValue$1(dataNode) {
  62649. // Postorder travel tree.
  62650. // If value of none-leaf node is not set,
  62651. // calculate it by suming up the value of all children.
  62652. var sum = 0;
  62653. each(dataNode.children, function (child) {
  62654. completeTreeValue$1(child);
  62655. var childValue = child.value; // TODO First value of array must be a number
  62656. isArray(childValue) && (childValue = childValue[0]);
  62657. sum += childValue;
  62658. });
  62659. var thisValue = dataNode.value;
  62660. if (isArray(thisValue)) {
  62661. thisValue = thisValue[0];
  62662. }
  62663. if (thisValue == null || isNaN(thisValue)) {
  62664. thisValue = sum;
  62665. } // Value should not less than 0.
  62666. if (thisValue < 0) {
  62667. thisValue = 0;
  62668. }
  62669. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  62670. }
  62671. var RADIAN$2 = Math.PI / 180;
  62672. function sunburstLayout(seriesType, ecModel, api) {
  62673. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  62674. var center = seriesModel.get('center');
  62675. var radius = seriesModel.get('radius');
  62676. if (!isArray(radius)) {
  62677. radius = [0, radius];
  62678. }
  62679. if (!isArray(center)) {
  62680. center = [center, center];
  62681. }
  62682. var width = api.getWidth();
  62683. var height = api.getHeight();
  62684. var size = Math.min(width, height);
  62685. var cx = parsePercent$1(center[0], width);
  62686. var cy = parsePercent$1(center[1], height);
  62687. var r0 = parsePercent$1(radius[0], size / 2);
  62688. var r = parsePercent$1(radius[1], size / 2);
  62689. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  62690. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  62691. var virtualRoot = seriesModel.getData().tree.root;
  62692. var treeRoot = seriesModel.getViewRoot();
  62693. var rootDepth = treeRoot.depth;
  62694. var sort = seriesModel.get('sort');
  62695. if (sort != null) {
  62696. initChildren$1(treeRoot, sort);
  62697. }
  62698. var validDataCount = 0;
  62699. each(treeRoot.children, function (child) {
  62700. !isNaN(child.getValue()) && validDataCount++;
  62701. });
  62702. var sum = treeRoot.getValue(); // Sum may be 0
  62703. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  62704. var renderRollupNode = treeRoot.depth > 0;
  62705. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  62706. var rPerLevel = (r - r0) / (levels || 1);
  62707. var clockwise = seriesModel.get('clockwise');
  62708. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // In the case some sector angle is smaller than minAngle
  62709. // let restAngle = PI2;
  62710. // let valueSumLargerThanMinAngle = 0;
  62711. var dir = clockwise ? 1 : -1;
  62712. /**
  62713. * Render a tree
  62714. * @return increased angle
  62715. */
  62716. var renderNode = function (node, startAngle) {
  62717. if (!node) {
  62718. return;
  62719. }
  62720. var endAngle = startAngle; // Render self
  62721. if (node !== virtualRoot) {
  62722. // Tree node is virtual, so it doesn't need to be drawn
  62723. var value = node.getValue();
  62724. var angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  62725. if (angle < minAngle) {
  62726. angle = minAngle; // restAngle -= minAngle;
  62727. } // else {
  62728. // valueSumLargerThanMinAngle += value;
  62729. // }
  62730. endAngle = startAngle + dir * angle;
  62731. var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1);
  62732. var rStart = r0 + rPerLevel * depth;
  62733. var rEnd = r0 + rPerLevel * (depth + 1);
  62734. var levelModel = seriesModel.getLevelModel(node);
  62735. if (levelModel) {
  62736. var r0_1 = levelModel.get('r0', true);
  62737. var r_1 = levelModel.get('r', true);
  62738. var radius_1 = levelModel.get('radius', true);
  62739. if (radius_1 != null) {
  62740. r0_1 = radius_1[0];
  62741. r_1 = radius_1[1];
  62742. }
  62743. r0_1 != null && (rStart = parsePercent$1(r0_1, size / 2));
  62744. r_1 != null && (rEnd = parsePercent$1(r_1, size / 2));
  62745. }
  62746. node.setLayout({
  62747. angle: angle,
  62748. startAngle: startAngle,
  62749. endAngle: endAngle,
  62750. clockwise: clockwise,
  62751. cx: cx,
  62752. cy: cy,
  62753. r0: rStart,
  62754. r: rEnd
  62755. });
  62756. } // Render children
  62757. if (node.children && node.children.length) {
  62758. // currentAngle = startAngle;
  62759. var siblingAngle_1 = 0;
  62760. each(node.children, function (node) {
  62761. siblingAngle_1 += renderNode(node, startAngle + siblingAngle_1);
  62762. });
  62763. }
  62764. return endAngle - startAngle;
  62765. }; // Virtual root node for roll up
  62766. if (renderRollupNode) {
  62767. var rStart = r0;
  62768. var rEnd = r0 + rPerLevel;
  62769. var angle = Math.PI * 2;
  62770. virtualRoot.setLayout({
  62771. angle: angle,
  62772. startAngle: startAngle,
  62773. endAngle: startAngle + angle,
  62774. clockwise: clockwise,
  62775. cx: cx,
  62776. cy: cy,
  62777. r0: rStart,
  62778. r: rEnd
  62779. });
  62780. }
  62781. renderNode(treeRoot, startAngle);
  62782. });
  62783. }
  62784. /**
  62785. * Init node children by order and update visual
  62786. */
  62787. function initChildren$1(node, sortOrder) {
  62788. var children = node.children || [];
  62789. node.children = sort$2(children, sortOrder); // Init children recursively
  62790. if (children.length) {
  62791. each(node.children, function (child) {
  62792. initChildren$1(child, sortOrder);
  62793. });
  62794. }
  62795. }
  62796. /**
  62797. * Sort children nodes
  62798. *
  62799. * @param {TreeNode[]} children children of node to be sorted
  62800. * @param {string | function | null} sort sort method
  62801. * See SunburstSeries.js for details.
  62802. */
  62803. function sort$2(children, sortOrder) {
  62804. if (isFunction(sortOrder)) {
  62805. var sortTargets = map(children, function (child, idx) {
  62806. var value = child.getValue();
  62807. return {
  62808. params: {
  62809. depth: child.depth,
  62810. height: child.height,
  62811. dataIndex: child.dataIndex,
  62812. getValue: function () {
  62813. return value;
  62814. }
  62815. },
  62816. index: idx
  62817. };
  62818. });
  62819. sortTargets.sort(function (a, b) {
  62820. return sortOrder(a.params, b.params);
  62821. });
  62822. return map(sortTargets, function (target) {
  62823. return children[target.index];
  62824. });
  62825. } else {
  62826. var isAsc_1 = sortOrder === 'asc';
  62827. return children.sort(function (a, b) {
  62828. var diff = (a.getValue() - b.getValue()) * (isAsc_1 ? 1 : -1);
  62829. return diff === 0 ? (a.dataIndex - b.dataIndex) * (isAsc_1 ? -1 : 1) : diff;
  62830. });
  62831. }
  62832. }
  62833. function sunburstVisual(ecModel) {
  62834. var paletteScope = {}; // Default color strategy
  62835. function pickColor(node, seriesModel, treeHeight) {
  62836. // Choose color from palette based on the first level.
  62837. var current = node;
  62838. while (current && current.depth > 1) {
  62839. current = current.parentNode;
  62840. }
  62841. var color = seriesModel.getColorFromPalette(current.name || current.dataIndex + '', paletteScope);
  62842. if (node.depth > 1 && isString(color)) {
  62843. // Lighter on the deeper level.
  62844. color = lift(color, (node.depth - 1) / (treeHeight - 1) * 0.5);
  62845. }
  62846. return color;
  62847. }
  62848. ecModel.eachSeriesByType('sunburst', function (seriesModel) {
  62849. var data = seriesModel.getData();
  62850. var tree = data.tree;
  62851. tree.eachNode(function (node) {
  62852. var model = node.getModel();
  62853. var style = model.getModel('itemStyle').getItemStyle();
  62854. if (!style.fill) {
  62855. style.fill = pickColor(node, seriesModel, tree.root.height);
  62856. }
  62857. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  62858. extend(existsStyle, style);
  62859. });
  62860. });
  62861. }
  62862. function install$q(registers) {
  62863. registers.registerChartView(SunburstView);
  62864. registers.registerSeriesModel(SunburstSeriesModel);
  62865. registers.registerLayout(curry(sunburstLayout, 'sunburst'));
  62866. registers.registerProcessor(curry(dataFilter, 'sunburst'));
  62867. registers.registerVisual(sunburstVisual);
  62868. installSunburstAction(registers);
  62869. }
  62870. // `visual('color') visual('borderColor')` is supported.
  62871. var STYLE_VISUAL_TYPE = {
  62872. color: 'fill',
  62873. borderColor: 'stroke'
  62874. };
  62875. var NON_STYLE_VISUAL_PROPS = {
  62876. symbol: 1,
  62877. symbolSize: 1,
  62878. symbolKeepAspect: 1,
  62879. legendIcon: 1,
  62880. visualMeta: 1,
  62881. liftZ: 1,
  62882. decal: 1
  62883. };
  62884. var customInnerStore = makeInner();
  62885. var CustomSeriesModel =
  62886. /** @class */
  62887. function (_super) {
  62888. __extends(CustomSeriesModel, _super);
  62889. function CustomSeriesModel() {
  62890. var _this = _super !== null && _super.apply(this, arguments) || this;
  62891. _this.type = CustomSeriesModel.type;
  62892. return _this;
  62893. }
  62894. CustomSeriesModel.prototype.optionUpdated = function () {
  62895. this.currentZLevel = this.get('zlevel', true);
  62896. this.currentZ = this.get('z', true);
  62897. };
  62898. CustomSeriesModel.prototype.getInitialData = function (option, ecModel) {
  62899. return createSeriesData(null, this);
  62900. };
  62901. CustomSeriesModel.prototype.getDataParams = function (dataIndex, dataType, el) {
  62902. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  62903. el && (params.info = customInnerStore(el).info);
  62904. return params;
  62905. };
  62906. CustomSeriesModel.type = 'series.custom';
  62907. CustomSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  62908. CustomSeriesModel.defaultOption = {
  62909. coordinateSystem: 'cartesian2d',
  62910. // zlevel: 0,
  62911. z: 2,
  62912. legendHoverLink: true,
  62913. // Custom series will not clip by default.
  62914. // Some case will use custom series to draw label
  62915. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  62916. clip: false // Cartesian coordinate system
  62917. // xAxisIndex: 0,
  62918. // yAxisIndex: 0,
  62919. // Polar coordinate system
  62920. // polarIndex: 0,
  62921. // Geo coordinate system
  62922. // geoIndex: 0,
  62923. };
  62924. return CustomSeriesModel;
  62925. }(SeriesModel);
  62926. function dataToCoordSize(dataSize, dataItem) {
  62927. // dataItem is necessary in log axis.
  62928. dataItem = dataItem || [0, 0];
  62929. return map(['x', 'y'], function (dim, dimIdx) {
  62930. var axis = this.getAxis(dim);
  62931. var val = dataItem[dimIdx];
  62932. var halfSize = dataSize[dimIdx] / 2;
  62933. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  62934. }, this);
  62935. }
  62936. function cartesianPrepareCustom(coordSys) {
  62937. var rect = coordSys.master.getRect();
  62938. return {
  62939. coordSys: {
  62940. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  62941. type: 'cartesian2d',
  62942. x: rect.x,
  62943. y: rect.y,
  62944. width: rect.width,
  62945. height: rect.height
  62946. },
  62947. api: {
  62948. coord: function (data) {
  62949. // do not provide "out" param
  62950. return coordSys.dataToPoint(data);
  62951. },
  62952. size: bind(dataToCoordSize, coordSys)
  62953. }
  62954. };
  62955. }
  62956. function dataToCoordSize$1(dataSize, dataItem) {
  62957. dataItem = dataItem || [0, 0];
  62958. return map([0, 1], function (dimIdx) {
  62959. var val = dataItem[dimIdx];
  62960. var halfSize = dataSize[dimIdx] / 2;
  62961. var p1 = [];
  62962. var p2 = [];
  62963. p1[dimIdx] = val - halfSize;
  62964. p2[dimIdx] = val + halfSize;
  62965. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  62966. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  62967. }, this);
  62968. }
  62969. function geoPrepareCustom(coordSys) {
  62970. var rect = coordSys.getBoundingRect();
  62971. return {
  62972. coordSys: {
  62973. type: 'geo',
  62974. x: rect.x,
  62975. y: rect.y,
  62976. width: rect.width,
  62977. height: rect.height,
  62978. zoom: coordSys.getZoom()
  62979. },
  62980. api: {
  62981. coord: function (data) {
  62982. // do not provide "out" and noRoam param,
  62983. // Compatible with this usage:
  62984. // echarts.util.map(item.points, api.coord)
  62985. return coordSys.dataToPoint(data);
  62986. },
  62987. size: bind(dataToCoordSize$1, coordSys)
  62988. }
  62989. };
  62990. }
  62991. function dataToCoordSize$2(dataSize, dataItem) {
  62992. // dataItem is necessary in log axis.
  62993. var axis = this.getAxis();
  62994. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  62995. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  62996. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  62997. }
  62998. function singlePrepareCustom(coordSys) {
  62999. var rect = coordSys.getRect();
  63000. return {
  63001. coordSys: {
  63002. type: 'singleAxis',
  63003. x: rect.x,
  63004. y: rect.y,
  63005. width: rect.width,
  63006. height: rect.height
  63007. },
  63008. api: {
  63009. coord: function (val) {
  63010. // do not provide "out" param
  63011. return coordSys.dataToPoint(val);
  63012. },
  63013. size: bind(dataToCoordSize$2, coordSys)
  63014. }
  63015. };
  63016. }
  63017. function dataToCoordSize$3(dataSize, dataItem) {
  63018. // dataItem is necessary in log axis.
  63019. dataItem = dataItem || [0, 0];
  63020. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  63021. var getterName = 'get' + dim + 'Axis'; // TODO: TYPE Check Angle Axis
  63022. var axis = this[getterName]();
  63023. var val = dataItem[dimIdx];
  63024. var halfSize = dataSize[dimIdx] / 2;
  63025. var result = axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63026. if (dim === 'Angle') {
  63027. result = result * Math.PI / 180;
  63028. }
  63029. return result;
  63030. }, this);
  63031. }
  63032. function polarPrepareCustom(coordSys) {
  63033. var radiusAxis = coordSys.getRadiusAxis();
  63034. var angleAxis = coordSys.getAngleAxis();
  63035. var radius = radiusAxis.getExtent();
  63036. radius[0] > radius[1] && radius.reverse();
  63037. return {
  63038. coordSys: {
  63039. type: 'polar',
  63040. cx: coordSys.cx,
  63041. cy: coordSys.cy,
  63042. r: radius[1],
  63043. r0: radius[0]
  63044. },
  63045. api: {
  63046. coord: function (data) {
  63047. var radius = radiusAxis.dataToRadius(data[0]);
  63048. var angle = angleAxis.dataToAngle(data[1]);
  63049. var coord = coordSys.coordToPoint([radius, angle]);
  63050. coord.push(radius, angle * Math.PI / 180);
  63051. return coord;
  63052. },
  63053. size: bind(dataToCoordSize$3, coordSys)
  63054. }
  63055. };
  63056. }
  63057. /*
  63058. * Licensed to the Apache Software Foundation (ASF) under one
  63059. * or more contributor license agreements. See the NOTICE file
  63060. * distributed with this work for additional information
  63061. * regarding copyright ownership. The ASF licenses this file
  63062. * to you under the Apache License, Version 2.0 (the
  63063. * "License"); you may not use this file except in compliance
  63064. * with the License. You may obtain a copy of the License at
  63065. *
  63066. * http://www.apache.org/licenses/LICENSE-2.0
  63067. *
  63068. * Unless required by applicable law or agreed to in writing,
  63069. * software distributed under the License is distributed on an
  63070. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63071. * KIND, either express or implied. See the License for the
  63072. * specific language governing permissions and limitations
  63073. * under the License.
  63074. */
  63075. /**
  63076. * AUTO-GENERATED FILE. DO NOT MODIFY.
  63077. */
  63078. /*
  63079. * Licensed to the Apache Software Foundation (ASF) under one
  63080. * or more contributor license agreements. See the NOTICE file
  63081. * distributed with this work for additional information
  63082. * regarding copyright ownership. The ASF licenses this file
  63083. * to you under the Apache License, Version 2.0 (the
  63084. * "License"); you may not use this file except in compliance
  63085. * with the License. You may obtain a copy of the License at
  63086. *
  63087. * http://www.apache.org/licenses/LICENSE-2.0
  63088. *
  63089. * Unless required by applicable law or agreed to in writing,
  63090. * software distributed under the License is distributed on an
  63091. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63092. * KIND, either express or implied. See the License for the
  63093. * specific language governing permissions and limitations
  63094. * under the License.
  63095. */
  63096. function calendarPrepareCustom(coordSys) {
  63097. var rect = coordSys.getRect();
  63098. var rangeInfo = coordSys.getRangeInfo();
  63099. return {
  63100. coordSys: {
  63101. type: 'calendar',
  63102. x: rect.x,
  63103. y: rect.y,
  63104. width: rect.width,
  63105. height: rect.height,
  63106. cellWidth: coordSys.getCellWidth(),
  63107. cellHeight: coordSys.getCellHeight(),
  63108. rangeInfo: {
  63109. start: rangeInfo.start,
  63110. end: rangeInfo.end,
  63111. weeks: rangeInfo.weeks,
  63112. dayCount: rangeInfo.allDay
  63113. }
  63114. },
  63115. api: {
  63116. coord: function (data, clamp) {
  63117. return coordSys.dataToPoint(data, clamp);
  63118. }
  63119. }
  63120. };
  63121. }
  63122. var deprecatedLogs = {};
  63123. /**
  63124. * Whether need to call `convertEC4CompatibleStyle`.
  63125. */
  63126. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  63127. // Since echarts5, `RectText` is separated from its host element and style.text
  63128. // does not exist any more. The compat work brings some extra burden on performance.
  63129. // So we provide:
  63130. // `legacy: true` force make compat.
  63131. // `legacy: false`, force do not compat.
  63132. // `legacy` not set: auto detect whether legacy.
  63133. // But in this case we do not compat (difficult to detect and rare case):
  63134. // Becuse custom series and graphic component support "merge", users may firstly
  63135. // only set `textStrokeWidth` style or secondly only set `text`.
  63136. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  63137. && (elType === 'text' || hasOwn(style, 'text')));
  63138. }
  63139. /**
  63140. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  63141. * @param hostStyle The properties might be modified.
  63142. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  63143. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  63144. * retried from the `hostStyle`.
  63145. */
  63146. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  63147. var srcStyle = hostStyle;
  63148. var textConfig;
  63149. var textContent;
  63150. var textContentStyle;
  63151. if (elType === 'text') {
  63152. textContentStyle = srcStyle;
  63153. } else {
  63154. textContentStyle = {};
  63155. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  63156. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  63157. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  63158. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  63159. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  63160. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  63161. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  63162. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  63163. textContent = {
  63164. type: 'text',
  63165. style: textContentStyle,
  63166. // ec4 does not support rectText trigger.
  63167. // And when text position is different in normal and emphasis
  63168. // => hover text trigger emphasis;
  63169. // => text position changed, leave mouse pointer immediately;
  63170. // That might cause incorrect state.
  63171. silent: true
  63172. };
  63173. textConfig = {};
  63174. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  63175. if (isNormal) {
  63176. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  63177. } else {
  63178. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  63179. }
  63180. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  63181. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  63182. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  63183. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  63184. }
  63185. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  63186. each(textContentStyle.rich, function (richItem) {
  63187. convertEC4CompatibleRichItem(richItem, richItem);
  63188. });
  63189. return {
  63190. textConfig: textConfig,
  63191. textContent: textContent
  63192. };
  63193. }
  63194. /**
  63195. * The result will be set to `out`.
  63196. */
  63197. function convertEC4CompatibleRichItem(out, richItem) {
  63198. if (!richItem) {
  63199. return;
  63200. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  63201. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  63202. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  63203. // richText in ec5.
  63204. // (2) `out === richItem` if and only if `out` is text el or rich item.
  63205. // So we can overwrite existing props in `out` since textXXX has higher priority.
  63206. richItem.font = richItem.textFont || richItem.font;
  63207. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  63208. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  63209. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  63210. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  63211. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  63212. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  63213. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  63214. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  63215. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  63216. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  63217. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  63218. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  63219. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  63220. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  63221. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  63222. }
  63223. /**
  63224. * Convert to pure echarts4 format style.
  63225. * `itemStyle` will be modified, added with ec4 style properties from
  63226. * `textStyle` and `textConfig`.
  63227. *
  63228. * [Caveat]: For simplicity, `insideRollback` in ec4 does not compat, where
  63229. * `styleEmphasis: {textFill: 'red'}` will remove the normal auto added stroke.
  63230. */
  63231. function convertToEC4StyleForCustomSerise(itemStl, txStl, txCfg) {
  63232. var out = itemStl; // See `custom.ts`, a trick to set extra `textPosition` firstly.
  63233. out.textPosition = out.textPosition || txCfg.position || 'inside';
  63234. txCfg.offset != null && (out.textOffset = txCfg.offset);
  63235. txCfg.rotation != null && (out.textRotation = txCfg.rotation);
  63236. txCfg.distance != null && (out.textDistance = txCfg.distance);
  63237. var isInside = out.textPosition.indexOf('inside') >= 0;
  63238. var hostFill = itemStl.fill || '#000';
  63239. convertToEC4RichItem(out, txStl);
  63240. var textFillNotSet = out.textFill == null;
  63241. if (isInside) {
  63242. if (textFillNotSet) {
  63243. out.textFill = txCfg.insideFill || '#fff';
  63244. !out.textStroke && txCfg.insideStroke && (out.textStroke = txCfg.insideStroke);
  63245. !out.textStroke && (out.textStroke = hostFill);
  63246. out.textStrokeWidth == null && (out.textStrokeWidth = 2);
  63247. }
  63248. } else {
  63249. if (textFillNotSet) {
  63250. out.textFill = itemStl.fill || txCfg.outsideFill || '#000';
  63251. }
  63252. !out.textStroke && txCfg.outsideStroke && (out.textStroke = txCfg.outsideStroke);
  63253. }
  63254. out.text = txStl.text;
  63255. out.rich = txStl.rich;
  63256. each(txStl.rich, function (richItem) {
  63257. convertToEC4RichItem(richItem, richItem);
  63258. });
  63259. return out;
  63260. }
  63261. function convertToEC4RichItem(out, richItem) {
  63262. if (!richItem) {
  63263. return;
  63264. }
  63265. hasOwn(richItem, 'fill') && (out.textFill = richItem.fill);
  63266. hasOwn(richItem, 'stroke') && (out.textStroke = richItem.fill);
  63267. hasOwn(richItem, 'lineWidth') && (out.textStrokeWidth = richItem.lineWidth);
  63268. hasOwn(richItem, 'font') && (out.font = richItem.font);
  63269. hasOwn(richItem, 'fontStyle') && (out.fontStyle = richItem.fontStyle);
  63270. hasOwn(richItem, 'fontWeight') && (out.fontWeight = richItem.fontWeight);
  63271. hasOwn(richItem, 'fontSize') && (out.fontSize = richItem.fontSize);
  63272. hasOwn(richItem, 'fontFamily') && (out.fontFamily = richItem.fontFamily);
  63273. hasOwn(richItem, 'align') && (out.textAlign = richItem.align);
  63274. hasOwn(richItem, 'verticalAlign') && (out.textVerticalAlign = richItem.verticalAlign);
  63275. hasOwn(richItem, 'lineHeight') && (out.textLineHeight = richItem.lineHeight);
  63276. hasOwn(richItem, 'width') && (out.textWidth = richItem.width);
  63277. hasOwn(richItem, 'height') && (out.textHeight = richItem.height);
  63278. hasOwn(richItem, 'backgroundColor') && (out.textBackgroundColor = richItem.backgroundColor);
  63279. hasOwn(richItem, 'padding') && (out.textPadding = richItem.padding);
  63280. hasOwn(richItem, 'borderColor') && (out.textBorderColor = richItem.borderColor);
  63281. hasOwn(richItem, 'borderWidth') && (out.textBorderWidth = richItem.borderWidth);
  63282. hasOwn(richItem, 'borderRadius') && (out.textBorderRadius = richItem.borderRadius);
  63283. hasOwn(richItem, 'shadowColor') && (out.textBoxShadowColor = richItem.shadowColor);
  63284. hasOwn(richItem, 'shadowBlur') && (out.textBoxShadowBlur = richItem.shadowBlur);
  63285. hasOwn(richItem, 'shadowOffsetX') && (out.textBoxShadowOffsetX = richItem.shadowOffsetX);
  63286. hasOwn(richItem, 'shadowOffsetY') && (out.textBoxShadowOffsetY = richItem.shadowOffsetY);
  63287. hasOwn(richItem, 'textShadowColor') && (out.textShadowColor = richItem.textShadowColor);
  63288. hasOwn(richItem, 'textShadowBlur') && (out.textShadowBlur = richItem.textShadowBlur);
  63289. hasOwn(richItem, 'textShadowOffsetX') && (out.textShadowOffsetX = richItem.textShadowOffsetX);
  63290. hasOwn(richItem, 'textShadowOffsetY') && (out.textShadowOffsetY = richItem.textShadowOffsetY);
  63291. }
  63292. function warnDeprecated(deprecated, insteadApproach) {
  63293. if ("development" !== 'production') {
  63294. var key = deprecated + '^_^' + insteadApproach;
  63295. if (!deprecatedLogs[key]) {
  63296. console.warn("[ECharts] DEPRECATED: \"" + deprecated + "\" has been deprecated. " + insteadApproach);
  63297. deprecatedLogs[key] = true;
  63298. }
  63299. }
  63300. }
  63301. var LEGACY_TRANSFORM_PROPS_MAP = {
  63302. position: ['x', 'y'],
  63303. scale: ['scaleX', 'scaleY'],
  63304. origin: ['originX', 'originY']
  63305. };
  63306. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  63307. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  63308. obj[key] = 1;
  63309. return obj;
  63310. }, {});
  63311. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', '); // '' means root
  63312. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  63313. var transitionInnerStore = makeInner();
  63314. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  63315. var animationProp = animationType + "Animation";
  63316. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  63317. var userDuring = transitionInnerStore(el).userDuring; // Only set when duration is > 0 and it's need to be animated.
  63318. if (config.duration > 0) {
  63319. // For simplicity, if during not specified, the previous during will not work any more.
  63320. config.during = userDuring ? bind(duringCall, {
  63321. el: el,
  63322. userDuring: userDuring
  63323. }) : null;
  63324. config.setToFinal = true;
  63325. config.scope = animationType;
  63326. }
  63327. extend(config, elOption[animationProp]);
  63328. return config;
  63329. }
  63330. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  63331. opts = opts || {};
  63332. var dataIndex = opts.dataIndex,
  63333. isInit = opts.isInit,
  63334. clearStyle = opts.clearStyle;
  63335. var hasAnimation = animatableModel.isAnimationEnabled(); // Save the meta info for further morphing. Like apply on the sub morphing elements.
  63336. var store = transitionInnerStore(el);
  63337. var styleOpt = elOption.style;
  63338. store.userDuring = elOption.during;
  63339. var transFromProps = {};
  63340. var propsToSet = {};
  63341. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  63342. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  63343. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  63344. if (!isInit && hasAnimation) {
  63345. prepareTransformTransitionFrom(el, elOption, transFromProps);
  63346. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  63347. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  63348. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  63349. }
  63350. propsToSet.style = styleOpt;
  63351. applyPropsDirectly(el, propsToSet, clearStyle);
  63352. applyMiscProps(el, elOption);
  63353. if (hasAnimation) {
  63354. if (isInit) {
  63355. var enterFromProps_1 = {};
  63356. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  63357. var prop = propName ? elOption[propName] : elOption;
  63358. if (prop && prop.enterFrom) {
  63359. if (propName) {
  63360. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  63361. }
  63362. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  63363. }
  63364. });
  63365. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  63366. if (config.duration > 0) {
  63367. el.animateFrom(enterFromProps_1, config);
  63368. }
  63369. } else {
  63370. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  63371. }
  63372. } // Store leave to be used in leave transition.
  63373. updateLeaveTo(el, elOption);
  63374. styleOpt ? el.dirty() : el.markRedraw();
  63375. }
  63376. function updateLeaveTo(el, elOption) {
  63377. // Try merge to previous set leaveTo
  63378. var leaveToProps = transitionInnerStore(el).leaveToProps;
  63379. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  63380. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  63381. var prop = propName ? elOption[propName] : elOption;
  63382. if (prop && prop.leaveTo) {
  63383. if (!leaveToProps) {
  63384. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  63385. }
  63386. if (propName) {
  63387. leaveToProps[propName] = leaveToProps[propName] || {};
  63388. }
  63389. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  63390. }
  63391. }
  63392. }
  63393. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  63394. if (el) {
  63395. var parent_1 = el.parent;
  63396. var leaveToProps = transitionInnerStore(el).leaveToProps;
  63397. if (leaveToProps) {
  63398. // TODO TODO use leave after leaveAnimation in series is introduced
  63399. // TODO Data index?
  63400. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  63401. config.done = function () {
  63402. parent_1.remove(el);
  63403. onRemove && onRemove();
  63404. };
  63405. el.animateTo(leaveToProps, config);
  63406. } else {
  63407. parent_1.remove(el);
  63408. onRemove && onRemove();
  63409. }
  63410. }
  63411. }
  63412. function isTransitionAll(transition) {
  63413. return transition === 'all';
  63414. }
  63415. function applyPropsDirectly(el, // Can be null/undefined
  63416. allPropsFinal, clearStyle) {
  63417. var styleOpt = allPropsFinal.style;
  63418. if (!el.isGroup && styleOpt) {
  63419. if (clearStyle) {
  63420. el.useStyle({}); // When style object changed, how to trade the existing animation?
  63421. // It is probably complicated and not needed to cover all the cases.
  63422. // But still need consider the case:
  63423. // (1) When using init animation on `style.opacity`, and before the animation
  63424. // ended users triggers an update by mousewhel. At that time the init
  63425. // animation should better be continued rather than terminated.
  63426. // So after `useStyle` called, we should change the animation target manually
  63427. // to continue the effect of the init animation.
  63428. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  63429. // to update the value to `val2` and no animation declared, should be terminate
  63430. // the previous animation or just modify the target of the animation?
  63431. // Therotically That will happen not only on `style` but also on `shape` and
  63432. // `transfrom` props. But we haven't handle this case at present yet.
  63433. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  63434. var animators = el.animators;
  63435. for (var i = 0; i < animators.length; i++) {
  63436. var animator = animators[i]; // targetName is the "topKey".
  63437. if (animator.targetName === 'style') {
  63438. animator.changeTarget(el.style);
  63439. }
  63440. }
  63441. }
  63442. el.setStyle(styleOpt);
  63443. }
  63444. if (allPropsFinal) {
  63445. // Not set style here.
  63446. allPropsFinal.style = null; // Set el to the final state firstly.
  63447. allPropsFinal && el.attr(allPropsFinal);
  63448. allPropsFinal.style = styleOpt;
  63449. }
  63450. }
  63451. function applyPropsTransition(el, elOption, dataIndex, model, // Can be null/undefined
  63452. transFromProps) {
  63453. if (transFromProps) {
  63454. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  63455. if (config.duration > 0) {
  63456. el.animateFrom(transFromProps, config);
  63457. }
  63458. }
  63459. }
  63460. function applyMiscProps(el, elOption) {
  63461. // Merge by default.
  63462. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  63463. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  63464. if (el instanceof Displayable) {
  63465. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  63466. }
  63467. if (el instanceof Path) {
  63468. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  63469. }
  63470. } // Use it to avoid it be exposed to user.
  63471. var tmpDuringScope = {};
  63472. var transitionDuringAPI = {
  63473. // Usually other props do not need to be changed in animation during.
  63474. setTransform: function (key, val) {
  63475. if ("development" !== 'production') {
  63476. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  63477. }
  63478. tmpDuringScope.el[key] = val;
  63479. return this;
  63480. },
  63481. getTransform: function (key) {
  63482. if ("development" !== 'production') {
  63483. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  63484. }
  63485. return tmpDuringScope.el[key];
  63486. },
  63487. setShape: function (key, val) {
  63488. if ("development" !== 'production') {
  63489. assertNotReserved(key);
  63490. }
  63491. var el = tmpDuringScope.el;
  63492. var shape = el.shape || (el.shape = {});
  63493. shape[key] = val;
  63494. el.dirtyShape && el.dirtyShape();
  63495. return this;
  63496. },
  63497. getShape: function (key) {
  63498. if ("development" !== 'production') {
  63499. assertNotReserved(key);
  63500. }
  63501. var shape = tmpDuringScope.el.shape;
  63502. if (shape) {
  63503. return shape[key];
  63504. }
  63505. },
  63506. setStyle: function (key, val) {
  63507. if ("development" !== 'production') {
  63508. assertNotReserved(key);
  63509. }
  63510. var el = tmpDuringScope.el;
  63511. var style = el.style;
  63512. if (style) {
  63513. if ("development" !== 'production') {
  63514. if (eqNaN(val)) {
  63515. warn('style.' + key + ' must not be assigned with NaN.');
  63516. }
  63517. }
  63518. style[key] = val;
  63519. el.dirtyStyle && el.dirtyStyle();
  63520. }
  63521. return this;
  63522. },
  63523. getStyle: function (key) {
  63524. if ("development" !== 'production') {
  63525. assertNotReserved(key);
  63526. }
  63527. var style = tmpDuringScope.el.style;
  63528. if (style) {
  63529. return style[key];
  63530. }
  63531. },
  63532. setExtra: function (key, val) {
  63533. if ("development" !== 'production') {
  63534. assertNotReserved(key);
  63535. }
  63536. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  63537. extra[key] = val;
  63538. return this;
  63539. },
  63540. getExtra: function (key) {
  63541. if ("development" !== 'production') {
  63542. assertNotReserved(key);
  63543. }
  63544. var extra = tmpDuringScope.el.extra;
  63545. if (extra) {
  63546. return extra[key];
  63547. }
  63548. }
  63549. };
  63550. function assertNotReserved(key) {
  63551. if ("development" !== 'production') {
  63552. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  63553. throw new Error('key must not be "' + key + '"');
  63554. }
  63555. }
  63556. }
  63557. function duringCall() {
  63558. // Do not provide "percent" until some requirements come.
  63559. // Because consider thies case:
  63560. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  63561. // And enter duration is different from update duration.
  63562. // Thus it might be confused about the meaning of "percent" in during callback.
  63563. var scope = this;
  63564. var el = scope.el;
  63565. if (!el) {
  63566. return;
  63567. } // If el is remove from zr by reason like legend, during still need to called,
  63568. // because el will be added back to zr and the prop value should not be incorrect.
  63569. var latestUserDuring = transitionInnerStore(el).userDuring;
  63570. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  63571. // If a during is called multiple times in one frame, maybe some users' calculation logic
  63572. // might be wrong (not sure whether this usage exists).
  63573. // The case of a during might be called twice can be: by default there is a animator for
  63574. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  63575. // another animators for 'style'/'shape'/'extra'.
  63576. if (latestUserDuring !== scopeUserDuring) {
  63577. // release
  63578. scope.el = scope.userDuring = null;
  63579. return;
  63580. }
  63581. tmpDuringScope.el = el; // Give no `this` to user in "during" calling.
  63582. scopeUserDuring(transitionDuringAPI); // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  63583. // consider the issue that the prop might be incorrect when return to "normal" state.
  63584. }
  63585. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  63586. var attrOpt = elOption[mainAttr];
  63587. if (!attrOpt) {
  63588. return;
  63589. }
  63590. var elPropsInAttr = fromEl[mainAttr];
  63591. var transFromPropsInAttr;
  63592. if (elPropsInAttr) {
  63593. var transition = elOption.transition;
  63594. var attrTransition = attrOpt.transition;
  63595. if (attrTransition) {
  63596. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  63597. if (isTransitionAll(attrTransition)) {
  63598. extend(transFromPropsInAttr, elPropsInAttr);
  63599. } else {
  63600. var transitionKeys = normalizeToArray(attrTransition);
  63601. for (var i = 0; i < transitionKeys.length; i++) {
  63602. var key = transitionKeys[i];
  63603. var elVal = elPropsInAttr[key];
  63604. transFromPropsInAttr[key] = elVal;
  63605. }
  63606. }
  63607. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  63608. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  63609. var elPropsInAttrKeys = keys(elPropsInAttr);
  63610. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  63611. var key = elPropsInAttrKeys[i];
  63612. var elVal = elPropsInAttr[key];
  63613. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  63614. transFromPropsInAttr[key] = elVal;
  63615. }
  63616. }
  63617. }
  63618. }
  63619. }
  63620. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  63621. var attrOpt = elOption[mainAttr];
  63622. if (!attrOpt) {
  63623. return;
  63624. }
  63625. var allPropsInAttr = allProps[mainAttr] = {};
  63626. var keysInAttr = keys(attrOpt);
  63627. for (var i = 0; i < keysInAttr.length; i++) {
  63628. var key = keysInAttr[i]; // To avoid share one object with different element, and
  63629. // to avoid user modify the object inexpectedly, have to clone.
  63630. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  63631. }
  63632. }
  63633. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  63634. var transition = elOption.transition;
  63635. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  63636. for (var i = 0; i < transitionKeys.length; i++) {
  63637. var key = transitionKeys[i];
  63638. if (key === 'style' || key === 'shape' || key === 'extra') {
  63639. continue;
  63640. }
  63641. var elVal = el[key];
  63642. if ("development" !== 'production') {
  63643. checkTransformPropRefer(key, 'el.transition');
  63644. } // Do not clone, animator will perform that clone.
  63645. transFromProps[key] = elVal;
  63646. }
  63647. }
  63648. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  63649. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  63650. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  63651. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  63652. var legacyArr = elOption[legacyName];
  63653. if (legacyArr) {
  63654. allProps[xyName[0]] = legacyArr[0];
  63655. allProps[xyName[1]] = legacyArr[1];
  63656. }
  63657. }
  63658. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  63659. var key = TRANSFORMABLE_PROPS[i];
  63660. if (elOption[key] != null) {
  63661. allProps[key] = elOption[key];
  63662. }
  63663. }
  63664. }
  63665. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  63666. if (!styleOpt) {
  63667. return;
  63668. }
  63669. var fromElStyle = fromEl.style;
  63670. var transFromStyleProps;
  63671. if (fromElStyle) {
  63672. var styleTransition = styleOpt.transition;
  63673. var elTransition = elOption.transition;
  63674. if (styleTransition && !isTransitionAll(styleTransition)) {
  63675. var transitionKeys = normalizeToArray(styleTransition);
  63676. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  63677. for (var i = 0; i < transitionKeys.length; i++) {
  63678. var key = transitionKeys[i];
  63679. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  63680. transFromStyleProps[key] = elVal;
  63681. }
  63682. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  63683. var animationProps = fromEl.getAnimationStyleProps();
  63684. var animationStyleProps = animationProps ? animationProps.style : null;
  63685. if (animationStyleProps) {
  63686. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  63687. var styleKeys = keys(styleOpt);
  63688. for (var i = 0; i < styleKeys.length; i++) {
  63689. var key = styleKeys[i];
  63690. if (animationStyleProps[key]) {
  63691. var elVal = fromElStyle[key];
  63692. transFromStyleProps[key] = elVal;
  63693. }
  63694. }
  63695. }
  63696. }
  63697. }
  63698. }
  63699. function isNonStyleTransitionEnabled(optVal, elVal) {
  63700. // The same as `checkNonStyleTansitionRefer`.
  63701. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  63702. }
  63703. var checkTransformPropRefer;
  63704. if ("development" !== 'production') {
  63705. checkTransformPropRefer = function (key, usedIn) {
  63706. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  63707. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  63708. }
  63709. };
  63710. }
  63711. var getStateToRestore = makeInner();
  63712. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  63713. /**
  63714. * Stop previous keyframe animation and restore the attributes.
  63715. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  63716. */
  63717. function stopPreviousKeyframeAnimationAndRestore(el) {
  63718. // Stop previous keyframe animation.
  63719. el.stopAnimation('keyframe'); // Restore
  63720. el.attr(getStateToRestore(el));
  63721. }
  63722. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  63723. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  63724. return;
  63725. }
  63726. if (isArray(animationOpts)) {
  63727. each(animationOpts, function (singleAnimationOpts) {
  63728. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  63729. });
  63730. return;
  63731. }
  63732. var keyframes = animationOpts.keyframes;
  63733. var duration = animationOpts.duration;
  63734. if (animatableModel && duration == null) {
  63735. // Default to use duration of config.
  63736. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  63737. var config = getAnimationConfig('enter', animatableModel, 0);
  63738. duration = config && config.duration;
  63739. }
  63740. if (!keyframes || !duration) {
  63741. return;
  63742. }
  63743. var stateToRestore = getStateToRestore(el);
  63744. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  63745. if (targetPropName && !el[targetPropName]) {
  63746. return;
  63747. }
  63748. var animator;
  63749. var endFrameIsSet = false; // Sort keyframes by percent.
  63750. keyframes.sort(function (a, b) {
  63751. return a.percent - b.percent;
  63752. });
  63753. each(keyframes, function (kf) {
  63754. // Stop current animation.
  63755. var animators = el.animators;
  63756. var kfValues = targetPropName ? kf[targetPropName] : kf;
  63757. if ("development" !== 'production') {
  63758. if (kf.percent >= 1) {
  63759. endFrameIsSet = true;
  63760. }
  63761. }
  63762. if (!kfValues) {
  63763. return;
  63764. }
  63765. var propKeys = keys(kfValues);
  63766. if (!targetPropName) {
  63767. // PENDING performance?
  63768. propKeys = filter(propKeys, function (key) {
  63769. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  63770. });
  63771. }
  63772. if (!propKeys.length) {
  63773. return;
  63774. }
  63775. if (!animator) {
  63776. animator = el.animate(targetPropName, animationOpts.loop, true);
  63777. animator.scope = 'keyframe';
  63778. }
  63779. for (var i = 0; i < animators.length; i++) {
  63780. // Stop all other animation that is not keyframe.
  63781. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  63782. animators[i].stopTracks(propKeys);
  63783. }
  63784. }
  63785. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  63786. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  63787. each(propKeys, function (key) {
  63788. // Save original value.
  63789. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  63790. });
  63791. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  63792. });
  63793. if (!animator) {
  63794. return;
  63795. }
  63796. if ("development" !== 'production') {
  63797. if (!endFrameIsSet) {
  63798. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  63799. }
  63800. }
  63801. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  63802. });
  63803. }
  63804. var EMPHASIS = 'emphasis';
  63805. var NORMAL = 'normal';
  63806. var BLUR = 'blur';
  63807. var SELECT = 'select';
  63808. var STATES = [NORMAL, EMPHASIS, BLUR, SELECT];
  63809. var PATH_ITEM_STYLE = {
  63810. normal: ['itemStyle'],
  63811. emphasis: [EMPHASIS, 'itemStyle'],
  63812. blur: [BLUR, 'itemStyle'],
  63813. select: [SELECT, 'itemStyle']
  63814. };
  63815. var PATH_LABEL = {
  63816. normal: ['label'],
  63817. emphasis: [EMPHASIS, 'label'],
  63818. blur: [BLUR, 'label'],
  63819. select: [SELECT, 'label']
  63820. };
  63821. var DEFAULT_TRANSITION = ['x', 'y']; // Use prefix to avoid index to be the same as el.name,
  63822. // which will cause weird update animation.
  63823. var GROUP_DIFF_PREFIX = 'e\0\0';
  63824. var attachedTxInfoTmp = {
  63825. normal: {},
  63826. emphasis: {},
  63827. blur: {},
  63828. select: {}
  63829. };
  63830. /**
  63831. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  63832. * of each coordinate systems are not required by each coordinate systems directly, but
  63833. * required by the module `custom`.
  63834. *
  63835. * prepareInfoForCustomSeries {Function}: optional
  63836. * @return {Object} {coordSys: {...}, api: {
  63837. * coord: function (data, clamp) {}, // return point in global.
  63838. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  63839. * }}
  63840. */
  63841. var prepareCustoms = {
  63842. cartesian2d: cartesianPrepareCustom,
  63843. geo: geoPrepareCustom,
  63844. single: singlePrepareCustom,
  63845. polar: polarPrepareCustom,
  63846. calendar: calendarPrepareCustom
  63847. };
  63848. function isPath$1(el) {
  63849. return el instanceof Path;
  63850. }
  63851. function isDisplayable(el) {
  63852. return el instanceof Displayable;
  63853. }
  63854. function copyElement(sourceEl, targetEl) {
  63855. targetEl.copyTransform(sourceEl);
  63856. if (isDisplayable(targetEl) && isDisplayable(sourceEl)) {
  63857. targetEl.setStyle(sourceEl.style);
  63858. targetEl.z = sourceEl.z;
  63859. targetEl.z2 = sourceEl.z2;
  63860. targetEl.zlevel = sourceEl.zlevel;
  63861. targetEl.invisible = sourceEl.invisible;
  63862. targetEl.ignore = sourceEl.ignore;
  63863. if (isPath$1(targetEl) && isPath$1(sourceEl)) {
  63864. targetEl.setShape(sourceEl.shape);
  63865. }
  63866. }
  63867. }
  63868. var CustomChartView =
  63869. /** @class */
  63870. function (_super) {
  63871. __extends(CustomChartView, _super);
  63872. function CustomChartView() {
  63873. var _this = _super !== null && _super.apply(this, arguments) || this;
  63874. _this.type = CustomChartView.type;
  63875. return _this;
  63876. }
  63877. CustomChartView.prototype.render = function (customSeries, ecModel, api, payload) {
  63878. // Clear previously rendered progressive elements.
  63879. this._progressiveEls = null;
  63880. var oldData = this._data;
  63881. var data = customSeries.getData();
  63882. var group = this.group;
  63883. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63884. if (!oldData) {
  63885. // Previous render is incremental render or first render.
  63886. // Needs remove the incremental rendered elements.
  63887. group.removeAll();
  63888. }
  63889. data.diff(oldData).add(function (newIdx) {
  63890. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  63891. }).remove(function (oldIdx) {
  63892. var el = oldData.getItemGraphicEl(oldIdx);
  63893. el && applyLeaveTransition(el, customInnerStore(el).option, customSeries);
  63894. }).update(function (newIdx, oldIdx) {
  63895. var oldEl = oldData.getItemGraphicEl(oldIdx);
  63896. createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  63897. }).execute(); // Do clipping
  63898. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  63899. if (clipPath) {
  63900. group.setClipPath(clipPath);
  63901. } else {
  63902. group.removeClipPath();
  63903. }
  63904. this._data = data;
  63905. };
  63906. CustomChartView.prototype.incrementalPrepareRender = function (customSeries, ecModel, api) {
  63907. this.group.removeAll();
  63908. this._data = null;
  63909. };
  63910. CustomChartView.prototype.incrementalRender = function (params, customSeries, ecModel, api, payload) {
  63911. var data = customSeries.getData();
  63912. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63913. var progressiveEls = this._progressiveEls = [];
  63914. function setIncrementalAndHoverLayer(el) {
  63915. if (!el.isGroup) {
  63916. el.incremental = true;
  63917. el.ensureState('emphasis').hoverLayer = true;
  63918. }
  63919. }
  63920. for (var idx = params.start; idx < params.end; idx++) {
  63921. var el = createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data);
  63922. if (el) {
  63923. el.traverse(setIncrementalAndHoverLayer);
  63924. progressiveEls.push(el);
  63925. }
  63926. }
  63927. };
  63928. CustomChartView.prototype.eachRendered = function (cb) {
  63929. traverseElements(this._progressiveEls || this.group, cb);
  63930. };
  63931. CustomChartView.prototype.filterForExposedEvent = function (eventType, query, targetEl, packedEvent) {
  63932. var elementName = query.element;
  63933. if (elementName == null || targetEl.name === elementName) {
  63934. return true;
  63935. } // Enable to give a name on a group made by `renderItem`, and listen
  63936. // events that are triggered by its descendents.
  63937. while ((targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group) {
  63938. if (targetEl.name === elementName) {
  63939. return true;
  63940. }
  63941. }
  63942. return false;
  63943. };
  63944. CustomChartView.type = 'custom';
  63945. return CustomChartView;
  63946. }(ChartView);
  63947. function createEl(elOption) {
  63948. var graphicType = elOption.type;
  63949. var el; // Those graphic elements are not shapes. They should not be
  63950. // overwritten by users, so do them first.
  63951. if (graphicType === 'path') {
  63952. var shape = elOption.shape; // Using pathRect brings convenience to users sacle svg path.
  63953. var pathRect = shape.width != null && shape.height != null ? {
  63954. x: shape.x || 0,
  63955. y: shape.y || 0,
  63956. width: shape.width,
  63957. height: shape.height
  63958. } : null;
  63959. var pathData = getPathData(shape); // Path is also used for icon, so layout 'center' by default.
  63960. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  63961. customInnerStore(el).customPathData = pathData;
  63962. } else if (graphicType === 'image') {
  63963. el = new ZRImage({});
  63964. customInnerStore(el).customImagePath = elOption.style.image;
  63965. } else if (graphicType === 'text') {
  63966. el = new ZRText({}); // customInnerStore(el).customText = (elOption.style as TextStyleProps).text;
  63967. } else if (graphicType === 'group') {
  63968. el = new Group();
  63969. } else if (graphicType === 'compoundPath') {
  63970. throw new Error('"compoundPath" is not supported yet.');
  63971. } else {
  63972. var Clz = getShapeClass(graphicType);
  63973. if (!Clz) {
  63974. var errMsg = '';
  63975. if ("development" !== 'production') {
  63976. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  63977. }
  63978. throwError(errMsg);
  63979. }
  63980. el = new Clz();
  63981. }
  63982. customInnerStore(el).customGraphicType = graphicType;
  63983. el.name = elOption.name; // Compat ec4: the default z2 lift is 1. If changing the number,
  63984. // some cases probably be broken: hierarchy layout along z, like circle packing,
  63985. // where emphasis only intending to modify color/border rather than lift z2.
  63986. el.z2EmphasisLift = 1;
  63987. el.z2SelectLift = 1;
  63988. return el;
  63989. }
  63990. function updateElNormal( // Can be null/undefined
  63991. api, el, dataIndex, elOption, attachedTxInfo, seriesModel, isInit) {
  63992. // Stop and restore before update any other attributes.
  63993. stopPreviousKeyframeAnimationAndRestore(el);
  63994. var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
  63995. if (txCfgOpt) {
  63996. // PENDING: whether use user object directly rather than clone?
  63997. // TODO:5.0 textConfig transition animation?
  63998. el.setTextConfig(txCfgOpt);
  63999. } // Default transition ['x', 'y']
  64000. if (elOption && elOption.transition == null) {
  64001. elOption.transition = DEFAULT_TRANSITION;
  64002. } // Do some normalization on style.
  64003. var styleOpt = elOption && elOption.style;
  64004. if (styleOpt) {
  64005. if (el.type === 'text') {
  64006. var textOptionStyle = styleOpt; // Compatible with ec4: if `textFill` or `textStroke` exists use them.
  64007. hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill);
  64008. hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke);
  64009. }
  64010. var decalPattern = void 0;
  64011. var decalObj = isPath$1(el) ? styleOpt.decal : null;
  64012. if (api && decalObj) {
  64013. decalObj.dirty = true;
  64014. decalPattern = createOrUpdatePatternFromDecal(decalObj, api);
  64015. } // Always overwrite in case user specify this prop.
  64016. styleOpt.__decalPattern = decalPattern;
  64017. }
  64018. if (isDisplayable(el)) {
  64019. if (styleOpt) {
  64020. var decalPattern = styleOpt.__decalPattern;
  64021. if (decalPattern) {
  64022. styleOpt.decal = decalPattern;
  64023. }
  64024. }
  64025. }
  64026. applyUpdateTransition(el, elOption, seriesModel, {
  64027. dataIndex: dataIndex,
  64028. isInit: isInit,
  64029. clearStyle: true
  64030. });
  64031. applyKeyframeAnimation(el, elOption.keyframeAnimation, seriesModel);
  64032. }
  64033. function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo) {
  64034. var elDisplayable = el.isGroup ? null : el;
  64035. var txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg; // PENDING:5.0 support customize scale change and transition animation?
  64036. if (elDisplayable) {
  64037. // By default support auto lift color when hover whether `emphasis` specified.
  64038. var stateObj = elDisplayable.ensureState(state);
  64039. if (styleOpt === false) {
  64040. var existingEmphasisState = elDisplayable.getState(state);
  64041. if (existingEmphasisState) {
  64042. existingEmphasisState.style = null;
  64043. }
  64044. } else {
  64045. // style is needed to enable default emphasis.
  64046. stateObj.style = styleOpt || null;
  64047. } // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
  64048. // remove hover style.
  64049. // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
  64050. // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
  64051. if (txCfgOpt) {
  64052. stateObj.textConfig = txCfgOpt;
  64053. }
  64054. setDefaultStateProxy(elDisplayable);
  64055. }
  64056. }
  64057. function updateZ$1(el, elOption, seriesModel) {
  64058. // Group not support textContent and not support z yet.
  64059. if (el.isGroup) {
  64060. return;
  64061. }
  64062. var elDisplayable = el;
  64063. var currentZ = seriesModel.currentZ;
  64064. var currentZLevel = seriesModel.currentZLevel; // Always erase.
  64065. elDisplayable.z = currentZ;
  64066. elDisplayable.zlevel = currentZLevel; // z2 must not be null/undefined, otherwise sort error may occur.
  64067. var optZ2 = elOption.z2;
  64068. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  64069. for (var i = 0; i < STATES.length; i++) {
  64070. updateZForEachState(elDisplayable, elOption, STATES[i]);
  64071. }
  64072. }
  64073. function updateZForEachState(elDisplayable, elOption, state) {
  64074. var isNormal = state === NORMAL;
  64075. var elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state);
  64076. var optZ2 = elStateOpt ? elStateOpt.z2 : null;
  64077. var stateObj;
  64078. if (optZ2 != null) {
  64079. // Do not `ensureState` until required.
  64080. stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
  64081. stateObj.z2 = optZ2 || 0;
  64082. }
  64083. }
  64084. function makeRenderItem(customSeries, data, ecModel, api) {
  64085. var renderItem = customSeries.get('renderItem');
  64086. var coordSys = customSeries.coordinateSystem;
  64087. var prepareResult = {};
  64088. if (coordSys) {
  64089. if ("development" !== 'production') {
  64090. assert(renderItem, 'series.render is required.');
  64091. assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.');
  64092. } // `coordSys.prepareCustoms` is used for external coord sys like bmap.
  64093. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys);
  64094. }
  64095. var userAPI = defaults({
  64096. getWidth: api.getWidth,
  64097. getHeight: api.getHeight,
  64098. getZr: api.getZr,
  64099. getDevicePixelRatio: api.getDevicePixelRatio,
  64100. value: value,
  64101. style: style,
  64102. ordinalRawValue: ordinalRawValue,
  64103. styleEmphasis: styleEmphasis,
  64104. visual: visual,
  64105. barLayout: barLayout,
  64106. currentSeriesIndices: currentSeriesIndices,
  64107. font: font
  64108. }, prepareResult.api || {});
  64109. var userParams = {
  64110. // The life cycle of context: current round of rendering.
  64111. // The global life cycle is probably not necessary, because
  64112. // user can store global status by themselves.
  64113. context: {},
  64114. seriesId: customSeries.id,
  64115. seriesName: customSeries.name,
  64116. seriesIndex: customSeries.seriesIndex,
  64117. coordSys: prepareResult.coordSys,
  64118. dataInsideLength: data.count(),
  64119. encode: wrapEncodeDef(customSeries.getData())
  64120. }; // If someday intending to refactor them to a class, should consider do not
  64121. // break change: currently these attribute member are encapsulated in a closure
  64122. // so that do not need to force user to call these method with a scope.
  64123. // Do not support call `api` asynchronously without dataIndexInside input.
  64124. var currDataIndexInside;
  64125. var currItemModel;
  64126. var currItemStyleModels = {};
  64127. var currLabelModels = {};
  64128. var seriesItemStyleModels = {};
  64129. var seriesLabelModels = {};
  64130. for (var i = 0; i < STATES.length; i++) {
  64131. var stateName = STATES[i];
  64132. seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]);
  64133. seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]);
  64134. }
  64135. function getItemModel(dataIndexInside) {
  64136. return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside);
  64137. }
  64138. function getItemStyleModel(dataIndexInside, state) {
  64139. return !data.hasItemOption ? seriesItemStyleModels[state] : dataIndexInside === currDataIndexInside ? currItemStyleModels[state] || (currItemStyleModels[state] = getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state])) : getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state]);
  64140. }
  64141. function getLabelModel(dataIndexInside, state) {
  64142. return !data.hasItemOption ? seriesLabelModels[state] : dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
  64143. }
  64144. return function (dataIndexInside, payload) {
  64145. currDataIndexInside = dataIndexInside;
  64146. currItemModel = null;
  64147. currItemStyleModels = {};
  64148. currLabelModels = {};
  64149. return renderItem && renderItem(defaults({
  64150. dataIndexInside: dataIndexInside,
  64151. dataIndex: data.getRawIndex(dataIndexInside),
  64152. // Can be used for optimization when zoom or roam.
  64153. actionType: payload ? payload.type : null
  64154. }, userParams), userAPI);
  64155. };
  64156. /**
  64157. * @public
  64158. * @param dim by default 0.
  64159. * @param dataIndexInside by default `currDataIndexInside`.
  64160. */
  64161. function value(dim, dataIndexInside) {
  64162. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64163. return data.getStore().get(data.getDimensionIndex(dim || 0), dataIndexInside);
  64164. }
  64165. /**
  64166. * @public
  64167. * @param dim by default 0.
  64168. * @param dataIndexInside by default `currDataIndexInside`.
  64169. */
  64170. function ordinalRawValue(dim, dataIndexInside) {
  64171. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64172. dim = dim || 0;
  64173. var dimInfo = data.getDimensionInfo(dim);
  64174. if (!dimInfo) {
  64175. var dimIndex = data.getDimensionIndex(dim);
  64176. return dimIndex >= 0 ? data.getStore().get(dimIndex, dataIndexInside) : undefined;
  64177. }
  64178. var val = data.get(dimInfo.name, dataIndexInside);
  64179. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  64180. return ordinalMeta ? ordinalMeta.categories[val] : val;
  64181. }
  64182. /**
  64183. * @deprecated The original intention of `api.style` is enable to set itemStyle
  64184. * like other series. But it is not necessary and not easy to give a strict definition
  64185. * of what it returns. And since echarts5 it needs to be make compat work. So
  64186. * deprecates it since echarts5.
  64187. *
  64188. * By default, `visual` is applied to style (to support visualMap).
  64189. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  64190. * it can be implemented as:
  64191. * `api.style({stroke: api.visual('color'), fill: null})`;
  64192. *
  64193. * [Compat]: since ec5, RectText has been separated from its hosts el.
  64194. * so `api.style()` will only return the style from `itemStyle` but not handle `label`
  64195. * any more. But `series.label` config is never published in doc.
  64196. * We still compat it in `api.style()`. But not encourage to use it and will still not
  64197. * to pulish it to doc.
  64198. * @public
  64199. * @param dataIndexInside by default `currDataIndexInside`.
  64200. */
  64201. function style(userProps, dataIndexInside) {
  64202. if ("development" !== 'production') {
  64203. warnDeprecated('api.style', 'Please write literal style directly instead.');
  64204. }
  64205. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64206. var style = data.getItemVisual(dataIndexInside, 'style');
  64207. var visualColor = style && style.fill;
  64208. var opacity = style && style.opacity;
  64209. var itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
  64210. visualColor != null && (itemStyle.fill = visualColor);
  64211. opacity != null && (itemStyle.opacity = opacity);
  64212. var opt = {
  64213. inheritColor: isString(visualColor) ? visualColor : '#000'
  64214. };
  64215. var labelModel = getLabelModel(dataIndexInside, NORMAL); // Now that the feature of "auto adjust text fill/stroke" has been migrated to zrender
  64216. // since ec5, we should set `isAttached` as `false` here and make compat in
  64217. // `convertToEC4StyleForCustomSerise`.
  64218. var textStyle = createTextStyle(labelModel, null, opt, false, true);
  64219. textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  64220. var textConfig = createTextConfig(labelModel, opt, false);
  64221. preFetchFromExtra(userProps, itemStyle);
  64222. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  64223. userProps && applyUserPropsAfter(itemStyle, userProps);
  64224. itemStyle.legacy = true;
  64225. return itemStyle;
  64226. }
  64227. /**
  64228. * @deprecated The reason see `api.style()`
  64229. * @public
  64230. * @param dataIndexInside by default `currDataIndexInside`.
  64231. */
  64232. function styleEmphasis(userProps, dataIndexInside) {
  64233. if ("development" !== 'production') {
  64234. warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
  64235. }
  64236. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64237. var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
  64238. var labelModel = getLabelModel(dataIndexInside, EMPHASIS);
  64239. var textStyle = createTextStyle(labelModel, null, null, true, true);
  64240. textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  64241. var textConfig = createTextConfig(labelModel, null, true);
  64242. preFetchFromExtra(userProps, itemStyle);
  64243. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  64244. userProps && applyUserPropsAfter(itemStyle, userProps);
  64245. itemStyle.legacy = true;
  64246. return itemStyle;
  64247. }
  64248. function applyUserPropsAfter(itemStyle, extra) {
  64249. for (var key in extra) {
  64250. if (hasOwn(extra, key)) {
  64251. itemStyle[key] = extra[key];
  64252. }
  64253. }
  64254. }
  64255. function preFetchFromExtra(extra, itemStyle) {
  64256. // A trick to retrieve those props firstly, which are used to
  64257. // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
  64258. // (It's not reasonable but only for a degree of compat)
  64259. if (extra) {
  64260. extra.textFill && (itemStyle.textFill = extra.textFill);
  64261. extra.textPosition && (itemStyle.textPosition = extra.textPosition);
  64262. }
  64263. }
  64264. /**
  64265. * @public
  64266. * @param dataIndexInside by default `currDataIndexInside`.
  64267. */
  64268. function visual(visualType, dataIndexInside) {
  64269. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64270. if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
  64271. var style_1 = data.getItemVisual(dataIndexInside, 'style');
  64272. return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null;
  64273. } // Only support these visuals. Other visual might be inner tricky
  64274. // for performance (like `style`), do not expose to users.
  64275. if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) {
  64276. return data.getItemVisual(dataIndexInside, visualType);
  64277. }
  64278. }
  64279. /**
  64280. * @public
  64281. * @return If not support, return undefined.
  64282. */
  64283. function barLayout(opt) {
  64284. if (coordSys.type === 'cartesian2d') {
  64285. var baseAxis = coordSys.getBaseAxis();
  64286. return getLayoutOnAxis(defaults({
  64287. axis: baseAxis
  64288. }, opt));
  64289. }
  64290. }
  64291. /**
  64292. * @public
  64293. */
  64294. function currentSeriesIndices() {
  64295. return ecModel.getCurrentSeriesIndices();
  64296. }
  64297. /**
  64298. * @public
  64299. * @return font string
  64300. */
  64301. function font(opt) {
  64302. return getFont(opt, ecModel);
  64303. }
  64304. }
  64305. function wrapEncodeDef(data) {
  64306. var encodeDef = {};
  64307. each(data.dimensions, function (dimName) {
  64308. var dimInfo = data.getDimensionInfo(dimName);
  64309. if (!dimInfo.isExtraCoord) {
  64310. var coordDim = dimInfo.coordDim;
  64311. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  64312. dataDims[dimInfo.coordDimIndex] = data.getDimensionIndex(dimName);
  64313. }
  64314. });
  64315. return encodeDef;
  64316. }
  64317. function createOrUpdateItem(api, existsEl, dataIndex, elOption, seriesModel, group, data) {
  64318. // [Rule]
  64319. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  64320. // (It seems that violate the "merge" principle, but most of users probably intuitively
  64321. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  64322. // most cases.)
  64323. // The rule or "merge" see [STRATEGY_MERGE].
  64324. // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
  64325. if (!elOption) {
  64326. group.remove(existsEl);
  64327. return;
  64328. }
  64329. var el = doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group);
  64330. el && data.setItemGraphicEl(dataIndex, el);
  64331. el && toggleHoverEmphasis(el, elOption.focus, elOption.blurScope, elOption.emphasisDisabled);
  64332. return el;
  64333. }
  64334. function doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group) {
  64335. if ("development" !== 'production') {
  64336. assert(elOption, 'should not have an null/undefined element setting');
  64337. }
  64338. var toBeReplacedIdx = -1;
  64339. var oldEl = existsEl;
  64340. if (existsEl && doesElNeedRecreate(existsEl, elOption, seriesModel) // || (
  64341. // // PENDING: even in one-to-one mapping case, if el is marked as morph,
  64342. // // do not sure whether the el will be mapped to another el with different
  64343. // // hierarchy in Group tree. So always recreate el rather than reuse the el.
  64344. // morphHelper && morphHelper.isOneToOneFrom(el)
  64345. // )
  64346. ) {
  64347. // Should keep at the original index, otherwise "merge by index" will be incorrect.
  64348. toBeReplacedIdx = indexOf(group.childrenRef(), existsEl);
  64349. existsEl = null;
  64350. }
  64351. var isInit = !existsEl;
  64352. var el = existsEl;
  64353. if (!el) {
  64354. el = createEl(elOption);
  64355. if (oldEl) {
  64356. copyElement(oldEl, el);
  64357. }
  64358. } else {
  64359. // FIMXE:NEXT unified clearState?
  64360. // If in some case the performance issue arised, consider
  64361. // do not clearState but update cached normal state directly.
  64362. el.clearStates();
  64363. } // Need to set morph: false explictly to disable automatically morphing.
  64364. if (elOption.morph === false) {
  64365. el.disableMorphing = true;
  64366. } else if (el.disableMorphing) {
  64367. el.disableMorphing = false;
  64368. }
  64369. attachedTxInfoTmp.normal.cfg = attachedTxInfoTmp.normal.conOpt = attachedTxInfoTmp.emphasis.cfg = attachedTxInfoTmp.emphasis.conOpt = attachedTxInfoTmp.blur.cfg = attachedTxInfoTmp.blur.conOpt = attachedTxInfoTmp.select.cfg = attachedTxInfoTmp.select.conOpt = null;
  64370. attachedTxInfoTmp.isLegacy = false;
  64371. doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp);
  64372. doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit);
  64373. updateElNormal(api, el, dataIndex, elOption, attachedTxInfoTmp, seriesModel, isInit); // `elOption.info` enables user to mount some info on
  64374. // elements and use them in event handlers.
  64375. // Update them only when user specified, otherwise, remain.
  64376. hasOwn(elOption, 'info') && (customInnerStore(el).info = elOption.info);
  64377. for (var i = 0; i < STATES.length; i++) {
  64378. var stateName = STATES[i];
  64379. if (stateName !== NORMAL) {
  64380. var otherStateOpt = retrieveStateOption(elOption, stateName);
  64381. var otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
  64382. updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp);
  64383. }
  64384. }
  64385. updateZ$1(el, elOption, seriesModel);
  64386. if (elOption.type === 'group') {
  64387. mergeChildren(api, el, dataIndex, elOption, seriesModel);
  64388. }
  64389. if (toBeReplacedIdx >= 0) {
  64390. group.replaceAt(el, toBeReplacedIdx);
  64391. } else {
  64392. group.add(el);
  64393. }
  64394. return el;
  64395. } // `el` must not be null/undefined.
  64396. function doesElNeedRecreate(el, elOption, seriesModel) {
  64397. var elInner = customInnerStore(el);
  64398. var elOptionType = elOption.type;
  64399. var elOptionShape = elOption.shape;
  64400. var elOptionStyle = elOption.style;
  64401. return (// Always create new if universal transition is enabled.
  64402. // Because we do transition after render. It needs to know what old element is. Replacement will loose it.
  64403. seriesModel.isUniversalTransitionEnabled() // If `elOptionType` is `null`, follow the merge principle.
  64404. || elOptionType != null && elOptionType !== elInner.customGraphicType || elOptionType === 'path' && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== elInner.customPathData || elOptionType === 'image' && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== elInner.customImagePath // // FIXME test and remove this restriction?
  64405. // || (elOptionType === 'text'
  64406. // && hasOwn(elOptionStyle, 'text')
  64407. // && (elOptionStyle as TextStyleProps).text !== elInner.customText
  64408. // )
  64409. );
  64410. }
  64411. function doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit) {
  64412. // Based on the "merge" principle, if no clipPath provided,
  64413. // do nothing. The exists clip will be totally removed only if
  64414. // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
  64415. var clipPathOpt = elOption.clipPath;
  64416. if (clipPathOpt === false) {
  64417. if (el && el.getClipPath()) {
  64418. el.removeClipPath();
  64419. }
  64420. } else if (clipPathOpt) {
  64421. var clipPath = el.getClipPath();
  64422. if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt, seriesModel)) {
  64423. clipPath = null;
  64424. }
  64425. if (!clipPath) {
  64426. clipPath = createEl(clipPathOpt);
  64427. if ("development" !== 'production') {
  64428. assert(isPath$1(clipPath), 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.');
  64429. }
  64430. el.setClipPath(clipPath);
  64431. }
  64432. updateElNormal(null, clipPath, dataIndex, clipPathOpt, null, seriesModel, isInit);
  64433. } // If not define `clipPath` in option, do nothing unnecessary.
  64434. }
  64435. function doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) {
  64436. // Group does not support textContent temporarily until necessary.
  64437. if (el.isGroup) {
  64438. return;
  64439. } // Normal must be called before emphasis, for `isLegacy` detection.
  64440. processTxInfo(elOption, null, attachedTxInfo);
  64441. processTxInfo(elOption, EMPHASIS, attachedTxInfo); // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sense.
  64442. // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
  64443. // trade them as set to null to el.
  64444. // Especially:
  64445. // `elOption.textContent: false` means remove textContent.
  64446. // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
  64447. var txConOptNormal = attachedTxInfo.normal.conOpt;
  64448. var txConOptEmphasis = attachedTxInfo.emphasis.conOpt;
  64449. var txConOptBlur = attachedTxInfo.blur.conOpt;
  64450. var txConOptSelect = attachedTxInfo.select.conOpt;
  64451. if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
  64452. var textContent = el.getTextContent();
  64453. if (txConOptNormal === false) {
  64454. textContent && el.removeTextContent();
  64455. } else {
  64456. txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {
  64457. type: 'text'
  64458. };
  64459. if (!textContent) {
  64460. textContent = createEl(txConOptNormal);
  64461. el.setTextContent(textContent);
  64462. } else {
  64463. // If in some case the performance issue arised, consider
  64464. // do not clearState but update cached normal state directly.
  64465. textContent.clearStates();
  64466. }
  64467. updateElNormal(null, textContent, dataIndex, txConOptNormal, null, seriesModel, isInit);
  64468. var txConStlOptNormal = txConOptNormal && txConOptNormal.style;
  64469. for (var i = 0; i < STATES.length; i++) {
  64470. var stateName = STATES[i];
  64471. if (stateName !== NORMAL) {
  64472. var txConOptOtherState = attachedTxInfo[stateName].conOpt;
  64473. updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null);
  64474. }
  64475. }
  64476. txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
  64477. }
  64478. }
  64479. }
  64480. function processTxInfo(elOption, state, attachedTxInfo) {
  64481. var stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
  64482. var styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);
  64483. var elType = elOption.type;
  64484. var txCfg = stateOpt ? stateOpt.textConfig : null;
  64485. var txConOptNormal = elOption.textContent;
  64486. var txConOpt = !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);
  64487. if (styleOpt && ( // Because emphasis style has little info to detect legacy,
  64488. // if normal is legacy, emphasis is trade as legacy.
  64489. attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) {
  64490. attachedTxInfo.isLegacy = true;
  64491. var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state); // Explicitly specified `textConfig` and `textContent` has higher priority than
  64492. // the ones generated by legacy style. Otherwise if users use them and `api.style`
  64493. // at the same time, they not both work and hardly to known why.
  64494. if (!txCfg && convertResult.textConfig) {
  64495. txCfg = convertResult.textConfig;
  64496. }
  64497. if (!txConOpt && convertResult.textContent) {
  64498. txConOpt = convertResult.textContent;
  64499. }
  64500. }
  64501. if (!state && txConOpt) {
  64502. var txConOptNormal_1 = txConOpt; // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
  64503. !txConOptNormal_1.type && (txConOptNormal_1.type = 'text');
  64504. if ("development" !== 'production') {
  64505. // Do not tolerate incorrcet type for forward compat.
  64506. assert(txConOptNormal_1.type === 'text', 'textContent.type must be "text"');
  64507. }
  64508. }
  64509. var info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
  64510. info.cfg = txCfg;
  64511. info.conOpt = txConOpt;
  64512. }
  64513. function retrieveStateOption(elOption, state) {
  64514. return !state ? elOption : elOption ? elOption[state] : null;
  64515. }
  64516. function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) {
  64517. var style = stateOption && stateOption.style;
  64518. if (style == null && state === EMPHASIS && stateOptionNormal) {
  64519. style = stateOptionNormal.styleEmphasis;
  64520. }
  64521. return style;
  64522. } // Usage:
  64523. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates
  64524. // that the existing children will not be removed, and enables the feature
  64525. // that update some of the props of some of the children simply by construct
  64526. // the returned children of `renderItem` like:
  64527. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  64528. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  64529. // by child.name. But that might be lower performance.
  64530. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  64531. // replaced totally.
  64532. // (4) If `!elOption.children`, following the "merge" principle, nothing will
  64533. // happen.
  64534. // (5) If `elOption.$mergeChildren` is not `false` neither `'byName'` and the
  64535. // `el` is a group, and if any of the new child is null, it means to remove
  64536. // the element at the same index, if exists. On the other hand, if the new
  64537. // child is and empty object `{}`, it means to keep the element not changed.
  64538. //
  64539. // For implementation simpleness, do not provide a direct way to remove single
  64540. // child (otherwise the total indices of the children array have to be modified).
  64541. // User can remove a single child by setting its `ignore` to `true`.
  64542. function mergeChildren(api, el, dataIndex, elOption, seriesModel) {
  64543. var newChildren = elOption.children;
  64544. var newLen = newChildren ? newChildren.length : 0;
  64545. var mergeChildren = elOption.$mergeChildren; // `diffChildrenByName` has been deprecated.
  64546. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  64547. var notMerge = mergeChildren === false; // For better performance on roam update, only enter if necessary.
  64548. if (!newLen && !byName && !notMerge) {
  64549. return;
  64550. }
  64551. if (byName) {
  64552. diffGroupChildren({
  64553. api: api,
  64554. oldChildren: el.children() || [],
  64555. newChildren: newChildren || [],
  64556. dataIndex: dataIndex,
  64557. seriesModel: seriesModel,
  64558. group: el
  64559. });
  64560. return;
  64561. }
  64562. notMerge && el.removeAll(); // Mapping children of a group simply by index, which
  64563. // might be better performance.
  64564. var index = 0;
  64565. for (; index < newLen; index++) {
  64566. var newChild = newChildren[index];
  64567. var oldChild = el.childAt(index);
  64568. if (newChild) {
  64569. if (newChild.ignore == null) {
  64570. // The old child is set to be ignored if null (see comments
  64571. // below). So we need to set ignore to be false back.
  64572. newChild.ignore = false;
  64573. }
  64574. doCreateOrUpdateEl(api, oldChild, dataIndex, newChild, seriesModel, el);
  64575. } else {
  64576. if ("development" !== 'production') {
  64577. assert(oldChild, 'renderItem should not return a group containing elements' + ' as null/undefined/{} if they do not exist before.');
  64578. } // If the new element option is null, it means to remove the old
  64579. // element. But we cannot really remove the element from the group
  64580. // directly, because the element order may not be stable when this
  64581. // element is added back. So we set the element to be ignored.
  64582. oldChild.ignore = true;
  64583. }
  64584. }
  64585. for (var i = el.childCount() - 1; i >= index; i--) {
  64586. var child = el.childAt(i);
  64587. removeChildFromGroup(el, child, seriesModel);
  64588. }
  64589. }
  64590. function removeChildFromGroup(group, child, seriesModel) {
  64591. // Do not support leave elements that are not mentioned in the latest
  64592. // `renderItem` return. Otherwise users may not have a clear and simple
  64593. // concept that how to control all of the elements.
  64594. child && applyLeaveTransition(child, customInnerStore(group).option, seriesModel);
  64595. }
  64596. function diffGroupChildren(context) {
  64597. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  64598. }
  64599. function getKey(item, idx) {
  64600. var name = item && item.name;
  64601. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  64602. }
  64603. function processAddUpdate(newIndex, oldIndex) {
  64604. var context = this.context;
  64605. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  64606. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  64607. doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group);
  64608. }
  64609. function processRemove(oldIndex) {
  64610. var context = this.context;
  64611. var child = context.oldChildren[oldIndex];
  64612. child && applyLeaveTransition(child, customInnerStore(child).option, context.seriesModel);
  64613. }
  64614. /**
  64615. * @return SVG Path data.
  64616. */
  64617. function getPathData(shape) {
  64618. // "d" follows the SVG convention.
  64619. return shape && (shape.pathData || shape.d);
  64620. }
  64621. function hasOwnPathData(shape) {
  64622. return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
  64623. }
  64624. function install$r(registers) {
  64625. registers.registerChartView(CustomChartView);
  64626. registers.registerSeriesModel(CustomSeriesModel);
  64627. }
  64628. var inner$a = makeInner();
  64629. var clone$3 = clone;
  64630. var bind$1 = bind;
  64631. /**
  64632. * Base axis pointer class in 2D.
  64633. */
  64634. var BaseAxisPointer =
  64635. /** @class */
  64636. function () {
  64637. function BaseAxisPointer() {
  64638. this._dragging = false;
  64639. /**
  64640. * In px, arbitrary value. Do not set too small,
  64641. * no animation is ok for most cases.
  64642. */
  64643. this.animationThreshold = 15;
  64644. }
  64645. /**
  64646. * @implement
  64647. */
  64648. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  64649. var value = axisPointerModel.get('value');
  64650. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  64651. // be replaced when user calling setOption in not merge mode.
  64652. this._axisModel = axisModel;
  64653. this._axisPointerModel = axisPointerModel;
  64654. this._api = api; // Optimize: `render` will be called repeatedly during mouse move.
  64655. // So it is power consuming if performing `render` each time,
  64656. // especially on mobile device.
  64657. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  64658. return;
  64659. }
  64660. this._lastValue = value;
  64661. this._lastStatus = status;
  64662. var group = this._group;
  64663. var handle = this._handle;
  64664. if (!status || status === 'hide') {
  64665. // Do not clear here, for animation better.
  64666. group && group.hide();
  64667. handle && handle.hide();
  64668. return;
  64669. }
  64670. group && group.show();
  64671. handle && handle.show(); // Otherwise status is 'show'
  64672. var elOption = {};
  64673. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  64674. var graphicKey = elOption.graphicKey;
  64675. if (graphicKey !== this._lastGraphicKey) {
  64676. this.clear(api);
  64677. }
  64678. this._lastGraphicKey = graphicKey;
  64679. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  64680. if (!group) {
  64681. group = this._group = new Group();
  64682. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  64683. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  64684. api.getZr().add(group);
  64685. } else {
  64686. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  64687. this.updatePointerEl(group, elOption, doUpdateProps);
  64688. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  64689. }
  64690. updateMandatoryProps(group, axisPointerModel, true);
  64691. this._renderHandle(value);
  64692. };
  64693. /**
  64694. * @implement
  64695. */
  64696. BaseAxisPointer.prototype.remove = function (api) {
  64697. this.clear(api);
  64698. };
  64699. /**
  64700. * @implement
  64701. */
  64702. BaseAxisPointer.prototype.dispose = function (api) {
  64703. this.clear(api);
  64704. };
  64705. /**
  64706. * @protected
  64707. */
  64708. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  64709. var animation = axisPointerModel.get('animation');
  64710. var axis = axisModel.axis;
  64711. var isCategoryAxis = axis.type === 'category';
  64712. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  64713. if (!useSnap && !isCategoryAxis) {
  64714. return false;
  64715. }
  64716. if (animation === 'auto' || animation == null) {
  64717. var animationThreshold = this.animationThreshold;
  64718. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  64719. return true;
  64720. } // It is important to auto animation when snap used. Consider if there is
  64721. // a dataZoom, animation will be disabled when too many points exist, while
  64722. // it will be enabled for better visual effect when little points exist.
  64723. if (useSnap) {
  64724. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  64725. var axisExtent = axis.getExtent(); // Approximate band width
  64726. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  64727. }
  64728. return false;
  64729. }
  64730. return animation === true;
  64731. };
  64732. /**
  64733. * add {pointer, label, graphicKey} to elOption
  64734. * @protected
  64735. */
  64736. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Should be implemenented by sub-class.
  64737. };
  64738. /**
  64739. * @protected
  64740. */
  64741. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  64742. var pointerOption = elOption.pointer;
  64743. if (pointerOption) {
  64744. var pointerEl = inner$a(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  64745. group.add(pointerEl);
  64746. }
  64747. };
  64748. /**
  64749. * @protected
  64750. */
  64751. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  64752. if (elOption.label) {
  64753. var labelEl = inner$a(group).labelEl = new ZRText(clone$3(elOption.label));
  64754. group.add(labelEl);
  64755. updateLabelShowHide(labelEl, axisPointerModel);
  64756. }
  64757. };
  64758. /**
  64759. * @protected
  64760. */
  64761. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  64762. var pointerEl = inner$a(group).pointerEl;
  64763. if (pointerEl && elOption.pointer) {
  64764. pointerEl.setStyle(elOption.pointer.style);
  64765. updateProps(pointerEl, {
  64766. shape: elOption.pointer.shape
  64767. });
  64768. }
  64769. };
  64770. /**
  64771. * @protected
  64772. */
  64773. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  64774. var labelEl = inner$a(group).labelEl;
  64775. if (labelEl) {
  64776. labelEl.setStyle(elOption.label.style);
  64777. updateProps(labelEl, {
  64778. // Consider text length change in vertical axis, animation should
  64779. // be used on shape, otherwise the effect will be weird.
  64780. // TODOTODO
  64781. // shape: elOption.label.shape,
  64782. x: elOption.label.x,
  64783. y: elOption.label.y
  64784. });
  64785. updateLabelShowHide(labelEl, axisPointerModel);
  64786. }
  64787. };
  64788. /**
  64789. * @private
  64790. */
  64791. BaseAxisPointer.prototype._renderHandle = function (value) {
  64792. if (this._dragging || !this.updateHandleTransform) {
  64793. return;
  64794. }
  64795. var axisPointerModel = this._axisPointerModel;
  64796. var zr = this._api.getZr();
  64797. var handle = this._handle;
  64798. var handleModel = axisPointerModel.getModel('handle');
  64799. var status = axisPointerModel.get('status');
  64800. if (!handleModel.get('show') || !status || status === 'hide') {
  64801. handle && zr.remove(handle);
  64802. this._handle = null;
  64803. return;
  64804. }
  64805. var isInit;
  64806. if (!this._handle) {
  64807. isInit = true;
  64808. handle = this._handle = createIcon(handleModel.get('icon'), {
  64809. cursor: 'move',
  64810. draggable: true,
  64811. onmousemove: function (e) {
  64812. // For mobile device, prevent screen slider on the button.
  64813. stop(e.event);
  64814. },
  64815. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  64816. drift: bind$1(this._onHandleDragMove, this),
  64817. ondragend: bind$1(this._onHandleDragEnd, this)
  64818. });
  64819. zr.add(handle);
  64820. }
  64821. updateMandatoryProps(handle, axisPointerModel, false); // update style
  64822. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  64823. var handleSize = handleModel.get('size');
  64824. if (!isArray(handleSize)) {
  64825. handleSize = [handleSize, handleSize];
  64826. }
  64827. handle.scaleX = handleSize[0] / 2;
  64828. handle.scaleY = handleSize[1] / 2;
  64829. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  64830. this._moveHandleToValue(value, isInit);
  64831. };
  64832. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  64833. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  64834. };
  64835. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  64836. var handle = this._handle;
  64837. if (!handle) {
  64838. return;
  64839. }
  64840. this._dragging = true; // Persistent for throttle.
  64841. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  64842. this._payloadInfo = trans;
  64843. handle.stopAnimation();
  64844. handle.attr(getHandleTransProps(trans));
  64845. inner$a(handle).lastProp = null;
  64846. this._doDispatchAxisPointer();
  64847. };
  64848. /**
  64849. * Throttled method.
  64850. */
  64851. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  64852. var handle = this._handle;
  64853. if (!handle) {
  64854. return;
  64855. }
  64856. var payloadInfo = this._payloadInfo;
  64857. var axisModel = this._axisModel;
  64858. this._api.dispatchAction({
  64859. type: 'updateAxisPointer',
  64860. x: payloadInfo.cursorPoint[0],
  64861. y: payloadInfo.cursorPoint[1],
  64862. tooltipOption: payloadInfo.tooltipOption,
  64863. axesInfo: [{
  64864. axisDim: axisModel.axis.dim,
  64865. axisIndex: axisModel.componentIndex
  64866. }]
  64867. });
  64868. };
  64869. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  64870. this._dragging = false;
  64871. var handle = this._handle;
  64872. if (!handle) {
  64873. return;
  64874. }
  64875. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  64876. // axisPointer. So move handle to align the exact value position when
  64877. // drag ended.
  64878. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  64879. // button, and will be hidden after finger left handle button.
  64880. this._api.dispatchAction({
  64881. type: 'hideTip'
  64882. });
  64883. };
  64884. /**
  64885. * @private
  64886. */
  64887. BaseAxisPointer.prototype.clear = function (api) {
  64888. this._lastValue = null;
  64889. this._lastStatus = null;
  64890. var zr = api.getZr();
  64891. var group = this._group;
  64892. var handle = this._handle;
  64893. if (zr && group) {
  64894. this._lastGraphicKey = null;
  64895. group && zr.remove(group);
  64896. handle && zr.remove(handle);
  64897. this._group = null;
  64898. this._handle = null;
  64899. this._payloadInfo = null;
  64900. }
  64901. clear(this, '_doDispatchAxisPointer');
  64902. };
  64903. /**
  64904. * @protected
  64905. */
  64906. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  64907. };
  64908. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  64909. xDimIndex = xDimIndex || 0;
  64910. return {
  64911. x: xy[xDimIndex],
  64912. y: xy[1 - xDimIndex],
  64913. width: wh[xDimIndex],
  64914. height: wh[1 - xDimIndex]
  64915. };
  64916. };
  64917. return BaseAxisPointer;
  64918. }();
  64919. function updateProps$1(animationModel, moveAnimation, el, props) {
  64920. // Animation optimize.
  64921. if (!propsEqual(inner$a(el).lastProp, props)) {
  64922. inner$a(el).lastProp = props;
  64923. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  64924. }
  64925. }
  64926. function propsEqual(lastProps, newProps) {
  64927. if (isObject(lastProps) && isObject(newProps)) {
  64928. var equals_1 = true;
  64929. each(newProps, function (item, key) {
  64930. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  64931. });
  64932. return !!equals_1;
  64933. } else {
  64934. return lastProps === newProps;
  64935. }
  64936. }
  64937. function updateLabelShowHide(labelEl, axisPointerModel) {
  64938. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  64939. }
  64940. function getHandleTransProps(trans) {
  64941. return {
  64942. x: trans.x || 0,
  64943. y: trans.y || 0,
  64944. rotation: trans.rotation || 0
  64945. };
  64946. }
  64947. function updateMandatoryProps(group, axisPointerModel, silent) {
  64948. var z = axisPointerModel.get('z');
  64949. var zlevel = axisPointerModel.get('zlevel');
  64950. group && group.traverse(function (el) {
  64951. if (el.type !== 'group') {
  64952. z != null && (el.z = z);
  64953. zlevel != null && (el.zlevel = zlevel);
  64954. el.silent = silent;
  64955. }
  64956. });
  64957. }
  64958. function buildElStyle(axisPointerModel) {
  64959. var axisPointerType = axisPointerModel.get('type');
  64960. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  64961. var style;
  64962. if (axisPointerType === 'line') {
  64963. style = styleModel.getLineStyle();
  64964. style.fill = null;
  64965. } else if (axisPointerType === 'shadow') {
  64966. style = styleModel.getAreaStyle();
  64967. style.stroke = null;
  64968. }
  64969. return style;
  64970. }
  64971. /**
  64972. * @param {Function} labelPos {align, verticalAlign, position}
  64973. */
  64974. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  64975. var value = axisPointerModel.get('value');
  64976. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  64977. precision: axisPointerModel.get(['label', 'precision']),
  64978. formatter: axisPointerModel.get(['label', 'formatter'])
  64979. });
  64980. var labelModel = axisPointerModel.getModel('label');
  64981. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  64982. var font = labelModel.getFont();
  64983. var textRect = getBoundingRect(text, font);
  64984. var position = labelPos.position;
  64985. var width = textRect.width + paddings[1] + paddings[3];
  64986. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  64987. var align = labelPos.align;
  64988. align === 'right' && (position[0] -= width);
  64989. align === 'center' && (position[0] -= width / 2);
  64990. var verticalAlign = labelPos.verticalAlign;
  64991. verticalAlign === 'bottom' && (position[1] -= height);
  64992. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  64993. confineInContainer(position, width, height, api);
  64994. var bgColor = labelModel.get('backgroundColor');
  64995. if (!bgColor || bgColor === 'auto') {
  64996. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  64997. }
  64998. elOption.label = {
  64999. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  65000. x: position[0],
  65001. y: position[1],
  65002. style: createTextStyle(labelModel, {
  65003. text: text,
  65004. font: font,
  65005. fill: labelModel.getTextColor(),
  65006. padding: paddings,
  65007. backgroundColor: bgColor
  65008. }),
  65009. // Label should be over axisPointer.
  65010. z2: 10
  65011. };
  65012. } // Do not overflow ec container
  65013. function confineInContainer(position, width, height, api) {
  65014. var viewWidth = api.getWidth();
  65015. var viewHeight = api.getHeight();
  65016. position[0] = Math.min(position[0] + width, viewWidth) - width;
  65017. position[1] = Math.min(position[1] + height, viewHeight) - height;
  65018. position[0] = Math.max(position[0], 0);
  65019. position[1] = Math.max(position[1], 0);
  65020. }
  65021. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  65022. value = axis.scale.parse(value);
  65023. var text = axis.scale.getLabel({
  65024. value: value
  65025. }, {
  65026. // If `precision` is set, width can be fixed (like '12.00500'), which
  65027. // helps to debounce when when moving label.
  65028. precision: opt.precision
  65029. });
  65030. var formatter = opt.formatter;
  65031. if (formatter) {
  65032. var params_1 = {
  65033. value: getAxisRawValue(axis, {
  65034. value: value
  65035. }),
  65036. axisDimension: axis.dim,
  65037. axisIndex: axis.index,
  65038. seriesData: []
  65039. };
  65040. each(seriesDataIndices, function (idxItem) {
  65041. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  65042. var dataIndex = idxItem.dataIndexInside;
  65043. var dataParams = series && series.getDataParams(dataIndex);
  65044. dataParams && params_1.seriesData.push(dataParams);
  65045. });
  65046. if (isString(formatter)) {
  65047. text = formatter.replace('{value}', text);
  65048. } else if (isFunction(formatter)) {
  65049. text = formatter(params_1);
  65050. }
  65051. }
  65052. return text;
  65053. }
  65054. function getTransformedPosition(axis, value, layoutInfo) {
  65055. var transform = create$1();
  65056. rotate(transform, transform, layoutInfo.rotation);
  65057. translate(transform, transform, layoutInfo.position);
  65058. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  65059. }
  65060. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  65061. // @ts-ignore
  65062. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  65063. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  65064. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  65065. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  65066. align: textLayout.textAlign,
  65067. verticalAlign: textLayout.textVerticalAlign
  65068. });
  65069. }
  65070. function makeLineShape(p1, p2, xDimIndex) {
  65071. xDimIndex = xDimIndex || 0;
  65072. return {
  65073. x1: p1[xDimIndex],
  65074. y1: p1[1 - xDimIndex],
  65075. x2: p2[xDimIndex],
  65076. y2: p2[1 - xDimIndex]
  65077. };
  65078. }
  65079. function makeRectShape(xy, wh, xDimIndex) {
  65080. xDimIndex = xDimIndex || 0;
  65081. return {
  65082. x: xy[xDimIndex],
  65083. y: xy[1 - xDimIndex],
  65084. width: wh[xDimIndex],
  65085. height: wh[1 - xDimIndex]
  65086. };
  65087. }
  65088. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  65089. return {
  65090. cx: cx,
  65091. cy: cy,
  65092. r0: r0,
  65093. r: r,
  65094. startAngle: startAngle,
  65095. endAngle: endAngle,
  65096. clockwise: true
  65097. };
  65098. }
  65099. var CartesianAxisPointer =
  65100. /** @class */
  65101. function (_super) {
  65102. __extends(CartesianAxisPointer, _super);
  65103. function CartesianAxisPointer() {
  65104. return _super !== null && _super.apply(this, arguments) || this;
  65105. }
  65106. /**
  65107. * @override
  65108. */
  65109. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  65110. var axis = axisModel.axis;
  65111. var grid = axis.grid;
  65112. var axisPointerType = axisPointerModel.get('type');
  65113. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  65114. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  65115. if (axisPointerType && axisPointerType !== 'none') {
  65116. var elStyle = buildElStyle(axisPointerModel);
  65117. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  65118. pointerOption.style = elStyle;
  65119. elOption.graphicKey = pointerOption.type;
  65120. elOption.pointer = pointerOption;
  65121. }
  65122. var layoutInfo = layout$1(grid.model, axisModel);
  65123. buildCartesianSingleLabelElOption( // @ts-ignore
  65124. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  65125. };
  65126. /**
  65127. * @override
  65128. */
  65129. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  65130. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  65131. labelInside: false
  65132. }); // @ts-ignore
  65133. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  65134. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  65135. return {
  65136. x: pos[0],
  65137. y: pos[1],
  65138. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  65139. };
  65140. };
  65141. /**
  65142. * @override
  65143. */
  65144. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  65145. var axis = axisModel.axis;
  65146. var grid = axis.grid;
  65147. var axisExtent = axis.getGlobalExtent(true);
  65148. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  65149. var dimIndex = axis.dim === 'x' ? 0 : 1;
  65150. var currPosition = [transform.x, transform.y];
  65151. currPosition[dimIndex] += delta[dimIndex];
  65152. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  65153. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  65154. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  65155. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  65156. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  65157. var tooltipOptions = [{
  65158. verticalAlign: 'middle'
  65159. }, {
  65160. align: 'center'
  65161. }];
  65162. return {
  65163. x: currPosition[0],
  65164. y: currPosition[1],
  65165. rotation: transform.rotation,
  65166. cursorPoint: cursorPoint,
  65167. tooltipOption: tooltipOptions[dimIndex]
  65168. };
  65169. };
  65170. return CartesianAxisPointer;
  65171. }(BaseAxisPointer);
  65172. function getCartesian(grid, axis) {
  65173. var opt = {};
  65174. opt[axis.dim + 'AxisIndex'] = axis.index;
  65175. return grid.getCartesian(opt);
  65176. }
  65177. var pointerShapeBuilder = {
  65178. line: function (axis, pixelValue, otherExtent) {
  65179. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  65180. return {
  65181. type: 'Line',
  65182. subPixelOptimize: true,
  65183. shape: targetShape
  65184. };
  65185. },
  65186. shadow: function (axis, pixelValue, otherExtent) {
  65187. var bandWidth = Math.max(1, axis.getBandWidth());
  65188. var span = otherExtent[1] - otherExtent[0];
  65189. return {
  65190. type: 'Rect',
  65191. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  65192. };
  65193. }
  65194. };
  65195. function getAxisDimIndex(axis) {
  65196. return axis.dim === 'x' ? 0 : 1;
  65197. }
  65198. var AxisPointerModel =
  65199. /** @class */
  65200. function (_super) {
  65201. __extends(AxisPointerModel, _super);
  65202. function AxisPointerModel() {
  65203. var _this = _super !== null && _super.apply(this, arguments) || this;
  65204. _this.type = AxisPointerModel.type;
  65205. return _this;
  65206. }
  65207. AxisPointerModel.type = 'axisPointer';
  65208. AxisPointerModel.defaultOption = {
  65209. // 'auto' means that show when triggered by tooltip or handle.
  65210. show: 'auto',
  65211. // zlevel: 0,
  65212. z: 50,
  65213. type: 'line',
  65214. // axispointer triggered by tootip determine snap automatically,
  65215. // see `modelHelper`.
  65216. snap: false,
  65217. triggerTooltip: true,
  65218. value: null,
  65219. status: null,
  65220. link: [],
  65221. // Do not set 'auto' here, otherwise global animation: false
  65222. // will not effect at this axispointer.
  65223. animation: null,
  65224. animationDurationUpdate: 200,
  65225. lineStyle: {
  65226. color: '#B9BEC9',
  65227. width: 1,
  65228. type: 'dashed'
  65229. },
  65230. shadowStyle: {
  65231. color: 'rgba(210,219,238,0.2)'
  65232. },
  65233. label: {
  65234. show: true,
  65235. formatter: null,
  65236. precision: 'auto',
  65237. margin: 3,
  65238. color: '#fff',
  65239. padding: [5, 7, 5, 7],
  65240. backgroundColor: 'auto',
  65241. borderColor: null,
  65242. borderWidth: 0,
  65243. borderRadius: 3
  65244. },
  65245. handle: {
  65246. show: false,
  65247. // eslint-disable-next-line
  65248. 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',
  65249. size: 45,
  65250. // handle margin is from symbol center to axis, which is stable when circular move.
  65251. margin: 50,
  65252. // color: '#1b8bbd'
  65253. // color: '#2f4554'
  65254. color: '#333',
  65255. shadowBlur: 3,
  65256. shadowColor: '#aaa',
  65257. shadowOffsetX: 0,
  65258. shadowOffsetY: 2,
  65259. // For mobile performance
  65260. throttle: 40
  65261. }
  65262. };
  65263. return AxisPointerModel;
  65264. }(ComponentModel);
  65265. var inner$b = makeInner();
  65266. var each$7 = each;
  65267. /**
  65268. * @param {string} key
  65269. * @param {module:echarts/ExtensionAPI} api
  65270. * @param {Function} handler
  65271. * param: {string} currTrigger
  65272. * param: {Array.<number>} point
  65273. */
  65274. function register(key, api, handler) {
  65275. if (env.node) {
  65276. return;
  65277. }
  65278. var zr = api.getZr();
  65279. inner$b(zr).records || (inner$b(zr).records = {});
  65280. initGlobalListeners(zr, api);
  65281. var record = inner$b(zr).records[key] || (inner$b(zr).records[key] = {});
  65282. record.handler = handler;
  65283. }
  65284. function initGlobalListeners(zr, api) {
  65285. if (inner$b(zr).initialized) {
  65286. return;
  65287. }
  65288. inner$b(zr).initialized = true;
  65289. useHandler('click', curry(doEnter, 'click'));
  65290. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  65291. useHandler('globalout', onLeave);
  65292. function useHandler(eventType, cb) {
  65293. zr.on(eventType, function (e) {
  65294. var dis = makeDispatchAction(api);
  65295. each$7(inner$b(zr).records, function (record) {
  65296. record && cb(record, e, dis.dispatchAction);
  65297. });
  65298. dispatchTooltipFinally(dis.pendings, api);
  65299. });
  65300. }
  65301. }
  65302. function dispatchTooltipFinally(pendings, api) {
  65303. var showLen = pendings.showTip.length;
  65304. var hideLen = pendings.hideTip.length;
  65305. var actuallyPayload;
  65306. if (showLen) {
  65307. actuallyPayload = pendings.showTip[showLen - 1];
  65308. } else if (hideLen) {
  65309. actuallyPayload = pendings.hideTip[hideLen - 1];
  65310. }
  65311. if (actuallyPayload) {
  65312. actuallyPayload.dispatchAction = null;
  65313. api.dispatchAction(actuallyPayload);
  65314. }
  65315. }
  65316. function onLeave(record, e, dispatchAction) {
  65317. record.handler('leave', null, dispatchAction);
  65318. }
  65319. function doEnter(currTrigger, record, e, dispatchAction) {
  65320. record.handler(currTrigger, e, dispatchAction);
  65321. }
  65322. function makeDispatchAction(api) {
  65323. var pendings = {
  65324. showTip: [],
  65325. hideTip: []
  65326. }; // FIXME
  65327. // better approach?
  65328. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  65329. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  65330. // So we have to add "final stage" to merge those dispatched actions.
  65331. var dispatchAction = function (payload) {
  65332. var pendingList = pendings[payload.type];
  65333. if (pendingList) {
  65334. pendingList.push(payload);
  65335. } else {
  65336. payload.dispatchAction = dispatchAction;
  65337. api.dispatchAction(payload);
  65338. }
  65339. };
  65340. return {
  65341. dispatchAction: dispatchAction,
  65342. pendings: pendings
  65343. };
  65344. }
  65345. function unregister(key, api) {
  65346. if (env.node) {
  65347. return;
  65348. }
  65349. var zr = api.getZr();
  65350. var record = (inner$b(zr).records || {})[key];
  65351. if (record) {
  65352. inner$b(zr).records[key] = null;
  65353. }
  65354. }
  65355. var AxisPointerView =
  65356. /** @class */
  65357. function (_super) {
  65358. __extends(AxisPointerView, _super);
  65359. function AxisPointerView() {
  65360. var _this = _super !== null && _super.apply(this, arguments) || this;
  65361. _this.type = AxisPointerView.type;
  65362. return _this;
  65363. }
  65364. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  65365. var globalTooltipModel = ecModel.getComponent('tooltip');
  65366. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  65367. // AxisPointerView to be independent to Tooltip.
  65368. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  65369. // If 'none', it is not controlled by mouse totally.
  65370. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  65371. dispatchAction({
  65372. type: 'updateAxisPointer',
  65373. currTrigger: currTrigger,
  65374. x: e && e.offsetX,
  65375. y: e && e.offsetY
  65376. });
  65377. }
  65378. });
  65379. };
  65380. AxisPointerView.prototype.remove = function (ecModel, api) {
  65381. unregister('axisPointer', api);
  65382. };
  65383. AxisPointerView.prototype.dispose = function (ecModel, api) {
  65384. unregister('axisPointer', api);
  65385. };
  65386. AxisPointerView.type = 'axisPointer';
  65387. return AxisPointerView;
  65388. }(ComponentView);
  65389. /**
  65390. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  65391. * @param ecModel
  65392. * @return {point: [x, y], el: ...} point Will not be null.
  65393. */
  65394. function findPointFromSeries(finder, ecModel) {
  65395. var point = [];
  65396. var seriesIndex = finder.seriesIndex;
  65397. var seriesModel;
  65398. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  65399. return {
  65400. point: []
  65401. };
  65402. }
  65403. var data = seriesModel.getData();
  65404. var dataIndex = queryDataIndex(data, finder);
  65405. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  65406. return {
  65407. point: []
  65408. };
  65409. }
  65410. var el = data.getItemGraphicEl(dataIndex);
  65411. var coordSys = seriesModel.coordinateSystem;
  65412. if (seriesModel.getTooltipPosition) {
  65413. point = seriesModel.getTooltipPosition(dataIndex) || [];
  65414. } else if (coordSys && coordSys.dataToPoint) {
  65415. if (finder.isStacked) {
  65416. var baseAxis = coordSys.getBaseAxis();
  65417. var valueAxis = coordSys.getOtherAxis(baseAxis);
  65418. var valueAxisDim = valueAxis.dim;
  65419. var baseAxisDim = baseAxis.dim;
  65420. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  65421. var baseDim = data.mapDimension(baseAxisDim);
  65422. var stackedData = [];
  65423. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  65424. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  65425. point = coordSys.dataToPoint(stackedData) || [];
  65426. } else {
  65427. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  65428. return data.mapDimension(dim);
  65429. }), dataIndex)) || [];
  65430. }
  65431. } else if (el) {
  65432. // Use graphic bounding rect
  65433. var rect = el.getBoundingRect().clone();
  65434. rect.applyTransform(el.transform);
  65435. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  65436. }
  65437. return {
  65438. point: point,
  65439. el: el
  65440. };
  65441. }
  65442. var inner$c = makeInner();
  65443. /**
  65444. * Basic logic: check all axis, if they do not demand show/highlight,
  65445. * then hide/downplay them.
  65446. *
  65447. * @return content of event obj for echarts.connect.
  65448. */
  65449. function axisTrigger(payload, ecModel, api) {
  65450. var currTrigger = payload.currTrigger;
  65451. var point = [payload.x, payload.y];
  65452. var finder = payload;
  65453. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  65454. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  65455. // See #6121. But we are not able to reproduce it yet.
  65456. if (!coordSysAxesInfo) {
  65457. return;
  65458. }
  65459. if (illegalPoint(point)) {
  65460. // Used in the default behavior of `connection`: use the sample seriesIndex
  65461. // and dataIndex. And also used in the tooltipView trigger.
  65462. point = findPointFromSeries({
  65463. seriesIndex: finder.seriesIndex,
  65464. // Do not use dataIndexInside from other ec instance.
  65465. // FIXME: auto detect it?
  65466. dataIndex: finder.dataIndex
  65467. }, ecModel).point;
  65468. }
  65469. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  65470. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  65471. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  65472. // and dataIndex.
  65473. var inputAxesInfo = finder.axesInfo;
  65474. var axesInfo = coordSysAxesInfo.axesInfo;
  65475. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  65476. var outputPayload = {};
  65477. var showValueMap = {};
  65478. var dataByCoordSys = {
  65479. list: [],
  65480. map: {}
  65481. };
  65482. var updaters = {
  65483. showPointer: curry(showPointer, showValueMap),
  65484. showTooltip: curry(showTooltip, dataByCoordSys)
  65485. }; // Process for triggered axes.
  65486. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  65487. // If a point given, it must be contained by the coordinate system.
  65488. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  65489. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  65490. var axis = axisInfo.axis;
  65491. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  65492. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  65493. var val = inputAxisInfo && inputAxisInfo.value;
  65494. if (val == null && !isIllegalPoint) {
  65495. val = axis.pointToData(point);
  65496. }
  65497. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  65498. }
  65499. });
  65500. }); // Process for linked axes.
  65501. var linkTriggers = {};
  65502. each(axesInfo, function (tarAxisInfo, tarKey) {
  65503. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  65504. if (linkGroup && !showValueMap[tarKey]) {
  65505. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  65506. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  65507. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  65508. var val = srcValItem.value;
  65509. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  65510. linkTriggers[tarAxisInfo.key] = val;
  65511. }
  65512. });
  65513. }
  65514. });
  65515. each(linkTriggers, function (val, tarKey) {
  65516. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  65517. });
  65518. updateModelActually(showValueMap, axesInfo, outputPayload);
  65519. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  65520. dispatchHighDownActually(axesInfo, dispatchAction, api);
  65521. return outputPayload;
  65522. }
  65523. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  65524. var axis = axisInfo.axis;
  65525. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  65526. return;
  65527. }
  65528. if (!axisInfo.involveSeries) {
  65529. updaters.showPointer(axisInfo, newValue);
  65530. return;
  65531. } // Heavy calculation. So put it after axis.containData checking.
  65532. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  65533. var payloadBatch = payloadInfo.payloadBatch;
  65534. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  65535. // By default use the first involved series data as a sample to connect.
  65536. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  65537. extend(outputFinder, payloadBatch[0]);
  65538. } // If no linkSource input, this process is for collecting link
  65539. // target, where snap should not be accepted.
  65540. if (!noSnap && axisInfo.snap) {
  65541. if (axis.containData(snapToValue) && snapToValue != null) {
  65542. newValue = snapToValue;
  65543. }
  65544. }
  65545. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  65546. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  65547. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  65548. }
  65549. function buildPayloadsBySeries(value, axisInfo) {
  65550. var axis = axisInfo.axis;
  65551. var dim = axis.dim;
  65552. var snapToValue = value;
  65553. var payloadBatch = [];
  65554. var minDist = Number.MAX_VALUE;
  65555. var minDiff = -1;
  65556. each(axisInfo.seriesModels, function (series, idx) {
  65557. var dataDim = series.getData().mapDimensionsAll(dim);
  65558. var seriesNestestValue;
  65559. var dataIndices;
  65560. if (series.getAxisTooltipData) {
  65561. var result = series.getAxisTooltipData(dataDim, value, axis);
  65562. dataIndices = result.dataIndices;
  65563. seriesNestestValue = result.nestestValue;
  65564. } else {
  65565. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  65566. // when data length is not same.
  65567. // false,
  65568. axis.type === 'category' ? 0.5 : null);
  65569. if (!dataIndices.length) {
  65570. return;
  65571. }
  65572. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  65573. }
  65574. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  65575. return;
  65576. }
  65577. var diff = value - seriesNestestValue;
  65578. var dist = Math.abs(diff); // Consider category case
  65579. if (dist <= minDist) {
  65580. if (dist < minDist || diff >= 0 && minDiff < 0) {
  65581. minDist = dist;
  65582. minDiff = diff;
  65583. snapToValue = seriesNestestValue;
  65584. payloadBatch.length = 0;
  65585. }
  65586. each(dataIndices, function (dataIndex) {
  65587. payloadBatch.push({
  65588. seriesIndex: series.seriesIndex,
  65589. dataIndexInside: dataIndex,
  65590. dataIndex: series.getData().getRawIndex(dataIndex)
  65591. });
  65592. });
  65593. }
  65594. });
  65595. return {
  65596. payloadBatch: payloadBatch,
  65597. snapToValue: snapToValue
  65598. };
  65599. }
  65600. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  65601. showValueMap[axisInfo.key] = {
  65602. value: value,
  65603. payloadBatch: payloadBatch
  65604. };
  65605. }
  65606. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  65607. var payloadBatch = payloadInfo.payloadBatch;
  65608. var axis = axisInfo.axis;
  65609. var axisModel = axis.model;
  65610. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  65611. // whose length will be used to judge whether dispatch action.
  65612. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  65613. return;
  65614. }
  65615. var coordSysModel = axisInfo.coordSys.model;
  65616. var coordSysKey = makeKey(coordSysModel);
  65617. var coordSysItem = dataByCoordSys.map[coordSysKey];
  65618. if (!coordSysItem) {
  65619. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  65620. coordSysId: coordSysModel.id,
  65621. coordSysIndex: coordSysModel.componentIndex,
  65622. coordSysType: coordSysModel.type,
  65623. coordSysMainType: coordSysModel.mainType,
  65624. dataByAxis: []
  65625. };
  65626. dataByCoordSys.list.push(coordSysItem);
  65627. }
  65628. coordSysItem.dataByAxis.push({
  65629. axisDim: axis.dim,
  65630. axisIndex: axisModel.componentIndex,
  65631. axisType: axisModel.type,
  65632. axisId: axisModel.id,
  65633. value: value,
  65634. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  65635. // depends that all models have been updated. So it should not be performed
  65636. // here. Considering axisPointerModel used here is volatile, which is hard
  65637. // to be retrieve in TooltipView, we prepare parameters here.
  65638. valueLabelOpt: {
  65639. precision: axisPointerModel.get(['label', 'precision']),
  65640. formatter: axisPointerModel.get(['label', 'formatter'])
  65641. },
  65642. seriesDataIndices: payloadBatch.slice()
  65643. });
  65644. }
  65645. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  65646. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  65647. each(axesInfo, function (axisInfo, key) {
  65648. var option = axisInfo.axisPointerModel.option;
  65649. var valItem = showValueMap[key];
  65650. if (valItem) {
  65651. !axisInfo.useHandle && (option.status = 'show');
  65652. option.value = valItem.value; // For label formatter param and highlight.
  65653. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  65654. } // When always show (e.g., handle used), remain
  65655. // original value and status.
  65656. else {
  65657. // If hide, value still need to be set, consider
  65658. // click legend to toggle axis blank.
  65659. !axisInfo.useHandle && (option.status = 'hide');
  65660. } // If status is 'hide', should be no info in payload.
  65661. option.status === 'show' && outputAxesInfo.push({
  65662. axisDim: axisInfo.axis.dim,
  65663. axisIndex: axisInfo.axis.model.componentIndex,
  65664. value: option.value
  65665. });
  65666. });
  65667. }
  65668. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  65669. // Basic logic: If no showTip required, hideTip will be dispatched.
  65670. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  65671. dispatchAction({
  65672. type: 'hideTip'
  65673. });
  65674. return;
  65675. } // In most case only one axis (or event one series is used). It is
  65676. // convenient to fetch payload.seriesIndex and payload.dataIndex
  65677. // directly. So put the first seriesIndex and dataIndex of the first
  65678. // axis on the payload.
  65679. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  65680. dispatchAction({
  65681. type: 'showTip',
  65682. escapeConnect: true,
  65683. x: point[0],
  65684. y: point[1],
  65685. tooltipOption: payload.tooltipOption,
  65686. position: payload.position,
  65687. dataIndexInside: sampleItem.dataIndexInside,
  65688. dataIndex: sampleItem.dataIndex,
  65689. seriesIndex: sampleItem.seriesIndex,
  65690. dataByCoordSys: dataByCoordSys.list
  65691. });
  65692. }
  65693. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  65694. // FIXME
  65695. // highlight status modification should be a stage of main process?
  65696. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  65697. var zr = api.getZr();
  65698. var highDownKey = 'axisPointerLastHighlights';
  65699. var lastHighlights = inner$c(zr)[highDownKey] || {};
  65700. var newHighlights = inner$c(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  65701. // Build hash map and remove duplicate incidentally.
  65702. each(axesInfo, function (axisInfo, key) {
  65703. var option = axisInfo.axisPointerModel.option;
  65704. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  65705. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  65706. newHighlights[key] = batchItem;
  65707. });
  65708. }); // Diff.
  65709. var toHighlight = [];
  65710. var toDownplay = [];
  65711. each(lastHighlights, function (batchItem, key) {
  65712. !newHighlights[key] && toDownplay.push(batchItem);
  65713. });
  65714. each(newHighlights, function (batchItem, key) {
  65715. !lastHighlights[key] && toHighlight.push(batchItem);
  65716. });
  65717. toDownplay.length && api.dispatchAction({
  65718. type: 'downplay',
  65719. escapeConnect: true,
  65720. // Not blur others when highlight in axisPointer.
  65721. notBlur: true,
  65722. batch: toDownplay
  65723. });
  65724. toHighlight.length && api.dispatchAction({
  65725. type: 'highlight',
  65726. escapeConnect: true,
  65727. // Not blur others when highlight in axisPointer.
  65728. notBlur: true,
  65729. batch: toHighlight
  65730. });
  65731. }
  65732. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  65733. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  65734. var inputAxisInfo = inputAxesInfo[i];
  65735. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  65736. return inputAxisInfo;
  65737. }
  65738. }
  65739. }
  65740. function makeMapperParam(axisInfo) {
  65741. var axisModel = axisInfo.axis.model;
  65742. var item = {};
  65743. var dim = item.axisDim = axisInfo.axis.dim;
  65744. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  65745. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  65746. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  65747. return item;
  65748. }
  65749. function illegalPoint(point) {
  65750. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  65751. }
  65752. function install$s(registers) {
  65753. // CartesianAxisPointer is not supposed to be required here. But consider
  65754. // echarts.simple.js and online build tooltip, which only require gridSimple,
  65755. // CartesianAxisPointer should be able to required somewhere.
  65756. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  65757. registers.registerComponentModel(AxisPointerModel);
  65758. registers.registerComponentView(AxisPointerView);
  65759. registers.registerPreprocessor(function (option) {
  65760. // Always has a global axisPointerModel for default setting.
  65761. if (option) {
  65762. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  65763. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  65764. // is not set, remain null/undefined, otherwise it will
  65765. // override existent link setting.
  65766. if (link && !isArray(link)) {
  65767. option.axisPointer.link = [link];
  65768. }
  65769. }
  65770. }); // This process should proformed after coordinate systems created
  65771. // and series data processed. So put it on statistic processing stage.
  65772. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  65773. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  65774. // allAxesInfo should be updated when setOption performed.
  65775. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  65776. }); // Broadcast to all views.
  65777. registers.registerAction({
  65778. type: 'updateAxisPointer',
  65779. event: 'updateAxisPointer',
  65780. update: ':updateAxisPointer'
  65781. }, axisTrigger);
  65782. }
  65783. function install$t(registers) {
  65784. use(install$5);
  65785. use(install$s);
  65786. }
  65787. var PolarAxisPointer =
  65788. /** @class */
  65789. function (_super) {
  65790. __extends(PolarAxisPointer, _super);
  65791. function PolarAxisPointer() {
  65792. return _super !== null && _super.apply(this, arguments) || this;
  65793. }
  65794. /**
  65795. * @override
  65796. */
  65797. PolarAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  65798. var axis = axisModel.axis;
  65799. if (axis.dim === 'angle') {
  65800. this.animationThreshold = Math.PI / 18;
  65801. }
  65802. var polar = axis.polar;
  65803. var otherAxis = polar.getOtherAxis(axis);
  65804. var otherExtent = otherAxis.getExtent();
  65805. var coordValue = axis.dataToCoord(value);
  65806. var axisPointerType = axisPointerModel.get('type');
  65807. if (axisPointerType && axisPointerType !== 'none') {
  65808. var elStyle = buildElStyle(axisPointerModel);
  65809. var pointerOption = pointerShapeBuilder$1[axisPointerType](axis, polar, coordValue, otherExtent);
  65810. pointerOption.style = elStyle;
  65811. elOption.graphicKey = pointerOption.type;
  65812. elOption.pointer = pointerOption;
  65813. }
  65814. var labelMargin = axisPointerModel.get(['label', 'margin']);
  65815. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  65816. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  65817. };
  65818. return PolarAxisPointer;
  65819. }(BaseAxisPointer);
  65820. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  65821. var axis = axisModel.axis;
  65822. var coord = axis.dataToCoord(value);
  65823. var axisAngle = polar.getAngleAxis().getExtent()[0];
  65824. axisAngle = axisAngle / 180 * Math.PI;
  65825. var radiusExtent = polar.getRadiusAxis().getExtent();
  65826. var position;
  65827. var align;
  65828. var verticalAlign;
  65829. if (axis.dim === 'radius') {
  65830. var transform = create$1();
  65831. rotate(transform, transform, axisAngle);
  65832. translate(transform, transform, [polar.cx, polar.cy]);
  65833. position = applyTransform$1([coord, -labelMargin], transform);
  65834. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0; // @ts-ignore
  65835. var labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1);
  65836. align = labelLayout.textAlign;
  65837. verticalAlign = labelLayout.textVerticalAlign;
  65838. } else {
  65839. // angle axis
  65840. var r = radiusExtent[1];
  65841. position = polar.coordToPoint([r + labelMargin, coord]);
  65842. var cx = polar.cx;
  65843. var cy = polar.cy;
  65844. align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right';
  65845. verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom';
  65846. }
  65847. return {
  65848. position: position,
  65849. align: align,
  65850. verticalAlign: verticalAlign
  65851. };
  65852. }
  65853. var pointerShapeBuilder$1 = {
  65854. line: function (axis, polar, coordValue, otherExtent) {
  65855. return axis.dim === 'angle' ? {
  65856. type: 'Line',
  65857. shape: makeLineShape(polar.coordToPoint([otherExtent[0], coordValue]), polar.coordToPoint([otherExtent[1], coordValue]))
  65858. } : {
  65859. type: 'Circle',
  65860. shape: {
  65861. cx: polar.cx,
  65862. cy: polar.cy,
  65863. r: coordValue
  65864. }
  65865. };
  65866. },
  65867. shadow: function (axis, polar, coordValue, otherExtent) {
  65868. var bandWidth = Math.max(1, axis.getBandWidth());
  65869. var radian = Math.PI / 180;
  65870. return axis.dim === 'angle' ? {
  65871. type: 'Sector',
  65872. shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], // In ECharts y is negative if angle is positive
  65873. (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian)
  65874. } : {
  65875. type: 'Sector',
  65876. shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, Math.PI * 2)
  65877. };
  65878. }
  65879. };
  65880. var PolarModel =
  65881. /** @class */
  65882. function (_super) {
  65883. __extends(PolarModel, _super);
  65884. function PolarModel() {
  65885. var _this = _super !== null && _super.apply(this, arguments) || this;
  65886. _this.type = PolarModel.type;
  65887. return _this;
  65888. }
  65889. PolarModel.prototype.findAxisModel = function (axisType) {
  65890. var foundAxisModel;
  65891. var ecModel = this.ecModel;
  65892. ecModel.eachComponent(axisType, function (axisModel) {
  65893. if (axisModel.getCoordSysModel() === this) {
  65894. foundAxisModel = axisModel;
  65895. }
  65896. }, this);
  65897. return foundAxisModel;
  65898. };
  65899. PolarModel.type = 'polar';
  65900. PolarModel.dependencies = ['radiusAxis', 'angleAxis'];
  65901. PolarModel.defaultOption = {
  65902. // zlevel: 0,
  65903. z: 0,
  65904. center: ['50%', '50%'],
  65905. radius: '80%'
  65906. };
  65907. return PolarModel;
  65908. }(ComponentModel);
  65909. var PolarAxisModel =
  65910. /** @class */
  65911. function (_super) {
  65912. __extends(PolarAxisModel, _super);
  65913. function PolarAxisModel() {
  65914. return _super !== null && _super.apply(this, arguments) || this;
  65915. }
  65916. PolarAxisModel.prototype.getCoordSysModel = function () {
  65917. return this.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  65918. };
  65919. PolarAxisModel.type = 'polarAxis';
  65920. return PolarAxisModel;
  65921. }(ComponentModel);
  65922. mixin(PolarAxisModel, AxisModelCommonMixin);
  65923. var AngleAxisModel =
  65924. /** @class */
  65925. function (_super) {
  65926. __extends(AngleAxisModel, _super);
  65927. function AngleAxisModel() {
  65928. var _this = _super !== null && _super.apply(this, arguments) || this;
  65929. _this.type = AngleAxisModel.type;
  65930. return _this;
  65931. }
  65932. AngleAxisModel.type = 'angleAxis';
  65933. return AngleAxisModel;
  65934. }(PolarAxisModel);
  65935. var RadiusAxisModel =
  65936. /** @class */
  65937. function (_super) {
  65938. __extends(RadiusAxisModel, _super);
  65939. function RadiusAxisModel() {
  65940. var _this = _super !== null && _super.apply(this, arguments) || this;
  65941. _this.type = RadiusAxisModel.type;
  65942. return _this;
  65943. }
  65944. RadiusAxisModel.type = 'radiusAxis';
  65945. return RadiusAxisModel;
  65946. }(PolarAxisModel);
  65947. var RadiusAxis =
  65948. /** @class */
  65949. function (_super) {
  65950. __extends(RadiusAxis, _super);
  65951. function RadiusAxis(scale, radiusExtent) {
  65952. return _super.call(this, 'radius', scale, radiusExtent) || this;
  65953. }
  65954. RadiusAxis.prototype.pointToData = function (point, clamp) {
  65955. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65956. };
  65957. return RadiusAxis;
  65958. }(Axis);
  65959. RadiusAxis.prototype.dataToRadius = Axis.prototype.dataToCoord;
  65960. RadiusAxis.prototype.radiusToData = Axis.prototype.coordToData;
  65961. var inner$d = makeInner();
  65962. var AngleAxis =
  65963. /** @class */
  65964. function (_super) {
  65965. __extends(AngleAxis, _super);
  65966. function AngleAxis(scale, angleExtent) {
  65967. return _super.call(this, 'angle', scale, angleExtent || [0, 360]) || this;
  65968. }
  65969. AngleAxis.prototype.pointToData = function (point, clamp) {
  65970. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65971. };
  65972. /**
  65973. * Only be called in category axis.
  65974. * Angle axis uses text height to decide interval
  65975. *
  65976. * @override
  65977. * @return {number} Auto interval for cateogry axis tick and label
  65978. */
  65979. AngleAxis.prototype.calculateCategoryInterval = function () {
  65980. var axis = this;
  65981. var labelModel = axis.getLabelModel();
  65982. var ordinalScale = axis.scale;
  65983. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  65984. // avoid generating a long array by `getTicks`
  65985. // in large category data case.
  65986. var tickCount = ordinalScale.count();
  65987. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  65988. return 0;
  65989. }
  65990. var tickValue = ordinalExtent[0];
  65991. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  65992. var unitH = Math.abs(unitSpan); // Not precise, just use height as text width
  65993. // and each distance from axis line yet.
  65994. var rect = getBoundingRect(tickValue == null ? '' : tickValue + '', labelModel.getFont(), 'center', 'top');
  65995. var maxH = Math.max(rect.height, 7);
  65996. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  65997. isNaN(dh) && (dh = Infinity);
  65998. var interval = Math.max(0, Math.floor(dh));
  65999. var cache = inner$d(axis.model);
  66000. var lastAutoInterval = cache.lastAutoInterval;
  66001. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  66002. // otherwise the calculated interval might jitter when the zoom
  66003. // window size is close to the interval-changing size.
  66004. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  66005. // point is not the same when zooming in or zooming out.
  66006. && lastAutoInterval > interval) {
  66007. interval = lastAutoInterval;
  66008. } // Only update cache if cache not used, otherwise the
  66009. // changing of interval is too insensitive.
  66010. else {
  66011. cache.lastTickCount = tickCount;
  66012. cache.lastAutoInterval = interval;
  66013. }
  66014. return interval;
  66015. };
  66016. return AngleAxis;
  66017. }(Axis);
  66018. AngleAxis.prototype.dataToAngle = Axis.prototype.dataToCoord;
  66019. AngleAxis.prototype.angleToData = Axis.prototype.coordToData;
  66020. var polarDimensions = ['radius', 'angle'];
  66021. var Polar =
  66022. /** @class */
  66023. function () {
  66024. function Polar(name) {
  66025. this.dimensions = polarDimensions;
  66026. this.type = 'polar';
  66027. /**
  66028. * x of polar center
  66029. */
  66030. this.cx = 0;
  66031. /**
  66032. * y of polar center
  66033. */
  66034. this.cy = 0;
  66035. this._radiusAxis = new RadiusAxis();
  66036. this._angleAxis = new AngleAxis();
  66037. this.axisPointerEnabled = true;
  66038. this.name = name || '';
  66039. this._radiusAxis.polar = this._angleAxis.polar = this;
  66040. }
  66041. /**
  66042. * If contain coord
  66043. */
  66044. Polar.prototype.containPoint = function (point) {
  66045. var coord = this.pointToCoord(point);
  66046. return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]);
  66047. };
  66048. /**
  66049. * If contain data
  66050. */
  66051. Polar.prototype.containData = function (data) {
  66052. return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]);
  66053. };
  66054. Polar.prototype.getAxis = function (dim) {
  66055. var key = '_' + dim + 'Axis';
  66056. return this[key];
  66057. };
  66058. Polar.prototype.getAxes = function () {
  66059. return [this._radiusAxis, this._angleAxis];
  66060. };
  66061. /**
  66062. * Get axes by type of scale
  66063. */
  66064. Polar.prototype.getAxesByScale = function (scaleType) {
  66065. var axes = [];
  66066. var angleAxis = this._angleAxis;
  66067. var radiusAxis = this._radiusAxis;
  66068. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  66069. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  66070. return axes;
  66071. };
  66072. Polar.prototype.getAngleAxis = function () {
  66073. return this._angleAxis;
  66074. };
  66075. Polar.prototype.getRadiusAxis = function () {
  66076. return this._radiusAxis;
  66077. };
  66078. Polar.prototype.getOtherAxis = function (axis) {
  66079. var angleAxis = this._angleAxis;
  66080. return axis === angleAxis ? this._radiusAxis : angleAxis;
  66081. };
  66082. /**
  66083. * Base axis will be used on stacking.
  66084. *
  66085. */
  66086. Polar.prototype.getBaseAxis = function () {
  66087. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis();
  66088. };
  66089. Polar.prototype.getTooltipAxes = function (dim) {
  66090. var baseAxis = dim != null && dim !== 'auto' ? this.getAxis(dim) : this.getBaseAxis();
  66091. return {
  66092. baseAxes: [baseAxis],
  66093. otherAxes: [this.getOtherAxis(baseAxis)]
  66094. };
  66095. };
  66096. /**
  66097. * Convert a single data item to (x, y) point.
  66098. * Parameter data is an array which the first element is radius and the second is angle
  66099. */
  66100. Polar.prototype.dataToPoint = function (data, clamp) {
  66101. return this.coordToPoint([this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp)]);
  66102. };
  66103. /**
  66104. * Convert a (x, y) point to data
  66105. */
  66106. Polar.prototype.pointToData = function (point, clamp) {
  66107. var coord = this.pointToCoord(point);
  66108. return [this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp)];
  66109. };
  66110. /**
  66111. * Convert a (x, y) point to (radius, angle) coord
  66112. */
  66113. Polar.prototype.pointToCoord = function (point) {
  66114. var dx = point[0] - this.cx;
  66115. var dy = point[1] - this.cy;
  66116. var angleAxis = this.getAngleAxis();
  66117. var extent = angleAxis.getExtent();
  66118. var minAngle = Math.min(extent[0], extent[1]);
  66119. var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator
  66120. // FIXME
  66121. angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360;
  66122. var radius = Math.sqrt(dx * dx + dy * dy);
  66123. dx /= radius;
  66124. dy /= radius;
  66125. var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent
  66126. var dir = radian < minAngle ? 1 : -1;
  66127. while (radian < minAngle || radian > maxAngle) {
  66128. radian += dir * 360;
  66129. }
  66130. return [radius, radian];
  66131. };
  66132. /**
  66133. * Convert a (radius, angle) coord to (x, y) point
  66134. */
  66135. Polar.prototype.coordToPoint = function (coord) {
  66136. var radius = coord[0];
  66137. var radian = coord[1] / 180 * Math.PI;
  66138. var x = Math.cos(radian) * radius + this.cx; // Inverse the y
  66139. var y = -Math.sin(radian) * radius + this.cy;
  66140. return [x, y];
  66141. };
  66142. /**
  66143. * Get ring area of cartesian.
  66144. * Area will have a contain function to determine if a point is in the coordinate system.
  66145. */
  66146. Polar.prototype.getArea = function () {
  66147. var angleAxis = this.getAngleAxis();
  66148. var radiusAxis = this.getRadiusAxis();
  66149. var radiusExtent = radiusAxis.getExtent().slice();
  66150. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  66151. var angleExtent = angleAxis.getExtent();
  66152. var RADIAN = Math.PI / 180;
  66153. return {
  66154. cx: this.cx,
  66155. cy: this.cy,
  66156. r0: radiusExtent[0],
  66157. r: radiusExtent[1],
  66158. startAngle: -angleExtent[0] * RADIAN,
  66159. endAngle: -angleExtent[1] * RADIAN,
  66160. clockwise: angleAxis.inverse,
  66161. contain: function (x, y) {
  66162. // It's a ring shape.
  66163. // Start angle and end angle don't matter
  66164. var dx = x - this.cx;
  66165. var dy = y - this.cy; // minus a tiny value 1e-4 to avoid being clipped unexpectedly
  66166. var d2 = dx * dx + dy * dy - 1e-4;
  66167. var r = this.r;
  66168. var r0 = this.r0;
  66169. return d2 <= r * r && d2 >= r0 * r0;
  66170. }
  66171. };
  66172. };
  66173. Polar.prototype.convertToPixel = function (ecModel, finder, value) {
  66174. var coordSys = getCoordSys$2(finder);
  66175. return coordSys === this ? this.dataToPoint(value) : null;
  66176. };
  66177. Polar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  66178. var coordSys = getCoordSys$2(finder);
  66179. return coordSys === this ? this.pointToData(pixel) : null;
  66180. };
  66181. return Polar;
  66182. }();
  66183. function getCoordSys$2(finder) {
  66184. var seriesModel = finder.seriesModel;
  66185. var polarModel = finder.polarModel;
  66186. return polarModel && polarModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  66187. }
  66188. /**
  66189. * Resize method bound to the polar
  66190. */
  66191. function resizePolar(polar, polarModel, api) {
  66192. var center = polarModel.get('center');
  66193. var width = api.getWidth();
  66194. var height = api.getHeight();
  66195. polar.cx = parsePercent$1(center[0], width);
  66196. polar.cy = parsePercent$1(center[1], height);
  66197. var radiusAxis = polar.getRadiusAxis();
  66198. var size = Math.min(width, height) / 2;
  66199. var radius = polarModel.get('radius');
  66200. if (radius == null) {
  66201. radius = [0, '100%'];
  66202. } else if (!isArray(radius)) {
  66203. // r0 = 0
  66204. radius = [0, radius];
  66205. }
  66206. var parsedRadius = [parsePercent$1(radius[0], size), parsePercent$1(radius[1], size)];
  66207. radiusAxis.inverse ? radiusAxis.setExtent(parsedRadius[1], parsedRadius[0]) : radiusAxis.setExtent(parsedRadius[0], parsedRadius[1]);
  66208. }
  66209. /**
  66210. * Update polar
  66211. */
  66212. function updatePolarScale(ecModel, api) {
  66213. var polar = this;
  66214. var angleAxis = polar.getAngleAxis();
  66215. var radiusAxis = polar.getRadiusAxis(); // Reset scale
  66216. angleAxis.scale.setExtent(Infinity, -Infinity);
  66217. radiusAxis.scale.setExtent(Infinity, -Infinity);
  66218. ecModel.eachSeries(function (seriesModel) {
  66219. if (seriesModel.coordinateSystem === polar) {
  66220. var data_1 = seriesModel.getData();
  66221. each(getDataDimensionsOnAxis(data_1, 'radius'), function (dim) {
  66222. radiusAxis.scale.unionExtentFromData(data_1, dim);
  66223. });
  66224. each(getDataDimensionsOnAxis(data_1, 'angle'), function (dim) {
  66225. angleAxis.scale.unionExtentFromData(data_1, dim);
  66226. });
  66227. }
  66228. });
  66229. niceScaleExtent(angleAxis.scale, angleAxis.model);
  66230. niceScaleExtent(radiusAxis.scale, radiusAxis.model); // Fix extent of category angle axis
  66231. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  66232. var extent = angleAxis.getExtent();
  66233. var diff = 360 / angleAxis.scale.count();
  66234. angleAxis.inverse ? extent[1] += diff : extent[1] -= diff;
  66235. angleAxis.setExtent(extent[0], extent[1]);
  66236. }
  66237. }
  66238. function isAngleAxisModel(axisModel) {
  66239. return axisModel.mainType === 'angleAxis';
  66240. }
  66241. /**
  66242. * Set common axis properties
  66243. */
  66244. function setAxis(axis, axisModel) {
  66245. axis.type = axisModel.get('type');
  66246. axis.scale = createScaleByModel(axisModel);
  66247. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  66248. axis.inverse = axisModel.get('inverse');
  66249. if (isAngleAxisModel(axisModel)) {
  66250. axis.inverse = axis.inverse !== axisModel.get('clockwise');
  66251. var startAngle = axisModel.get('startAngle');
  66252. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  66253. } // Inject axis instance
  66254. axisModel.axis = axis;
  66255. axis.model = axisModel;
  66256. }
  66257. var polarCreator = {
  66258. dimensions: polarDimensions,
  66259. create: function (ecModel, api) {
  66260. var polarList = [];
  66261. ecModel.eachComponent('polar', function (polarModel, idx) {
  66262. var polar = new Polar(idx + ''); // Inject resize and update method
  66263. polar.update = updatePolarScale;
  66264. var radiusAxis = polar.getRadiusAxis();
  66265. var angleAxis = polar.getAngleAxis();
  66266. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  66267. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  66268. setAxis(radiusAxis, radiusAxisModel);
  66269. setAxis(angleAxis, angleAxisModel);
  66270. resizePolar(polar, polarModel, api);
  66271. polarList.push(polar);
  66272. polarModel.coordinateSystem = polar;
  66273. polar.model = polarModel;
  66274. }); // Inject coordinateSystem to series
  66275. ecModel.eachSeries(function (seriesModel) {
  66276. if (seriesModel.get('coordinateSystem') === 'polar') {
  66277. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  66278. if ("development" !== 'production') {
  66279. if (!polarModel) {
  66280. throw new Error('Polar "' + retrieve(seriesModel.get('polarIndex'), seriesModel.get('polarId'), 0) + '" not found');
  66281. }
  66282. }
  66283. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  66284. }
  66285. });
  66286. return polarList;
  66287. }
  66288. };
  66289. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  66290. function getAxisLineShape(polar, rExtent, angle) {
  66291. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  66292. var start = polar.coordToPoint([rExtent[0], angle]);
  66293. var end = polar.coordToPoint([rExtent[1], angle]);
  66294. return {
  66295. x1: start[0],
  66296. y1: start[1],
  66297. x2: end[0],
  66298. y2: end[1]
  66299. };
  66300. }
  66301. function getRadiusIdx(polar) {
  66302. var radiusAxis = polar.getRadiusAxis();
  66303. return radiusAxis.inverse ? 0 : 1;
  66304. } // Remove the last tick which will overlap the first tick
  66305. function fixAngleOverlap(list) {
  66306. var firstItem = list[0];
  66307. var lastItem = list[list.length - 1];
  66308. if (firstItem && lastItem && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4) {
  66309. list.pop();
  66310. }
  66311. }
  66312. var AngleAxisView =
  66313. /** @class */
  66314. function (_super) {
  66315. __extends(AngleAxisView, _super);
  66316. function AngleAxisView() {
  66317. var _this = _super !== null && _super.apply(this, arguments) || this;
  66318. _this.type = AngleAxisView.type;
  66319. _this.axisPointerClass = 'PolarAxisPointer';
  66320. return _this;
  66321. }
  66322. AngleAxisView.prototype.render = function (angleAxisModel, ecModel) {
  66323. this.group.removeAll();
  66324. if (!angleAxisModel.get('show')) {
  66325. return;
  66326. }
  66327. var angleAxis = angleAxisModel.axis;
  66328. var polar = angleAxis.polar;
  66329. var radiusExtent = polar.getRadiusAxis().getExtent();
  66330. var ticksAngles = angleAxis.getTicksCoords();
  66331. var minorTickAngles = angleAxis.getMinorTicksCoords();
  66332. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  66333. labelItem = clone(labelItem);
  66334. var scale = angleAxis.scale;
  66335. var tickValue = scale.type === 'ordinal' ? scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  66336. labelItem.coord = angleAxis.dataToCoord(tickValue);
  66337. return labelItem;
  66338. });
  66339. fixAngleOverlap(labels);
  66340. fixAngleOverlap(ticksAngles);
  66341. each(elementList$1, function (name) {
  66342. if (angleAxisModel.get([name, 'show']) && (!angleAxis.scale.isBlank() || name === 'axisLine')) {
  66343. angelAxisElementsBuilders[name](this.group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  66344. }
  66345. }, this);
  66346. };
  66347. AngleAxisView.type = 'angleAxis';
  66348. return AngleAxisView;
  66349. }(AxisView);
  66350. var angelAxisElementsBuilders = {
  66351. axisLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66352. var lineStyleModel = angleAxisModel.getModel(['axisLine', 'lineStyle']); // extent id of the axis radius (r0 and r)
  66353. var rId = getRadiusIdx(polar);
  66354. var r0Id = rId ? 0 : 1;
  66355. var shape;
  66356. if (radiusExtent[r0Id] === 0) {
  66357. shape = new Circle({
  66358. shape: {
  66359. cx: polar.cx,
  66360. cy: polar.cy,
  66361. r: radiusExtent[rId]
  66362. },
  66363. style: lineStyleModel.getLineStyle(),
  66364. z2: 1,
  66365. silent: true
  66366. });
  66367. } else {
  66368. shape = new Ring({
  66369. shape: {
  66370. cx: polar.cx,
  66371. cy: polar.cy,
  66372. r: radiusExtent[rId],
  66373. r0: radiusExtent[r0Id]
  66374. },
  66375. style: lineStyleModel.getLineStyle(),
  66376. z2: 1,
  66377. silent: true
  66378. });
  66379. }
  66380. shape.style.fill = null;
  66381. group.add(shape);
  66382. },
  66383. axisTick: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66384. var tickModel = angleAxisModel.getModel('axisTick');
  66385. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  66386. var radius = radiusExtent[getRadiusIdx(polar)];
  66387. var lines = map(ticksAngles, function (tickAngleItem) {
  66388. return new Line({
  66389. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  66390. });
  66391. });
  66392. group.add(mergePath$1(lines, {
  66393. style: defaults(tickModel.getModel('lineStyle').getLineStyle(), {
  66394. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  66395. })
  66396. }));
  66397. },
  66398. minorTick: function (group, angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  66399. if (!minorTickAngles.length) {
  66400. return;
  66401. }
  66402. var tickModel = angleAxisModel.getModel('axisTick');
  66403. var minorTickModel = angleAxisModel.getModel('minorTick');
  66404. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  66405. var radius = radiusExtent[getRadiusIdx(polar)];
  66406. var lines = [];
  66407. for (var i = 0; i < minorTickAngles.length; i++) {
  66408. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66409. lines.push(new Line({
  66410. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  66411. }));
  66412. }
  66413. }
  66414. group.add(mergePath$1(lines, {
  66415. style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), {
  66416. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  66417. }))
  66418. }));
  66419. },
  66420. axisLabel: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  66421. var rawCategoryData = angleAxisModel.getCategories(true);
  66422. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  66423. var labelMargin = commonLabelModel.get('margin');
  66424. var triggerEvent = angleAxisModel.get('triggerEvent'); // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  66425. each(labels, function (labelItem, idx) {
  66426. var labelModel = commonLabelModel;
  66427. var tickValue = labelItem.tickValue;
  66428. var r = radiusExtent[getRadiusIdx(polar)];
  66429. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  66430. var cx = polar.cx;
  66431. var cy = polar.cy;
  66432. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right';
  66433. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom';
  66434. if (rawCategoryData && rawCategoryData[tickValue]) {
  66435. var rawCategoryItem = rawCategoryData[tickValue];
  66436. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  66437. labelModel = new Model(rawCategoryItem.textStyle, commonLabelModel, commonLabelModel.ecModel);
  66438. }
  66439. }
  66440. var textEl = new ZRText({
  66441. silent: AxisBuilder.isLabelSilent(angleAxisModel),
  66442. style: createTextStyle(labelModel, {
  66443. x: p[0],
  66444. y: p[1],
  66445. fill: labelModel.getTextColor() || angleAxisModel.get(['axisLine', 'lineStyle', 'color']),
  66446. text: labelItem.formattedLabel,
  66447. align: labelTextAlign,
  66448. verticalAlign: labelTextVerticalAlign
  66449. })
  66450. });
  66451. group.add(textEl); // Pack data for mouse event
  66452. if (triggerEvent) {
  66453. var eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  66454. eventData.targetType = 'axisLabel';
  66455. eventData.value = labelItem.rawLabel;
  66456. getECData(textEl).eventData = eventData;
  66457. }
  66458. }, this);
  66459. },
  66460. splitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66461. var splitLineModel = angleAxisModel.getModel('splitLine');
  66462. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66463. var lineColors = lineStyleModel.get('color');
  66464. var lineCount = 0;
  66465. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66466. var splitLines = [];
  66467. for (var i = 0; i < ticksAngles.length; i++) {
  66468. var colorIndex = lineCount++ % lineColors.length;
  66469. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66470. splitLines[colorIndex].push(new Line({
  66471. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  66472. }));
  66473. } // Simple optimization
  66474. // Batching the lines if color are the same
  66475. for (var i = 0; i < splitLines.length; i++) {
  66476. group.add(mergePath$1(splitLines[i], {
  66477. style: defaults({
  66478. stroke: lineColors[i % lineColors.length]
  66479. }, lineStyleModel.getLineStyle()),
  66480. silent: true,
  66481. z: angleAxisModel.get('z')
  66482. }));
  66483. }
  66484. },
  66485. minorSplitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66486. if (!minorTickAngles.length) {
  66487. return;
  66488. }
  66489. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  66490. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66491. var lines = [];
  66492. for (var i = 0; i < minorTickAngles.length; i++) {
  66493. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66494. lines.push(new Line({
  66495. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  66496. }));
  66497. }
  66498. }
  66499. group.add(mergePath$1(lines, {
  66500. style: lineStyleModel.getLineStyle(),
  66501. silent: true,
  66502. z: angleAxisModel.get('z')
  66503. }));
  66504. },
  66505. splitArea: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66506. if (!ticksAngles.length) {
  66507. return;
  66508. }
  66509. var splitAreaModel = angleAxisModel.getModel('splitArea');
  66510. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66511. var areaColors = areaStyleModel.get('color');
  66512. var lineCount = 0;
  66513. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66514. var splitAreas = [];
  66515. var RADIAN = Math.PI / 180;
  66516. var prevAngle = -ticksAngles[0].coord * RADIAN;
  66517. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  66518. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  66519. var clockwise = angleAxisModel.get('clockwise');
  66520. for (var i = 1, len = ticksAngles.length; i <= len; i++) {
  66521. var coord = i === len ? ticksAngles[0].coord : ticksAngles[i].coord;
  66522. var colorIndex = lineCount++ % areaColors.length;
  66523. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66524. splitAreas[colorIndex].push(new Sector({
  66525. shape: {
  66526. cx: polar.cx,
  66527. cy: polar.cy,
  66528. r0: r0,
  66529. r: r1,
  66530. startAngle: prevAngle,
  66531. endAngle: -coord * RADIAN,
  66532. clockwise: clockwise
  66533. },
  66534. silent: true
  66535. }));
  66536. prevAngle = -coord * RADIAN;
  66537. } // Simple optimization
  66538. // Batching the lines if color are the same
  66539. for (var i = 0; i < splitAreas.length; i++) {
  66540. group.add(mergePath$1(splitAreas[i], {
  66541. style: defaults({
  66542. fill: areaColors[i % areaColors.length]
  66543. }, areaStyleModel.getAreaStyle()),
  66544. silent: true
  66545. }));
  66546. }
  66547. }
  66548. };
  66549. var axisBuilderAttrs$2 = ['axisLine', 'axisTickLabel', 'axisName'];
  66550. var selfBuilderAttrs$1 = ['splitLine', 'splitArea', 'minorSplitLine'];
  66551. var RadiusAxisView =
  66552. /** @class */
  66553. function (_super) {
  66554. __extends(RadiusAxisView, _super);
  66555. function RadiusAxisView() {
  66556. var _this = _super !== null && _super.apply(this, arguments) || this;
  66557. _this.type = RadiusAxisView.type;
  66558. _this.axisPointerClass = 'PolarAxisPointer';
  66559. return _this;
  66560. }
  66561. RadiusAxisView.prototype.render = function (radiusAxisModel, ecModel) {
  66562. this.group.removeAll();
  66563. if (!radiusAxisModel.get('show')) {
  66564. return;
  66565. }
  66566. var oldAxisGroup = this._axisGroup;
  66567. var newAxisGroup = this._axisGroup = new Group();
  66568. this.group.add(newAxisGroup);
  66569. var radiusAxis = radiusAxisModel.axis;
  66570. var polar = radiusAxis.polar;
  66571. var angleAxis = polar.getAngleAxis();
  66572. var ticksCoords = radiusAxis.getTicksCoords();
  66573. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  66574. var axisAngle = angleAxis.getExtent()[0];
  66575. var radiusExtent = radiusAxis.getExtent();
  66576. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  66577. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  66578. each(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  66579. newAxisGroup.add(axisBuilder.getGroup());
  66580. groupTransition(oldAxisGroup, newAxisGroup, radiusAxisModel);
  66581. each(selfBuilderAttrs$1, function (name) {
  66582. if (radiusAxisModel.get([name, 'show']) && !radiusAxis.scale.isBlank()) {
  66583. axisElementBuilders$1[name](this.group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  66584. }
  66585. }, this);
  66586. };
  66587. RadiusAxisView.type = 'radiusAxis';
  66588. return RadiusAxisView;
  66589. }(AxisView);
  66590. var axisElementBuilders$1 = {
  66591. splitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66592. var splitLineModel = radiusAxisModel.getModel('splitLine');
  66593. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66594. var lineColors = lineStyleModel.get('color');
  66595. var lineCount = 0;
  66596. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66597. var splitLines = [];
  66598. for (var i = 0; i < ticksCoords.length; i++) {
  66599. var colorIndex = lineCount++ % lineColors.length;
  66600. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66601. splitLines[colorIndex].push(new Circle({
  66602. shape: {
  66603. cx: polar.cx,
  66604. cy: polar.cy,
  66605. // ensure circle radius >= 0
  66606. r: Math.max(ticksCoords[i].coord, 0)
  66607. }
  66608. }));
  66609. } // Simple optimization
  66610. // Batching the lines if color are the same
  66611. for (var i = 0; i < splitLines.length; i++) {
  66612. group.add(mergePath$1(splitLines[i], {
  66613. style: defaults({
  66614. stroke: lineColors[i % lineColors.length],
  66615. fill: null
  66616. }, lineStyleModel.getLineStyle()),
  66617. silent: true
  66618. }));
  66619. }
  66620. },
  66621. minorSplitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  66622. if (!minorTicksCoords.length) {
  66623. return;
  66624. }
  66625. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  66626. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66627. var lines = [];
  66628. for (var i = 0; i < minorTicksCoords.length; i++) {
  66629. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  66630. lines.push(new Circle({
  66631. shape: {
  66632. cx: polar.cx,
  66633. cy: polar.cy,
  66634. r: minorTicksCoords[i][k].coord
  66635. }
  66636. }));
  66637. }
  66638. }
  66639. group.add(mergePath$1(lines, {
  66640. style: defaults({
  66641. fill: null
  66642. }, lineStyleModel.getLineStyle()),
  66643. silent: true
  66644. }));
  66645. },
  66646. splitArea: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66647. if (!ticksCoords.length) {
  66648. return;
  66649. }
  66650. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  66651. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66652. var areaColors = areaStyleModel.get('color');
  66653. var lineCount = 0;
  66654. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66655. var splitAreas = [];
  66656. var prevRadius = ticksCoords[0].coord;
  66657. for (var i = 1; i < ticksCoords.length; i++) {
  66658. var colorIndex = lineCount++ % areaColors.length;
  66659. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66660. splitAreas[colorIndex].push(new Sector({
  66661. shape: {
  66662. cx: polar.cx,
  66663. cy: polar.cy,
  66664. r0: prevRadius,
  66665. r: ticksCoords[i].coord,
  66666. startAngle: 0,
  66667. endAngle: Math.PI * 2
  66668. },
  66669. silent: true
  66670. }));
  66671. prevRadius = ticksCoords[i].coord;
  66672. } // Simple optimization
  66673. // Batching the lines if color are the same
  66674. for (var i = 0; i < splitAreas.length; i++) {
  66675. group.add(mergePath$1(splitAreas[i], {
  66676. style: defaults({
  66677. fill: areaColors[i % areaColors.length]
  66678. }, areaStyleModel.getAreaStyle()),
  66679. silent: true
  66680. }));
  66681. }
  66682. }
  66683. };
  66684. /**
  66685. * @inner
  66686. */
  66687. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  66688. return {
  66689. position: [polar.cx, polar.cy],
  66690. rotation: axisAngle / 180 * Math.PI,
  66691. labelDirection: -1,
  66692. tickDirection: -1,
  66693. nameDirection: 1,
  66694. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  66695. // Over splitLine and splitArea
  66696. z2: 1
  66697. };
  66698. }
  66699. function getSeriesStackId$1(seriesModel) {
  66700. return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex;
  66701. }
  66702. function getAxisKey$1(polar, axis) {
  66703. return axis.dim + polar.model.componentIndex;
  66704. }
  66705. function barLayoutPolar(seriesType, ecModel, api) {
  66706. var lastStackCoords = {};
  66707. var barWidthAndOffset = calRadialBar(filter(ecModel.getSeriesByType(seriesType), function (seriesModel) {
  66708. return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'polar';
  66709. }));
  66710. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  66711. // Check series coordinate, do layout for polar only
  66712. if (seriesModel.coordinateSystem.type !== 'polar') {
  66713. return;
  66714. }
  66715. var data = seriesModel.getData();
  66716. var polar = seriesModel.coordinateSystem;
  66717. var baseAxis = polar.getBaseAxis();
  66718. var axisKey = getAxisKey$1(polar, baseAxis);
  66719. var stackId = getSeriesStackId$1(seriesModel);
  66720. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  66721. var columnOffset = columnLayoutInfo.offset;
  66722. var columnWidth = columnLayoutInfo.width;
  66723. var valueAxis = polar.getOtherAxis(baseAxis);
  66724. var cx = seriesModel.coordinateSystem.cx;
  66725. var cy = seriesModel.coordinateSystem.cy;
  66726. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  66727. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  66728. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  66729. var valueDim = data.mapDimension(valueAxis.dim);
  66730. var baseDim = data.mapDimension(baseAxis.dim);
  66731. var stacked = isDimensionStacked(data, valueDim
  66732. /* , baseDim */
  66733. );
  66734. var clampLayout = baseAxis.dim !== 'radius' || !seriesModel.get('roundCap', true);
  66735. var valueAxisStart = valueAxis.dataToCoord(0);
  66736. for (var idx = 0, len = data.count(); idx < len; idx++) {
  66737. var value = data.get(valueDim, idx);
  66738. var baseValue = data.get(baseDim, idx);
  66739. var sign = value >= 0 ? 'p' : 'n';
  66740. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  66741. // stackResultDimension directly.
  66742. // Only ordinal axis can be stacked.
  66743. if (stacked) {
  66744. if (!lastStackCoords[stackId][baseValue]) {
  66745. lastStackCoords[stackId][baseValue] = {
  66746. p: valueAxisStart,
  66747. n: valueAxisStart // Negative stack
  66748. };
  66749. } // Should also consider #4243
  66750. baseCoord = lastStackCoords[stackId][baseValue][sign];
  66751. }
  66752. var r0 = void 0;
  66753. var r = void 0;
  66754. var startAngle = void 0;
  66755. var endAngle = void 0; // radial sector
  66756. if (valueAxis.dim === 'radius') {
  66757. var radiusSpan = valueAxis.dataToCoord(value) - valueAxisStart;
  66758. var angle = baseAxis.dataToCoord(baseValue);
  66759. if (Math.abs(radiusSpan) < barMinHeight) {
  66760. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  66761. }
  66762. r0 = baseCoord;
  66763. r = baseCoord + radiusSpan;
  66764. startAngle = angle - columnOffset;
  66765. endAngle = startAngle - columnWidth;
  66766. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  66767. } // tangential sector
  66768. else {
  66769. var angleSpan = valueAxis.dataToCoord(value, clampLayout) - valueAxisStart;
  66770. var radius = baseAxis.dataToCoord(baseValue);
  66771. if (Math.abs(angleSpan) < barMinAngle) {
  66772. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  66773. }
  66774. r0 = radius + columnOffset;
  66775. r = r0 + columnWidth;
  66776. startAngle = baseCoord;
  66777. endAngle = baseCoord + angleSpan; // if the previous stack is at the end of the ring,
  66778. // add a round to differentiate it from origin
  66779. // let extent = angleAxis.getExtent();
  66780. // let stackCoord = angle;
  66781. // if (stackCoord === extent[0] && value > 0) {
  66782. // stackCoord = extent[1];
  66783. // }
  66784. // else if (stackCoord === extent[1] && value < 0) {
  66785. // stackCoord = extent[0];
  66786. // }
  66787. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  66788. }
  66789. data.setItemLayout(idx, {
  66790. cx: cx,
  66791. cy: cy,
  66792. r0: r0,
  66793. r: r,
  66794. // Consider that positive angle is anti-clockwise,
  66795. // while positive radian of sector is clockwise
  66796. startAngle: -startAngle * Math.PI / 180,
  66797. endAngle: -endAngle * Math.PI / 180,
  66798. /**
  66799. * Keep the same logic with bar in catesion: use end value to
  66800. * control direction. Notice that if clockwise is true (by
  66801. * default), the sector will always draw clockwisely, no matter
  66802. * whether endAngle is greater or less than startAngle.
  66803. */
  66804. clockwise: startAngle >= endAngle
  66805. });
  66806. }
  66807. });
  66808. }
  66809. /**
  66810. * Calculate bar width and offset for radial bar charts
  66811. */
  66812. function calRadialBar(barSeries) {
  66813. // Columns info on each category axis. Key is polar name
  66814. var columnsMap = {};
  66815. each(barSeries, function (seriesModel, idx) {
  66816. var data = seriesModel.getData();
  66817. var polar = seriesModel.coordinateSystem;
  66818. var baseAxis = polar.getBaseAxis();
  66819. var axisKey = getAxisKey$1(polar, baseAxis);
  66820. var axisExtent = baseAxis.getExtent();
  66821. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  66822. var columnsOnAxis = columnsMap[axisKey] || {
  66823. bandWidth: bandWidth,
  66824. remainedWidth: bandWidth,
  66825. autoWidthCount: 0,
  66826. categoryGap: '20%',
  66827. gap: '30%',
  66828. stacks: {}
  66829. };
  66830. var stacks = columnsOnAxis.stacks;
  66831. columnsMap[axisKey] = columnsOnAxis;
  66832. var stackId = getSeriesStackId$1(seriesModel);
  66833. if (!stacks[stackId]) {
  66834. columnsOnAxis.autoWidthCount++;
  66835. }
  66836. stacks[stackId] = stacks[stackId] || {
  66837. width: 0,
  66838. maxWidth: 0
  66839. };
  66840. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  66841. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  66842. var barGap = seriesModel.get('barGap');
  66843. var barCategoryGap = seriesModel.get('barCategoryGap');
  66844. if (barWidth && !stacks[stackId].width) {
  66845. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  66846. stacks[stackId].width = barWidth;
  66847. columnsOnAxis.remainedWidth -= barWidth;
  66848. }
  66849. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  66850. barGap != null && (columnsOnAxis.gap = barGap);
  66851. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  66852. });
  66853. var result = {};
  66854. each(columnsMap, function (columnsOnAxis, coordSysName) {
  66855. result[coordSysName] = {};
  66856. var stacks = columnsOnAxis.stacks;
  66857. var bandWidth = columnsOnAxis.bandWidth;
  66858. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  66859. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  66860. var remainedWidth = columnsOnAxis.remainedWidth;
  66861. var autoWidthCount = columnsOnAxis.autoWidthCount;
  66862. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  66863. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  66864. each(stacks, function (column, stack) {
  66865. var maxWidth = column.maxWidth;
  66866. if (maxWidth && maxWidth < autoWidth) {
  66867. maxWidth = Math.min(maxWidth, remainedWidth);
  66868. if (column.width) {
  66869. maxWidth = Math.min(maxWidth, column.width);
  66870. }
  66871. remainedWidth -= maxWidth;
  66872. column.width = maxWidth;
  66873. autoWidthCount--;
  66874. }
  66875. }); // Recalculate width again
  66876. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  66877. autoWidth = Math.max(autoWidth, 0);
  66878. var widthSum = 0;
  66879. var lastColumn;
  66880. each(stacks, function (column, idx) {
  66881. if (!column.width) {
  66882. column.width = autoWidth;
  66883. }
  66884. lastColumn = column;
  66885. widthSum += column.width * (1 + barGapPercent);
  66886. });
  66887. if (lastColumn) {
  66888. widthSum -= lastColumn.width * barGapPercent;
  66889. }
  66890. var offset = -widthSum / 2;
  66891. each(stacks, function (column, stackId) {
  66892. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  66893. offset: offset,
  66894. width: column.width
  66895. };
  66896. offset += column.width * (1 + barGapPercent);
  66897. });
  66898. });
  66899. return result;
  66900. }
  66901. var angleAxisExtraOption = {
  66902. startAngle: 90,
  66903. clockwise: true,
  66904. splitNumber: 12,
  66905. axisLabel: {
  66906. rotate: 0
  66907. }
  66908. };
  66909. var radiusAxisExtraOption = {
  66910. splitNumber: 5
  66911. };
  66912. var PolarView =
  66913. /** @class */
  66914. function (_super) {
  66915. __extends(PolarView, _super);
  66916. function PolarView() {
  66917. var _this = _super !== null && _super.apply(this, arguments) || this;
  66918. _this.type = PolarView.type;
  66919. return _this;
  66920. }
  66921. PolarView.type = 'polar';
  66922. return PolarView;
  66923. }(ComponentView);
  66924. function install$u(registers) {
  66925. use(install$s);
  66926. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  66927. registers.registerCoordinateSystem('polar', polarCreator);
  66928. registers.registerComponentModel(PolarModel);
  66929. registers.registerComponentView(PolarView); // Model and view for angleAxis and radiusAxis
  66930. axisModelCreator(registers, 'angle', AngleAxisModel, angleAxisExtraOption);
  66931. axisModelCreator(registers, 'radius', RadiusAxisModel, radiusAxisExtraOption);
  66932. registers.registerComponentView(AngleAxisView);
  66933. registers.registerComponentView(RadiusAxisView);
  66934. registers.registerLayout(curry(barLayoutPolar, 'bar'));
  66935. }
  66936. function layout$2(axisModel, opt) {
  66937. opt = opt || {};
  66938. var single = axisModel.coordinateSystem;
  66939. var axis = axisModel.axis;
  66940. var layout = {};
  66941. var axisPosition = axis.position;
  66942. var orient = axis.orient;
  66943. var rect = single.getRect();
  66944. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  66945. var positionMap = {
  66946. horizontal: {
  66947. top: rectBound[2],
  66948. bottom: rectBound[3]
  66949. },
  66950. vertical: {
  66951. left: rectBound[0],
  66952. right: rectBound[1]
  66953. }
  66954. };
  66955. layout.position = [orient === 'vertical' ? positionMap.vertical[axisPosition] : rectBound[0], orient === 'horizontal' ? positionMap.horizontal[axisPosition] : rectBound[3]];
  66956. var r = {
  66957. horizontal: 0,
  66958. vertical: 1
  66959. };
  66960. layout.rotation = Math.PI / 2 * r[orient];
  66961. var directionMap = {
  66962. top: -1,
  66963. bottom: 1,
  66964. right: 1,
  66965. left: -1
  66966. };
  66967. layout.labelDirection = layout.tickDirection = layout.nameDirection = directionMap[axisPosition];
  66968. if (axisModel.get(['axisTick', 'inside'])) {
  66969. layout.tickDirection = -layout.tickDirection;
  66970. }
  66971. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  66972. layout.labelDirection = -layout.labelDirection;
  66973. }
  66974. var labelRotation = opt.rotate;
  66975. labelRotation == null && (labelRotation = axisModel.get(['axisLabel', 'rotate']));
  66976. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  66977. layout.z2 = 1;
  66978. return layout;
  66979. }
  66980. var axisBuilderAttrs$3 = ['axisLine', 'axisTickLabel', 'axisName'];
  66981. var selfBuilderAttrs$2 = ['splitArea', 'splitLine'];
  66982. var SingleAxisView =
  66983. /** @class */
  66984. function (_super) {
  66985. __extends(SingleAxisView, _super);
  66986. function SingleAxisView() {
  66987. var _this = _super !== null && _super.apply(this, arguments) || this;
  66988. _this.type = SingleAxisView.type;
  66989. _this.axisPointerClass = 'SingleAxisPointer';
  66990. return _this;
  66991. }
  66992. SingleAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  66993. var group = this.group;
  66994. group.removeAll();
  66995. var oldAxisGroup = this._axisGroup;
  66996. this._axisGroup = new Group();
  66997. var layout = layout$2(axisModel);
  66998. var axisBuilder = new AxisBuilder(axisModel, layout);
  66999. each(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  67000. group.add(this._axisGroup);
  67001. group.add(axisBuilder.getGroup());
  67002. each(selfBuilderAttrs$2, function (name) {
  67003. if (axisModel.get([name, 'show'])) {
  67004. axisElementBuilders$2[name](this, this.group, this._axisGroup, axisModel);
  67005. }
  67006. }, this);
  67007. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  67008. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  67009. };
  67010. SingleAxisView.prototype.remove = function () {
  67011. rectCoordAxisHandleRemove(this);
  67012. };
  67013. SingleAxisView.type = 'singleAxis';
  67014. return SingleAxisView;
  67015. }(AxisView);
  67016. var axisElementBuilders$2 = {
  67017. splitLine: function (axisView, group, axisGroup, axisModel) {
  67018. var axis = axisModel.axis;
  67019. if (axis.scale.isBlank()) {
  67020. return;
  67021. }
  67022. var splitLineModel = axisModel.getModel('splitLine');
  67023. var lineStyleModel = splitLineModel.getModel('lineStyle');
  67024. var lineColors = lineStyleModel.get('color');
  67025. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  67026. var lineWidth = lineStyleModel.get('width');
  67027. var gridRect = axisModel.coordinateSystem.getRect();
  67028. var isHorizontal = axis.isHorizontal();
  67029. var splitLines = [];
  67030. var lineCount = 0;
  67031. var ticksCoords = axis.getTicksCoords({
  67032. tickModel: splitLineModel
  67033. });
  67034. var p1 = [];
  67035. var p2 = [];
  67036. for (var i = 0; i < ticksCoords.length; ++i) {
  67037. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  67038. if (isHorizontal) {
  67039. p1[0] = tickCoord;
  67040. p1[1] = gridRect.y;
  67041. p2[0] = tickCoord;
  67042. p2[1] = gridRect.y + gridRect.height;
  67043. } else {
  67044. p1[0] = gridRect.x;
  67045. p1[1] = tickCoord;
  67046. p2[0] = gridRect.x + gridRect.width;
  67047. p2[1] = tickCoord;
  67048. }
  67049. var line = new Line({
  67050. shape: {
  67051. x1: p1[0],
  67052. y1: p1[1],
  67053. x2: p2[0],
  67054. y2: p2[1]
  67055. },
  67056. silent: true
  67057. });
  67058. subPixelOptimizeLine$1(line.shape, lineWidth);
  67059. var colorIndex = lineCount++ % lineColors.length;
  67060. splitLines[colorIndex] = splitLines[colorIndex] || [];
  67061. splitLines[colorIndex].push(line);
  67062. }
  67063. var lineStyle = lineStyleModel.getLineStyle(['color']);
  67064. for (var i = 0; i < splitLines.length; ++i) {
  67065. group.add(mergePath$1(splitLines[i], {
  67066. style: defaults({
  67067. stroke: lineColors[i % lineColors.length]
  67068. }, lineStyle),
  67069. silent: true
  67070. }));
  67071. }
  67072. },
  67073. splitArea: function (axisView, group, axisGroup, axisModel) {
  67074. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, axisModel);
  67075. }
  67076. };
  67077. var SingleAxisModel =
  67078. /** @class */
  67079. function (_super) {
  67080. __extends(SingleAxisModel, _super);
  67081. function SingleAxisModel() {
  67082. var _this = _super !== null && _super.apply(this, arguments) || this;
  67083. _this.type = SingleAxisModel.type;
  67084. return _this;
  67085. }
  67086. SingleAxisModel.prototype.getCoordSysModel = function () {
  67087. return this;
  67088. };
  67089. SingleAxisModel.type = 'singleAxis';
  67090. SingleAxisModel.layoutMode = 'box';
  67091. SingleAxisModel.defaultOption = {
  67092. left: '5%',
  67093. top: '5%',
  67094. right: '5%',
  67095. bottom: '5%',
  67096. type: 'value',
  67097. position: 'bottom',
  67098. orient: 'horizontal',
  67099. axisLine: {
  67100. show: true,
  67101. lineStyle: {
  67102. width: 1,
  67103. type: 'solid'
  67104. }
  67105. },
  67106. // Single coordinate system and single axis is the,
  67107. // which is used as the parent tooltip model.
  67108. // same model, so we set default tooltip show as true.
  67109. tooltip: {
  67110. show: true
  67111. },
  67112. axisTick: {
  67113. show: true,
  67114. length: 6,
  67115. lineStyle: {
  67116. width: 1
  67117. }
  67118. },
  67119. axisLabel: {
  67120. show: true,
  67121. interval: 'auto'
  67122. },
  67123. splitLine: {
  67124. show: true,
  67125. lineStyle: {
  67126. type: 'dashed',
  67127. opacity: 0.2
  67128. }
  67129. }
  67130. };
  67131. return SingleAxisModel;
  67132. }(ComponentModel);
  67133. mixin(SingleAxisModel, AxisModelCommonMixin.prototype);
  67134. var SingleAxis =
  67135. /** @class */
  67136. function (_super) {
  67137. __extends(SingleAxis, _super);
  67138. function SingleAxis(dim, scale, coordExtent, axisType, position) {
  67139. var _this = _super.call(this, dim, scale, coordExtent) || this;
  67140. _this.type = axisType || 'value';
  67141. _this.position = position || 'bottom';
  67142. return _this;
  67143. }
  67144. /**
  67145. * Judge the orient of the axis.
  67146. */
  67147. SingleAxis.prototype.isHorizontal = function () {
  67148. var position = this.position;
  67149. return position === 'top' || position === 'bottom';
  67150. };
  67151. SingleAxis.prototype.pointToData = function (point, clamp) {
  67152. return this.coordinateSystem.pointToData(point)[0];
  67153. };
  67154. return SingleAxis;
  67155. }(Axis);
  67156. var singleDimensions = ['single'];
  67157. /**
  67158. * Create a single coordinates system.
  67159. */
  67160. var Single =
  67161. /** @class */
  67162. function () {
  67163. function Single(axisModel, ecModel, api) {
  67164. this.type = 'single';
  67165. this.dimension = 'single';
  67166. /**
  67167. * Add it just for draw tooltip.
  67168. */
  67169. this.dimensions = singleDimensions;
  67170. this.axisPointerEnabled = true;
  67171. this.model = axisModel;
  67172. this._init(axisModel, ecModel, api);
  67173. }
  67174. /**
  67175. * Initialize single coordinate system.
  67176. */
  67177. Single.prototype._init = function (axisModel, ecModel, api) {
  67178. var dim = this.dimension;
  67179. var axis = new SingleAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisModel.get('position'));
  67180. var isCategory = axis.type === 'category';
  67181. axis.onBand = isCategory && axisModel.get('boundaryGap');
  67182. axis.inverse = axisModel.get('inverse');
  67183. axis.orient = axisModel.get('orient');
  67184. axisModel.axis = axis;
  67185. axis.model = axisModel;
  67186. axis.coordinateSystem = this;
  67187. this._axis = axis;
  67188. };
  67189. /**
  67190. * Update axis scale after data processed
  67191. */
  67192. Single.prototype.update = function (ecModel, api) {
  67193. ecModel.eachSeries(function (seriesModel) {
  67194. if (seriesModel.coordinateSystem === this) {
  67195. var data_1 = seriesModel.getData();
  67196. each(data_1.mapDimensionsAll(this.dimension), function (dim) {
  67197. this._axis.scale.unionExtentFromData(data_1, dim);
  67198. }, this);
  67199. niceScaleExtent(this._axis.scale, this._axis.model);
  67200. }
  67201. }, this);
  67202. };
  67203. /**
  67204. * Resize the single coordinate system.
  67205. */
  67206. Single.prototype.resize = function (axisModel, api) {
  67207. this._rect = getLayoutRect({
  67208. left: axisModel.get('left'),
  67209. top: axisModel.get('top'),
  67210. right: axisModel.get('right'),
  67211. bottom: axisModel.get('bottom'),
  67212. width: axisModel.get('width'),
  67213. height: axisModel.get('height')
  67214. }, {
  67215. width: api.getWidth(),
  67216. height: api.getHeight()
  67217. });
  67218. this._adjustAxis();
  67219. };
  67220. Single.prototype.getRect = function () {
  67221. return this._rect;
  67222. };
  67223. Single.prototype._adjustAxis = function () {
  67224. var rect = this._rect;
  67225. var axis = this._axis;
  67226. var isHorizontal = axis.isHorizontal();
  67227. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  67228. var idx = axis.inverse ? 1 : 0;
  67229. axis.setExtent(extent[idx], extent[1 - idx]);
  67230. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  67231. };
  67232. Single.prototype._updateAxisTransform = function (axis, coordBase) {
  67233. var axisExtent = axis.getExtent();
  67234. var extentSum = axisExtent[0] + axisExtent[1];
  67235. var isHorizontal = axis.isHorizontal();
  67236. axis.toGlobalCoord = isHorizontal ? function (coord) {
  67237. return coord + coordBase;
  67238. } : function (coord) {
  67239. return extentSum - coord + coordBase;
  67240. };
  67241. axis.toLocalCoord = isHorizontal ? function (coord) {
  67242. return coord - coordBase;
  67243. } : function (coord) {
  67244. return extentSum - coord + coordBase;
  67245. };
  67246. };
  67247. /**
  67248. * Get axis.
  67249. */
  67250. Single.prototype.getAxis = function () {
  67251. return this._axis;
  67252. };
  67253. /**
  67254. * Get axis, add it just for draw tooltip.
  67255. */
  67256. Single.prototype.getBaseAxis = function () {
  67257. return this._axis;
  67258. };
  67259. Single.prototype.getAxes = function () {
  67260. return [this._axis];
  67261. };
  67262. Single.prototype.getTooltipAxes = function () {
  67263. return {
  67264. baseAxes: [this.getAxis()],
  67265. // Empty otherAxes
  67266. otherAxes: []
  67267. };
  67268. };
  67269. /**
  67270. * If contain point.
  67271. */
  67272. Single.prototype.containPoint = function (point) {
  67273. var rect = this.getRect();
  67274. var axis = this.getAxis();
  67275. var orient = axis.orient;
  67276. if (orient === 'horizontal') {
  67277. return axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height;
  67278. } else {
  67279. return axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height;
  67280. }
  67281. };
  67282. Single.prototype.pointToData = function (point) {
  67283. var axis = this.getAxis();
  67284. return [axis.coordToData(axis.toLocalCoord(point[axis.orient === 'horizontal' ? 0 : 1]))];
  67285. };
  67286. /**
  67287. * Convert the series data to concrete point.
  67288. * Can be [val] | val
  67289. */
  67290. Single.prototype.dataToPoint = function (val) {
  67291. var axis = this.getAxis();
  67292. var rect = this.getRect();
  67293. var pt = [];
  67294. var idx = axis.orient === 'horizontal' ? 0 : 1;
  67295. if (val instanceof Array) {
  67296. val = val[0];
  67297. }
  67298. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  67299. pt[1 - idx] = idx === 0 ? rect.y + rect.height / 2 : rect.x + rect.width / 2;
  67300. return pt;
  67301. };
  67302. Single.prototype.convertToPixel = function (ecModel, finder, value) {
  67303. var coordSys = getCoordSys$3(finder);
  67304. return coordSys === this ? this.dataToPoint(value) : null;
  67305. };
  67306. Single.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  67307. var coordSys = getCoordSys$3(finder);
  67308. return coordSys === this ? this.pointToData(pixel) : null;
  67309. };
  67310. return Single;
  67311. }();
  67312. function getCoordSys$3(finder) {
  67313. var seriesModel = finder.seriesModel;
  67314. var singleModel = finder.singleAxisModel;
  67315. return singleModel && singleModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  67316. }
  67317. /**
  67318. * Create single coordinate system and inject it into seriesModel.
  67319. */
  67320. function create$2(ecModel, api) {
  67321. var singles = [];
  67322. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  67323. var single = new Single(axisModel, ecModel, api);
  67324. single.name = 'single_' + idx;
  67325. single.resize(axisModel, api);
  67326. axisModel.coordinateSystem = single;
  67327. singles.push(single);
  67328. });
  67329. ecModel.eachSeries(function (seriesModel) {
  67330. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  67331. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  67332. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  67333. }
  67334. });
  67335. return singles;
  67336. }
  67337. var singleCreator = {
  67338. create: create$2,
  67339. dimensions: singleDimensions
  67340. };
  67341. var XY = ['x', 'y'];
  67342. var WH = ['width', 'height'];
  67343. var SingleAxisPointer =
  67344. /** @class */
  67345. function (_super) {
  67346. __extends(SingleAxisPointer, _super);
  67347. function SingleAxisPointer() {
  67348. return _super !== null && _super.apply(this, arguments) || this;
  67349. }
  67350. /**
  67351. * @override
  67352. */
  67353. SingleAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  67354. var axis = axisModel.axis;
  67355. var coordSys = axis.coordinateSystem;
  67356. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  67357. var pixelValue = coordSys.dataToPoint(value)[0];
  67358. var axisPointerType = axisPointerModel.get('type');
  67359. if (axisPointerType && axisPointerType !== 'none') {
  67360. var elStyle = buildElStyle(axisPointerModel);
  67361. var pointerOption = pointerShapeBuilder$2[axisPointerType](axis, pixelValue, otherExtent);
  67362. pointerOption.style = elStyle;
  67363. elOption.graphicKey = pointerOption.type;
  67364. elOption.pointer = pointerOption;
  67365. }
  67366. var layoutInfo = layout$2(axisModel);
  67367. buildCartesianSingleLabelElOption( // @ts-ignore
  67368. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  67369. };
  67370. /**
  67371. * @override
  67372. */
  67373. SingleAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  67374. var layoutInfo = layout$2(axisModel, {
  67375. labelInside: false
  67376. }); // @ts-ignore
  67377. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  67378. var position = getTransformedPosition(axisModel.axis, value, layoutInfo);
  67379. return {
  67380. x: position[0],
  67381. y: position[1],
  67382. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  67383. };
  67384. };
  67385. /**
  67386. * @override
  67387. */
  67388. SingleAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  67389. var axis = axisModel.axis;
  67390. var coordSys = axis.coordinateSystem;
  67391. var dimIndex = getPointDimIndex(axis);
  67392. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  67393. var currPosition = [transform.x, transform.y];
  67394. currPosition[dimIndex] += delta[dimIndex];
  67395. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  67396. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  67397. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  67398. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  67399. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  67400. cursorPoint[dimIndex] = currPosition[dimIndex];
  67401. return {
  67402. x: currPosition[0],
  67403. y: currPosition[1],
  67404. rotation: transform.rotation,
  67405. cursorPoint: cursorPoint,
  67406. tooltipOption: {
  67407. verticalAlign: 'middle'
  67408. }
  67409. };
  67410. };
  67411. return SingleAxisPointer;
  67412. }(BaseAxisPointer);
  67413. var pointerShapeBuilder$2 = {
  67414. line: function (axis, pixelValue, otherExtent) {
  67415. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getPointDimIndex(axis));
  67416. return {
  67417. type: 'Line',
  67418. subPixelOptimize: true,
  67419. shape: targetShape
  67420. };
  67421. },
  67422. shadow: function (axis, pixelValue, otherExtent) {
  67423. var bandWidth = axis.getBandWidth();
  67424. var span = otherExtent[1] - otherExtent[0];
  67425. return {
  67426. type: 'Rect',
  67427. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getPointDimIndex(axis))
  67428. };
  67429. }
  67430. };
  67431. function getPointDimIndex(axis) {
  67432. return axis.isHorizontal() ? 0 : 1;
  67433. }
  67434. function getGlobalExtent(coordSys, dimIndex) {
  67435. var rect = coordSys.getRect();
  67436. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  67437. }
  67438. var SingleView =
  67439. /** @class */
  67440. function (_super) {
  67441. __extends(SingleView, _super);
  67442. function SingleView() {
  67443. var _this = _super !== null && _super.apply(this, arguments) || this;
  67444. _this.type = SingleView.type;
  67445. return _this;
  67446. }
  67447. SingleView.type = 'single';
  67448. return SingleView;
  67449. }(ComponentView);
  67450. function install$v(registers) {
  67451. use(install$s);
  67452. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  67453. registers.registerComponentView(SingleView); // Axis
  67454. registers.registerComponentView(SingleAxisView);
  67455. registers.registerComponentModel(SingleAxisModel);
  67456. axisModelCreator(registers, 'single', SingleAxisModel, SingleAxisModel.defaultOption);
  67457. registers.registerCoordinateSystem('single', singleCreator);
  67458. }
  67459. var CalendarModel =
  67460. /** @class */
  67461. function (_super) {
  67462. __extends(CalendarModel, _super);
  67463. function CalendarModel() {
  67464. var _this = _super !== null && _super.apply(this, arguments) || this;
  67465. _this.type = CalendarModel.type;
  67466. return _this;
  67467. }
  67468. /**
  67469. * @override
  67470. */
  67471. CalendarModel.prototype.init = function (option, parentModel, ecModel) {
  67472. var inputPositionParams = getLayoutParams(option);
  67473. _super.prototype.init.apply(this, arguments);
  67474. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  67475. };
  67476. /**
  67477. * @override
  67478. */
  67479. CalendarModel.prototype.mergeOption = function (option) {
  67480. _super.prototype.mergeOption.apply(this, arguments);
  67481. mergeAndNormalizeLayoutParams(this.option, option);
  67482. };
  67483. CalendarModel.prototype.getCellSize = function () {
  67484. // Has been normalized
  67485. return this.option.cellSize;
  67486. };
  67487. CalendarModel.type = 'calendar';
  67488. CalendarModel.defaultOption = {
  67489. // zlevel: 0,
  67490. z: 2,
  67491. left: 80,
  67492. top: 60,
  67493. cellSize: 20,
  67494. // horizontal vertical
  67495. orient: 'horizontal',
  67496. // month separate line style
  67497. splitLine: {
  67498. show: true,
  67499. lineStyle: {
  67500. color: '#000',
  67501. width: 1,
  67502. type: 'solid'
  67503. }
  67504. },
  67505. // rect style temporarily unused emphasis
  67506. itemStyle: {
  67507. color: '#fff',
  67508. borderWidth: 1,
  67509. borderColor: '#ccc'
  67510. },
  67511. // week text style
  67512. dayLabel: {
  67513. show: true,
  67514. firstDay: 0,
  67515. // start end
  67516. position: 'start',
  67517. margin: '50%',
  67518. color: '#000'
  67519. },
  67520. // month text style
  67521. monthLabel: {
  67522. show: true,
  67523. // start end
  67524. position: 'start',
  67525. margin: 5,
  67526. // center or left
  67527. align: 'center',
  67528. formatter: null,
  67529. color: '#000'
  67530. },
  67531. // year text style
  67532. yearLabel: {
  67533. show: true,
  67534. // top bottom left right
  67535. position: null,
  67536. margin: 30,
  67537. formatter: null,
  67538. color: '#ccc',
  67539. fontFamily: 'sans-serif',
  67540. fontWeight: 'bolder',
  67541. fontSize: 20
  67542. }
  67543. };
  67544. return CalendarModel;
  67545. }(ComponentModel);
  67546. function mergeAndNormalizeLayoutParams(target, raw) {
  67547. // Normalize cellSize
  67548. var cellSize = target.cellSize;
  67549. var cellSizeArr;
  67550. if (!isArray(cellSize)) {
  67551. cellSizeArr = target.cellSize = [cellSize, cellSize];
  67552. } else {
  67553. cellSizeArr = cellSize;
  67554. }
  67555. if (cellSizeArr.length === 1) {
  67556. cellSizeArr[1] = cellSizeArr[0];
  67557. }
  67558. var ignoreSize = map([0, 1], function (hvIdx) {
  67559. // If user have set `width` or both `left` and `right`, cellSizeArr
  67560. // will be automatically set to 'auto', otherwise the default
  67561. // setting of cellSizeArr will make `width` setting not work.
  67562. if (sizeCalculable(raw, hvIdx)) {
  67563. cellSizeArr[hvIdx] = 'auto';
  67564. }
  67565. return cellSizeArr[hvIdx] != null && cellSizeArr[hvIdx] !== 'auto';
  67566. });
  67567. mergeLayoutParam(target, raw, {
  67568. type: 'box',
  67569. ignoreSize: ignoreSize
  67570. });
  67571. }
  67572. var CalendarView =
  67573. /** @class */
  67574. function (_super) {
  67575. __extends(CalendarView, _super);
  67576. function CalendarView() {
  67577. var _this = _super !== null && _super.apply(this, arguments) || this;
  67578. _this.type = CalendarView.type;
  67579. return _this;
  67580. }
  67581. CalendarView.prototype.render = function (calendarModel, ecModel, api) {
  67582. var group = this.group;
  67583. group.removeAll();
  67584. var coordSys = calendarModel.coordinateSystem; // range info
  67585. var rangeData = coordSys.getRangeInfo();
  67586. var orient = coordSys.getOrient(); // locale
  67587. var localeModel = ecModel.getLocaleModel();
  67588. this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function
  67589. this._renderLines(calendarModel, rangeData, orient, group);
  67590. this._renderYearText(calendarModel, rangeData, orient, group);
  67591. this._renderMonthText(calendarModel, localeModel, orient, group);
  67592. this._renderWeekText(calendarModel, localeModel, rangeData, orient, group);
  67593. }; // render day rect
  67594. CalendarView.prototype._renderDayRect = function (calendarModel, rangeData, group) {
  67595. var coordSys = calendarModel.coordinateSystem;
  67596. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  67597. var sw = coordSys.getCellWidth();
  67598. var sh = coordSys.getCellHeight();
  67599. for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time) {
  67600. var point = coordSys.dataToRect([i], false).tl; // every rect
  67601. var rect = new Rect({
  67602. shape: {
  67603. x: point[0],
  67604. y: point[1],
  67605. width: sw,
  67606. height: sh
  67607. },
  67608. cursor: 'default',
  67609. style: itemRectStyleModel
  67610. });
  67611. group.add(rect);
  67612. }
  67613. }; // render separate line
  67614. CalendarView.prototype._renderLines = function (calendarModel, rangeData, orient, group) {
  67615. var self = this;
  67616. var coordSys = calendarModel.coordinateSystem;
  67617. var lineStyleModel = calendarModel.getModel(['splitLine', 'lineStyle']).getLineStyle();
  67618. var show = calendarModel.get(['splitLine', 'show']);
  67619. var lineWidth = lineStyleModel.lineWidth;
  67620. this._tlpoints = [];
  67621. this._blpoints = [];
  67622. this._firstDayOfMonth = [];
  67623. this._firstDayPoints = [];
  67624. var firstDay = rangeData.start;
  67625. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  67626. addPoints(firstDay.formatedDate);
  67627. if (i === 0) {
  67628. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  67629. }
  67630. var date = firstDay.date;
  67631. date.setMonth(date.getMonth() + 1);
  67632. firstDay = coordSys.getDateInfo(date);
  67633. }
  67634. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  67635. function addPoints(date) {
  67636. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  67637. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  67638. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  67639. self._tlpoints.push(points[0]);
  67640. self._blpoints.push(points[points.length - 1]);
  67641. show && self._drawSplitline(points, lineStyleModel, group);
  67642. } // render top/left line
  67643. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line
  67644. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  67645. }; // get points at both ends
  67646. CalendarView.prototype._getEdgesPoints = function (points, lineWidth, orient) {
  67647. var rs = [points[0].slice(), points[points.length - 1].slice()];
  67648. var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth
  67649. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  67650. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  67651. return rs;
  67652. }; // render split line
  67653. CalendarView.prototype._drawSplitline = function (points, lineStyle, group) {
  67654. var poyline = new Polyline({
  67655. z2: 20,
  67656. shape: {
  67657. points: points
  67658. },
  67659. style: lineStyle
  67660. });
  67661. group.add(poyline);
  67662. }; // render month line of one week points
  67663. CalendarView.prototype._getLinePointsOfOneWeek = function (calendarModel, date, orient) {
  67664. var coordSys = calendarModel.coordinateSystem;
  67665. var parsedDate = coordSys.getDateInfo(date);
  67666. var points = [];
  67667. for (var i = 0; i < 7; i++) {
  67668. var tmpD = coordSys.getNextNDay(parsedDate.time, i);
  67669. var point = coordSys.dataToRect([tmpD.time], false);
  67670. points[2 * tmpD.day] = point.tl;
  67671. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  67672. }
  67673. return points;
  67674. };
  67675. CalendarView.prototype._formatterLabel = function (formatter, params) {
  67676. if (isString(formatter) && formatter) {
  67677. return formatTplSimple(formatter, params);
  67678. }
  67679. if (isFunction(formatter)) {
  67680. return formatter(params);
  67681. }
  67682. return params.nameMap;
  67683. };
  67684. CalendarView.prototype._yearTextPositionControl = function (textEl, point, orient, position, margin) {
  67685. var x = point[0];
  67686. var y = point[1];
  67687. var aligns = ['center', 'bottom'];
  67688. if (position === 'bottom') {
  67689. y += margin;
  67690. aligns = ['center', 'top'];
  67691. } else if (position === 'left') {
  67692. x -= margin;
  67693. } else if (position === 'right') {
  67694. x += margin;
  67695. aligns = ['center', 'top'];
  67696. } else {
  67697. // top
  67698. y -= margin;
  67699. }
  67700. var rotate = 0;
  67701. if (position === 'left' || position === 'right') {
  67702. rotate = Math.PI / 2;
  67703. }
  67704. return {
  67705. rotation: rotate,
  67706. x: x,
  67707. y: y,
  67708. style: {
  67709. align: aligns[0],
  67710. verticalAlign: aligns[1]
  67711. }
  67712. };
  67713. }; // render year
  67714. CalendarView.prototype._renderYearText = function (calendarModel, rangeData, orient, group) {
  67715. var yearLabel = calendarModel.getModel('yearLabel');
  67716. if (!yearLabel.get('show')) {
  67717. return;
  67718. }
  67719. var margin = yearLabel.get('margin');
  67720. var pos = yearLabel.get('position');
  67721. if (!pos) {
  67722. pos = orient !== 'horizontal' ? 'top' : 'left';
  67723. }
  67724. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  67725. var xc = (points[0][0] + points[1][0]) / 2;
  67726. var yc = (points[0][1] + points[1][1]) / 2;
  67727. var idx = orient === 'horizontal' ? 0 : 1;
  67728. var posPoints = {
  67729. top: [xc, points[idx][1]],
  67730. bottom: [xc, points[1 - idx][1]],
  67731. left: [points[1 - idx][0], yc],
  67732. right: [points[idx][0], yc]
  67733. };
  67734. var name = rangeData.start.y;
  67735. if (+rangeData.end.y > +rangeData.start.y) {
  67736. name = name + '-' + rangeData.end.y;
  67737. }
  67738. var formatter = yearLabel.get('formatter');
  67739. var params = {
  67740. start: rangeData.start.y,
  67741. end: rangeData.end.y,
  67742. nameMap: name
  67743. };
  67744. var content = this._formatterLabel(formatter, params);
  67745. var yearText = new ZRText({
  67746. z2: 30,
  67747. style: createTextStyle(yearLabel, {
  67748. text: content
  67749. })
  67750. });
  67751. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  67752. group.add(yearText);
  67753. };
  67754. CalendarView.prototype._monthTextPositionControl = function (point, isCenter, orient, position, margin) {
  67755. var align = 'left';
  67756. var vAlign = 'top';
  67757. var x = point[0];
  67758. var y = point[1];
  67759. if (orient === 'horizontal') {
  67760. y = y + margin;
  67761. if (isCenter) {
  67762. align = 'center';
  67763. }
  67764. if (position === 'start') {
  67765. vAlign = 'bottom';
  67766. }
  67767. } else {
  67768. x = x + margin;
  67769. if (isCenter) {
  67770. vAlign = 'middle';
  67771. }
  67772. if (position === 'start') {
  67773. align = 'right';
  67774. }
  67775. }
  67776. return {
  67777. x: x,
  67778. y: y,
  67779. align: align,
  67780. verticalAlign: vAlign
  67781. };
  67782. }; // render month and year text
  67783. CalendarView.prototype._renderMonthText = function (calendarModel, localeModel, orient, group) {
  67784. var monthLabel = calendarModel.getModel('monthLabel');
  67785. if (!monthLabel.get('show')) {
  67786. return;
  67787. }
  67788. var nameMap = monthLabel.get('nameMap');
  67789. var margin = monthLabel.get('margin');
  67790. var pos = monthLabel.get('position');
  67791. var align = monthLabel.get('align');
  67792. var termPoints = [this._tlpoints, this._blpoints];
  67793. if (!nameMap || isString(nameMap)) {
  67794. if (nameMap) {
  67795. // case-sensitive
  67796. localeModel = getLocaleModel(nameMap) || localeModel;
  67797. } // PENDING
  67798. // for ZH locale, original form is `一月` but current form is `1月`
  67799. nameMap = localeModel.get(['time', 'monthAbbr']) || [];
  67800. }
  67801. var idx = pos === 'start' ? 0 : 1;
  67802. var axis = orient === 'horizontal' ? 0 : 1;
  67803. margin = pos === 'start' ? -margin : margin;
  67804. var isCenter = align === 'center';
  67805. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  67806. var tmp = termPoints[idx][i].slice();
  67807. var firstDay = this._firstDayOfMonth[i];
  67808. if (isCenter) {
  67809. var firstDayPoints = this._firstDayPoints[i];
  67810. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  67811. }
  67812. var formatter = monthLabel.get('formatter');
  67813. var name_1 = nameMap[+firstDay.m - 1];
  67814. var params = {
  67815. yyyy: firstDay.y,
  67816. yy: (firstDay.y + '').slice(2),
  67817. MM: firstDay.m,
  67818. M: +firstDay.m,
  67819. nameMap: name_1
  67820. };
  67821. var content = this._formatterLabel(formatter, params);
  67822. var monthText = new ZRText({
  67823. z2: 30,
  67824. style: extend(createTextStyle(monthLabel, {
  67825. text: content
  67826. }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin))
  67827. });
  67828. group.add(monthText);
  67829. }
  67830. };
  67831. CalendarView.prototype._weekTextPositionControl = function (point, orient, position, margin, cellSize) {
  67832. var align = 'center';
  67833. var vAlign = 'middle';
  67834. var x = point[0];
  67835. var y = point[1];
  67836. var isStart = position === 'start';
  67837. if (orient === 'horizontal') {
  67838. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  67839. align = isStart ? 'right' : 'left';
  67840. } else {
  67841. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  67842. vAlign = isStart ? 'bottom' : 'top';
  67843. }
  67844. return {
  67845. x: x,
  67846. y: y,
  67847. align: align,
  67848. verticalAlign: vAlign
  67849. };
  67850. }; // render weeks
  67851. CalendarView.prototype._renderWeekText = function (calendarModel, localeModel, rangeData, orient, group) {
  67852. var dayLabel = calendarModel.getModel('dayLabel');
  67853. if (!dayLabel.get('show')) {
  67854. return;
  67855. }
  67856. var coordSys = calendarModel.coordinateSystem;
  67857. var pos = dayLabel.get('position');
  67858. var nameMap = dayLabel.get('nameMap');
  67859. var margin = dayLabel.get('margin');
  67860. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  67861. if (!nameMap || isString(nameMap)) {
  67862. if (nameMap) {
  67863. // case-sensitive
  67864. localeModel = getLocaleModel(nameMap) || localeModel;
  67865. } // Use the first letter of `dayOfWeekAbbr` if `dayOfWeekShort` doesn't exist in the locale file
  67866. var dayOfWeekShort = localeModel.get(['time', 'dayOfWeekShort']);
  67867. nameMap = dayOfWeekShort || map(localeModel.get(['time', 'dayOfWeekAbbr']), function (val) {
  67868. return val[0];
  67869. });
  67870. }
  67871. var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time;
  67872. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  67873. margin = parsePercent$1(margin, Math.min(cellSize[1], cellSize[0]));
  67874. if (pos === 'start') {
  67875. start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time;
  67876. margin = -margin;
  67877. }
  67878. for (var i = 0; i < 7; i++) {
  67879. var tmpD = coordSys.getNextNDay(start, i);
  67880. var point = coordSys.dataToRect([tmpD.time], false).center;
  67881. var day = i;
  67882. day = Math.abs((i + firstDayOfWeek) % 7);
  67883. var weekText = new ZRText({
  67884. z2: 30,
  67885. style: extend(createTextStyle(dayLabel, {
  67886. text: nameMap[day]
  67887. }), this._weekTextPositionControl(point, orient, pos, margin, cellSize))
  67888. });
  67889. group.add(weekText);
  67890. }
  67891. };
  67892. CalendarView.type = 'calendar';
  67893. return CalendarView;
  67894. }(ComponentView);
  67895. var PROXIMATE_ONE_DAY = 86400000;
  67896. var Calendar =
  67897. /** @class */
  67898. function () {
  67899. function Calendar(calendarModel, ecModel, api) {
  67900. this.type = 'calendar';
  67901. this.dimensions = Calendar.dimensions; // Required in createListFromData
  67902. this.getDimensionsInfo = Calendar.getDimensionsInfo;
  67903. this._model = calendarModel;
  67904. }
  67905. Calendar.getDimensionsInfo = function () {
  67906. return [{
  67907. name: 'time',
  67908. type: 'time'
  67909. }, 'value'];
  67910. };
  67911. Calendar.prototype.getRangeInfo = function () {
  67912. return this._rangeInfo;
  67913. };
  67914. Calendar.prototype.getModel = function () {
  67915. return this._model;
  67916. };
  67917. Calendar.prototype.getRect = function () {
  67918. return this._rect;
  67919. };
  67920. Calendar.prototype.getCellWidth = function () {
  67921. return this._sw;
  67922. };
  67923. Calendar.prototype.getCellHeight = function () {
  67924. return this._sh;
  67925. };
  67926. Calendar.prototype.getOrient = function () {
  67927. return this._orient;
  67928. };
  67929. /**
  67930. * getFirstDayOfWeek
  67931. *
  67932. * @example
  67933. * 0 : start at Sunday
  67934. * 1 : start at Monday
  67935. *
  67936. * @return {number}
  67937. */
  67938. Calendar.prototype.getFirstDayOfWeek = function () {
  67939. return this._firstDayOfWeek;
  67940. };
  67941. /**
  67942. * get date info
  67943. * }
  67944. */
  67945. Calendar.prototype.getDateInfo = function (date) {
  67946. date = parseDate(date);
  67947. var y = date.getFullYear();
  67948. var m = date.getMonth() + 1;
  67949. var mStr = m < 10 ? '0' + m : '' + m;
  67950. var d = date.getDate();
  67951. var dStr = d < 10 ? '0' + d : '' + d;
  67952. var day = date.getDay();
  67953. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  67954. return {
  67955. y: y + '',
  67956. m: mStr,
  67957. d: dStr,
  67958. day: day,
  67959. time: date.getTime(),
  67960. formatedDate: y + '-' + mStr + '-' + dStr,
  67961. date: date
  67962. };
  67963. };
  67964. Calendar.prototype.getNextNDay = function (date, n) {
  67965. n = n || 0;
  67966. if (n === 0) {
  67967. return this.getDateInfo(date);
  67968. }
  67969. date = new Date(this.getDateInfo(date).time);
  67970. date.setDate(date.getDate() + n);
  67971. return this.getDateInfo(date);
  67972. };
  67973. Calendar.prototype.update = function (ecModel, api) {
  67974. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  67975. this._orient = this._model.get('orient');
  67976. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  67977. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  67978. var weeks = this._rangeInfo.weeks || 1;
  67979. var whNames = ['width', 'height'];
  67980. var cellSize = this._model.getCellSize().slice();
  67981. var layoutParams = this._model.getBoxLayoutParams();
  67982. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  67983. each([0, 1], function (idx) {
  67984. if (cellSizeSpecified(cellSize, idx)) {
  67985. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  67986. }
  67987. });
  67988. var whGlobal = {
  67989. width: api.getWidth(),
  67990. height: api.getHeight()
  67991. };
  67992. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  67993. each([0, 1], function (idx) {
  67994. if (!cellSizeSpecified(cellSize, idx)) {
  67995. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  67996. }
  67997. });
  67998. function cellSizeSpecified(cellSize, idx) {
  67999. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  68000. } // Has been calculated out number.
  68001. this._sw = cellSize[0];
  68002. this._sh = cellSize[1];
  68003. };
  68004. /**
  68005. * Convert a time data(time, value) item to (x, y) point.
  68006. */
  68007. // TODO Clamp of calendar is not same with cartesian coordinate systems.
  68008. // It will return NaN if data exceeds.
  68009. Calendar.prototype.dataToPoint = function (data, clamp) {
  68010. isArray(data) && (data = data[0]);
  68011. clamp == null && (clamp = true);
  68012. var dayInfo = this.getDateInfo(data);
  68013. var range = this._rangeInfo;
  68014. var date = dayInfo.formatedDate; // if not in range return [NaN, NaN]
  68015. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY)) {
  68016. return [NaN, NaN];
  68017. }
  68018. var week = dayInfo.day;
  68019. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  68020. if (this._orient === 'vertical') {
  68021. return [this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2];
  68022. }
  68023. return [this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2];
  68024. };
  68025. /**
  68026. * Convert a (x, y) point to time data
  68027. */
  68028. Calendar.prototype.pointToData = function (point) {
  68029. var date = this.pointToDate(point);
  68030. return date && date.time;
  68031. };
  68032. /**
  68033. * Convert a time date item to (x, y) four point.
  68034. */
  68035. Calendar.prototype.dataToRect = function (data, clamp) {
  68036. var point = this.dataToPoint(data, clamp);
  68037. return {
  68038. contentShape: {
  68039. x: point[0] - (this._sw - this._lineWidth) / 2,
  68040. y: point[1] - (this._sh - this._lineWidth) / 2,
  68041. width: this._sw - this._lineWidth,
  68042. height: this._sh - this._lineWidth
  68043. },
  68044. center: point,
  68045. tl: [point[0] - this._sw / 2, point[1] - this._sh / 2],
  68046. tr: [point[0] + this._sw / 2, point[1] - this._sh / 2],
  68047. br: [point[0] + this._sw / 2, point[1] + this._sh / 2],
  68048. bl: [point[0] - this._sw / 2, point[1] + this._sh / 2]
  68049. };
  68050. };
  68051. /**
  68052. * Convert a (x, y) point to time date
  68053. *
  68054. * @param {Array} point point
  68055. * @return {Object} date
  68056. */
  68057. Calendar.prototype.pointToDate = function (point) {
  68058. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  68059. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  68060. var range = this._rangeInfo.range;
  68061. if (this._orient === 'vertical') {
  68062. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  68063. }
  68064. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  68065. };
  68066. Calendar.prototype.convertToPixel = function (ecModel, finder, value) {
  68067. var coordSys = getCoordSys$4(finder);
  68068. return coordSys === this ? coordSys.dataToPoint(value) : null;
  68069. };
  68070. Calendar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  68071. var coordSys = getCoordSys$4(finder);
  68072. return coordSys === this ? coordSys.pointToData(pixel) : null;
  68073. };
  68074. Calendar.prototype.containPoint = function (point) {
  68075. console.warn('Not implemented.');
  68076. return false;
  68077. };
  68078. /**
  68079. * initRange
  68080. * Normalize to an [start, end] array
  68081. */
  68082. Calendar.prototype._initRangeOption = function () {
  68083. var range = this._model.get('range');
  68084. var normalizedRange; // Convert [1990] to 1990
  68085. if (isArray(range) && range.length === 1) {
  68086. range = range[0];
  68087. }
  68088. if (!isArray(range)) {
  68089. var rangeStr = range.toString(); // One year.
  68090. if (/^\d{4}$/.test(rangeStr)) {
  68091. normalizedRange = [rangeStr + '-01-01', rangeStr + '-12-31'];
  68092. } // One month
  68093. if (/^\d{4}[\/|-]\d{1,2}$/.test(rangeStr)) {
  68094. var start = this.getDateInfo(rangeStr);
  68095. var firstDay = start.date;
  68096. firstDay.setMonth(firstDay.getMonth() + 1);
  68097. var end = this.getNextNDay(firstDay, -1);
  68098. normalizedRange = [start.formatedDate, end.formatedDate];
  68099. } // One day
  68100. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rangeStr)) {
  68101. normalizedRange = [rangeStr, rangeStr];
  68102. }
  68103. } else {
  68104. normalizedRange = range;
  68105. }
  68106. if (!normalizedRange) {
  68107. if ("development" !== 'production') {
  68108. logError('Invalid date range.');
  68109. } // Not handling it.
  68110. return range;
  68111. }
  68112. var tmp = this._getRangeInfo(normalizedRange);
  68113. if (tmp.start.time > tmp.end.time) {
  68114. normalizedRange.reverse();
  68115. }
  68116. return normalizedRange;
  68117. };
  68118. /**
  68119. * range info
  68120. *
  68121. * @private
  68122. * @param {Array} range range ['2017-01-01', '2017-07-08']
  68123. * If range[0] > range[1], they will not be reversed.
  68124. * @return {Object} obj
  68125. */
  68126. Calendar.prototype._getRangeInfo = function (range) {
  68127. var parsedRange = [this.getDateInfo(range[0]), this.getDateInfo(range[1])];
  68128. var reversed;
  68129. if (parsedRange[0].time > parsedRange[1].time) {
  68130. reversed = true;
  68131. parsedRange.reverse();
  68132. }
  68133. var allDay = Math.floor(parsedRange[1].time / PROXIMATE_ONE_DAY) - Math.floor(parsedRange[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case1 (#11677 #10430):
  68134. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  68135. // Consider case2:
  68136. // Firstly set system timezone as "Time Zone: America/Toronto",
  68137. // ```
  68138. // let first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  68139. // let second = new Date(1478412000000);
  68140. // let allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  68141. // ```
  68142. // will get wrong result because of DST. So we should fix it.
  68143. var date = new Date(parsedRange[0].time);
  68144. var startDateNum = date.getDate();
  68145. var endDateNum = parsedRange[1].date.getDate();
  68146. date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date.
  68147. var dateNum = date.getDate();
  68148. if (dateNum !== endDateNum) {
  68149. var sign = date.getTime() - parsedRange[1].time > 0 ? 1 : -1;
  68150. while ((dateNum = date.getDate()) !== endDateNum && (date.getTime() - parsedRange[1].time) * sign > 0) {
  68151. allDay -= sign;
  68152. date.setDate(dateNum - sign);
  68153. }
  68154. }
  68155. var weeks = Math.floor((allDay + parsedRange[0].day + 6) / 7);
  68156. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  68157. reversed && parsedRange.reverse();
  68158. return {
  68159. range: [parsedRange[0].formatedDate, parsedRange[1].formatedDate],
  68160. start: parsedRange[0],
  68161. end: parsedRange[1],
  68162. allDay: allDay,
  68163. weeks: weeks,
  68164. // From 0.
  68165. nthWeek: nthWeek,
  68166. fweek: parsedRange[0].day,
  68167. lweek: parsedRange[1].day
  68168. };
  68169. };
  68170. /**
  68171. * get date by nthWeeks and week day in range
  68172. *
  68173. * @private
  68174. * @param {number} nthWeek the week
  68175. * @param {number} day the week day
  68176. * @param {Array} range [d1, d2]
  68177. * @return {Object}
  68178. */
  68179. Calendar.prototype._getDateByWeeksAndDay = function (nthWeek, day, range) {
  68180. var rangeInfo = this._getRangeInfo(range);
  68181. if (nthWeek > rangeInfo.weeks || nthWeek === 0 && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) {
  68182. return null;
  68183. }
  68184. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  68185. var date = new Date(rangeInfo.start.time);
  68186. date.setDate(+rangeInfo.start.d + nthDay);
  68187. return this.getDateInfo(date);
  68188. };
  68189. Calendar.create = function (ecModel, api) {
  68190. var calendarList = [];
  68191. ecModel.eachComponent('calendar', function (calendarModel) {
  68192. var calendar = new Calendar(calendarModel, ecModel, api);
  68193. calendarList.push(calendar);
  68194. calendarModel.coordinateSystem = calendar;
  68195. });
  68196. ecModel.eachSeries(function (calendarSeries) {
  68197. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  68198. // Inject coordinate system
  68199. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  68200. }
  68201. });
  68202. return calendarList;
  68203. };
  68204. Calendar.dimensions = ['time', 'value'];
  68205. return Calendar;
  68206. }();
  68207. function getCoordSys$4(finder) {
  68208. var calendarModel = finder.calendarModel;
  68209. var seriesModel = finder.seriesModel;
  68210. var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null;
  68211. return coordSys;
  68212. }
  68213. function install$w(registers) {
  68214. registers.registerComponentModel(CalendarModel);
  68215. registers.registerComponentView(CalendarView);
  68216. registers.registerCoordinateSystem('calendar', Calendar);
  68217. }
  68218. function setKeyInfoToNewElOption(resultItem, newElOption) {
  68219. var existElOption = resultItem.existing; // Set id and type after id assigned.
  68220. newElOption.id = resultItem.keyInfo.id;
  68221. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  68222. if (newElOption.parentId == null) {
  68223. var newElParentOption = newElOption.parentOption;
  68224. if (newElParentOption) {
  68225. newElOption.parentId = newElParentOption.id;
  68226. } else if (existElOption) {
  68227. newElOption.parentId = existElOption.parentId;
  68228. }
  68229. } // Clear
  68230. newElOption.parentOption = null;
  68231. }
  68232. function isSetLoc(obj, props) {
  68233. var isSet;
  68234. each(props, function (prop) {
  68235. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  68236. });
  68237. return isSet;
  68238. }
  68239. function mergeNewElOptionToExist(existList, index, newElOption) {
  68240. // Update existing options, for `getOption` feature.
  68241. var newElOptCopy = extend({}, newElOption);
  68242. var existElOption = existList[index];
  68243. var $action = newElOption.$action || 'merge';
  68244. if ($action === 'merge') {
  68245. if (existElOption) {
  68246. if ("development" !== 'production') {
  68247. var newType = newElOption.type;
  68248. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  68249. } // We can ensure that newElOptCopy and existElOption are not
  68250. // the same object, so `merge` will not change newElOptCopy.
  68251. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  68252. mergeLayoutParam(existElOption, newElOptCopy, {
  68253. ignoreSize: true
  68254. }); // Will be used in render.
  68255. copyLayoutParams(newElOption, existElOption); // Copy transition info to new option so it can be used in the transition.
  68256. // DO IT AFTER merge
  68257. copyTransitionInfo(newElOption, existElOption);
  68258. copyTransitionInfo(newElOption, existElOption, 'shape');
  68259. copyTransitionInfo(newElOption, existElOption, 'style');
  68260. copyTransitionInfo(newElOption, existElOption, 'extra'); // Copy clipPath
  68261. newElOption.clipPath = existElOption.clipPath;
  68262. } else {
  68263. existList[index] = newElOptCopy;
  68264. }
  68265. } else if ($action === 'replace') {
  68266. existList[index] = newElOptCopy;
  68267. } else if ($action === 'remove') {
  68268. // null will be cleaned later.
  68269. existElOption && (existList[index] = null);
  68270. }
  68271. }
  68272. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  68273. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  68274. function copyTransitionInfo(target, source, targetProp) {
  68275. if (targetProp) {
  68276. if (!target[targetProp] && source[targetProp]) {
  68277. // TODO avoid creating this empty object when there is no transition configuration.
  68278. target[targetProp] = {};
  68279. }
  68280. target = target[targetProp];
  68281. source = source[targetProp];
  68282. }
  68283. if (!target || !source) {
  68284. return;
  68285. }
  68286. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  68287. for (var i = 0; i < props.length; i++) {
  68288. var prop = props[i];
  68289. if (target[prop] == null && source[prop] != null) {
  68290. target[prop] = source[prop];
  68291. }
  68292. }
  68293. }
  68294. function setLayoutInfoToExist(existItem, newElOption) {
  68295. if (!existItem) {
  68296. return;
  68297. }
  68298. existItem.hv = newElOption.hv = [// Rigid body, don't care about `width`.
  68299. isSetLoc(newElOption, ['left', 'right']), // Rigid body, don't care about `height`.
  68300. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  68301. if (existItem.type === 'group') {
  68302. var existingGroupOpt = existItem;
  68303. var newGroupOpt = newElOption;
  68304. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  68305. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  68306. }
  68307. }
  68308. var GraphicComponentModel =
  68309. /** @class */
  68310. function (_super) {
  68311. __extends(GraphicComponentModel, _super);
  68312. function GraphicComponentModel() {
  68313. var _this = _super !== null && _super.apply(this, arguments) || this;
  68314. _this.type = GraphicComponentModel.type;
  68315. _this.preventAutoZ = true;
  68316. return _this;
  68317. }
  68318. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  68319. // Prevent default merge to elements
  68320. var elements = this.option.elements;
  68321. this.option.elements = null;
  68322. _super.prototype.mergeOption.call(this, option, ecModel);
  68323. this.option.elements = elements;
  68324. };
  68325. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  68326. var thisOption = this.option;
  68327. var newList = (isInit ? thisOption : newOption).elements;
  68328. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  68329. var flattenedList = [];
  68330. this._flatten(newList, flattenedList, null);
  68331. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  68332. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  68333. each(mappingResult, function (resultItem, index) {
  68334. var newElOption = resultItem.newOption;
  68335. if ("development" !== 'production') {
  68336. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  68337. }
  68338. if (!newElOption) {
  68339. return;
  68340. }
  68341. elOptionsToUpdate.push(newElOption);
  68342. setKeyInfoToNewElOption(resultItem, newElOption);
  68343. mergeNewElOptionToExist(existList, index, newElOption);
  68344. setLayoutInfoToExist(existList[index], newElOption);
  68345. }, this); // Clean
  68346. thisOption.elements = filter(existList, function (item) {
  68347. // $action should be volatile, otherwise option gotten from
  68348. // `getOption` will contain unexpected $action.
  68349. item && delete item.$action;
  68350. return item != null;
  68351. });
  68352. };
  68353. /**
  68354. * Convert
  68355. * [{
  68356. * type: 'group',
  68357. * id: 'xx',
  68358. * children: [{type: 'circle'}, {type: 'polygon'}]
  68359. * }]
  68360. * to
  68361. * [
  68362. * {type: 'group', id: 'xx'},
  68363. * {type: 'circle', parentId: 'xx'},
  68364. * {type: 'polygon', parentId: 'xx'}
  68365. * ]
  68366. */
  68367. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  68368. each(optionList, function (option) {
  68369. if (!option) {
  68370. return;
  68371. }
  68372. if (parentOption) {
  68373. option.parentOption = parentOption;
  68374. }
  68375. result.push(option);
  68376. var children = option.children; // here we don't judge if option.type is `group`
  68377. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  68378. if (children && children.length) {
  68379. this._flatten(children, result, option);
  68380. } // Deleting for JSON output, and for not affecting group creation.
  68381. delete option.children;
  68382. }, this);
  68383. }; // FIXME
  68384. // Pass to view using payload? setOption has a payload?
  68385. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  68386. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  68387. this._elOptionsToUpdate = null;
  68388. return els;
  68389. };
  68390. GraphicComponentModel.type = 'graphic';
  68391. GraphicComponentModel.defaultOption = {
  68392. elements: [] // parentId: null
  68393. };
  68394. return GraphicComponentModel;
  68395. }(ComponentModel);
  68396. var nonShapeGraphicElements = {
  68397. // Reserved but not supported in graphic component.
  68398. path: null,
  68399. compoundPath: null,
  68400. // Supported in graphic component.
  68401. group: Group,
  68402. image: ZRImage,
  68403. text: ZRText
  68404. };
  68405. var inner$e = makeInner(); // ------------------------
  68406. // View
  68407. // ------------------------
  68408. var GraphicComponentView =
  68409. /** @class */
  68410. function (_super) {
  68411. __extends(GraphicComponentView, _super);
  68412. function GraphicComponentView() {
  68413. var _this = _super !== null && _super.apply(this, arguments) || this;
  68414. _this.type = GraphicComponentView.type;
  68415. return _this;
  68416. }
  68417. GraphicComponentView.prototype.init = function () {
  68418. this._elMap = createHashMap();
  68419. };
  68420. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  68421. // Having leveraged between use cases and algorithm complexity, a very
  68422. // simple layout mechanism is used:
  68423. // The size(width/height) can be determined by itself or its parent (not
  68424. // implemented yet), but can not by its children. (Top-down travel)
  68425. // The location(x/y) can be determined by the bounding rect of itself
  68426. // (can including its descendants or not) and the size of its parent.
  68427. // (Bottom-up travel)
  68428. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  68429. // view will be reused.
  68430. if (graphicModel !== this._lastGraphicModel) {
  68431. this._clear();
  68432. }
  68433. this._lastGraphicModel = graphicModel;
  68434. this._updateElements(graphicModel);
  68435. this._relocate(graphicModel, api);
  68436. };
  68437. /**
  68438. * Update graphic elements.
  68439. */
  68440. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  68441. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  68442. if (!elOptionsToUpdate) {
  68443. return;
  68444. }
  68445. var elMap = this._elMap;
  68446. var rootGroup = this.group;
  68447. var globalZ = graphicModel.get('z');
  68448. var globalZLevel = graphicModel.get('zlevel'); // Top-down tranverse to assign graphic settings to each elements.
  68449. each(elOptionsToUpdate, function (elOption) {
  68450. var id = convertOptionIdName(elOption.id, null);
  68451. var elExisting = id != null ? elMap.get(id) : null;
  68452. var parentId = convertOptionIdName(elOption.parentId, null);
  68453. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  68454. var elType = elOption.type;
  68455. var elOptionStyle = elOption.style;
  68456. if (elType === 'text' && elOptionStyle) {
  68457. // In top/bottom mode, textVerticalAlign should not be used, which cause
  68458. // inaccurately locating.
  68459. if (elOption.hv && elOption.hv[1]) {
  68460. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  68461. }
  68462. }
  68463. var textContentOption = elOption.textContent;
  68464. var textConfig = elOption.textConfig;
  68465. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  68466. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  68467. if (!textConfig && convertResult.textConfig) {
  68468. textConfig = elOption.textConfig = convertResult.textConfig;
  68469. }
  68470. if (!textContentOption && convertResult.textContent) {
  68471. textContentOption = convertResult.textContent;
  68472. }
  68473. } // Remove unnecessary props to avoid potential problems.
  68474. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  68475. if ("development" !== 'production') {
  68476. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  68477. }
  68478. var $action = elOption.$action || 'merge';
  68479. var isMerge = $action === 'merge';
  68480. var isReplace = $action === 'replace';
  68481. if (isMerge) {
  68482. var isInit = !elExisting;
  68483. var el_1 = elExisting;
  68484. if (isInit) {
  68485. el_1 = createEl$1(id, targetElParent, elOption.type, elMap);
  68486. } else {
  68487. el_1 && (inner$e(el_1).isNew = false); // Stop and restore before update any other attributes.
  68488. stopPreviousKeyframeAnimationAndRestore(el_1);
  68489. }
  68490. if (el_1) {
  68491. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  68492. isInit: isInit
  68493. });
  68494. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  68495. }
  68496. } else if (isReplace) {
  68497. removeEl(elExisting, elOption, elMap, graphicModel);
  68498. var el_2 = createEl$1(id, targetElParent, elOption.type, elMap);
  68499. if (el_2) {
  68500. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  68501. isInit: true
  68502. });
  68503. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  68504. }
  68505. } else if ($action === 'remove') {
  68506. updateLeaveTo(elExisting, elOption);
  68507. removeEl(elExisting, elOption, elMap, graphicModel);
  68508. }
  68509. var el = elMap.get(id);
  68510. if (el && textContentOption) {
  68511. if (isMerge) {
  68512. var textContentExisting = el.getTextContent();
  68513. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  68514. } else if (isReplace) {
  68515. el.setTextContent(new ZRText(textContentOption));
  68516. }
  68517. }
  68518. if (el) {
  68519. var clipPathOption = elOption.clipPath;
  68520. if (clipPathOption) {
  68521. var clipPathType = clipPathOption.type;
  68522. var clipPath = void 0;
  68523. var isInit = false;
  68524. if (isMerge) {
  68525. var oldClipPath = el.getClipPath();
  68526. isInit = !oldClipPath || inner$e(oldClipPath).type !== clipPathType;
  68527. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  68528. } else if (isReplace) {
  68529. isInit = true;
  68530. clipPath = newEl(clipPathType);
  68531. }
  68532. el.setClipPath(clipPath);
  68533. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  68534. isInit: isInit
  68535. });
  68536. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  68537. }
  68538. var elInner = inner$e(el);
  68539. el.setTextConfig(textConfig);
  68540. elInner.option = elOption;
  68541. setEventData(el, graphicModel, elOption);
  68542. setTooltipConfig({
  68543. el: el,
  68544. componentModel: graphicModel,
  68545. itemName: el.name,
  68546. itemTooltipOption: elOption.tooltip
  68547. });
  68548. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  68549. }
  68550. });
  68551. };
  68552. /**
  68553. * Locate graphic elements.
  68554. */
  68555. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  68556. var elOptions = graphicModel.option.elements;
  68557. var rootGroup = this.group;
  68558. var elMap = this._elMap;
  68559. var apiWidth = api.getWidth();
  68560. var apiHeight = api.getHeight();
  68561. var xy = ['x', 'y']; // Top-down to calculate percentage width/height of group
  68562. for (var i = 0; i < elOptions.length; i++) {
  68563. var elOption = elOptions[i];
  68564. var id = convertOptionIdName(elOption.id, null);
  68565. var el = id != null ? elMap.get(id) : null;
  68566. if (!el || !el.isGroup) {
  68567. continue;
  68568. }
  68569. var parentEl = el.parent;
  68570. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  68571. var elInner = inner$e(el);
  68572. var parentElInner = inner$e(parentEl);
  68573. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  68574. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  68575. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  68576. for (var i = elOptions.length - 1; i >= 0; i--) {
  68577. var elOption = elOptions[i];
  68578. var id = convertOptionIdName(elOption.id, null);
  68579. var el = id != null ? elMap.get(id) : null;
  68580. if (!el) {
  68581. continue;
  68582. }
  68583. var parentEl = el.parent;
  68584. var parentElInner = inner$e(parentEl);
  68585. var containerInfo = parentEl === rootGroup ? {
  68586. width: apiWidth,
  68587. height: apiHeight
  68588. } : {
  68589. width: parentElInner.width,
  68590. height: parentElInner.height
  68591. }; // PENDING
  68592. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  68593. // does not include the rect of [0, 0, group.width, group.height], which
  68594. // is probably weird for users. Should we make a break change for it?
  68595. var layoutPos = {};
  68596. var layouted = positionElement(el, elOption, containerInfo, null, {
  68597. hv: elOption.hv,
  68598. boundingMode: elOption.bounding
  68599. }, layoutPos);
  68600. if (!inner$e(el).isNew && layouted) {
  68601. var transition = elOption.transition;
  68602. var animatePos = {};
  68603. for (var k = 0; k < xy.length; k++) {
  68604. var key = xy[k];
  68605. var val = layoutPos[key];
  68606. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  68607. animatePos[key] = val;
  68608. } else {
  68609. el[key] = val;
  68610. }
  68611. }
  68612. updateProps(el, animatePos, graphicModel, 0);
  68613. } else {
  68614. el.attr(layoutPos);
  68615. }
  68616. }
  68617. };
  68618. /**
  68619. * Clear all elements.
  68620. */
  68621. GraphicComponentView.prototype._clear = function () {
  68622. var _this = this;
  68623. var elMap = this._elMap;
  68624. elMap.each(function (el) {
  68625. removeEl(el, inner$e(el).option, elMap, _this._lastGraphicModel);
  68626. });
  68627. this._elMap = createHashMap();
  68628. };
  68629. GraphicComponentView.prototype.dispose = function () {
  68630. this._clear();
  68631. };
  68632. GraphicComponentView.type = 'graphic';
  68633. return GraphicComponentView;
  68634. }(ComponentView);
  68635. function newEl(graphicType) {
  68636. if ("development" !== 'production') {
  68637. assert(graphicType, 'graphic type MUST be set');
  68638. }
  68639. var Clz = hasOwn(nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  68640. // overwritten by users, so do them first.
  68641. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  68642. if ("development" !== 'production') {
  68643. assert(Clz, "graphic type " + graphicType + " can not be found");
  68644. }
  68645. var el = new Clz({});
  68646. inner$e(el).type = graphicType;
  68647. return el;
  68648. }
  68649. function createEl$1(id, targetElParent, graphicType, elMap) {
  68650. var el = newEl(graphicType);
  68651. targetElParent.add(el);
  68652. elMap.set(id, el);
  68653. inner$e(el).id = id;
  68654. inner$e(el).isNew = true;
  68655. return el;
  68656. }
  68657. function removeEl(elExisting, elOption, elMap, graphicModel) {
  68658. var existElParent = elExisting && elExisting.parent;
  68659. if (existElParent) {
  68660. elExisting.type === 'group' && elExisting.traverse(function (el) {
  68661. removeEl(el, elOption, elMap, graphicModel);
  68662. });
  68663. applyLeaveTransition(elExisting, elOption, graphicModel);
  68664. elMap.removeKey(inner$e(elExisting).id);
  68665. }
  68666. }
  68667. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  68668. if (!el.isGroup) {
  68669. each([['cursor', Displayable.prototype.cursor], // We should not support configure z and zlevel in the element level.
  68670. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  68671. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0], // z2 must not be null/undefined, otherwise sort error may occur.
  68672. ['z2', 0]], function (item) {
  68673. var prop = item[0];
  68674. if (hasOwn(elOption, prop)) {
  68675. el[prop] = retrieve2(elOption[prop], item[1]);
  68676. } else if (el[prop] == null) {
  68677. el[prop] = item[1];
  68678. }
  68679. });
  68680. }
  68681. each(keys(elOption), function (key) {
  68682. // Assign event handlers.
  68683. // PENDING: should enumerate all event names or use pattern matching?
  68684. if (key.indexOf('on') === 0) {
  68685. var val = elOption[key];
  68686. el[key] = isFunction(val) ? val : null;
  68687. }
  68688. });
  68689. if (hasOwn(elOption, 'draggable')) {
  68690. el.draggable = elOption.draggable;
  68691. } // Other attributes
  68692. elOption.name != null && (el.name = elOption.name);
  68693. elOption.id != null && (el.id = elOption.id);
  68694. } // Remove unnecessary props to avoid potential problems.
  68695. function getCleanedElOption(elOption) {
  68696. elOption = extend({}, elOption);
  68697. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  68698. delete elOption[name];
  68699. });
  68700. return elOption;
  68701. }
  68702. function setEventData(el, graphicModel, elOption) {
  68703. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  68704. if (!el.silent && !el.ignore && !eventData) {
  68705. eventData = getECData(el).eventData = {
  68706. componentType: 'graphic',
  68707. componentIndex: graphicModel.componentIndex,
  68708. name: el.name
  68709. };
  68710. } // `elOption.info` enables user to mount some info on
  68711. // elements and use them in event handlers.
  68712. if (eventData) {
  68713. eventData.info = elOption.info;
  68714. }
  68715. }
  68716. function install$x(registers) {
  68717. registers.registerComponentModel(GraphicComponentModel);
  68718. registers.registerComponentView(GraphicComponentView);
  68719. registers.registerPreprocessor(function (option) {
  68720. var graphicOption = option.graphic; // Convert
  68721. // {graphic: [{left: 10, type: 'circle'}, ...]}
  68722. // or
  68723. // {graphic: {left: 10, type: 'circle'}}
  68724. // to
  68725. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  68726. if (isArray(graphicOption)) {
  68727. if (!graphicOption[0] || !graphicOption[0].elements) {
  68728. option.graphic = [{
  68729. elements: graphicOption
  68730. }];
  68731. } else {
  68732. // Only one graphic instance can be instantiated. (We don't
  68733. // want that too many views are created in echarts._viewMap.)
  68734. option.graphic = [option.graphic[0]];
  68735. }
  68736. } else if (graphicOption && !graphicOption.elements) {
  68737. option.graphic = [{
  68738. elements: [graphicOption]
  68739. }];
  68740. }
  68741. });
  68742. }
  68743. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  68744. // FIXME: polar has been broken (but rarely used).
  68745. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  68746. function isCoordSupported(seriesModel) {
  68747. var coordType = seriesModel.get('coordinateSystem');
  68748. return indexOf(SERIES_COORDS, coordType) >= 0;
  68749. }
  68750. function getAxisMainType(axisDim) {
  68751. if ("development" !== 'production') {
  68752. assert(axisDim);
  68753. }
  68754. return axisDim + 'Axis';
  68755. }
  68756. /**
  68757. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  68758. * This function finds all linked dataZoomModels start from the given payload.
  68759. */
  68760. function findEffectedDataZooms(ecModel, payload) {
  68761. // Key: `DataZoomAxisDimension`
  68762. var axisRecords = createHashMap();
  68763. var effectedModels = []; // Key: uid of dataZoomModel
  68764. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  68765. ecModel.eachComponent({
  68766. mainType: 'dataZoom',
  68767. query: payload
  68768. }, function (dataZoomModel) {
  68769. if (!effectedModelMap.get(dataZoomModel.uid)) {
  68770. addToEffected(dataZoomModel);
  68771. }
  68772. }); // Start from the given dataZoomModels, travel the graph to find
  68773. // all of the linked dataZoom models.
  68774. var foundNewLink;
  68775. do {
  68776. foundNewLink = false;
  68777. ecModel.eachComponent('dataZoom', processSingle);
  68778. } while (foundNewLink);
  68779. function processSingle(dataZoomModel) {
  68780. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  68781. addToEffected(dataZoomModel);
  68782. foundNewLink = true;
  68783. }
  68784. }
  68785. function addToEffected(dataZoom) {
  68786. effectedModelMap.set(dataZoom.uid, true);
  68787. effectedModels.push(dataZoom);
  68788. markAxisControlled(dataZoom);
  68789. }
  68790. function isLinked(dataZoomModel) {
  68791. var isLink = false;
  68792. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68793. var axisIdxArr = axisRecords.get(axisDim);
  68794. if (axisIdxArr && axisIdxArr[axisIndex]) {
  68795. isLink = true;
  68796. }
  68797. });
  68798. return isLink;
  68799. }
  68800. function markAxisControlled(dataZoomModel) {
  68801. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68802. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  68803. });
  68804. }
  68805. return effectedModels;
  68806. }
  68807. /**
  68808. * Find the first target coordinate system.
  68809. * Available after model built.
  68810. *
  68811. * @return Like {
  68812. * grid: [
  68813. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  68814. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  68815. * ...
  68816. * ], // cartesians must not be null/undefined.
  68817. * polar: [
  68818. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  68819. * ...
  68820. * ], // polars must not be null/undefined.
  68821. * singleAxis: [
  68822. * {model: coord0, axisModels: [], coordIndex: 0}
  68823. * ]
  68824. * }
  68825. */
  68826. function collectReferCoordSysModelInfo(dataZoomModel) {
  68827. var ecModel = dataZoomModel.ecModel;
  68828. var coordSysInfoWrap = {
  68829. infoList: [],
  68830. infoMap: createHashMap()
  68831. };
  68832. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68833. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  68834. if (!axisModel) {
  68835. return;
  68836. }
  68837. var coordSysModel = axisModel.getCoordSysModel();
  68838. if (!coordSysModel) {
  68839. return;
  68840. }
  68841. var coordSysUid = coordSysModel.uid;
  68842. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  68843. if (!coordSysInfo) {
  68844. coordSysInfo = {
  68845. model: coordSysModel,
  68846. axisModels: []
  68847. };
  68848. coordSysInfoWrap.infoList.push(coordSysInfo);
  68849. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  68850. }
  68851. coordSysInfo.axisModels.push(axisModel);
  68852. });
  68853. return coordSysInfoWrap;
  68854. }
  68855. var DataZoomAxisInfo =
  68856. /** @class */
  68857. function () {
  68858. function DataZoomAxisInfo() {
  68859. this.indexList = [];
  68860. this.indexMap = [];
  68861. }
  68862. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  68863. // Remove duplication.
  68864. if (!this.indexMap[axisCmptIdx]) {
  68865. this.indexList.push(axisCmptIdx);
  68866. this.indexMap[axisCmptIdx] = true;
  68867. }
  68868. };
  68869. return DataZoomAxisInfo;
  68870. }();
  68871. var DataZoomModel =
  68872. /** @class */
  68873. function (_super) {
  68874. __extends(DataZoomModel, _super);
  68875. function DataZoomModel() {
  68876. var _this = _super !== null && _super.apply(this, arguments) || this;
  68877. _this.type = DataZoomModel.type;
  68878. _this._autoThrottle = true;
  68879. _this._noTarget = true;
  68880. /**
  68881. * It is `[rangeModeForMin, rangeModeForMax]`.
  68882. * The optional values for `rangeMode`:
  68883. * + `'value'` mode: the axis extent will always be determined by
  68884. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  68885. * how data like and how `axis.min` and `axis.max` are.
  68886. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  68887. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  68888. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  68889. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  68890. *
  68891. * For example, when users are using dynamic data (update data periodically via `setOption`),
  68892. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  68893. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  68894. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  68895. */
  68896. _this._rangePropMode = ['percent', 'percent'];
  68897. return _this;
  68898. }
  68899. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  68900. var inputRawOption = retrieveRawOption(option);
  68901. /**
  68902. * Suppose a "main process" start at the point that model prepared (that is,
  68903. * model initialized or merged or method called in `action`).
  68904. * We should keep the `main process` idempotent, that is, given a set of values
  68905. * on `option`, we get the same result.
  68906. *
  68907. * But sometimes, values on `option` will be updated for providing users
  68908. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  68909. * should not be the base/input of the `main process`.
  68910. *
  68911. * So in that case we should save and keep the input of the `main process`
  68912. * separately, called `settledOption`.
  68913. *
  68914. * For example, consider the case:
  68915. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  68916. * where the original input `option.startValue`, `option.endValue` are earsed by
  68917. * calculated value.
  68918. * (Step)2) click the legend to hide and show a series,
  68919. * where the new range is calculated by the earsed `startValue` and `endValue`,
  68920. * which brings incorrect result.
  68921. */
  68922. this.settledOption = inputRawOption;
  68923. this.mergeDefaultAndTheme(option, ecModel);
  68924. this._doInit(inputRawOption);
  68925. };
  68926. DataZoomModel.prototype.mergeOption = function (newOption) {
  68927. var inputRawOption = retrieveRawOption(newOption); // FIX #2591
  68928. merge(this.option, newOption, true);
  68929. merge(this.settledOption, inputRawOption, true);
  68930. this._doInit(inputRawOption);
  68931. };
  68932. DataZoomModel.prototype._doInit = function (inputRawOption) {
  68933. var thisOption = this.option;
  68934. this._setDefaultThrottle(inputRawOption);
  68935. this._updateRangeUse(inputRawOption);
  68936. var settledOption = this.settledOption;
  68937. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  68938. // start/end has higher priority over startValue/endValue if they
  68939. // both set, but we should make chart.setOption({endValue: 1000})
  68940. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  68941. if (this._rangePropMode[index] === 'value') {
  68942. thisOption[names[0]] = settledOption[names[0]] = null;
  68943. } // Otherwise do nothing and use the merge result.
  68944. }, this);
  68945. this._resetTarget();
  68946. };
  68947. DataZoomModel.prototype._resetTarget = function () {
  68948. var optionOrient = this.get('orient', true);
  68949. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  68950. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  68951. if (hasAxisSpecified) {
  68952. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  68953. } else {
  68954. this._orient = optionOrient || 'horizontal';
  68955. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  68956. }
  68957. this._noTarget = true;
  68958. targetAxisIndexMap.each(function (axisInfo) {
  68959. if (axisInfo.indexList.length) {
  68960. this._noTarget = false;
  68961. }
  68962. }, this);
  68963. };
  68964. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  68965. var hasAxisSpecified = false;
  68966. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  68967. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  68968. // but do not want use auto mode. Because empty array may be encountered when
  68969. // some error occurred.
  68970. if (!refering.specified) {
  68971. return;
  68972. }
  68973. hasAxisSpecified = true;
  68974. var axisInfo = new DataZoomAxisInfo();
  68975. each(refering.models, function (axisModel) {
  68976. axisInfo.add(axisModel.componentIndex);
  68977. });
  68978. targetAxisIndexMap.set(axisDim, axisInfo);
  68979. }, this);
  68980. return hasAxisSpecified;
  68981. };
  68982. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  68983. var ecModel = this.ecModel;
  68984. var needAuto = true; // Find axis that parallel to dataZoom as default.
  68985. if (needAuto) {
  68986. var axisDim = orient === 'vertical' ? 'y' : 'x';
  68987. var axisModels = ecModel.findComponents({
  68988. mainType: axisDim + 'Axis'
  68989. });
  68990. setParallelAxis(axisModels, axisDim);
  68991. } // Find axis that parallel to dataZoom as default.
  68992. if (needAuto) {
  68993. var axisModels = ecModel.findComponents({
  68994. mainType: 'singleAxis',
  68995. filter: function (axisModel) {
  68996. return axisModel.get('orient', true) === orient;
  68997. }
  68998. });
  68999. setParallelAxis(axisModels, 'single');
  69000. }
  69001. function setParallelAxis(axisModels, axisDim) {
  69002. // At least use the first parallel axis as the target axis.
  69003. var axisModel = axisModels[0];
  69004. if (!axisModel) {
  69005. return;
  69006. }
  69007. var axisInfo = new DataZoomAxisInfo();
  69008. axisInfo.add(axisModel.componentIndex);
  69009. targetAxisIndexMap.set(axisDim, axisInfo);
  69010. needAuto = false; // Find parallel axes in the same grid.
  69011. if (axisDim === 'x' || axisDim === 'y') {
  69012. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  69013. gridModel_1 && each(axisModels, function (axModel) {
  69014. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  69015. axisInfo.add(axModel.componentIndex);
  69016. }
  69017. });
  69018. }
  69019. }
  69020. if (needAuto) {
  69021. // If no parallel axis, find the first category axis as default. (Also consider polar).
  69022. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  69023. if (!needAuto) {
  69024. return;
  69025. }
  69026. var axisModels = ecModel.findComponents({
  69027. mainType: getAxisMainType(axisDim),
  69028. filter: function (axisModel) {
  69029. return axisModel.get('type', true) === 'category';
  69030. }
  69031. });
  69032. if (axisModels[0]) {
  69033. var axisInfo = new DataZoomAxisInfo();
  69034. axisInfo.add(axisModels[0].componentIndex);
  69035. targetAxisIndexMap.set(axisDim, axisInfo);
  69036. needAuto = false;
  69037. }
  69038. }, this);
  69039. }
  69040. };
  69041. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  69042. var dim; // Find the first axis
  69043. this.eachTargetAxis(function (axisDim) {
  69044. !dim && (dim = axisDim);
  69045. }, this);
  69046. return dim === 'y' ? 'vertical' : 'horizontal';
  69047. };
  69048. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  69049. // When first time user set throttle, auto throttle ends.
  69050. if (inputRawOption.hasOwnProperty('throttle')) {
  69051. this._autoThrottle = false;
  69052. }
  69053. if (this._autoThrottle) {
  69054. var globalOption = this.ecModel.option;
  69055. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  69056. }
  69057. };
  69058. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  69059. var rangePropMode = this._rangePropMode;
  69060. var rangeModeInOption = this.get('rangeMode');
  69061. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69062. var percentSpecified = inputRawOption[names[0]] != null;
  69063. var valueSpecified = inputRawOption[names[1]] != null;
  69064. if (percentSpecified && !valueSpecified) {
  69065. rangePropMode[index] = 'percent';
  69066. } else if (!percentSpecified && valueSpecified) {
  69067. rangePropMode[index] = 'value';
  69068. } else if (rangeModeInOption) {
  69069. rangePropMode[index] = rangeModeInOption[index];
  69070. } else if (percentSpecified) {
  69071. // percentSpecified && valueSpecified
  69072. rangePropMode[index] = 'percent';
  69073. } // else remain its original setting.
  69074. });
  69075. };
  69076. DataZoomModel.prototype.noTarget = function () {
  69077. return this._noTarget;
  69078. };
  69079. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  69080. var firstAxisModel;
  69081. this.eachTargetAxis(function (axisDim, axisIndex) {
  69082. if (firstAxisModel == null) {
  69083. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69084. }
  69085. }, this);
  69086. return firstAxisModel;
  69087. };
  69088. /**
  69089. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  69090. */
  69091. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  69092. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  69093. each(axisInfo.indexList, function (axisIndex) {
  69094. callback.call(context, axisDim, axisIndex);
  69095. });
  69096. });
  69097. };
  69098. /**
  69099. * @return If not found, return null/undefined.
  69100. */
  69101. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  69102. var axisModel = this.getAxisModel(axisDim, axisIndex);
  69103. if (axisModel) {
  69104. return axisModel.__dzAxisProxy;
  69105. }
  69106. };
  69107. /**
  69108. * @return If not found, return null/undefined.
  69109. */
  69110. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  69111. if ("development" !== 'production') {
  69112. assert(axisDim && axisIndex != null);
  69113. }
  69114. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  69115. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  69116. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69117. }
  69118. };
  69119. /**
  69120. * If not specified, set to undefined.
  69121. */
  69122. DataZoomModel.prototype.setRawRange = function (opt) {
  69123. var thisOption = this.option;
  69124. var settledOption = this.settledOption;
  69125. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  69126. // Consider the pair <start, startValue>:
  69127. // If one has value and the other one is `null/undefined`, we both set them
  69128. // to `settledOption`. This strategy enables the feature to clear the original
  69129. // value in `settledOption` to `null/undefined`.
  69130. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  69131. // and keep `settledOption` with the original value. This strategy enables users to
  69132. // only set <end or endValue> but not set <start or startValue> when calling
  69133. // `dispatchAction`.
  69134. // The pair <end, endValue> is treated in the same way.
  69135. if (opt[names[0]] != null || opt[names[1]] != null) {
  69136. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  69137. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  69138. }
  69139. }, this);
  69140. this._updateRangeUse(opt);
  69141. };
  69142. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  69143. var option = this.option;
  69144. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  69145. option[name] = opt[name];
  69146. });
  69147. };
  69148. DataZoomModel.prototype.getPercentRange = function () {
  69149. var axisProxy = this.findRepresentativeAxisProxy();
  69150. if (axisProxy) {
  69151. return axisProxy.getDataPercentWindow();
  69152. }
  69153. };
  69154. /**
  69155. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  69156. *
  69157. * @return [startValue, endValue] value can only be '-' or finite number.
  69158. */
  69159. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  69160. if (axisDim == null && axisIndex == null) {
  69161. var axisProxy = this.findRepresentativeAxisProxy();
  69162. if (axisProxy) {
  69163. return axisProxy.getDataValueWindow();
  69164. }
  69165. } else {
  69166. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  69167. }
  69168. };
  69169. /**
  69170. * @param axisModel If axisModel given, find axisProxy
  69171. * corresponding to the axisModel
  69172. */
  69173. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  69174. if (axisModel) {
  69175. return axisModel.__dzAxisProxy;
  69176. } // Find the first hosted axisProxy
  69177. var firstProxy;
  69178. var axisDimList = this._targetAxisInfoMap.keys();
  69179. for (var i = 0; i < axisDimList.length; i++) {
  69180. var axisDim = axisDimList[i];
  69181. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  69182. for (var j = 0; j < axisInfo.indexList.length; j++) {
  69183. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  69184. if (proxy.hostedBy(this)) {
  69185. return proxy;
  69186. }
  69187. if (!firstProxy) {
  69188. firstProxy = proxy;
  69189. }
  69190. }
  69191. } // If no hosted proxy found, still need to return a proxy.
  69192. // This case always happens in toolbox dataZoom, where axes are all hosted by
  69193. // other dataZooms.
  69194. return firstProxy;
  69195. };
  69196. DataZoomModel.prototype.getRangePropMode = function () {
  69197. return this._rangePropMode.slice();
  69198. };
  69199. DataZoomModel.prototype.getOrient = function () {
  69200. if ("development" !== 'production') {
  69201. // Should not be called before initialized.
  69202. assert(this._orient);
  69203. }
  69204. return this._orient;
  69205. };
  69206. DataZoomModel.type = 'dataZoom';
  69207. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  69208. DataZoomModel.defaultOption = {
  69209. // zlevel: 0,
  69210. z: 4,
  69211. filterMode: 'filter',
  69212. start: 0,
  69213. end: 100
  69214. };
  69215. return DataZoomModel;
  69216. }(ComponentModel);
  69217. /**
  69218. * Retrieve those raw params from option, which will be cached separately,
  69219. * because they will be overwritten by normalized/calculated values in the main
  69220. * process.
  69221. */
  69222. function retrieveRawOption(option) {
  69223. var ret = {};
  69224. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  69225. option.hasOwnProperty(name) && (ret[name] = option[name]);
  69226. });
  69227. return ret;
  69228. }
  69229. var SelectDataZoomModel =
  69230. /** @class */
  69231. function (_super) {
  69232. __extends(SelectDataZoomModel, _super);
  69233. function SelectDataZoomModel() {
  69234. var _this = _super !== null && _super.apply(this, arguments) || this;
  69235. _this.type = SelectDataZoomModel.type;
  69236. return _this;
  69237. }
  69238. SelectDataZoomModel.type = 'dataZoom.select';
  69239. return SelectDataZoomModel;
  69240. }(DataZoomModel);
  69241. var DataZoomView =
  69242. /** @class */
  69243. function (_super) {
  69244. __extends(DataZoomView, _super);
  69245. function DataZoomView() {
  69246. var _this = _super !== null && _super.apply(this, arguments) || this;
  69247. _this.type = DataZoomView.type;
  69248. return _this;
  69249. }
  69250. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  69251. this.dataZoomModel = dataZoomModel;
  69252. this.ecModel = ecModel;
  69253. this.api = api;
  69254. };
  69255. DataZoomView.type = 'dataZoom';
  69256. return DataZoomView;
  69257. }(ComponentView);
  69258. var SelectDataZoomView =
  69259. /** @class */
  69260. function (_super) {
  69261. __extends(SelectDataZoomView, _super);
  69262. function SelectDataZoomView() {
  69263. var _this = _super !== null && _super.apply(this, arguments) || this;
  69264. _this.type = SelectDataZoomView.type;
  69265. return _this;
  69266. }
  69267. SelectDataZoomView.type = 'dataZoom.select';
  69268. return SelectDataZoomView;
  69269. }(DataZoomView);
  69270. var each$8 = each;
  69271. var asc$1 = asc;
  69272. /**
  69273. * Operate single axis.
  69274. * One axis can only operated by one axis operator.
  69275. * Different dataZoomModels may be defined to operate the same axis.
  69276. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69277. * So dataZoomModels share one axisProxy in that case.
  69278. */
  69279. var AxisProxy =
  69280. /** @class */
  69281. function () {
  69282. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  69283. this._dimName = dimName;
  69284. this._axisIndex = axisIndex;
  69285. this.ecModel = ecModel;
  69286. this._dataZoomModel = dataZoomModel; // /**
  69287. // * @readOnly
  69288. // * @private
  69289. // */
  69290. // this.hasSeriesStacked;
  69291. }
  69292. /**
  69293. * Whether the axisProxy is hosted by dataZoomModel.
  69294. */
  69295. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  69296. return this._dataZoomModel === dataZoomModel;
  69297. };
  69298. /**
  69299. * @return Value can only be NaN or finite value.
  69300. */
  69301. AxisProxy.prototype.getDataValueWindow = function () {
  69302. return this._valueWindow.slice();
  69303. };
  69304. /**
  69305. * @return {Array.<number>}
  69306. */
  69307. AxisProxy.prototype.getDataPercentWindow = function () {
  69308. return this._percentWindow.slice();
  69309. };
  69310. AxisProxy.prototype.getTargetSeriesModels = function () {
  69311. var seriesModels = [];
  69312. this.ecModel.eachSeries(function (seriesModel) {
  69313. if (isCoordSupported(seriesModel)) {
  69314. var axisMainType = getAxisMainType(this._dimName);
  69315. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  69316. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  69317. seriesModels.push(seriesModel);
  69318. }
  69319. }
  69320. }, this);
  69321. return seriesModels;
  69322. };
  69323. AxisProxy.prototype.getAxisModel = function () {
  69324. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69325. };
  69326. AxisProxy.prototype.getMinMaxSpan = function () {
  69327. return clone(this._minMaxSpan);
  69328. };
  69329. /**
  69330. * Only calculate by given range and this._dataExtent, do not change anything.
  69331. */
  69332. AxisProxy.prototype.calculateDataWindow = function (opt) {
  69333. var dataExtent = this._dataExtent;
  69334. var axisModel = this.getAxisModel();
  69335. var scale = axisModel.axis.scale;
  69336. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69337. var percentExtent = [0, 100];
  69338. var percentWindow = [];
  69339. var valueWindow = [];
  69340. var hasPropModeValue;
  69341. each$8(['start', 'end'], function (prop, idx) {
  69342. var boundPercent = opt[prop];
  69343. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69344. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  69345. // but not min/max of axis, which will be calculated by data window then).
  69346. // The former one is suitable for cases that a dataZoom component controls multiple
  69347. // axes with different unit or extent, and the latter one is suitable for accurate
  69348. // zoom by pixel (e.g., in dataZoomSelect).
  69349. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  69350. // only when setOption or dispatchAction, otherwise it remains its original value.
  69351. // (Why not only record `percentProp` and always map to `valueProp`? Because
  69352. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  69353. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  69354. // data extent. All of values that are overflow the `dataExtent` will be calculated
  69355. // to percent '100%').
  69356. if (rangePropMode[idx] === 'percent') {
  69357. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  69358. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  69359. } else {
  69360. hasPropModeValue = true;
  69361. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  69362. // This calculation can not be inversed, because all of values that
  69363. // are overflow the `dataExtent` will be calculated to percent '100%'
  69364. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  69365. } // valueWindow[idx] = round(boundValue);
  69366. // percentWindow[idx] = round(boundPercent);
  69367. // fallback to extent start/end when parsed value or percent is invalid
  69368. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  69369. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  69370. });
  69371. asc$1(valueWindow);
  69372. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  69373. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  69374. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  69375. // where API is able to initialize/modify the window size even though `zoomLock`
  69376. // specified.
  69377. var spans = this._minMaxSpan;
  69378. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  69379. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  69380. var suffix = toValue ? 'Span' : 'ValueSpan';
  69381. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  69382. for (var i = 0; i < 2; i++) {
  69383. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  69384. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  69385. }
  69386. }
  69387. return {
  69388. valueWindow: valueWindow,
  69389. percentWindow: percentWindow
  69390. };
  69391. };
  69392. /**
  69393. * Notice: reset should not be called before series.restoreData() is called,
  69394. * so it is recommended to be called in "process stage" but not "model init
  69395. * stage".
  69396. */
  69397. AxisProxy.prototype.reset = function (dataZoomModel) {
  69398. if (dataZoomModel !== this._dataZoomModel) {
  69399. return;
  69400. }
  69401. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  69402. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // `calculateDataWindow` uses min/maxSpan.
  69403. this._updateMinMaxSpan();
  69404. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  69405. this._valueWindow = dataWindow.valueWindow;
  69406. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  69407. this._setAxisModel();
  69408. };
  69409. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  69410. if (dataZoomModel !== this._dataZoomModel) {
  69411. return;
  69412. }
  69413. var axisDim = this._dimName;
  69414. var seriesModels = this.getTargetSeriesModels();
  69415. var filterMode = dataZoomModel.get('filterMode');
  69416. var valueWindow = this._valueWindow;
  69417. if (filterMode === 'none') {
  69418. return;
  69419. } // FIXME
  69420. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69421. // with NaN data, NaN will be filtered and stack will be wrong.
  69422. // So we need to force the mode to be set empty.
  69423. // In fect, it is not a big deal that do not support filterMode-'filter'
  69424. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69425. // selection" some day, which might need "adapt to data extent on the
  69426. // otherAxis", which is disabled by filterMode-'empty'.
  69427. // But currently, stack has been fixed to based on value but not index,
  69428. // so this is not an issue any more.
  69429. // let otherAxisModel = this.getOtherAxisModel();
  69430. // if (dataZoomModel.get('$fromToolbox')
  69431. // && otherAxisModel
  69432. // && otherAxisModel.hasSeriesStacked
  69433. // ) {
  69434. // filterMode = 'empty';
  69435. // }
  69436. // TODO
  69437. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69438. each$8(seriesModels, function (seriesModel) {
  69439. var seriesData = seriesModel.getData();
  69440. var dataDims = seriesData.mapDimensionsAll(axisDim);
  69441. if (!dataDims.length) {
  69442. return;
  69443. }
  69444. if (filterMode === 'weakFilter') {
  69445. var store_1 = seriesData.getStore();
  69446. var dataDimIndices_1 = map(dataDims, function (dim) {
  69447. return seriesData.getDimensionIndex(dim);
  69448. }, seriesData);
  69449. seriesData.filterSelf(function (dataIndex) {
  69450. var leftOut;
  69451. var rightOut;
  69452. var hasValue;
  69453. for (var i = 0; i < dataDims.length; i++) {
  69454. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  69455. var thisHasValue = !isNaN(value);
  69456. var thisLeftOut = value < valueWindow[0];
  69457. var thisRightOut = value > valueWindow[1];
  69458. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69459. return true;
  69460. }
  69461. thisHasValue && (hasValue = true);
  69462. thisLeftOut && (leftOut = true);
  69463. thisRightOut && (rightOut = true);
  69464. } // If both left out and right out, do not filter.
  69465. return hasValue && leftOut && rightOut;
  69466. });
  69467. } else {
  69468. each$8(dataDims, function (dim) {
  69469. if (filterMode === 'empty') {
  69470. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  69471. return !isInWindow(value) ? NaN : value;
  69472. }));
  69473. } else {
  69474. var range = {};
  69475. range[dim] = valueWindow; // console.time('select');
  69476. seriesData.selectRange(range); // console.timeEnd('select');
  69477. }
  69478. });
  69479. }
  69480. each$8(dataDims, function (dim) {
  69481. seriesData.setApproximateExtent(valueWindow, dim);
  69482. });
  69483. });
  69484. function isInWindow(value) {
  69485. return value >= valueWindow[0] && value <= valueWindow[1];
  69486. }
  69487. };
  69488. AxisProxy.prototype._updateMinMaxSpan = function () {
  69489. var minMaxSpan = this._minMaxSpan = {};
  69490. var dataZoomModel = this._dataZoomModel;
  69491. var dataExtent = this._dataExtent;
  69492. each$8(['min', 'max'], function (minMax) {
  69493. var percentSpan = dataZoomModel.get(minMax + 'Span');
  69494. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69495. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69496. if (valueSpan != null) {
  69497. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  69498. } else if (percentSpan != null) {
  69499. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  69500. }
  69501. minMaxSpan[minMax + 'Span'] = percentSpan;
  69502. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69503. }, this);
  69504. };
  69505. AxisProxy.prototype._setAxisModel = function () {
  69506. var axisModel = this.getAxisModel();
  69507. var percentWindow = this._percentWindow;
  69508. var valueWindow = this._valueWindow;
  69509. if (!percentWindow) {
  69510. return;
  69511. } // [0, 500]: arbitrary value, guess axis extent.
  69512. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69513. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  69514. // by series data, which may be a little different from the extent calculated by
  69515. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69516. // little when zooming. So it will not be fixed until some users require it strongly.
  69517. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  69518. if (percentWindow[0] !== 0) {
  69519. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  69520. }
  69521. if (percentWindow[1] !== 100) {
  69522. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  69523. }
  69524. rawExtentInfo.freeze();
  69525. };
  69526. return AxisProxy;
  69527. }();
  69528. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69529. var dataExtent = [Infinity, -Infinity];
  69530. each$8(seriesModels, function (seriesModel) {
  69531. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  69532. }); // It is important to get "consistent" extent when more then one axes is
  69533. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69534. // when zooming. But it is difficult to know what is "consistent", considering
  69535. // axes have different type or even different meanings (For example, two
  69536. // time axes are used to compare data of the same date in different years).
  69537. // So basically dataZoom just obtains extent by series.data (in category axis
  69538. // extent can be obtained from axis.data).
  69539. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69540. // consistent.
  69541. var axisModel = axisProxy.getAxisModel();
  69542. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  69543. return [rawExtentResult.min, rawExtentResult.max];
  69544. }
  69545. var dataZoomProcessor = {
  69546. // `dataZoomProcessor` will only be performed in needed series. Consider if
  69547. // there is a line series and a pie series, it is better not to update the
  69548. // line series if only pie series is needed to be updated.
  69549. getTargetSeries: function (ecModel) {
  69550. function eachAxisModel(cb) {
  69551. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69552. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69553. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69554. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  69555. });
  69556. });
  69557. } // FIXME: it brings side-effect to `getTargetSeries`.
  69558. // Prepare axis proxies.
  69559. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  69560. // dispose all last axis proxy, in case that some axis are deleted.
  69561. axisModel.__dzAxisProxy = null;
  69562. });
  69563. var proxyList = [];
  69564. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  69565. // Different dataZooms may constrol the same axis. In that case,
  69566. // an axisProxy serves both of them.
  69567. if (!axisModel.__dzAxisProxy) {
  69568. // Use the first dataZoomModel as the main model of axisProxy.
  69569. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  69570. proxyList.push(axisModel.__dzAxisProxy);
  69571. }
  69572. });
  69573. var seriesModelMap = createHashMap();
  69574. each(proxyList, function (axisProxy) {
  69575. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  69576. seriesModelMap.set(seriesModel.uid, seriesModel);
  69577. });
  69578. });
  69579. return seriesModelMap;
  69580. },
  69581. // Consider appendData, where filter should be performed. Because data process is
  69582. // in block mode currently, it is not need to worry about that the overallProgress
  69583. // execute every frame.
  69584. overallReset: function (ecModel, api) {
  69585. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69586. // We calculate window and reset axis here but not in model
  69587. // init stage and not after action dispatch handler, because
  69588. // reset should be called after seriesData.restoreData.
  69589. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69590. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  69591. }); // Caution: data zoom filtering is order sensitive when using
  69592. // percent range and no min/max/scale set on axis.
  69593. // For example, we have dataZoom definition:
  69594. // [
  69595. // {xAxisIndex: 0, start: 30, end: 70},
  69596. // {yAxisIndex: 0, start: 20, end: 80}
  69597. // ]
  69598. // In this case, [20, 80] of y-dataZoom should be based on data
  69599. // that have filtered by x-dataZoom using range of [30, 70],
  69600. // but should not be based on full raw data. Thus sliding
  69601. // x-dataZoom will change both ranges of xAxis and yAxis,
  69602. // while sliding y-dataZoom will only change the range of yAxis.
  69603. // So we should filter x-axis after reset x-axis immediately,
  69604. // and then reset y-axis and filter y-axis.
  69605. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69606. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  69607. });
  69608. });
  69609. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69610. // Fullfill all of the range props so that user
  69611. // is able to get them from chart.getOption().
  69612. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  69613. if (axisProxy) {
  69614. var percentRange = axisProxy.getDataPercentWindow();
  69615. var valueRange = axisProxy.getDataValueWindow();
  69616. dataZoomModel.setCalculatedRange({
  69617. start: percentRange[0],
  69618. end: percentRange[1],
  69619. startValue: valueRange[0],
  69620. endValue: valueRange[1]
  69621. });
  69622. }
  69623. });
  69624. }
  69625. };
  69626. function installDataZoomAction(registers) {
  69627. registers.registerAction('dataZoom', function (payload, ecModel) {
  69628. var effectedModels = findEffectedDataZooms(ecModel, payload);
  69629. each(effectedModels, function (dataZoomModel) {
  69630. dataZoomModel.setRawRange({
  69631. start: payload.start,
  69632. end: payload.end,
  69633. startValue: payload.startValue,
  69634. endValue: payload.endValue
  69635. });
  69636. });
  69637. });
  69638. }
  69639. var installed = false;
  69640. function installCommon(registers) {
  69641. if (installed) {
  69642. return;
  69643. }
  69644. installed = true;
  69645. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  69646. installDataZoomAction(registers);
  69647. registers.registerSubTypeDefaulter('dataZoom', function () {
  69648. // Default 'slider' when no type specified.
  69649. return 'slider';
  69650. });
  69651. }
  69652. function install$y(registers) {
  69653. registers.registerComponentModel(SelectDataZoomModel);
  69654. registers.registerComponentView(SelectDataZoomView);
  69655. installCommon(registers);
  69656. }
  69657. /*
  69658. * Licensed to the Apache Software Foundation (ASF) under one
  69659. * or more contributor license agreements. See the NOTICE file
  69660. * distributed with this work for additional information
  69661. * regarding copyright ownership. The ASF licenses this file
  69662. * to you under the Apache License, Version 2.0 (the
  69663. * "License"); you may not use this file except in compliance
  69664. * with the License. You may obtain a copy of the License at
  69665. *
  69666. * http://www.apache.org/licenses/LICENSE-2.0
  69667. *
  69668. * Unless required by applicable law or agreed to in writing,
  69669. * software distributed under the License is distributed on an
  69670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69671. * KIND, either express or implied. See the License for the
  69672. * specific language governing permissions and limitations
  69673. * under the License.
  69674. */
  69675. /**
  69676. * AUTO-GENERATED FILE. DO NOT MODIFY.
  69677. */
  69678. var ToolboxFeature =
  69679. /** @class */
  69680. function () {
  69681. function ToolboxFeature() {}
  69682. return ToolboxFeature;
  69683. }();
  69684. var features = {};
  69685. function registerFeature(name, ctor) {
  69686. features[name] = ctor;
  69687. }
  69688. function getFeature(name) {
  69689. return features[name];
  69690. }
  69691. var ToolboxModel =
  69692. /** @class */
  69693. function (_super) {
  69694. __extends(ToolboxModel, _super);
  69695. function ToolboxModel() {
  69696. var _this = _super !== null && _super.apply(this, arguments) || this;
  69697. _this.type = ToolboxModel.type;
  69698. return _this;
  69699. }
  69700. ToolboxModel.prototype.optionUpdated = function () {
  69701. _super.prototype.optionUpdated.apply(this, arguments);
  69702. var ecModel = this.ecModel;
  69703. each(this.option.feature, function (featureOpt, featureName) {
  69704. var Feature = getFeature(featureName);
  69705. if (Feature) {
  69706. if (Feature.getDefaultOption) {
  69707. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  69708. }
  69709. merge(featureOpt, Feature.defaultOption);
  69710. }
  69711. });
  69712. };
  69713. ToolboxModel.type = 'toolbox';
  69714. ToolboxModel.layoutMode = {
  69715. type: 'box',
  69716. ignoreSize: true
  69717. };
  69718. ToolboxModel.defaultOption = {
  69719. show: true,
  69720. z: 6,
  69721. // zlevel: 0,
  69722. orient: 'horizontal',
  69723. left: 'right',
  69724. top: 'top',
  69725. // right
  69726. // bottom
  69727. backgroundColor: 'transparent',
  69728. borderColor: '#ccc',
  69729. borderRadius: 0,
  69730. borderWidth: 0,
  69731. padding: 5,
  69732. itemSize: 15,
  69733. itemGap: 8,
  69734. showTitle: true,
  69735. iconStyle: {
  69736. borderColor: '#666',
  69737. color: 'none'
  69738. },
  69739. emphasis: {
  69740. iconStyle: {
  69741. borderColor: '#3E98C5'
  69742. }
  69743. },
  69744. // textStyle: {},
  69745. // feature
  69746. tooltip: {
  69747. show: false,
  69748. position: 'bottom'
  69749. }
  69750. };
  69751. return ToolboxModel;
  69752. }(ComponentModel);
  69753. /**
  69754. * Layout list like component.
  69755. * It will box layout each items in group of component and then position the whole group in the viewport
  69756. * @param {module:zrender/group/Group} group
  69757. * @param {module:echarts/model/Component} componentModel
  69758. * @param {module:echarts/ExtensionAPI}
  69759. */
  69760. function layout$3(group, componentModel, api) {
  69761. var boxLayoutParams = componentModel.getBoxLayoutParams();
  69762. var padding = componentModel.get('padding');
  69763. var viewportSize = {
  69764. width: api.getWidth(),
  69765. height: api.getHeight()
  69766. };
  69767. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  69768. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  69769. positionElement(group, boxLayoutParams, viewportSize, padding);
  69770. }
  69771. function makeBackground(rect, componentModel) {
  69772. var padding = normalizeCssArray$1(componentModel.get('padding'));
  69773. var style = componentModel.getItemStyle(['color', 'opacity']);
  69774. style.fill = componentModel.get('backgroundColor');
  69775. rect = new Rect({
  69776. shape: {
  69777. x: rect.x - padding[3],
  69778. y: rect.y - padding[0],
  69779. width: rect.width + padding[1] + padding[3],
  69780. height: rect.height + padding[0] + padding[2],
  69781. r: componentModel.get('borderRadius')
  69782. },
  69783. style: style,
  69784. silent: true,
  69785. z2: -1
  69786. }); // FIXME
  69787. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  69788. // and background rect when setting like `left: 0`, `top: 0`.
  69789. // graphic.subPixelOptimizeRect(rect);
  69790. return rect;
  69791. }
  69792. var ToolboxView =
  69793. /** @class */
  69794. function (_super) {
  69795. __extends(ToolboxView, _super);
  69796. function ToolboxView() {
  69797. return _super !== null && _super.apply(this, arguments) || this;
  69798. }
  69799. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  69800. var group = this.group;
  69801. group.removeAll();
  69802. if (!toolboxModel.get('show')) {
  69803. return;
  69804. }
  69805. var itemSize = +toolboxModel.get('itemSize');
  69806. var isVertical = toolboxModel.get('orient') === 'vertical';
  69807. var featureOpts = toolboxModel.get('feature') || {};
  69808. var features = this._features || (this._features = {});
  69809. var featureNames = [];
  69810. each(featureOpts, function (opt, name) {
  69811. featureNames.push(name);
  69812. });
  69813. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  69814. this._featureNames = featureNames;
  69815. function processFeature(newIndex, oldIndex) {
  69816. var featureName = featureNames[newIndex];
  69817. var oldName = featureNames[oldIndex];
  69818. var featureOpt = featureOpts[featureName];
  69819. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  69820. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  69821. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  69822. featureOpt.title = payload.newTitle;
  69823. }
  69824. if (featureName && !oldName) {
  69825. // Create
  69826. if (isUserFeatureName(featureName)) {
  69827. feature = {
  69828. onclick: featureModel.option.onclick,
  69829. featureName: featureName
  69830. };
  69831. } else {
  69832. var Feature = getFeature(featureName);
  69833. if (!Feature) {
  69834. return;
  69835. }
  69836. feature = new Feature();
  69837. }
  69838. features[featureName] = feature;
  69839. } else {
  69840. feature = features[oldName]; // If feature does not exist.
  69841. if (!feature) {
  69842. return;
  69843. }
  69844. }
  69845. feature.uid = getUID('toolbox-feature');
  69846. feature.model = featureModel;
  69847. feature.ecModel = ecModel;
  69848. feature.api = api;
  69849. var isToolboxFeature = feature instanceof ToolboxFeature;
  69850. if (!featureName && oldName) {
  69851. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  69852. return;
  69853. }
  69854. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  69855. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  69856. return;
  69857. }
  69858. createIconPaths(featureModel, feature, featureName);
  69859. featureModel.setIconStatus = function (iconName, status) {
  69860. var option = this.option;
  69861. var iconPaths = this.iconPaths;
  69862. option.iconStatus = option.iconStatus || {};
  69863. option.iconStatus[iconName] = status;
  69864. if (iconPaths[iconName]) {
  69865. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  69866. }
  69867. };
  69868. if (feature instanceof ToolboxFeature) {
  69869. if (feature.render) {
  69870. feature.render(featureModel, ecModel, api, payload);
  69871. }
  69872. }
  69873. }
  69874. function createIconPaths(featureModel, feature, featureName) {
  69875. var iconStyleModel = featureModel.getModel('iconStyle');
  69876. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has multiple icons, they are organized as
  69877. // {
  69878. // icon: {
  69879. // foo: '',
  69880. // bar: ''
  69881. // },
  69882. // title: {
  69883. // foo: '',
  69884. // bar: ''
  69885. // }
  69886. // }
  69887. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  69888. var titles = featureModel.get('title') || {};
  69889. var iconsMap;
  69890. var titlesMap;
  69891. if (isString(icons)) {
  69892. iconsMap = {};
  69893. iconsMap[featureName] = icons;
  69894. } else {
  69895. iconsMap = icons;
  69896. }
  69897. if (isString(titles)) {
  69898. titlesMap = {};
  69899. titlesMap[featureName] = titles;
  69900. } else {
  69901. titlesMap = titles;
  69902. }
  69903. var iconPaths = featureModel.iconPaths = {};
  69904. each(iconsMap, function (iconStr, iconName) {
  69905. var path = createIcon(iconStr, {}, {
  69906. x: -itemSize / 2,
  69907. y: -itemSize / 2,
  69908. width: itemSize,
  69909. height: itemSize
  69910. }); // TODO handling image
  69911. path.setStyle(iconStyleModel.getItemStyle());
  69912. var pathEmphasisState = path.ensureState('emphasis');
  69913. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  69914. var textContent = new ZRText({
  69915. style: {
  69916. text: titlesMap[iconName],
  69917. align: iconStyleEmphasisModel.get('textAlign'),
  69918. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  69919. padding: iconStyleEmphasisModel.get('textPadding'),
  69920. fill: null
  69921. },
  69922. ignore: true
  69923. });
  69924. path.setTextContent(textContent);
  69925. setTooltipConfig({
  69926. el: path,
  69927. componentModel: toolboxModel,
  69928. itemName: iconName,
  69929. formatterParamsExtra: {
  69930. title: titlesMap[iconName]
  69931. }
  69932. });
  69933. path.__title = titlesMap[iconName];
  69934. path.on('mouseover', function () {
  69935. // Should not reuse above hoverStyle, which might be modified.
  69936. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  69937. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  69938. textContent.setStyle({
  69939. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  69940. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  69941. });
  69942. path.setTextConfig({
  69943. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  69944. });
  69945. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  69946. // There are flags managed by the echarts.
  69947. api.enterEmphasis(this);
  69948. }).on('mouseout', function () {
  69949. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  69950. api.leaveEmphasis(this);
  69951. }
  69952. textContent.hide();
  69953. });
  69954. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  69955. group.add(path);
  69956. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  69957. iconPaths[iconName] = path;
  69958. });
  69959. }
  69960. layout$3(group, toolboxModel, api); // Render background after group is layout
  69961. // FIXME
  69962. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  69963. isVertical || group.eachChild(function (icon) {
  69964. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  69965. // TODO simplify code?
  69966. var emphasisState = icon.ensureState('emphasis');
  69967. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  69968. var textContent = icon.getTextContent();
  69969. var emphasisTextState = textContent && textContent.ensureState('emphasis'); // May be background element
  69970. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  69971. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  69972. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  69973. var offsetX = icon.x + group.x;
  69974. var offsetY = icon.y + group.y + itemSize;
  69975. var needPutOnTop = false;
  69976. if (offsetY + rect.height > api.getHeight()) {
  69977. emphasisTextConfig.position = 'top';
  69978. needPutOnTop = true;
  69979. }
  69980. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  69981. if (offsetX + rect.width / 2 > api.getWidth()) {
  69982. emphasisTextConfig.position = ['100%', topOffset];
  69983. emphasisTextStyle.align = 'right';
  69984. } else if (offsetX - rect.width / 2 < 0) {
  69985. emphasisTextConfig.position = [0, topOffset];
  69986. emphasisTextStyle.align = 'left';
  69987. }
  69988. }
  69989. });
  69990. };
  69991. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  69992. each(this._features, function (feature) {
  69993. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  69994. });
  69995. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  69996. // zrUtil.each(this._features, function (feature) {
  69997. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  69998. // });
  69999. // },
  70000. ToolboxView.prototype.remove = function (ecModel, api) {
  70001. each(this._features, function (feature) {
  70002. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  70003. });
  70004. this.group.removeAll();
  70005. };
  70006. ToolboxView.prototype.dispose = function (ecModel, api) {
  70007. each(this._features, function (feature) {
  70008. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  70009. });
  70010. };
  70011. ToolboxView.type = 'toolbox';
  70012. return ToolboxView;
  70013. }(ComponentView);
  70014. function isUserFeatureName(featureName) {
  70015. return featureName.indexOf('my') === 0;
  70016. }
  70017. /* global window, document */
  70018. var SaveAsImage =
  70019. /** @class */
  70020. function (_super) {
  70021. __extends(SaveAsImage, _super);
  70022. function SaveAsImage() {
  70023. return _super !== null && _super.apply(this, arguments) || this;
  70024. }
  70025. SaveAsImage.prototype.onclick = function (ecModel, api) {
  70026. var model = this.model;
  70027. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  70028. var isSvg = api.getZr().painter.getType() === 'svg';
  70029. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  70030. var url = api.getConnectedDataURL({
  70031. type: type,
  70032. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  70033. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  70034. excludeComponents: model.get('excludeComponents'),
  70035. pixelRatio: model.get('pixelRatio')
  70036. });
  70037. var browser = env.browser; // Chrome, Firefox, New Edge
  70038. if (isFunction(MouseEvent) && (browser.newEdge || !browser.ie && !browser.edge)) {
  70039. var $a = document.createElement('a');
  70040. $a.download = title + '.' + type;
  70041. $a.target = '_blank';
  70042. $a.href = url;
  70043. var evt = new MouseEvent('click', {
  70044. // some micro front-end framework, window maybe is a Proxy
  70045. view: document.defaultView,
  70046. bubbles: true,
  70047. cancelable: false
  70048. });
  70049. $a.dispatchEvent(evt);
  70050. } // IE or old Edge
  70051. else {
  70052. // @ts-ignore
  70053. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  70054. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  70055. var base64Encoded = parts[0].indexOf('base64') > -1;
  70056. var bstr = isSvg // should decode the svg data uri first
  70057. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  70058. // otherwise, like `svg` data uri exported by zrender,
  70059. // there will be an error, for it's not encoded with base64.
  70060. // (just a url-encoded string through `encodeURIComponent`)
  70061. base64Encoded && (bstr = window.atob(bstr));
  70062. var filename = title + '.' + type; // @ts-ignore
  70063. if (window.navigator.msSaveOrOpenBlob) {
  70064. var n = bstr.length;
  70065. var u8arr = new Uint8Array(n);
  70066. while (n--) {
  70067. u8arr[n] = bstr.charCodeAt(n);
  70068. }
  70069. var blob = new Blob([u8arr]); // @ts-ignore
  70070. window.navigator.msSaveOrOpenBlob(blob, filename);
  70071. } else {
  70072. var frame = document.createElement('iframe');
  70073. document.body.appendChild(frame);
  70074. var cw = frame.contentWindow;
  70075. var doc = cw.document;
  70076. doc.open('image/svg+xml', 'replace');
  70077. doc.write(bstr);
  70078. doc.close();
  70079. cw.focus();
  70080. doc.execCommand('SaveAs', true, filename);
  70081. document.body.removeChild(frame);
  70082. }
  70083. } else {
  70084. var lang = model.get('lang');
  70085. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  70086. var tab = window.open();
  70087. tab.document.write(html);
  70088. tab.document.title = title;
  70089. }
  70090. }
  70091. };
  70092. SaveAsImage.getDefaultOption = function (ecModel) {
  70093. var defaultOption = {
  70094. show: true,
  70095. 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',
  70096. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  70097. type: 'png',
  70098. // Default use option.backgroundColor
  70099. // backgroundColor: '#fff',
  70100. connectedBackgroundColor: '#fff',
  70101. name: '',
  70102. excludeComponents: ['toolbox'],
  70103. // use current pixel ratio of device by default
  70104. // pixelRatio: 1,
  70105. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  70106. };
  70107. return defaultOption;
  70108. };
  70109. return SaveAsImage;
  70110. }(ToolboxFeature);
  70111. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  70112. var radioTypes = [['line', 'bar'], ['stack']];
  70113. var MagicType =
  70114. /** @class */
  70115. function (_super) {
  70116. __extends(MagicType, _super);
  70117. function MagicType() {
  70118. return _super !== null && _super.apply(this, arguments) || this;
  70119. }
  70120. MagicType.prototype.getIcons = function () {
  70121. var model = this.model;
  70122. var availableIcons = model.get('icon');
  70123. var icons = {};
  70124. each(model.get('type'), function (type) {
  70125. if (availableIcons[type]) {
  70126. icons[type] = availableIcons[type];
  70127. }
  70128. });
  70129. return icons;
  70130. };
  70131. MagicType.getDefaultOption = function (ecModel) {
  70132. var defaultOption = {
  70133. show: true,
  70134. type: [],
  70135. // Icon group
  70136. icon: {
  70137. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  70138. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  70139. // eslint-disable-next-line
  70140. 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
  70141. },
  70142. // `line`, `bar`, `stack`, `tiled`
  70143. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  70144. option: {},
  70145. seriesIndex: {}
  70146. };
  70147. return defaultOption;
  70148. };
  70149. MagicType.prototype.onclick = function (ecModel, api, type) {
  70150. var model = this.model;
  70151. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  70152. if (!seriesOptGenreator[type]) {
  70153. return;
  70154. }
  70155. var newOption = {
  70156. series: []
  70157. };
  70158. var generateNewSeriesTypes = function (seriesModel) {
  70159. var seriesType = seriesModel.subType;
  70160. var seriesId = seriesModel.id;
  70161. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  70162. if (newSeriesOpt) {
  70163. // PENDING If merge original option?
  70164. defaults(newSeriesOpt, seriesModel.option);
  70165. newOption.series.push(newSeriesOpt);
  70166. } // Modify boundaryGap
  70167. var coordSys = seriesModel.coordinateSystem;
  70168. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  70169. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  70170. if (categoryAxis) {
  70171. var axisDim = categoryAxis.dim;
  70172. var axisType = axisDim + 'Axis';
  70173. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  70174. var axisIndex = axisModel.componentIndex;
  70175. newOption[axisType] = newOption[axisType] || [];
  70176. for (var i = 0; i <= axisIndex; i++) {
  70177. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  70178. }
  70179. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  70180. }
  70181. }
  70182. };
  70183. each(radioTypes, function (radio) {
  70184. if (indexOf(radio, type) >= 0) {
  70185. each(radio, function (item) {
  70186. model.setIconStatus(item, 'normal');
  70187. });
  70188. }
  70189. });
  70190. model.setIconStatus(type, 'emphasis');
  70191. ecModel.eachComponent({
  70192. mainType: 'series',
  70193. query: seriesIndex == null ? null : {
  70194. seriesIndex: seriesIndex
  70195. }
  70196. }, generateNewSeriesTypes);
  70197. var newTitle;
  70198. var currentType = type; // Change title of stack
  70199. if (type === 'stack') {
  70200. // use titles in model instead of ecModel
  70201. // as stack and tiled appears in pair, just flip them
  70202. // no need of checking stack state
  70203. newTitle = merge({
  70204. stack: model.option.title.tiled,
  70205. tiled: model.option.title.stack
  70206. }, model.option.title);
  70207. if (model.get(['iconStatus', type]) !== 'emphasis') {
  70208. currentType = 'tiled';
  70209. }
  70210. }
  70211. api.dispatchAction({
  70212. type: 'changeMagicType',
  70213. currentType: currentType,
  70214. newOption: newOption,
  70215. newTitle: newTitle,
  70216. featureName: 'magicType'
  70217. });
  70218. };
  70219. return MagicType;
  70220. }(ToolboxFeature);
  70221. var seriesOptGenreator = {
  70222. 'line': function (seriesType, seriesId, seriesModel, model) {
  70223. if (seriesType === 'bar') {
  70224. return merge({
  70225. id: seriesId,
  70226. type: 'line',
  70227. // Preserve data related option
  70228. data: seriesModel.get('data'),
  70229. stack: seriesModel.get('stack'),
  70230. markPoint: seriesModel.get('markPoint'),
  70231. markLine: seriesModel.get('markLine')
  70232. }, model.get(['option', 'line']) || {}, true);
  70233. }
  70234. },
  70235. 'bar': function (seriesType, seriesId, seriesModel, model) {
  70236. if (seriesType === 'line') {
  70237. return merge({
  70238. id: seriesId,
  70239. type: 'bar',
  70240. // Preserve data related option
  70241. data: seriesModel.get('data'),
  70242. stack: seriesModel.get('stack'),
  70243. markPoint: seriesModel.get('markPoint'),
  70244. markLine: seriesModel.get('markLine')
  70245. }, model.get(['option', 'bar']) || {}, true);
  70246. }
  70247. },
  70248. 'stack': function (seriesType, seriesId, seriesModel, model) {
  70249. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  70250. if (seriesType === 'line' || seriesType === 'bar') {
  70251. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  70252. return merge({
  70253. id: seriesId,
  70254. stack: isStack ? '' : INNER_STACK_KEYWORD
  70255. }, model.get(['option', 'stack']) || {}, true);
  70256. }
  70257. }
  70258. }; // TODO: SELF REGISTERED.
  70259. registerAction({
  70260. type: 'changeMagicType',
  70261. event: 'magicTypeChanged',
  70262. update: 'prepareAndUpdate'
  70263. }, function (payload, ecModel) {
  70264. ecModel.mergeOption(payload.newOption);
  70265. });
  70266. /* global document */
  70267. var BLOCK_SPLITER = new Array(60).join('-');
  70268. var ITEM_SPLITER = '\t';
  70269. /**
  70270. * Group series into two types
  70271. * 1. on category axis, like line, bar
  70272. * 2. others, like scatter, pie
  70273. */
  70274. function groupSeries(ecModel) {
  70275. var seriesGroupByCategoryAxis = {};
  70276. var otherSeries = [];
  70277. var meta = [];
  70278. ecModel.eachRawSeries(function (seriesModel) {
  70279. var coordSys = seriesModel.coordinateSystem;
  70280. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  70281. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  70282. var baseAxis = coordSys.getBaseAxis();
  70283. if (baseAxis.type === 'category') {
  70284. var key = baseAxis.dim + '_' + baseAxis.index;
  70285. if (!seriesGroupByCategoryAxis[key]) {
  70286. seriesGroupByCategoryAxis[key] = {
  70287. categoryAxis: baseAxis,
  70288. valueAxis: coordSys.getOtherAxis(baseAxis),
  70289. series: []
  70290. };
  70291. meta.push({
  70292. axisDim: baseAxis.dim,
  70293. axisIndex: baseAxis.index
  70294. });
  70295. }
  70296. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  70297. } else {
  70298. otherSeries.push(seriesModel);
  70299. }
  70300. } else {
  70301. otherSeries.push(seriesModel);
  70302. }
  70303. });
  70304. return {
  70305. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  70306. other: otherSeries,
  70307. meta: meta
  70308. };
  70309. }
  70310. /**
  70311. * Assemble content of series on cateogory axis
  70312. * @inner
  70313. */
  70314. function assembleSeriesWithCategoryAxis(groups) {
  70315. var tables = [];
  70316. each(groups, function (group, key) {
  70317. var categoryAxis = group.categoryAxis;
  70318. var valueAxis = group.valueAxis;
  70319. var valueAxisDim = valueAxis.dim;
  70320. var headers = [' '].concat(map(group.series, function (series) {
  70321. return series.name;
  70322. })); // @ts-ignore TODO Polar
  70323. var columns = [categoryAxis.model.getCategories()];
  70324. each(group.series, function (series) {
  70325. var rawData = series.getRawData();
  70326. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  70327. return val;
  70328. }));
  70329. }); // Assemble table content
  70330. var lines = [headers.join(ITEM_SPLITER)];
  70331. for (var i = 0; i < columns[0].length; i++) {
  70332. var items = [];
  70333. for (var j = 0; j < columns.length; j++) {
  70334. items.push(columns[j][i]);
  70335. }
  70336. lines.push(items.join(ITEM_SPLITER));
  70337. }
  70338. tables.push(lines.join('\n'));
  70339. });
  70340. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  70341. }
  70342. /**
  70343. * Assemble content of other series
  70344. */
  70345. function assembleOtherSeries(series) {
  70346. return map(series, function (series) {
  70347. var data = series.getRawData();
  70348. var lines = [series.name];
  70349. var vals = [];
  70350. data.each(data.dimensions, function () {
  70351. var argLen = arguments.length;
  70352. var dataIndex = arguments[argLen - 1];
  70353. var name = data.getName(dataIndex);
  70354. for (var i = 0; i < argLen - 1; i++) {
  70355. vals[i] = arguments[i];
  70356. }
  70357. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  70358. });
  70359. return lines.join('\n');
  70360. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  70361. }
  70362. function getContentFromModel(ecModel) {
  70363. var result = groupSeries(ecModel);
  70364. return {
  70365. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  70366. return !!str.replace(/[\n\t\s]/g, '');
  70367. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  70368. meta: result.meta
  70369. };
  70370. }
  70371. function trim$1(str) {
  70372. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  70373. }
  70374. /**
  70375. * If a block is tsv format
  70376. */
  70377. function isTSVFormat(block) {
  70378. // Simple method to find out if a block is tsv format
  70379. var firstLine = block.slice(0, block.indexOf('\n'));
  70380. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  70381. return true;
  70382. }
  70383. }
  70384. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  70385. /**
  70386. * @param {string} tsv
  70387. * @return {Object}
  70388. */
  70389. function parseTSVContents(tsv) {
  70390. var tsvLines = tsv.split(/\n+/g);
  70391. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  70392. var categories = [];
  70393. var series = map(headers, function (header) {
  70394. return {
  70395. name: header,
  70396. data: []
  70397. };
  70398. });
  70399. for (var i = 0; i < tsvLines.length; i++) {
  70400. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  70401. categories.push(items.shift());
  70402. for (var j = 0; j < items.length; j++) {
  70403. series[j] && (series[j].data[i] = items[j]);
  70404. }
  70405. }
  70406. return {
  70407. series: series,
  70408. categories: categories
  70409. };
  70410. }
  70411. function parseListContents(str) {
  70412. var lines = str.split(/\n+/g);
  70413. var seriesName = trim$1(lines.shift());
  70414. var data = [];
  70415. for (var i = 0; i < lines.length; i++) {
  70416. // if line is empty, ignore it.
  70417. // there is a case that a user forgot to delete `\n`.
  70418. var line = trim$1(lines[i]);
  70419. if (!line) {
  70420. continue;
  70421. }
  70422. var items = line.split(itemSplitRegex);
  70423. var name_1 = '';
  70424. var value = void 0;
  70425. var hasName = false;
  70426. if (isNaN(items[0])) {
  70427. // First item is name
  70428. hasName = true;
  70429. name_1 = items[0];
  70430. items = items.slice(1);
  70431. data[i] = {
  70432. name: name_1,
  70433. value: []
  70434. };
  70435. value = data[i].value;
  70436. } else {
  70437. value = data[i] = [];
  70438. }
  70439. for (var j = 0; j < items.length; j++) {
  70440. value.push(+items[j]);
  70441. }
  70442. if (value.length === 1) {
  70443. hasName ? data[i].value = value[0] : data[i] = value[0];
  70444. }
  70445. }
  70446. return {
  70447. name: seriesName,
  70448. data: data
  70449. };
  70450. }
  70451. function parseContents(str, blockMetaList) {
  70452. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  70453. var newOption = {
  70454. series: []
  70455. };
  70456. each(blocks, function (block, idx) {
  70457. if (isTSVFormat(block)) {
  70458. var result = parseTSVContents(block);
  70459. var blockMeta = blockMetaList[idx];
  70460. var axisKey = blockMeta.axisDim + 'Axis';
  70461. if (blockMeta) {
  70462. newOption[axisKey] = newOption[axisKey] || [];
  70463. newOption[axisKey][blockMeta.axisIndex] = {
  70464. data: result.categories
  70465. };
  70466. newOption.series = newOption.series.concat(result.series);
  70467. }
  70468. } else {
  70469. var result = parseListContents(block);
  70470. newOption.series.push(result);
  70471. }
  70472. });
  70473. return newOption;
  70474. }
  70475. var DataView =
  70476. /** @class */
  70477. function (_super) {
  70478. __extends(DataView, _super);
  70479. function DataView() {
  70480. return _super !== null && _super.apply(this, arguments) || this;
  70481. }
  70482. DataView.prototype.onclick = function (ecModel, api) {
  70483. // FIXME: better way?
  70484. setTimeout(function () {
  70485. api.dispatchAction({
  70486. type: 'hideTip'
  70487. });
  70488. });
  70489. var container = api.getDom();
  70490. var model = this.model;
  70491. if (this._dom) {
  70492. container.removeChild(this._dom);
  70493. }
  70494. var root = document.createElement('div'); // use padding to avoid 5px whitespace
  70495. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  70496. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  70497. var header = document.createElement('h4');
  70498. var lang = model.get('lang') || [];
  70499. header.innerHTML = lang[0] || model.get('title');
  70500. header.style.cssText = 'margin:10px 20px';
  70501. header.style.color = model.get('textColor');
  70502. var viewMain = document.createElement('div');
  70503. var textarea = document.createElement('textarea');
  70504. viewMain.style.cssText = 'overflow:auto';
  70505. var optionToContent = model.get('optionToContent');
  70506. var contentToOption = model.get('contentToOption');
  70507. var result = getContentFromModel(ecModel);
  70508. if (isFunction(optionToContent)) {
  70509. var htmlOrDom = optionToContent(api.getOption());
  70510. if (isString(htmlOrDom)) {
  70511. viewMain.innerHTML = htmlOrDom;
  70512. } else if (isDom(htmlOrDom)) {
  70513. viewMain.appendChild(htmlOrDom);
  70514. }
  70515. } else {
  70516. // Use default textarea
  70517. textarea.readOnly = model.get('readOnly');
  70518. var style = textarea.style; // eslint-disable-next-line max-len
  70519. 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';
  70520. style.color = model.get('textColor');
  70521. style.borderColor = model.get('textareaBorderColor');
  70522. style.backgroundColor = model.get('textareaColor');
  70523. textarea.value = result.value;
  70524. viewMain.appendChild(textarea);
  70525. }
  70526. var blockMetaList = result.meta;
  70527. var buttonContainer = document.createElement('div');
  70528. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0'; // eslint-disable-next-line max-len
  70529. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  70530. var closeButton = document.createElement('div');
  70531. var refreshButton = document.createElement('div');
  70532. buttonStyle += ';background-color:' + model.get('buttonColor');
  70533. buttonStyle += ';color:' + model.get('buttonTextColor');
  70534. var self = this;
  70535. function close() {
  70536. container.removeChild(root);
  70537. self._dom = null;
  70538. }
  70539. addEventListener(closeButton, 'click', close);
  70540. addEventListener(refreshButton, 'click', function () {
  70541. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  70542. if ("development" !== 'production') {
  70543. // eslint-disable-next-line
  70544. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  70545. }
  70546. close();
  70547. return;
  70548. }
  70549. var newOption;
  70550. try {
  70551. if (isFunction(contentToOption)) {
  70552. newOption = contentToOption(viewMain, api.getOption());
  70553. } else {
  70554. newOption = parseContents(textarea.value, blockMetaList);
  70555. }
  70556. } catch (e) {
  70557. close();
  70558. throw new Error('Data view format error ' + e);
  70559. }
  70560. if (newOption) {
  70561. api.dispatchAction({
  70562. type: 'changeDataView',
  70563. newOption: newOption
  70564. });
  70565. }
  70566. close();
  70567. });
  70568. closeButton.innerHTML = lang[1];
  70569. refreshButton.innerHTML = lang[2];
  70570. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  70571. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  70572. buttonContainer.appendChild(closeButton);
  70573. root.appendChild(header);
  70574. root.appendChild(viewMain);
  70575. root.appendChild(buttonContainer);
  70576. viewMain.style.height = container.clientHeight - 80 + 'px';
  70577. container.appendChild(root);
  70578. this._dom = root;
  70579. };
  70580. DataView.prototype.remove = function (ecModel, api) {
  70581. this._dom && api.getDom().removeChild(this._dom);
  70582. };
  70583. DataView.prototype.dispose = function (ecModel, api) {
  70584. this.remove(ecModel, api);
  70585. };
  70586. DataView.getDefaultOption = function (ecModel) {
  70587. var defaultOption = {
  70588. show: true,
  70589. readOnly: false,
  70590. optionToContent: null,
  70591. contentToOption: null,
  70592. // eslint-disable-next-line
  70593. 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',
  70594. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  70595. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  70596. backgroundColor: '#fff',
  70597. textColor: '#000',
  70598. textareaColor: '#fff',
  70599. textareaBorderColor: '#333',
  70600. buttonColor: '#c23531',
  70601. buttonTextColor: '#fff'
  70602. };
  70603. return defaultOption;
  70604. };
  70605. return DataView;
  70606. }(ToolboxFeature);
  70607. /**
  70608. * @inner
  70609. */
  70610. function tryMergeDataOption(newData, originalData) {
  70611. return map(newData, function (newVal, idx) {
  70612. var original = originalData && originalData[idx];
  70613. if (isObject(original) && !isArray(original)) {
  70614. var newValIsObject = isObject(newVal) && !isArray(newVal);
  70615. if (!newValIsObject) {
  70616. newVal = {
  70617. value: newVal
  70618. };
  70619. } // original data has name but new data has no name
  70620. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  70621. newVal = defaults(newVal, original);
  70622. shouldDeleteName && delete newVal.name;
  70623. return newVal;
  70624. } else {
  70625. return newVal;
  70626. }
  70627. });
  70628. } // TODO: SELF REGISTERED.
  70629. registerAction({
  70630. type: 'changeDataView',
  70631. event: 'dataViewChanged',
  70632. update: 'prepareAndUpdate'
  70633. }, function (payload, ecModel) {
  70634. var newSeriesOptList = [];
  70635. each(payload.newOption.series, function (seriesOpt) {
  70636. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  70637. if (!seriesModel) {
  70638. // New created series
  70639. // Geuss the series type
  70640. newSeriesOptList.push(extend({
  70641. // Default is scatter
  70642. type: 'scatter'
  70643. }, seriesOpt));
  70644. } else {
  70645. var originalData = seriesModel.get('data');
  70646. newSeriesOptList.push({
  70647. name: seriesOpt.name,
  70648. data: tryMergeDataOption(seriesOpt.data, originalData)
  70649. });
  70650. }
  70651. });
  70652. ecModel.mergeOption(defaults({
  70653. series: newSeriesOptList
  70654. }, payload.newOption));
  70655. });
  70656. var each$9 = each;
  70657. var inner$f = makeInner();
  70658. /**
  70659. * @param ecModel
  70660. * @param newSnapshot key is dataZoomId
  70661. */
  70662. function push(ecModel, newSnapshot) {
  70663. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  70664. // complete an range with current range.
  70665. each$9(newSnapshot, function (batchItem, dataZoomId) {
  70666. var i = storedSnapshots.length - 1;
  70667. for (; i >= 0; i--) {
  70668. var snapshot = storedSnapshots[i];
  70669. if (snapshot[dataZoomId]) {
  70670. break;
  70671. }
  70672. }
  70673. if (i < 0) {
  70674. // No origin range set, create one by current range.
  70675. var dataZoomModel = ecModel.queryComponents({
  70676. mainType: 'dataZoom',
  70677. subType: 'select',
  70678. id: dataZoomId
  70679. })[0];
  70680. if (dataZoomModel) {
  70681. var percentRange = dataZoomModel.getPercentRange();
  70682. storedSnapshots[0][dataZoomId] = {
  70683. dataZoomId: dataZoomId,
  70684. start: percentRange[0],
  70685. end: percentRange[1]
  70686. };
  70687. }
  70688. }
  70689. });
  70690. storedSnapshots.push(newSnapshot);
  70691. }
  70692. function pop(ecModel) {
  70693. var storedSnapshots = getStoreSnapshots(ecModel);
  70694. var head = storedSnapshots[storedSnapshots.length - 1];
  70695. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  70696. var snapshot = {};
  70697. each$9(head, function (batchItem, dataZoomId) {
  70698. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  70699. batchItem = storedSnapshots[i][dataZoomId];
  70700. if (batchItem) {
  70701. snapshot[dataZoomId] = batchItem;
  70702. break;
  70703. }
  70704. }
  70705. });
  70706. return snapshot;
  70707. }
  70708. function clear$1(ecModel) {
  70709. inner$f(ecModel).snapshots = null;
  70710. }
  70711. function count(ecModel) {
  70712. return getStoreSnapshots(ecModel).length;
  70713. }
  70714. /**
  70715. * History length of each dataZoom may be different.
  70716. * this._history[0] is used to store origin range.
  70717. */
  70718. function getStoreSnapshots(ecModel) {
  70719. var store = inner$f(ecModel);
  70720. if (!store.snapshots) {
  70721. store.snapshots = [{}];
  70722. }
  70723. return store.snapshots;
  70724. }
  70725. var RestoreOption =
  70726. /** @class */
  70727. function (_super) {
  70728. __extends(RestoreOption, _super);
  70729. function RestoreOption() {
  70730. return _super !== null && _super.apply(this, arguments) || this;
  70731. }
  70732. RestoreOption.prototype.onclick = function (ecModel, api) {
  70733. clear$1(ecModel);
  70734. api.dispatchAction({
  70735. type: 'restore',
  70736. from: this.uid
  70737. });
  70738. };
  70739. RestoreOption.getDefaultOption = function (ecModel) {
  70740. var defaultOption = {
  70741. show: true,
  70742. // eslint-disable-next-line
  70743. 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',
  70744. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  70745. };
  70746. return defaultOption;
  70747. };
  70748. return RestoreOption;
  70749. }(ToolboxFeature); // TODO: SELF REGISTERED.
  70750. registerAction({
  70751. type: 'restore',
  70752. event: 'restore',
  70753. update: 'prepareAndUpdate'
  70754. }, function (payload, ecModel) {
  70755. ecModel.resetOption('recreate');
  70756. });
  70757. // how to genarialize to more coordinate systems.
  70758. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  70759. var BrushTargetManager =
  70760. /** @class */
  70761. function () {
  70762. /**
  70763. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  70764. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  70765. * @param opt.include include coordinate system types.
  70766. */
  70767. function BrushTargetManager(finder, ecModel, opt) {
  70768. var _this = this;
  70769. this._targetInfoList = [];
  70770. var foundCpts = parseFinder$1(ecModel, finder);
  70771. each(targetInfoBuilders, function (builder, type) {
  70772. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  70773. builder(foundCpts, _this._targetInfoList);
  70774. }
  70775. });
  70776. }
  70777. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  70778. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  70779. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  70780. if (!area.coordRange) {
  70781. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  70782. // rebuild range by coordRange accrately, which may bring trouble when
  70783. // brushing only one item. So we use __rangeOffset to rebuilding range
  70784. // by coordRange. And this it only used in brush component so it is no
  70785. // need to be adapted to coordRanges.
  70786. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  70787. area.__rangeOffset = {
  70788. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  70789. xyMinMax: result.xyMinMax
  70790. };
  70791. }
  70792. });
  70793. return areas;
  70794. };
  70795. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  70796. each(areas, function (area) {
  70797. var targetInfo = this.findTargetInfo(area, ecModel);
  70798. if (targetInfo && targetInfo !== true) {
  70799. each(targetInfo.coordSyses, function (coordSys) {
  70800. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  70801. cb(area, result.values, coordSys, ecModel);
  70802. });
  70803. }
  70804. }, this);
  70805. };
  70806. /**
  70807. * the `areas` is `BrushModel.areas`.
  70808. * Called in layout stage.
  70809. * convert `area.coordRange` to global range and set panelId to `area.range`.
  70810. */
  70811. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  70812. each(areas, function (area) {
  70813. var targetInfo = this.findTargetInfo(area, ecModel);
  70814. if ("development" !== 'production') {
  70815. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  70816. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  70817. }
  70818. area.range = area.range || []; // convert coordRange to global range and set panelId.
  70819. if (targetInfo && targetInfo !== true) {
  70820. area.panelId = targetInfo.panelId; // (1) area.range should always be calculate from coordRange but does
  70821. // not keep its original value, for the sake of the dataZoom scenario,
  70822. // where area.coordRange remains unchanged but area.range may be changed.
  70823. // (2) Only support converting one coordRange to pixel range in brush
  70824. // component. So do not consider `coordRanges`.
  70825. // (3) About __rangeOffset, see comment above.
  70826. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  70827. var rangeOffset = area.__rangeOffset;
  70828. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  70829. }
  70830. }, this);
  70831. };
  70832. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  70833. return map(this._targetInfoList, function (targetInfo) {
  70834. var rect = targetInfo.getPanelRect();
  70835. return {
  70836. panelId: targetInfo.panelId,
  70837. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  70838. clipPath: makeRectPanelClipPath(rect),
  70839. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  70840. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  70841. };
  70842. });
  70843. };
  70844. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  70845. // Check whether area is bound in coord, and series do not belong to that coord.
  70846. // If do not do this check, some brush (like lineX) will controll all axes.
  70847. var targetInfo = this.findTargetInfo(area, ecModel);
  70848. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  70849. };
  70850. /**
  70851. * If return Object, a coord found.
  70852. * If return true, global found.
  70853. * Otherwise nothing found.
  70854. */
  70855. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  70856. var targetInfoList = this._targetInfoList;
  70857. var foundCpts = parseFinder$1(ecModel, area);
  70858. for (var i = 0; i < targetInfoList.length; i++) {
  70859. var targetInfo = targetInfoList[i];
  70860. var areaPanelId = area.panelId;
  70861. if (areaPanelId) {
  70862. if (targetInfo.panelId === areaPanelId) {
  70863. return targetInfo;
  70864. }
  70865. } else {
  70866. for (var j = 0; j < targetInfoMatchers.length; j++) {
  70867. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  70868. return targetInfo;
  70869. }
  70870. }
  70871. }
  70872. }
  70873. return true;
  70874. };
  70875. return BrushTargetManager;
  70876. }();
  70877. function formatMinMax(minMax) {
  70878. minMax[0] > minMax[1] && minMax.reverse();
  70879. return minMax;
  70880. }
  70881. function parseFinder$1(ecModel, finder) {
  70882. return parseFinder(ecModel, finder, {
  70883. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  70884. });
  70885. }
  70886. var targetInfoBuilders = {
  70887. grid: function (foundCpts, targetInfoList) {
  70888. var xAxisModels = foundCpts.xAxisModels;
  70889. var yAxisModels = foundCpts.yAxisModels;
  70890. var gridModels = foundCpts.gridModels; // Remove duplicated.
  70891. var gridModelMap = createHashMap();
  70892. var xAxesHas = {};
  70893. var yAxesHas = {};
  70894. if (!xAxisModels && !yAxisModels && !gridModels) {
  70895. return;
  70896. }
  70897. each(xAxisModels, function (axisModel) {
  70898. var gridModel = axisModel.axis.grid.model;
  70899. gridModelMap.set(gridModel.id, gridModel);
  70900. xAxesHas[gridModel.id] = true;
  70901. });
  70902. each(yAxisModels, function (axisModel) {
  70903. var gridModel = axisModel.axis.grid.model;
  70904. gridModelMap.set(gridModel.id, gridModel);
  70905. yAxesHas[gridModel.id] = true;
  70906. });
  70907. each(gridModels, function (gridModel) {
  70908. gridModelMap.set(gridModel.id, gridModel);
  70909. xAxesHas[gridModel.id] = true;
  70910. yAxesHas[gridModel.id] = true;
  70911. });
  70912. gridModelMap.each(function (gridModel) {
  70913. var grid = gridModel.coordinateSystem;
  70914. var cartesians = [];
  70915. each(grid.getCartesians(), function (cartesian, index) {
  70916. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  70917. cartesians.push(cartesian);
  70918. }
  70919. });
  70920. targetInfoList.push({
  70921. panelId: 'grid--' + gridModel.id,
  70922. gridModel: gridModel,
  70923. coordSysModel: gridModel,
  70924. // Use the first one as the representitive coordSys.
  70925. coordSys: cartesians[0],
  70926. coordSyses: cartesians,
  70927. getPanelRect: panelRectBuilders.grid,
  70928. xAxisDeclared: xAxesHas[gridModel.id],
  70929. yAxisDeclared: yAxesHas[gridModel.id]
  70930. });
  70931. });
  70932. },
  70933. geo: function (foundCpts, targetInfoList) {
  70934. each(foundCpts.geoModels, function (geoModel) {
  70935. var coordSys = geoModel.coordinateSystem;
  70936. targetInfoList.push({
  70937. panelId: 'geo--' + geoModel.id,
  70938. geoModel: geoModel,
  70939. coordSysModel: geoModel,
  70940. coordSys: coordSys,
  70941. coordSyses: [coordSys],
  70942. getPanelRect: panelRectBuilders.geo
  70943. });
  70944. });
  70945. }
  70946. };
  70947. var targetInfoMatchers = [// grid
  70948. function (foundCpts, targetInfo) {
  70949. var xAxisModel = foundCpts.xAxisModel;
  70950. var yAxisModel = foundCpts.yAxisModel;
  70951. var gridModel = foundCpts.gridModel;
  70952. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  70953. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  70954. return gridModel && gridModel === targetInfo.gridModel;
  70955. }, // geo
  70956. function (foundCpts, targetInfo) {
  70957. var geoModel = foundCpts.geoModel;
  70958. return geoModel && geoModel === targetInfo.geoModel;
  70959. }];
  70960. var panelRectBuilders = {
  70961. grid: function () {
  70962. // grid is not Transformable.
  70963. return this.coordSys.master.getRect().clone();
  70964. },
  70965. geo: function () {
  70966. var coordSys = this.coordSys;
  70967. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  70968. rect.applyTransform(getTransform(coordSys));
  70969. return rect;
  70970. }
  70971. };
  70972. var coordConvert = {
  70973. lineX: curry(axisConvert, 0),
  70974. lineY: curry(axisConvert, 1),
  70975. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  70976. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  70977. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  70978. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  70979. return {
  70980. values: values,
  70981. xyMinMax: values
  70982. };
  70983. },
  70984. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  70985. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  70986. var values = map(rangeOrCoordRange, function (item) {
  70987. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  70988. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  70989. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  70990. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  70991. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  70992. return p;
  70993. });
  70994. return {
  70995. values: values,
  70996. xyMinMax: xyMinMax
  70997. };
  70998. }
  70999. };
  71000. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  71001. if ("development" !== 'production') {
  71002. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  71003. }
  71004. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  71005. var values = formatMinMax(map([0, 1], function (i) {
  71006. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  71007. }));
  71008. var xyMinMax = [];
  71009. xyMinMax[axisNameIndex] = values;
  71010. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  71011. return {
  71012. values: values,
  71013. xyMinMax: xyMinMax
  71014. };
  71015. }
  71016. var diffProcessor = {
  71017. lineX: curry(axisDiffProcessor, 0),
  71018. lineY: curry(axisDiffProcessor, 1),
  71019. rect: function (values, refer, scales) {
  71020. 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]]];
  71021. },
  71022. polygon: function (values, refer, scales) {
  71023. return map(values, function (item, idx) {
  71024. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  71025. });
  71026. }
  71027. };
  71028. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  71029. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  71030. } // We have to process scale caused by dataZoom manually,
  71031. // although it might be not accurate.
  71032. // Return [0~1, 0~1]
  71033. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  71034. var sizeCurr = getSize$1(xyMinMaxCurr);
  71035. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  71036. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  71037. isNaN(scales[0]) && (scales[0] = 1);
  71038. isNaN(scales[1]) && (scales[1] = 1);
  71039. return scales;
  71040. }
  71041. function getSize$1(xyMinMax) {
  71042. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  71043. }
  71044. var each$a = each;
  71045. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  71046. var DataZoomFeature =
  71047. /** @class */
  71048. function (_super) {
  71049. __extends(DataZoomFeature, _super);
  71050. function DataZoomFeature() {
  71051. return _super !== null && _super.apply(this, arguments) || this;
  71052. }
  71053. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  71054. if (!this._brushController) {
  71055. this._brushController = new BrushController(api.getZr());
  71056. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  71057. }
  71058. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  71059. updateBackBtnStatus(featureModel, ecModel);
  71060. };
  71061. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  71062. handlers$1[type].call(this);
  71063. };
  71064. DataZoomFeature.prototype.remove = function (ecModel, api) {
  71065. this._brushController && this._brushController.unmount();
  71066. };
  71067. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  71068. this._brushController && this._brushController.dispose();
  71069. };
  71070. DataZoomFeature.prototype._onBrush = function (eventParam) {
  71071. var areas = eventParam.areas;
  71072. if (!eventParam.isEnd || !areas.length) {
  71073. return;
  71074. }
  71075. var snapshot = {};
  71076. var ecModel = this.ecModel;
  71077. this._brushController.updateCovers([]); // remove cover
  71078. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  71079. include: ['grid']
  71080. });
  71081. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  71082. if (coordSys.type !== 'cartesian2d') {
  71083. return;
  71084. }
  71085. var brushType = area.brushType;
  71086. if (brushType === 'rect') {
  71087. setBatch('x', coordSys, coordRange[0]);
  71088. setBatch('y', coordSys, coordRange[1]);
  71089. } else {
  71090. setBatch({
  71091. lineX: 'x',
  71092. lineY: 'y'
  71093. }[brushType], coordSys, coordRange);
  71094. }
  71095. });
  71096. push(ecModel, snapshot);
  71097. this._dispatchZoomAction(snapshot);
  71098. function setBatch(dimName, coordSys, minMax) {
  71099. var axis = coordSys.getAxis(dimName);
  71100. var axisModel = axis.model;
  71101. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  71102. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  71103. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  71104. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  71105. }
  71106. dataZoomModel && (snapshot[dataZoomModel.id] = {
  71107. dataZoomId: dataZoomModel.id,
  71108. startValue: minMax[0],
  71109. endValue: minMax[1]
  71110. });
  71111. }
  71112. function findDataZoom(dimName, axisModel, ecModel) {
  71113. var found;
  71114. ecModel.eachComponent({
  71115. mainType: 'dataZoom',
  71116. subType: 'select'
  71117. }, function (dzModel) {
  71118. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  71119. has && (found = dzModel);
  71120. });
  71121. return found;
  71122. }
  71123. };
  71124. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  71125. var batch = []; // Convert from hash map to array.
  71126. each$a(snapshot, function (batchItem, dataZoomId) {
  71127. batch.push(clone(batchItem));
  71128. });
  71129. batch.length && this.api.dispatchAction({
  71130. type: 'dataZoom',
  71131. from: this.uid,
  71132. batch: batch
  71133. });
  71134. };
  71135. DataZoomFeature.getDefaultOption = function (ecModel) {
  71136. var defaultOption = {
  71137. show: true,
  71138. filterMode: 'filter',
  71139. // Icon group
  71140. icon: {
  71141. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  71142. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  71143. },
  71144. // `zoom`, `back`
  71145. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  71146. brushStyle: {
  71147. borderWidth: 0,
  71148. color: 'rgba(210,219,238,0.2)'
  71149. }
  71150. };
  71151. return defaultOption;
  71152. };
  71153. return DataZoomFeature;
  71154. }(ToolboxFeature);
  71155. var handlers$1 = {
  71156. zoom: function () {
  71157. var nextActive = !this._isZoomActive;
  71158. this.api.dispatchAction({
  71159. type: 'takeGlobalCursor',
  71160. key: 'dataZoomSelect',
  71161. dataZoomSelectActive: nextActive
  71162. });
  71163. },
  71164. back: function () {
  71165. this._dispatchZoomAction(pop(this.ecModel));
  71166. }
  71167. };
  71168. function makeAxisFinder(dzFeatureModel) {
  71169. var setting = {
  71170. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  71171. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  71172. xAxisId: dzFeatureModel.get('xAxisId', true),
  71173. yAxisId: dzFeatureModel.get('yAxisId', true)
  71174. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  71175. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  71176. // Some old cases set like this below to close yAxis control but leave xAxis control:
  71177. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  71178. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  71179. setting.xAxisIndex = 'all';
  71180. }
  71181. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  71182. setting.yAxisIndex = 'all';
  71183. }
  71184. return setting;
  71185. }
  71186. function updateBackBtnStatus(featureModel, ecModel) {
  71187. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  71188. }
  71189. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  71190. var zoomActive = view._isZoomActive;
  71191. if (payload && payload.type === 'takeGlobalCursor') {
  71192. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  71193. }
  71194. view._isZoomActive = zoomActive;
  71195. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  71196. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  71197. include: ['grid']
  71198. });
  71199. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  71200. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  71201. });
  71202. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  71203. brushType: 'auto',
  71204. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  71205. } : false);
  71206. }
  71207. registerInternalOptionCreator('dataZoom', function (ecModel) {
  71208. var toolboxModel = ecModel.getComponent('toolbox', 0);
  71209. var featureDataZoomPath = ['feature', 'dataZoom'];
  71210. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  71211. return;
  71212. }
  71213. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  71214. var dzOptions = [];
  71215. var finder = makeAxisFinder(dzFeatureModel);
  71216. var finderResult = parseFinder(ecModel, finder);
  71217. each$a(finderResult.xAxisModels, function (axisModel) {
  71218. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  71219. });
  71220. each$a(finderResult.yAxisModels, function (axisModel) {
  71221. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  71222. });
  71223. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  71224. var axisIndex = axisModel.componentIndex;
  71225. var newOpt = {
  71226. type: 'select',
  71227. $fromToolbox: true,
  71228. // Default to be filter
  71229. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  71230. // Id for merge mapping.
  71231. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  71232. };
  71233. newOpt[axisIndexPropName] = axisIndex;
  71234. dzOptions.push(newOpt);
  71235. }
  71236. return dzOptions;
  71237. });
  71238. function install$z(registers) {
  71239. registers.registerComponentModel(ToolboxModel);
  71240. registers.registerComponentView(ToolboxView);
  71241. registerFeature('saveAsImage', SaveAsImage);
  71242. registerFeature('magicType', MagicType);
  71243. registerFeature('dataView', DataView);
  71244. registerFeature('dataZoom', DataZoomFeature);
  71245. registerFeature('restore', RestoreOption);
  71246. use(install$y);
  71247. }
  71248. var TooltipModel =
  71249. /** @class */
  71250. function (_super) {
  71251. __extends(TooltipModel, _super);
  71252. function TooltipModel() {
  71253. var _this = _super !== null && _super.apply(this, arguments) || this;
  71254. _this.type = TooltipModel.type;
  71255. return _this;
  71256. }
  71257. TooltipModel.type = 'tooltip';
  71258. TooltipModel.dependencies = ['axisPointer'];
  71259. TooltipModel.defaultOption = {
  71260. // zlevel: 0,
  71261. z: 60,
  71262. show: true,
  71263. // tooltip main content
  71264. showContent: true,
  71265. // 'trigger' only works on coordinate system.
  71266. // 'item' | 'axis' | 'none'
  71267. trigger: 'item',
  71268. // 'click' | 'mousemove' | 'none'
  71269. triggerOn: 'mousemove|click',
  71270. alwaysShowContent: false,
  71271. displayMode: 'single',
  71272. renderMode: 'auto',
  71273. // whether restraint content inside viewRect.
  71274. // If renderMode: 'richText', default true.
  71275. // If renderMode: 'html', defaut false (for backward compat).
  71276. confine: null,
  71277. showDelay: 0,
  71278. hideDelay: 100,
  71279. // Animation transition time, unit is second
  71280. transitionDuration: 0.4,
  71281. enterable: false,
  71282. backgroundColor: '#fff',
  71283. // box shadow
  71284. shadowBlur: 10,
  71285. shadowColor: 'rgba(0, 0, 0, .2)',
  71286. shadowOffsetX: 1,
  71287. shadowOffsetY: 2,
  71288. // tooltip border radius, unit is px, default is 4
  71289. borderRadius: 4,
  71290. // tooltip border width, unit is px, default is 0 (no border)
  71291. borderWidth: 1,
  71292. // Tooltip inside padding, default is 5 for all direction
  71293. // Array is allowed to set up, right, bottom, left, same with css
  71294. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  71295. padding: null,
  71296. // Extra css text
  71297. extraCssText: '',
  71298. // axis indicator, trigger by axis
  71299. axisPointer: {
  71300. // default is line
  71301. // legal values: 'line' | 'shadow' | 'cross'
  71302. type: 'line',
  71303. // Valid when type is line, appoint tooltip line locate on which line. Optional
  71304. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  71305. // default is 'auto', chose the axis which type is category.
  71306. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  71307. axis: 'auto',
  71308. animation: 'auto',
  71309. animationDurationUpdate: 200,
  71310. animationEasingUpdate: 'exponentialOut',
  71311. crossStyle: {
  71312. color: '#999',
  71313. width: 1,
  71314. type: 'dashed',
  71315. // TODO formatter
  71316. textStyle: {}
  71317. } // lineStyle and shadowStyle should not be specified here,
  71318. // otherwise it will always override those styles on option.axisPointer.
  71319. },
  71320. textStyle: {
  71321. color: '#666',
  71322. fontSize: 14
  71323. }
  71324. };
  71325. return TooltipModel;
  71326. }(ComponentModel);
  71327. /* global document */
  71328. function shouldTooltipConfine(tooltipModel) {
  71329. var confineOption = tooltipModel.get('confine');
  71330. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  71331. : tooltipModel.get('renderMode') === 'richText';
  71332. }
  71333. function testStyle(styleProps) {
  71334. if (!env.domSupported) {
  71335. return;
  71336. }
  71337. var style = document.documentElement.style;
  71338. for (var i = 0, len = styleProps.length; i < len; i++) {
  71339. if (styleProps[i] in style) {
  71340. return styleProps[i];
  71341. }
  71342. }
  71343. }
  71344. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  71345. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  71346. function toCSSVendorPrefix(styleVendor, styleProp) {
  71347. if (!styleVendor) {
  71348. return styleProp;
  71349. }
  71350. styleProp = toCamelCase(styleProp, true);
  71351. var idx = styleVendor.indexOf(styleProp);
  71352. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  71353. return styleVendor.toLowerCase();
  71354. }
  71355. function getComputedStyle(el, style) {
  71356. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  71357. return stl ? style ? stl[style] : stl : null;
  71358. }
  71359. /* global document, window */
  71360. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  71361. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'); // eslint-disable-next-line
  71362. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  71363. function mirrorPos(pos) {
  71364. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  71365. return pos;
  71366. }
  71367. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  71368. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  71369. return '';
  71370. }
  71371. var backgroundColor = tooltipModel.get('backgroundColor');
  71372. var borderWidth = tooltipModel.get('borderWidth');
  71373. borderColor = convertToColorString(borderColor);
  71374. var arrowPos = mirrorPos(arrowPosition);
  71375. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  71376. var positionStyle = '';
  71377. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  71378. var rotateDeg;
  71379. if (indexOf(['left', 'right'], arrowPos) > -1) {
  71380. positionStyle += 'top:50%';
  71381. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  71382. } else {
  71383. positionStyle += 'left:50%';
  71384. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  71385. }
  71386. var rotateRadian = rotateDeg * Math.PI / 180;
  71387. var arrowWH = arrowSize + borderWidth;
  71388. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  71389. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  71390. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  71391. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  71392. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  71393. return "<div style=\"" + styleCss.join('') + "\"></div>";
  71394. }
  71395. function assembleTransition(duration, onlyFade) {
  71396. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  71397. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  71398. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  71399. if (!onlyFade) {
  71400. transitionOption = " " + duration + "s " + transitionCurve;
  71401. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  71402. }
  71403. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  71404. }
  71405. function assembleTransform(x, y, toString) {
  71406. // If using float on style, the final width of the dom might
  71407. // keep changing slightly while mouse move. So `toFixed(0)` them.
  71408. var x0 = x.toFixed(0) + 'px';
  71409. var y0 = y.toFixed(0) + 'px'; // not support transform, use `left` and `top` instead.
  71410. if (!env.transformSupported) {
  71411. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  71412. } // support transform
  71413. var is3d = env.transform3dSupported;
  71414. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  71415. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  71416. }
  71417. /**
  71418. * @param {Object} textStyle
  71419. * @return {string}
  71420. * @inner
  71421. */
  71422. function assembleFont(textStyleModel) {
  71423. var cssText = [];
  71424. var fontSize = textStyleModel.get('fontSize');
  71425. var color = textStyleModel.getTextColor();
  71426. color && cssText.push('color:' + color);
  71427. cssText.push('font:' + textStyleModel.getFont());
  71428. fontSize // @ts-ignore, leave it to the tooltip refactor.
  71429. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  71430. var shadowColor = textStyleModel.get('textShadowColor');
  71431. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  71432. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  71433. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  71434. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  71435. each(['decoration', 'align'], function (name) {
  71436. var val = textStyleModel.get(name);
  71437. val && cssText.push('text-' + name + ':' + val);
  71438. });
  71439. return cssText.join(';');
  71440. }
  71441. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  71442. var cssText = [];
  71443. var transitionDuration = tooltipModel.get('transitionDuration');
  71444. var backgroundColor = tooltipModel.get('backgroundColor');
  71445. var shadowBlur = tooltipModel.get('shadowBlur');
  71446. var shadowColor = tooltipModel.get('shadowColor');
  71447. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  71448. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  71449. var textStyleModel = tooltipModel.getModel('textStyle');
  71450. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  71451. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  71452. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  71453. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  71454. if (backgroundColor) {
  71455. cssText.push('background-color:' + backgroundColor);
  71456. } // Border style
  71457. each(['width', 'color', 'radius'], function (name) {
  71458. var borderName = 'border-' + name;
  71459. var camelCase = toCamelCase(borderName);
  71460. var val = tooltipModel.get(camelCase);
  71461. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  71462. }); // Text style
  71463. cssText.push(assembleFont(textStyleModel)); // Padding
  71464. if (padding != null) {
  71465. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  71466. }
  71467. return cssText.join(';') + ';';
  71468. } // If not able to make, do not modify the input `out`.
  71469. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  71470. var zrPainter = zr && zr.painter;
  71471. if (appendToBody) {
  71472. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  71473. if (zrViewportRoot) {
  71474. // Some APPs might use scale on body, so we support CSS transform here.
  71475. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  71476. }
  71477. } else {
  71478. out[0] = zrX;
  71479. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  71480. // the sibling of canvas root. So padding of ec container
  71481. // should be considered here.
  71482. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  71483. if (viewportRootOffset) {
  71484. out[0] += viewportRootOffset.offsetLeft;
  71485. out[1] += viewportRootOffset.offsetTop;
  71486. }
  71487. }
  71488. out[2] = out[0] / zr.getWidth();
  71489. out[3] = out[1] / zr.getHeight();
  71490. }
  71491. var TooltipHTMLContent =
  71492. /** @class */
  71493. function () {
  71494. function TooltipHTMLContent(container, api, opt) {
  71495. this._show = false;
  71496. this._styleCoord = [0, 0, 0, 0];
  71497. this._enterable = true;
  71498. this._alwaysShowContent = false;
  71499. this._firstShow = true;
  71500. this._longHide = true;
  71501. if (env.wxa) {
  71502. return null;
  71503. }
  71504. var el = document.createElement('div'); // TODO: TYPE
  71505. el.domBelongToZr = true;
  71506. this.el = el;
  71507. var zr = this._zr = api.getZr();
  71508. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  71509. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  71510. if (appendToBody) {
  71511. document.body.appendChild(el);
  71512. } else {
  71513. container.appendChild(el);
  71514. }
  71515. this._container = container; // FIXME
  71516. // Is it needed to trigger zr event manually if
  71517. // the browser do not support `pointer-events: none`.
  71518. var self = this;
  71519. el.onmouseenter = function () {
  71520. // clear the timeout in hideLater and keep showing tooltip
  71521. if (self._enterable) {
  71522. clearTimeout(self._hideTimeout);
  71523. self._show = true;
  71524. }
  71525. self._inContent = true;
  71526. };
  71527. el.onmousemove = function (e) {
  71528. e = e || window.event;
  71529. if (!self._enterable) {
  71530. // `pointer-events: none` is set to tooltip content div
  71531. // if `enterable` is set as `false`, and `el.onmousemove`
  71532. // can not be triggered. But in browser that do not
  71533. // support `pointer-events`, we need to do this:
  71534. // Try trigger zrender event to avoid mouse
  71535. // in and out shape too frequently
  71536. var handler = zr.handler;
  71537. var zrViewportRoot = zr.painter.getViewportRoot();
  71538. normalizeEvent(zrViewportRoot, e, true);
  71539. handler.dispatch('mousemove', e);
  71540. }
  71541. };
  71542. el.onmouseleave = function () {
  71543. // set `_inContent` to `false` before `hideLater`
  71544. self._inContent = false;
  71545. if (self._enterable) {
  71546. if (self._show) {
  71547. self.hideLater(self._hideDelay);
  71548. }
  71549. }
  71550. };
  71551. }
  71552. /**
  71553. * Update when tooltip is rendered
  71554. */
  71555. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  71556. // FIXME
  71557. // Move this logic to ec main?
  71558. var container = this._container;
  71559. var position = getComputedStyle(container, 'position');
  71560. var domStyle = container.style;
  71561. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  71562. domStyle.position = 'relative';
  71563. } // move tooltip if chart resized
  71564. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71565. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  71566. this._alwaysShowContent = alwaysShowContent; // update className
  71567. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  71568. // PENDING
  71569. // this.hide();
  71570. };
  71571. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  71572. clearTimeout(this._hideTimeout);
  71573. clearTimeout(this._longHideTimeout);
  71574. var el = this.el;
  71575. var style = el.style;
  71576. var styleCoord = this._styleCoord;
  71577. if (!el.innerHTML) {
  71578. style.display = 'none';
  71579. } else {
  71580. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // initial transform
  71581. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '') // If mouse occasionally move over the tooltip, a mouseout event will be
  71582. // triggered by canvas, and cause some unexpectable result like dragging
  71583. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  71584. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  71585. // scenario.
  71586. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  71587. }
  71588. this._show = true;
  71589. this._firstShow = false;
  71590. this._longHide = false;
  71591. };
  71592. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  71593. var el = this.el;
  71594. if (content == null) {
  71595. el.innerHTML = '';
  71596. return;
  71597. }
  71598. var arrow = '';
  71599. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  71600. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  71601. }
  71602. if (isString(content)) {
  71603. el.innerHTML = content + arrow;
  71604. } else if (content) {
  71605. // Clear previous
  71606. el.innerHTML = '';
  71607. if (!isArray(content)) {
  71608. content = [content];
  71609. }
  71610. for (var i = 0; i < content.length; i++) {
  71611. if (isDom(content[i]) && content[i].parentNode !== el) {
  71612. el.appendChild(content[i]);
  71613. }
  71614. } // no arrow if empty
  71615. if (arrow && el.childNodes.length) {
  71616. // no need to create a new parent element, but it's not supported by IE 10 and older.
  71617. // const arrowEl = document.createRange().createContextualFragment(arrow);
  71618. var arrowEl = document.createElement('div');
  71619. arrowEl.innerHTML = arrow;
  71620. el.appendChild(arrowEl);
  71621. }
  71622. }
  71623. };
  71624. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  71625. this._enterable = enterable;
  71626. };
  71627. TooltipHTMLContent.prototype.getSize = function () {
  71628. var el = this.el;
  71629. return [el.offsetWidth, el.offsetHeight];
  71630. };
  71631. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  71632. var styleCoord = this._styleCoord;
  71633. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  71634. if (styleCoord[0] != null && styleCoord[1] != null) {
  71635. var style_1 = this.el.style;
  71636. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  71637. each(transforms, function (transform) {
  71638. style_1[transform[0]] = transform[1];
  71639. });
  71640. }
  71641. };
  71642. /**
  71643. * when `alwaysShowContent` is true,
  71644. * move the tooltip after chart resized
  71645. */
  71646. TooltipHTMLContent.prototype._moveIfResized = function () {
  71647. // The ratio of left to width
  71648. var ratioX = this._styleCoord[2]; // The ratio of top to height
  71649. var ratioY = this._styleCoord[3];
  71650. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  71651. };
  71652. TooltipHTMLContent.prototype.hide = function () {
  71653. var _this = this;
  71654. var style = this.el.style;
  71655. style.visibility = 'hidden';
  71656. style.opacity = '0';
  71657. env.transform3dSupported && (style.willChange = '');
  71658. this._show = false;
  71659. this._longHideTimeout = setTimeout(function () {
  71660. return _this._longHide = true;
  71661. }, 500);
  71662. };
  71663. TooltipHTMLContent.prototype.hideLater = function (time) {
  71664. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  71665. if (time) {
  71666. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  71667. this._show = false;
  71668. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71669. } else {
  71670. this.hide();
  71671. }
  71672. }
  71673. };
  71674. TooltipHTMLContent.prototype.isShow = function () {
  71675. return this._show;
  71676. };
  71677. TooltipHTMLContent.prototype.dispose = function () {
  71678. this.el.parentNode.removeChild(this.el);
  71679. };
  71680. return TooltipHTMLContent;
  71681. }();
  71682. var TooltipRichContent =
  71683. /** @class */
  71684. function () {
  71685. function TooltipRichContent(api) {
  71686. this._show = false;
  71687. this._styleCoord = [0, 0, 0, 0];
  71688. this._alwaysShowContent = false;
  71689. this._enterable = true;
  71690. this._zr = api.getZr();
  71691. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  71692. }
  71693. /**
  71694. * Update when tooltip is rendered
  71695. */
  71696. TooltipRichContent.prototype.update = function (tooltipModel) {
  71697. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71698. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  71699. this._alwaysShowContent = alwaysShowContent;
  71700. };
  71701. TooltipRichContent.prototype.show = function () {
  71702. if (this._hideTimeout) {
  71703. clearTimeout(this._hideTimeout);
  71704. }
  71705. this.el.show();
  71706. this._show = true;
  71707. };
  71708. /**
  71709. * Set tooltip content
  71710. */
  71711. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  71712. var _this = this;
  71713. if (isObject(content)) {
  71714. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  71715. }
  71716. if (this.el) {
  71717. this._zr.remove(this.el);
  71718. }
  71719. var textStyleModel = tooltipModel.getModel('textStyle');
  71720. this.el = new ZRText({
  71721. style: {
  71722. rich: markupStyleCreator.richTextStyles,
  71723. text: content,
  71724. lineHeight: 22,
  71725. borderWidth: 1,
  71726. borderColor: borderColor,
  71727. textShadowColor: textStyleModel.get('textShadowColor'),
  71728. fill: tooltipModel.get(['textStyle', 'color']),
  71729. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  71730. verticalAlign: 'top',
  71731. align: 'left'
  71732. },
  71733. z: tooltipModel.get('z')
  71734. });
  71735. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  71736. _this.el.style[propName] = tooltipModel.get(propName);
  71737. });
  71738. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  71739. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  71740. });
  71741. this._zr.add(this.el);
  71742. var self = this;
  71743. this.el.on('mouseover', function () {
  71744. // clear the timeout in hideLater and keep showing tooltip
  71745. if (self._enterable) {
  71746. clearTimeout(self._hideTimeout);
  71747. self._show = true;
  71748. }
  71749. self._inContent = true;
  71750. });
  71751. this.el.on('mouseout', function () {
  71752. if (self._enterable) {
  71753. if (self._show) {
  71754. self.hideLater(self._hideDelay);
  71755. }
  71756. }
  71757. self._inContent = false;
  71758. });
  71759. };
  71760. TooltipRichContent.prototype.setEnterable = function (enterable) {
  71761. this._enterable = enterable;
  71762. };
  71763. TooltipRichContent.prototype.getSize = function () {
  71764. var el = this.el;
  71765. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  71766. // if overflow, it will be cut. So calculate them accurately.
  71767. var shadowOuterSize = calcShadowOuterSize(el.style);
  71768. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  71769. };
  71770. TooltipRichContent.prototype.moveTo = function (x, y) {
  71771. var el = this.el;
  71772. if (el) {
  71773. var styleCoord = this._styleCoord;
  71774. makeStyleCoord$1(styleCoord, this._zr, x, y);
  71775. x = styleCoord[0];
  71776. y = styleCoord[1];
  71777. var style = el.style;
  71778. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  71779. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  71780. el.x = x + borderWidth + shadowOuterSize.left;
  71781. el.y = y + borderWidth + shadowOuterSize.top;
  71782. el.markRedraw();
  71783. }
  71784. };
  71785. /**
  71786. * when `alwaysShowContent` is true,
  71787. * move the tooltip after chart resized
  71788. */
  71789. TooltipRichContent.prototype._moveIfResized = function () {
  71790. // The ratio of left to width
  71791. var ratioX = this._styleCoord[2]; // The ratio of top to height
  71792. var ratioY = this._styleCoord[3];
  71793. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  71794. };
  71795. TooltipRichContent.prototype.hide = function () {
  71796. if (this.el) {
  71797. this.el.hide();
  71798. }
  71799. this._show = false;
  71800. };
  71801. TooltipRichContent.prototype.hideLater = function (time) {
  71802. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  71803. if (time) {
  71804. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  71805. this._show = false;
  71806. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71807. } else {
  71808. this.hide();
  71809. }
  71810. }
  71811. };
  71812. TooltipRichContent.prototype.isShow = function () {
  71813. return this._show;
  71814. };
  71815. TooltipRichContent.prototype.dispose = function () {
  71816. this._zr.remove(this.el);
  71817. };
  71818. return TooltipRichContent;
  71819. }();
  71820. function mathMaxWith0(val) {
  71821. return Math.max(0, val);
  71822. }
  71823. function calcShadowOuterSize(style) {
  71824. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  71825. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  71826. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  71827. return {
  71828. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  71829. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  71830. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  71831. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  71832. };
  71833. }
  71834. function makeStyleCoord$1(out, zr, zrX, zrY) {
  71835. out[0] = zrX;
  71836. out[1] = zrY;
  71837. out[2] = out[0] / zr.getWidth();
  71838. out[3] = out[1] / zr.getHeight();
  71839. }
  71840. var proxyRect = new Rect({
  71841. shape: {
  71842. x: -1,
  71843. y: -1,
  71844. width: 2,
  71845. height: 2
  71846. }
  71847. });
  71848. var TooltipView =
  71849. /** @class */
  71850. function (_super) {
  71851. __extends(TooltipView, _super);
  71852. function TooltipView() {
  71853. var _this = _super !== null && _super.apply(this, arguments) || this;
  71854. _this.type = TooltipView.type;
  71855. return _this;
  71856. }
  71857. TooltipView.prototype.init = function (ecModel, api) {
  71858. if (env.node || !api.getDom()) {
  71859. return;
  71860. }
  71861. var tooltipModel = ecModel.getComponent('tooltip');
  71862. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  71863. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  71864. appendToBody: tooltipModel.get('appendToBody', true)
  71865. });
  71866. };
  71867. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  71868. if (env.node || !api.getDom()) {
  71869. return;
  71870. } // Reset
  71871. this.group.removeAll();
  71872. this._tooltipModel = tooltipModel;
  71873. this._ecModel = ecModel;
  71874. this._api = api;
  71875. var tooltipContent = this._tooltipContent;
  71876. tooltipContent.update(tooltipModel);
  71877. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  71878. this._initGlobalListener();
  71879. this._keepShow(); // PENDING
  71880. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  71881. // which causes that the `updatePosition` function was also called frequently.
  71882. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  71883. // To avoid frequent triggering,
  71884. // consider throttling it in 50ms when transition is enabled
  71885. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  71886. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  71887. } else {
  71888. clear(this, '_updatePosition');
  71889. }
  71890. };
  71891. TooltipView.prototype._initGlobalListener = function () {
  71892. var tooltipModel = this._tooltipModel;
  71893. var triggerOn = tooltipModel.get('triggerOn');
  71894. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  71895. // If 'none', it is not controlled by mouse totally.
  71896. if (triggerOn !== 'none') {
  71897. if (triggerOn.indexOf(currTrigger) >= 0) {
  71898. this._tryShow(e, dispatchAction);
  71899. } else if (currTrigger === 'leave') {
  71900. this._hide(dispatchAction);
  71901. }
  71902. }
  71903. }, this));
  71904. };
  71905. TooltipView.prototype._keepShow = function () {
  71906. var tooltipModel = this._tooltipModel;
  71907. var ecModel = this._ecModel;
  71908. var api = this._api;
  71909. var triggerOn = tooltipModel.get('triggerOn'); // Try to keep the tooltip show when refreshing
  71910. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  71911. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  71912. // which is not expected.
  71913. && triggerOn !== 'none' && triggerOn !== 'click') {
  71914. var self_1 = this;
  71915. clearTimeout(this._refreshUpdateTimeout);
  71916. this._refreshUpdateTimeout = setTimeout(function () {
  71917. // Show tip next tick after other charts are rendered
  71918. // In case highlight action has wrong result
  71919. // FIXME
  71920. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  71921. x: self_1._lastX,
  71922. y: self_1._lastY,
  71923. dataByCoordSys: self_1._lastDataByCoordSys
  71924. });
  71925. });
  71926. }
  71927. };
  71928. /**
  71929. * Show tip manually by
  71930. * dispatchAction({
  71931. * type: 'showTip',
  71932. * x: 10,
  71933. * y: 10
  71934. * });
  71935. * Or
  71936. * dispatchAction({
  71937. * type: 'showTip',
  71938. * seriesIndex: 0,
  71939. * dataIndex or dataIndexInside or name
  71940. * });
  71941. *
  71942. * TODO Batch
  71943. */
  71944. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  71945. if (payload.from === this.uid || env.node || !api.getDom()) {
  71946. return;
  71947. }
  71948. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  71949. this._ticket = ''; // When triggered from axisPointer.
  71950. var dataByCoordSys = payload.dataByCoordSys;
  71951. var cmptRef = findComponentReference(payload, ecModel, api);
  71952. if (cmptRef) {
  71953. var rect = cmptRef.el.getBoundingRect().clone();
  71954. rect.applyTransform(cmptRef.el.transform);
  71955. this._tryShow({
  71956. offsetX: rect.x + rect.width / 2,
  71957. offsetY: rect.y + rect.height / 2,
  71958. target: cmptRef.el,
  71959. position: payload.position,
  71960. // When manully trigger, the mouse is not on the el, so we'd better to
  71961. // position tooltip on the bottom of the el and display arrow is possible.
  71962. positionDefault: 'bottom'
  71963. }, dispatchAction);
  71964. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  71965. var el = proxyRect;
  71966. el.x = payload.x;
  71967. el.y = payload.y;
  71968. el.update();
  71969. getECData(el).tooltipConfig = {
  71970. name: null,
  71971. option: payload.tooltip
  71972. }; // Manually show tooltip while view is not using zrender elements.
  71973. this._tryShow({
  71974. offsetX: payload.x,
  71975. offsetY: payload.y,
  71976. target: el
  71977. }, dispatchAction);
  71978. } else if (dataByCoordSys) {
  71979. this._tryShow({
  71980. offsetX: payload.x,
  71981. offsetY: payload.y,
  71982. position: payload.position,
  71983. dataByCoordSys: dataByCoordSys,
  71984. tooltipOption: payload.tooltipOption
  71985. }, dispatchAction);
  71986. } else if (payload.seriesIndex != null) {
  71987. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  71988. return;
  71989. }
  71990. var pointInfo = findPointFromSeries(payload, ecModel);
  71991. var cx = pointInfo.point[0];
  71992. var cy = pointInfo.point[1];
  71993. if (cx != null && cy != null) {
  71994. this._tryShow({
  71995. offsetX: cx,
  71996. offsetY: cy,
  71997. target: pointInfo.el,
  71998. position: payload.position,
  71999. // When manully trigger, the mouse is not on the el, so we'd better to
  72000. // position tooltip on the bottom of the el and display arrow is possible.
  72001. positionDefault: 'bottom'
  72002. }, dispatchAction);
  72003. }
  72004. } else if (payload.x != null && payload.y != null) {
  72005. // FIXME
  72006. // should wrap dispatchAction like `axisPointer/globalListener` ?
  72007. api.dispatchAction({
  72008. type: 'updateAxisPointer',
  72009. x: payload.x,
  72010. y: payload.y
  72011. });
  72012. this._tryShow({
  72013. offsetX: payload.x,
  72014. offsetY: payload.y,
  72015. position: payload.position,
  72016. target: api.getZr().findHover(payload.x, payload.y).target
  72017. }, dispatchAction);
  72018. }
  72019. };
  72020. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  72021. var tooltipContent = this._tooltipContent;
  72022. if (this._tooltipModel) {
  72023. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  72024. }
  72025. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  72026. if (payload.from !== this.uid) {
  72027. this._hide(makeDispatchAction$1(payload, api));
  72028. }
  72029. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  72030. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  72031. // and tooltip.
  72032. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  72033. var seriesIndex = payload.seriesIndex;
  72034. var dataIndex = payload.dataIndex; // @ts-ignore
  72035. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  72036. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  72037. return;
  72038. }
  72039. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  72040. if (!seriesModel) {
  72041. return;
  72042. }
  72043. var data = seriesModel.getData();
  72044. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  72045. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  72046. return;
  72047. }
  72048. api.dispatchAction({
  72049. type: 'updateAxisPointer',
  72050. seriesIndex: seriesIndex,
  72051. dataIndex: dataIndex,
  72052. position: payload.position
  72053. });
  72054. return true;
  72055. };
  72056. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  72057. var el = e.target;
  72058. var tooltipModel = this._tooltipModel;
  72059. if (!tooltipModel) {
  72060. return;
  72061. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  72062. this._lastX = e.offsetX;
  72063. this._lastY = e.offsetY;
  72064. var dataByCoordSys = e.dataByCoordSys;
  72065. if (dataByCoordSys && dataByCoordSys.length) {
  72066. this._showAxisTooltip(dataByCoordSys, e);
  72067. } else if (el) {
  72068. this._lastDataByCoordSys = null;
  72069. var seriesDispatcher_1;
  72070. var cmptDispatcher_1;
  72071. findEventDispatcher(el, function (target) {
  72072. // Always show item tooltip if mouse is on the element with dataIndex
  72073. if (getECData(target).dataIndex != null) {
  72074. seriesDispatcher_1 = target;
  72075. return true;
  72076. } // Tooltip provided directly. Like legend.
  72077. if (getECData(target).tooltipConfig != null) {
  72078. cmptDispatcher_1 = target;
  72079. return true;
  72080. }
  72081. }, true);
  72082. if (seriesDispatcher_1) {
  72083. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  72084. } else if (cmptDispatcher_1) {
  72085. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  72086. } else {
  72087. this._hide(dispatchAction);
  72088. }
  72089. } else {
  72090. this._lastDataByCoordSys = null;
  72091. this._hide(dispatchAction);
  72092. }
  72093. };
  72094. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  72095. // showDelay is used in this case: tooltip.enterable is set
  72096. // as true. User intent to move mouse into tooltip and click
  72097. // something. `showDelay` makes it easier to enter the content
  72098. // but tooltip do not move immediately.
  72099. var delay = tooltipModel.get('showDelay');
  72100. cb = bind(cb, this);
  72101. clearTimeout(this._showTimout);
  72102. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  72103. };
  72104. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  72105. var ecModel = this._ecModel;
  72106. var globalTooltipModel = this._tooltipModel;
  72107. var point = [e.offsetX, e.offsetY];
  72108. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  72109. var renderMode = this._renderMode;
  72110. var cbParamsList = [];
  72111. var articleMarkup = createTooltipMarkup('section', {
  72112. blocks: [],
  72113. noHeader: true
  72114. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  72115. var markupTextArrLegacy = [];
  72116. var markupStyleCreator = new TooltipMarkupStyleCreator();
  72117. each(dataByCoordSys, function (itemCoordSys) {
  72118. each(itemCoordSys.dataByAxis, function (axisItem) {
  72119. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  72120. var axisValue = axisItem.value;
  72121. if (!axisModel || axisValue == null) {
  72122. return;
  72123. }
  72124. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  72125. var axisSectionMarkup = createTooltipMarkup('section', {
  72126. header: axisValueLabel,
  72127. noHeader: !trim(axisValueLabel),
  72128. sortBlocks: true,
  72129. blocks: []
  72130. });
  72131. articleMarkup.blocks.push(axisSectionMarkup);
  72132. each(axisItem.seriesDataIndices, function (idxItem) {
  72133. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  72134. var dataIndex = idxItem.dataIndexInside;
  72135. var cbParams = series.getDataParams(dataIndex); // Can't find data.
  72136. if (cbParams.dataIndex < 0) {
  72137. return;
  72138. }
  72139. cbParams.axisDim = axisItem.axisDim;
  72140. cbParams.axisIndex = axisItem.axisIndex;
  72141. cbParams.axisType = axisItem.axisType;
  72142. cbParams.axisId = axisItem.axisId;
  72143. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  72144. value: axisValue
  72145. });
  72146. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  72147. // text in `formatter` callback and use those markers style.
  72148. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  72149. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  72150. var frag = seriesTooltipResult.frag;
  72151. if (frag) {
  72152. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  72153. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  72154. valueFormatter: valueFormatter
  72155. }, frag) : frag);
  72156. }
  72157. if (seriesTooltipResult.text) {
  72158. markupTextArrLegacy.push(seriesTooltipResult.text);
  72159. }
  72160. cbParamsList.push(cbParams);
  72161. });
  72162. });
  72163. }); // In most cases, the second axis is displays upper on the first one.
  72164. // So we reverse it to look better.
  72165. articleMarkup.blocks.reverse();
  72166. markupTextArrLegacy.reverse();
  72167. var positionExpr = e.position;
  72168. var orderMode = singleTooltipModel.get('order');
  72169. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  72170. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  72171. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  72172. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  72173. this._showOrMove(singleTooltipModel, function () {
  72174. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  72175. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  72176. } else {
  72177. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  72178. }
  72179. }); // Do not trigger events here, because this branch only be entered
  72180. // from dispatchAction.
  72181. };
  72182. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  72183. var ecModel = this._ecModel;
  72184. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  72185. // Used when mouseover on a element like markPoint or edge
  72186. // In which case, the data is not main data in series.
  72187. var seriesIndex = ecData.seriesIndex;
  72188. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  72189. var dataModel = ecData.dataModel || seriesModel;
  72190. var dataIndex = ecData.dataIndex;
  72191. var dataType = ecData.dataType;
  72192. var data = dataModel.getData(dataType);
  72193. var renderMode = this._renderMode;
  72194. var positionDefault = e.positionDefault;
  72195. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  72196. position: positionDefault
  72197. } : null);
  72198. var tooltipTrigger = tooltipModel.get('trigger');
  72199. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  72200. return;
  72201. }
  72202. var params = dataModel.getDataParams(dataIndex, dataType);
  72203. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  72204. // text in `formatter` callback and use those markers style.
  72205. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  72206. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  72207. var orderMode = tooltipModel.get('order');
  72208. var valueFormatter = tooltipModel.get('valueFormatter');
  72209. var frag = seriesTooltipResult.frag;
  72210. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  72211. valueFormatter: valueFormatter
  72212. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  72213. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  72214. this._showOrMove(tooltipModel, function () {
  72215. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  72216. }); // FIXME
  72217. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  72218. dispatchAction({
  72219. type: 'showTip',
  72220. dataIndexInside: dataIndex,
  72221. dataIndex: data.getRawIndex(dataIndex),
  72222. seriesIndex: seriesIndex,
  72223. from: this.uid
  72224. });
  72225. };
  72226. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  72227. var ecData = getECData(el);
  72228. var tooltipConfig = ecData.tooltipConfig;
  72229. var tooltipOpt = tooltipConfig.option || {};
  72230. if (isString(tooltipOpt)) {
  72231. var content = tooltipOpt;
  72232. tooltipOpt = {
  72233. content: content,
  72234. // Fixed formatter
  72235. formatter: content
  72236. };
  72237. }
  72238. var tooltipModelCascade = [tooltipOpt];
  72239. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  72240. if (cmpt) {
  72241. tooltipModelCascade.push(cmpt);
  72242. } // In most cases, component tooltip formatter has different params with series tooltip formatter,
  72243. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  72244. // by convention, we do not use it as the default formatter for component.
  72245. tooltipModelCascade.push({
  72246. formatter: tooltipOpt.content
  72247. });
  72248. var positionDefault = e.positionDefault;
  72249. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  72250. position: positionDefault
  72251. } : null);
  72252. var defaultHtml = subTooltipModel.get('content');
  72253. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  72254. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  72255. // only works on coordinate system. In fact, we have not found case
  72256. // that requires setting `trigger` nothing on component yet.
  72257. this._showOrMove(subTooltipModel, function () {
  72258. // Use formatterParams from element defined in component
  72259. // Avoid users modify it.
  72260. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  72261. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  72262. }); // If not dispatch showTip, tip may be hide triggered by axis.
  72263. dispatchAction({
  72264. type: 'showTip',
  72265. from: this.uid
  72266. });
  72267. };
  72268. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  72269. // Instead of top level tooltip.
  72270. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  72271. // Reset ticket
  72272. this._ticket = '';
  72273. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  72274. return;
  72275. }
  72276. var tooltipContent = this._tooltipContent;
  72277. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  72278. var formatter = tooltipModel.get('formatter');
  72279. positionExpr = positionExpr || tooltipModel.get('position');
  72280. var html = defaultHtml;
  72281. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  72282. var nearPointColor = nearPoint.color;
  72283. if (formatter) {
  72284. if (isString(formatter)) {
  72285. var useUTC = tooltipModel.ecModel.get('useUTC');
  72286. var params0 = isArray(params) ? params[0] : params;
  72287. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  72288. html = formatter;
  72289. if (isTimeAxis) {
  72290. html = format(params0.axisValue, html, useUTC);
  72291. }
  72292. html = formatTpl(html, params, true);
  72293. } else if (isFunction(formatter)) {
  72294. var callback = bind(function (cbTicket, html) {
  72295. if (cbTicket === this._ticket) {
  72296. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  72297. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  72298. }
  72299. }, this);
  72300. this._ticket = asyncTicket;
  72301. html = formatter(params, asyncTicket, callback);
  72302. } else {
  72303. html = formatter;
  72304. }
  72305. }
  72306. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  72307. tooltipContent.show(tooltipModel, nearPointColor);
  72308. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  72309. };
  72310. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  72311. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  72312. return {
  72313. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  72314. };
  72315. }
  72316. if (!isArray(tooltipDataParams)) {
  72317. return {
  72318. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  72319. };
  72320. }
  72321. };
  72322. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  72323. y, // Mouse y
  72324. content, params, el) {
  72325. var viewWidth = this._api.getWidth();
  72326. var viewHeight = this._api.getHeight();
  72327. positionExpr = positionExpr || tooltipModel.get('position');
  72328. var contentSize = content.getSize();
  72329. var align = tooltipModel.get('align');
  72330. var vAlign = tooltipModel.get('verticalAlign');
  72331. var rect = el && el.getBoundingRect().clone();
  72332. el && rect.applyTransform(el.transform);
  72333. if (isFunction(positionExpr)) {
  72334. // Callback of position can be an array or a string specify the position
  72335. positionExpr = positionExpr([x, y], params, content.el, rect, {
  72336. viewSize: [viewWidth, viewHeight],
  72337. contentSize: contentSize.slice()
  72338. });
  72339. }
  72340. if (isArray(positionExpr)) {
  72341. x = parsePercent$1(positionExpr[0], viewWidth);
  72342. y = parsePercent$1(positionExpr[1], viewHeight);
  72343. } else if (isObject(positionExpr)) {
  72344. var boxLayoutPosition = positionExpr;
  72345. boxLayoutPosition.width = contentSize[0];
  72346. boxLayoutPosition.height = contentSize[1];
  72347. var layoutRect = getLayoutRect(boxLayoutPosition, {
  72348. width: viewWidth,
  72349. height: viewHeight
  72350. });
  72351. x = layoutRect.x;
  72352. y = layoutRect.y;
  72353. align = null; // When positionExpr is left/top/right/bottom,
  72354. // align and verticalAlign will not work.
  72355. vAlign = null;
  72356. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  72357. else if (isString(positionExpr) && el) {
  72358. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  72359. x = pos[0];
  72360. y = pos[1];
  72361. } else {
  72362. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  72363. x = pos[0];
  72364. y = pos[1];
  72365. }
  72366. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  72367. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  72368. if (shouldTooltipConfine(tooltipModel)) {
  72369. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  72370. x = pos[0];
  72371. y = pos[1];
  72372. }
  72373. content.moveTo(x, y);
  72374. }; // FIXME
  72375. // Should we remove this but leave this to user?
  72376. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  72377. var lastCoordSys = this._lastDataByCoordSys;
  72378. var lastCbParamsList = this._cbParamsList;
  72379. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  72380. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  72381. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  72382. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  72383. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  72384. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  72385. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  72386. var thisItem = thisDataByAxis[indexAxis] || {};
  72387. var lastIndices = lastItem.seriesDataIndices || [];
  72388. var newIndices = thisItem.seriesDataIndices || [];
  72389. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  72390. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  72391. var newIdxItem = newIndices[j];
  72392. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  72393. }); // check is cbParams data value changed
  72394. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  72395. var seriesIdx = idxItem.seriesIndex;
  72396. var cbParams = cbParamsList[seriesIdx];
  72397. var lastCbParams = lastCbParamsList[seriesIdx];
  72398. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  72399. contentNotChanged = false;
  72400. }
  72401. });
  72402. });
  72403. });
  72404. this._lastDataByCoordSys = dataByCoordSys;
  72405. this._cbParamsList = cbParamsList;
  72406. return !!contentNotChanged;
  72407. };
  72408. TooltipView.prototype._hide = function (dispatchAction) {
  72409. // Do not directly hideLater here, because this behavior may be prevented
  72410. // in dispatchAction when showTip is dispatched.
  72411. // FIXME
  72412. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  72413. this._lastDataByCoordSys = null;
  72414. dispatchAction({
  72415. type: 'hideTip',
  72416. from: this.uid
  72417. });
  72418. };
  72419. TooltipView.prototype.dispose = function (ecModel, api) {
  72420. if (env.node || !api.getDom()) {
  72421. return;
  72422. }
  72423. clear(this, '_updatePosition');
  72424. this._tooltipContent.dispose();
  72425. unregister('itemTooltip', api);
  72426. };
  72427. TooltipView.type = 'tooltip';
  72428. return TooltipView;
  72429. }(ComponentView);
  72430. /**
  72431. * From top to bottom. (the last one should be globalTooltipModel);
  72432. */
  72433. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  72434. // Last is always tooltip model.
  72435. var ecModel = globalTooltipModel.ecModel;
  72436. var resultModel;
  72437. if (defaultTooltipOption) {
  72438. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  72439. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  72440. } else {
  72441. resultModel = globalTooltipModel;
  72442. }
  72443. for (var i = modelCascade.length - 1; i >= 0; i--) {
  72444. var tooltipOpt = modelCascade[i];
  72445. if (tooltipOpt) {
  72446. if (tooltipOpt instanceof Model) {
  72447. tooltipOpt = tooltipOpt.get('tooltip', true);
  72448. } // In each data item tooltip can be simply write:
  72449. // {
  72450. // value: 10,
  72451. // tooltip: 'Something you need to know'
  72452. // }
  72453. if (isString(tooltipOpt)) {
  72454. tooltipOpt = {
  72455. formatter: tooltipOpt
  72456. };
  72457. }
  72458. if (tooltipOpt) {
  72459. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  72460. }
  72461. }
  72462. }
  72463. return resultModel;
  72464. }
  72465. function makeDispatchAction$1(payload, api) {
  72466. return payload.dispatchAction || bind(api.dispatchAction, api);
  72467. }
  72468. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  72469. var size = content.getSize();
  72470. var width = size[0];
  72471. var height = size[1];
  72472. if (gapH != null) {
  72473. // Add extra 2 pixels for this case:
  72474. // At present the "values" in default tooltip are using CSS `float: right`.
  72475. // When the right edge of the tooltip box is on the right side of the
  72476. // viewport, the `float` layout might push the "values" to the second line.
  72477. if (x + width + gapH + 2 > viewWidth) {
  72478. x -= width + gapH;
  72479. } else {
  72480. x += gapH;
  72481. }
  72482. }
  72483. if (gapV != null) {
  72484. if (y + height + gapV > viewHeight) {
  72485. y -= height + gapV;
  72486. } else {
  72487. y += gapV;
  72488. }
  72489. }
  72490. return [x, y];
  72491. }
  72492. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  72493. var size = content.getSize();
  72494. var width = size[0];
  72495. var height = size[1];
  72496. x = Math.min(x + width, viewWidth) - width;
  72497. y = Math.min(y + height, viewHeight) - height;
  72498. x = Math.max(x, 0);
  72499. y = Math.max(y, 0);
  72500. return [x, y];
  72501. }
  72502. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  72503. var domWidth = contentSize[0];
  72504. var domHeight = contentSize[1];
  72505. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  72506. var x = 0;
  72507. var y = 0;
  72508. var rectWidth = rect.width;
  72509. var rectHeight = rect.height;
  72510. switch (position) {
  72511. case 'inside':
  72512. x = rect.x + rectWidth / 2 - domWidth / 2;
  72513. y = rect.y + rectHeight / 2 - domHeight / 2;
  72514. break;
  72515. case 'top':
  72516. x = rect.x + rectWidth / 2 - domWidth / 2;
  72517. y = rect.y - domHeight - offset;
  72518. break;
  72519. case 'bottom':
  72520. x = rect.x + rectWidth / 2 - domWidth / 2;
  72521. y = rect.y + rectHeight + offset;
  72522. break;
  72523. case 'left':
  72524. x = rect.x - domWidth - offset;
  72525. y = rect.y + rectHeight / 2 - domHeight / 2;
  72526. break;
  72527. case 'right':
  72528. x = rect.x + rectWidth + offset;
  72529. y = rect.y + rectHeight / 2 - domHeight / 2;
  72530. }
  72531. return [x, y];
  72532. }
  72533. function isCenterAlign(align) {
  72534. return align === 'center' || align === 'middle';
  72535. }
  72536. /**
  72537. * Find target component by payload like:
  72538. * ```js
  72539. * { legendId: 'some_id', name: 'xxx' }
  72540. * { toolboxIndex: 1, name: 'xxx' }
  72541. * { geoName: 'some_name', name: 'xxx' }
  72542. * ```
  72543. * PENDING: at present only
  72544. *
  72545. * If not found, return null/undefined.
  72546. */
  72547. function findComponentReference(payload, ecModel, api) {
  72548. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  72549. var componentMainType = queryOptionMap.keys()[0];
  72550. if (!componentMainType || componentMainType === 'series') {
  72551. return;
  72552. }
  72553. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  72554. useDefault: false,
  72555. enableAll: false,
  72556. enableNone: false
  72557. });
  72558. var model = queryResult.models[0];
  72559. if (!model) {
  72560. return;
  72561. }
  72562. var view = api.getViewOfComponentModel(model);
  72563. var el;
  72564. view.group.traverse(function (subEl) {
  72565. var tooltipConfig = getECData(subEl).tooltipConfig;
  72566. if (tooltipConfig && tooltipConfig.name === payload.name) {
  72567. el = subEl;
  72568. return true; // stop
  72569. }
  72570. });
  72571. if (el) {
  72572. return {
  72573. componentMainType: componentMainType,
  72574. componentIndex: model.componentIndex,
  72575. el: el
  72576. };
  72577. }
  72578. }
  72579. function install$A(registers) {
  72580. use(install$s);
  72581. registers.registerComponentModel(TooltipModel);
  72582. registers.registerComponentView(TooltipView);
  72583. /**
  72584. * @action
  72585. * @property {string} type
  72586. * @property {number} seriesIndex
  72587. * @property {number} dataIndex
  72588. * @property {number} [x]
  72589. * @property {number} [y]
  72590. */
  72591. registers.registerAction({
  72592. type: 'showTip',
  72593. event: 'showTip',
  72594. update: 'tooltip:manuallyShowTip'
  72595. }, noop);
  72596. registers.registerAction({
  72597. type: 'hideTip',
  72598. event: 'hideTip',
  72599. update: 'tooltip:manuallyHideTip'
  72600. }, noop);
  72601. }
  72602. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  72603. function brushPreprocessor(option, isNew) {
  72604. var brushComponents = normalizeToArray(option ? option.brush : []);
  72605. if (!brushComponents.length) {
  72606. return;
  72607. }
  72608. var brushComponentSpecifiedBtns = [];
  72609. each(brushComponents, function (brushOpt) {
  72610. var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : [];
  72611. if (tbs instanceof Array) {
  72612. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  72613. }
  72614. });
  72615. var toolbox = option && option.toolbox;
  72616. if (isArray(toolbox)) {
  72617. toolbox = toolbox[0];
  72618. }
  72619. if (!toolbox) {
  72620. toolbox = {
  72621. feature: {}
  72622. };
  72623. option.toolbox = [toolbox];
  72624. }
  72625. var toolboxFeature = toolbox.feature || (toolbox.feature = {});
  72626. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  72627. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  72628. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  72629. removeDuplicate(brushTypes);
  72630. if (isNew && !brushTypes.length) {
  72631. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  72632. }
  72633. }
  72634. function removeDuplicate(arr) {
  72635. var map = {};
  72636. each(arr, function (val) {
  72637. map[val] = 1;
  72638. });
  72639. arr.length = 0;
  72640. each(map, function (flag, val) {
  72641. arr.push(val);
  72642. });
  72643. }
  72644. var each$b = each;
  72645. function hasKeys(obj) {
  72646. if (obj) {
  72647. for (var name_1 in obj) {
  72648. if (obj.hasOwnProperty(name_1)) {
  72649. return true;
  72650. }
  72651. }
  72652. }
  72653. }
  72654. function createVisualMappings(option, stateList, supplementVisualOption) {
  72655. var visualMappings = {};
  72656. each$b(stateList, function (state) {
  72657. var mappings = visualMappings[state] = createMappings();
  72658. each$b(option[state], function (visualData, visualType) {
  72659. if (!VisualMapping.isValidType(visualType)) {
  72660. return;
  72661. }
  72662. var mappingOption = {
  72663. type: visualType,
  72664. visual: visualData
  72665. };
  72666. supplementVisualOption && supplementVisualOption(mappingOption, state);
  72667. mappings[visualType] = new VisualMapping(mappingOption); // Prepare a alpha for opacity, for some case that opacity
  72668. // is not supported, such as rendering using gradient color.
  72669. if (visualType === 'opacity') {
  72670. mappingOption = clone(mappingOption);
  72671. mappingOption.type = 'colorAlpha';
  72672. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  72673. }
  72674. });
  72675. });
  72676. return visualMappings;
  72677. function createMappings() {
  72678. var Creater = function () {}; // Make sure hidden fields will not be visited by
  72679. // object iteration (with hasOwnProperty checking).
  72680. Creater.prototype.__hidden = Creater.prototype;
  72681. var obj = new Creater();
  72682. return obj;
  72683. }
  72684. }
  72685. function replaceVisualOption(thisOption, newOption, keys) {
  72686. // Visual attributes merge is not supported, otherwise it
  72687. // brings overcomplicated merge logic. See #2853. So if
  72688. // newOption has anyone of these keys, all of these keys
  72689. // will be reset. Otherwise, all keys remain.
  72690. var has;
  72691. each(keys, function (key) {
  72692. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72693. has = true;
  72694. }
  72695. });
  72696. has && each(keys, function (key) {
  72697. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72698. thisOption[key] = clone(newOption[key]);
  72699. } else {
  72700. delete thisOption[key];
  72701. }
  72702. });
  72703. }
  72704. /**
  72705. * @param stateList
  72706. * @param visualMappings
  72707. * @param list
  72708. * @param getValueState param: valueOrIndex, return: state.
  72709. * @param scope Scope for getValueState
  72710. * @param dimension Concrete dimension, if used.
  72711. */
  72712. // ???! handle brush?
  72713. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  72714. var visualTypesMap = {};
  72715. each(stateList, function (state) {
  72716. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72717. visualTypesMap[state] = visualTypes;
  72718. });
  72719. var dataIndex;
  72720. function getVisual(key) {
  72721. return getItemVisualFromData(data, dataIndex, key);
  72722. }
  72723. function setVisual(key, value) {
  72724. setItemVisualFromData(data, dataIndex, key, value);
  72725. }
  72726. if (dimension == null) {
  72727. data.each(eachItem);
  72728. } else {
  72729. data.each([dimension], eachItem);
  72730. }
  72731. function eachItem(valueOrIndex, index) {
  72732. dataIndex = dimension == null ? valueOrIndex // First argument is index
  72733. : index;
  72734. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  72735. // @ts-ignore
  72736. if (rawDataItem && rawDataItem.visualMap === false) {
  72737. return;
  72738. }
  72739. var valueState = getValueState.call(scope, valueOrIndex);
  72740. var mappings = visualMappings[valueState];
  72741. var visualTypes = visualTypesMap[valueState];
  72742. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72743. var type = visualTypes[i];
  72744. mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual);
  72745. }
  72746. }
  72747. }
  72748. /**
  72749. * @param data
  72750. * @param stateList
  72751. * @param visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72752. * @param getValueState param: valueOrIndex, return: state.
  72753. * @param dim dimension or dimension index.
  72754. */
  72755. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  72756. var visualTypesMap = {};
  72757. each(stateList, function (state) {
  72758. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72759. visualTypesMap[state] = visualTypes;
  72760. });
  72761. return {
  72762. progress: function progress(params, data) {
  72763. var dimIndex;
  72764. if (dim != null) {
  72765. dimIndex = data.getDimensionIndex(dim);
  72766. }
  72767. function getVisual(key) {
  72768. return getItemVisualFromData(data, dataIndex, key);
  72769. }
  72770. function setVisual(key, value) {
  72771. setItemVisualFromData(data, dataIndex, key, value);
  72772. }
  72773. var dataIndex;
  72774. var store = data.getStore();
  72775. while ((dataIndex = params.next()) != null) {
  72776. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  72777. // @ts-ignore
  72778. if (rawDataItem && rawDataItem.visualMap === false) {
  72779. continue;
  72780. }
  72781. var value = dim != null ? store.get(dimIndex, dataIndex) : dataIndex;
  72782. var valueState = getValueState(value);
  72783. var mappings = visualMappings[valueState];
  72784. var visualTypes = visualTypesMap[valueState];
  72785. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72786. var type = visualTypes[i];
  72787. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  72788. }
  72789. }
  72790. }
  72791. };
  72792. }
  72793. function makeBrushCommonSelectorForSeries(area) {
  72794. var brushType = area.brushType; // Do not use function binding or curry for performance.
  72795. var selectors = {
  72796. point: function (itemLayout) {
  72797. return selector[brushType].point(itemLayout, selectors, area);
  72798. },
  72799. rect: function (itemLayout) {
  72800. return selector[brushType].rect(itemLayout, selectors, area);
  72801. }
  72802. };
  72803. return selectors;
  72804. }
  72805. var selector = {
  72806. lineX: getLineSelectors(0),
  72807. lineY: getLineSelectors(1),
  72808. rect: {
  72809. point: function (itemLayout, selectors, area) {
  72810. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  72811. },
  72812. rect: function (itemLayout, selectors, area) {
  72813. return itemLayout && area.boundingRect.intersect(itemLayout);
  72814. }
  72815. },
  72816. polygon: {
  72817. point: function (itemLayout, selectors, area) {
  72818. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$2(area.range, itemLayout[0], itemLayout[1]);
  72819. },
  72820. rect: function (itemLayout, selectors, area) {
  72821. var points = area.range;
  72822. if (!itemLayout || points.length <= 1) {
  72823. return false;
  72824. }
  72825. var x = itemLayout.x;
  72826. var y = itemLayout.y;
  72827. var width = itemLayout.width;
  72828. var height = itemLayout.height;
  72829. var p = points[0];
  72830. if (contain$2(points, x, y) || contain$2(points, x + width, y) || contain$2(points, x, y + height) || contain$2(points, x + width, y + height) || BoundingRect.create(itemLayout).contain(p[0], p[1]) || linePolygonIntersect(x, y, x + width, y, points) || linePolygonIntersect(x, y, x, y + height, points) || linePolygonIntersect(x + width, y, x + width, y + height, points) || linePolygonIntersect(x, y + height, x + width, y + height, points)) {
  72831. return true;
  72832. }
  72833. }
  72834. }
  72835. };
  72836. function getLineSelectors(xyIndex) {
  72837. var xy = ['x', 'y'];
  72838. var wh = ['width', 'height'];
  72839. return {
  72840. point: function (itemLayout, selectors, area) {
  72841. if (itemLayout) {
  72842. var range = area.range;
  72843. var p = itemLayout[xyIndex];
  72844. return inLineRange(p, range);
  72845. }
  72846. },
  72847. rect: function (itemLayout, selectors, area) {
  72848. if (itemLayout) {
  72849. var range = area.range;
  72850. var layoutRange = [itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]];
  72851. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  72852. return inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange);
  72853. }
  72854. }
  72855. };
  72856. }
  72857. function inLineRange(p, range) {
  72858. return range[0] <= p && p <= range[1];
  72859. }
  72860. var STATE_LIST = ['inBrush', 'outOfBrush'];
  72861. var DISPATCH_METHOD = '__ecBrushSelect';
  72862. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  72863. function layoutCovers(ecModel) {
  72864. ecModel.eachComponent({
  72865. mainType: 'brush'
  72866. }, function (brushModel) {
  72867. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  72868. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  72869. });
  72870. }
  72871. /**
  72872. * Register the visual encoding if this modules required.
  72873. */
  72874. function brushVisual(ecModel, api, payload) {
  72875. var brushSelected = [];
  72876. var throttleType;
  72877. var throttleDelay;
  72878. ecModel.eachComponent({
  72879. mainType: 'brush'
  72880. }, function (brushModel) {
  72881. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(payload.key === 'brush' ? payload.brushOption : {
  72882. brushType: false
  72883. });
  72884. });
  72885. layoutCovers(ecModel);
  72886. ecModel.eachComponent({
  72887. mainType: 'brush'
  72888. }, function (brushModel, brushIndex) {
  72889. var thisBrushSelected = {
  72890. brushId: brushModel.id,
  72891. brushIndex: brushIndex,
  72892. brushName: brushModel.name,
  72893. areas: clone(brushModel.areas),
  72894. selected: []
  72895. }; // Every brush component exists in event params, convenient
  72896. // for user to find by index.
  72897. brushSelected.push(thisBrushSelected);
  72898. var brushOption = brushModel.option;
  72899. var brushLink = brushOption.brushLink;
  72900. var linkedSeriesMap = [];
  72901. var selectedDataIndexForLink = [];
  72902. var rangeInfoBySeries = [];
  72903. var hasBrushExists = false;
  72904. if (!brushIndex) {
  72905. // Only the first throttle setting works.
  72906. throttleType = brushOption.throttleType;
  72907. throttleDelay = brushOption.throttleDelay;
  72908. } // Add boundingRect and selectors to range.
  72909. var areas = map(brushModel.areas, function (area) {
  72910. var builder = boundingRectBuilders[area.brushType];
  72911. var selectableArea = defaults({
  72912. boundingRect: builder ? builder(area) : void 0
  72913. }, area);
  72914. selectableArea.selectors = makeBrushCommonSelectorForSeries(selectableArea);
  72915. return selectableArea;
  72916. });
  72917. var visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function (mappingOption) {
  72918. mappingOption.mappingMethod = 'fixed';
  72919. });
  72920. isArray(brushLink) && each(brushLink, function (seriesIndex) {
  72921. linkedSeriesMap[seriesIndex] = 1;
  72922. });
  72923. function linkOthers(seriesIndex) {
  72924. return brushLink === 'all' || !!linkedSeriesMap[seriesIndex];
  72925. } // If no supported brush or no brush on the series,
  72926. // all visuals should be in original state.
  72927. function brushed(rangeInfoList) {
  72928. return !!rangeInfoList.length;
  72929. }
  72930. /**
  72931. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  72932. *
  72933. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  72934. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  72935. * └!hasBrushExist┘ └nothing.
  72936. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  72937. * └!hasBrushExist┘ └nothing.
  72938. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  72939. * !brushed┘ └nothing.
  72940. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  72941. */
  72942. // Step A
  72943. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72944. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  72945. seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex) : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  72946. });
  72947. function stepAParallel(seriesModel, seriesIndex) {
  72948. var coordSys = seriesModel.coordinateSystem;
  72949. hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed();
  72950. linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function (activeState, dataIndex) {
  72951. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  72952. });
  72953. }
  72954. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  72955. if (!seriesModel.brushSelector || brushModelNotControll(brushModel, seriesIndex)) {
  72956. return;
  72957. }
  72958. each(areas, function (area) {
  72959. if (brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)) {
  72960. rangeInfoList.push(area);
  72961. }
  72962. hasBrushExists = hasBrushExists || brushed(rangeInfoList);
  72963. });
  72964. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  72965. var data_1 = seriesModel.getData();
  72966. data_1.each(function (dataIndex) {
  72967. if (checkInRange(seriesModel, rangeInfoList, data_1, dataIndex)) {
  72968. selectedDataIndexForLink[dataIndex] = 1;
  72969. }
  72970. });
  72971. }
  72972. } // Step B
  72973. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72974. var seriesBrushSelected = {
  72975. seriesId: seriesModel.id,
  72976. seriesIndex: seriesIndex,
  72977. seriesName: seriesModel.name,
  72978. dataIndex: []
  72979. }; // Every series exists in event params, convenient
  72980. // for user to find series by seriesIndex.
  72981. thisBrushSelected.selected.push(seriesBrushSelected);
  72982. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  72983. var data = seriesModel.getData();
  72984. var getValueState = linkOthers(seriesIndex) ? function (dataIndex) {
  72985. return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  72986. } : function (dataIndex) {
  72987. return checkInRange(seriesModel, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  72988. }; // If no supported brush or no brush, all visuals are in original state.
  72989. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual(STATE_LIST, visualMappings, data, getValueState);
  72990. });
  72991. });
  72992. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  72993. }
  72994. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  72995. // This event will not be triggered when `setOpion`, otherwise dead lock may
  72996. // triggered when do `setOption` in event listener, which we do not find
  72997. // satisfactory way to solve yet. Some considered resolutions:
  72998. // (a) Diff with prevoius selected data ant only trigger event when changed.
  72999. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  73000. // also detect value changes in selected data) might bring complexity or fragility.
  73001. // (b) Use spectial param like `silent` to suppress event triggering.
  73002. // But such kind of volatile param may be weird in `setOption`.
  73003. if (!payload) {
  73004. return;
  73005. }
  73006. var zr = api.getZr();
  73007. if (zr[DISPATCH_FLAG]) {
  73008. return;
  73009. }
  73010. if (!zr[DISPATCH_METHOD]) {
  73011. zr[DISPATCH_METHOD] = doDispatch;
  73012. }
  73013. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  73014. fn(api, brushSelected);
  73015. }
  73016. function doDispatch(api, brushSelected) {
  73017. if (!api.isDisposed()) {
  73018. var zr = api.getZr();
  73019. zr[DISPATCH_FLAG] = true;
  73020. api.dispatchAction({
  73021. type: 'brushSelect',
  73022. batch: brushSelected
  73023. });
  73024. zr[DISPATCH_FLAG] = false;
  73025. }
  73026. }
  73027. function checkInRange(seriesModel, rangeInfoList, data, dataIndex) {
  73028. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  73029. var area = rangeInfoList[i];
  73030. if (seriesModel.brushSelector(dataIndex, data, area.selectors, area)) {
  73031. return true;
  73032. }
  73033. }
  73034. }
  73035. function brushModelNotControll(brushModel, seriesIndex) {
  73036. var seriesIndices = brushModel.option.seriesIndex;
  73037. return seriesIndices != null && seriesIndices !== 'all' && (isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices);
  73038. }
  73039. var boundingRectBuilders = {
  73040. rect: function (area) {
  73041. return getBoundingRectFromMinMax(area.range);
  73042. },
  73043. polygon: function (area) {
  73044. var minMax;
  73045. var range = area.range;
  73046. for (var i = 0, len = range.length; i < len; i++) {
  73047. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  73048. var rg = range[i];
  73049. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  73050. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  73051. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  73052. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  73053. }
  73054. return minMax && getBoundingRectFromMinMax(minMax);
  73055. }
  73056. };
  73057. function getBoundingRectFromMinMax(minMax) {
  73058. return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]);
  73059. }
  73060. var BrushView =
  73061. /** @class */
  73062. function (_super) {
  73063. __extends(BrushView, _super);
  73064. function BrushView() {
  73065. var _this = _super !== null && _super.apply(this, arguments) || this;
  73066. _this.type = BrushView.type;
  73067. return _this;
  73068. }
  73069. BrushView.prototype.init = function (ecModel, api) {
  73070. this.ecModel = ecModel;
  73071. this.api = api;
  73072. this.model;
  73073. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  73074. };
  73075. BrushView.prototype.render = function (brushModel, ecModel, api, payload) {
  73076. this.model = brushModel;
  73077. this._updateController(brushModel, ecModel, api, payload);
  73078. };
  73079. BrushView.prototype.updateTransform = function (brushModel, ecModel, api, payload) {
  73080. // PENDING: `updateTransform` is a little tricky, whose layout need
  73081. // to be calculate mandatorily and other stages will not be performed.
  73082. // Take care the correctness of the logic. See #11754 .
  73083. layoutCovers(ecModel);
  73084. this._updateController(brushModel, ecModel, api, payload);
  73085. };
  73086. BrushView.prototype.updateVisual = function (brushModel, ecModel, api, payload) {
  73087. this.updateTransform(brushModel, ecModel, api, payload);
  73088. };
  73089. BrushView.prototype.updateView = function (brushModel, ecModel, api, payload) {
  73090. this._updateController(brushModel, ecModel, api, payload);
  73091. };
  73092. BrushView.prototype._updateController = function (brushModel, ecModel, api, payload) {
  73093. // Do not update controller when drawing.
  73094. (!payload || payload.$from !== brushModel.id) && this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice());
  73095. }; // updateLayout: updateController,
  73096. // updateVisual: updateController,
  73097. BrushView.prototype.dispose = function () {
  73098. this._brushController.dispose();
  73099. };
  73100. BrushView.prototype._onBrush = function (eventParam) {
  73101. var modelId = this.model.id;
  73102. var areas = this.model.brushTargetManager.setOutputRanges(eventParam.areas, this.ecModel); // Action is not dispatched on drag end, because the drag end
  73103. // emits the same params with the last drag move event, and
  73104. // may have some delay when using touch pad, which makes
  73105. // animation not smooth (when using debounce).
  73106. (!eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({
  73107. type: 'brush',
  73108. brushId: modelId,
  73109. areas: clone(areas),
  73110. $from: modelId
  73111. });
  73112. eventParam.isEnd && this.api.dispatchAction({
  73113. type: 'brushEnd',
  73114. brushId: modelId,
  73115. areas: clone(areas),
  73116. $from: modelId
  73117. });
  73118. };
  73119. BrushView.type = 'brush';
  73120. return BrushView;
  73121. }(ComponentView);
  73122. var DEFAULT_OUT_OF_BRUSH_COLOR = '#ddd';
  73123. var BrushModel =
  73124. /** @class */
  73125. function (_super) {
  73126. __extends(BrushModel, _super);
  73127. function BrushModel() {
  73128. var _this = _super !== null && _super.apply(this, arguments) || this;
  73129. _this.type = BrushModel.type;
  73130. /**
  73131. * @readOnly
  73132. */
  73133. _this.areas = [];
  73134. /**
  73135. * Current brush painting area settings.
  73136. * @readOnly
  73137. */
  73138. _this.brushOption = {};
  73139. return _this;
  73140. }
  73141. BrushModel.prototype.optionUpdated = function (newOption, isInit) {
  73142. var thisOption = this.option;
  73143. !isInit && replaceVisualOption(thisOption, newOption, ['inBrush', 'outOfBrush']);
  73144. var inBrush = thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time.
  73145. thisOption.outOfBrush = thisOption.outOfBrush || {
  73146. color: DEFAULT_OUT_OF_BRUSH_COLOR
  73147. };
  73148. if (!inBrush.hasOwnProperty('liftZ')) {
  73149. // Bigger than the highlight z lift, otherwise it will
  73150. // be effected by the highlight z when brush.
  73151. inBrush.liftZ = 5;
  73152. }
  73153. };
  73154. /**
  73155. * If `areas` is null/undefined, range state remain.
  73156. */
  73157. BrushModel.prototype.setAreas = function (areas) {
  73158. if ("development" !== 'production') {
  73159. assert(isArray(areas));
  73160. each(areas, function (area) {
  73161. assert(area.brushType, 'Illegal areas');
  73162. });
  73163. } // If areas is null/undefined, range state remain.
  73164. // This helps user to dispatchAction({type: 'brush'}) with no areas
  73165. // set but just want to get the current brush select info from a `brush` event.
  73166. if (!areas) {
  73167. return;
  73168. }
  73169. this.areas = map(areas, function (area) {
  73170. return generateBrushOption(this.option, area);
  73171. }, this);
  73172. };
  73173. /**
  73174. * Set the current painting brush option.
  73175. */
  73176. BrushModel.prototype.setBrushOption = function (brushOption) {
  73177. this.brushOption = generateBrushOption(this.option, brushOption);
  73178. this.brushType = this.brushOption.brushType;
  73179. };
  73180. BrushModel.type = 'brush';
  73181. BrushModel.dependencies = ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'];
  73182. BrushModel.defaultOption = {
  73183. seriesIndex: 'all',
  73184. brushType: 'rect',
  73185. brushMode: 'single',
  73186. transformable: true,
  73187. brushStyle: {
  73188. borderWidth: 1,
  73189. color: 'rgba(210,219,238,0.3)',
  73190. borderColor: '#D2DBEE'
  73191. },
  73192. throttleType: 'fixRate',
  73193. throttleDelay: 0,
  73194. removeOnClick: true,
  73195. z: 10000
  73196. };
  73197. return BrushModel;
  73198. }(ComponentModel);
  73199. function generateBrushOption(option, brushOption) {
  73200. return merge({
  73201. brushType: option.brushType,
  73202. brushMode: option.brushMode,
  73203. transformable: option.transformable,
  73204. brushStyle: new Model(option.brushStyle).getItemStyle(),
  73205. removeOnClick: option.removeOnClick,
  73206. z: option.z
  73207. }, brushOption, true);
  73208. }
  73209. var ICON_TYPES = ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'];
  73210. var BrushFeature =
  73211. /** @class */
  73212. function (_super) {
  73213. __extends(BrushFeature, _super);
  73214. function BrushFeature() {
  73215. return _super !== null && _super.apply(this, arguments) || this;
  73216. }
  73217. BrushFeature.prototype.render = function (featureModel, ecModel, api) {
  73218. var brushType;
  73219. var brushMode;
  73220. var isBrushed;
  73221. ecModel.eachComponent({
  73222. mainType: 'brush'
  73223. }, function (brushModel) {
  73224. brushType = brushModel.brushType;
  73225. brushMode = brushModel.brushOption.brushMode || 'single';
  73226. isBrushed = isBrushed || !!brushModel.areas.length;
  73227. });
  73228. this._brushType = brushType;
  73229. this._brushMode = brushMode;
  73230. each(featureModel.get('type', true), function (type) {
  73231. featureModel.setIconStatus(type, (type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType) ? 'emphasis' : 'normal');
  73232. });
  73233. };
  73234. BrushFeature.prototype.updateView = function (featureModel, ecModel, api) {
  73235. this.render(featureModel, ecModel, api);
  73236. };
  73237. BrushFeature.prototype.getIcons = function () {
  73238. var model = this.model;
  73239. var availableIcons = model.get('icon', true);
  73240. var icons = {};
  73241. each(model.get('type', true), function (type) {
  73242. if (availableIcons[type]) {
  73243. icons[type] = availableIcons[type];
  73244. }
  73245. });
  73246. return icons;
  73247. };
  73248. BrushFeature.prototype.onclick = function (ecModel, api, type) {
  73249. var brushType = this._brushType;
  73250. var brushMode = this._brushMode;
  73251. if (type === 'clear') {
  73252. // Trigger parallel action firstly
  73253. api.dispatchAction({
  73254. type: 'axisAreaSelect',
  73255. intervals: []
  73256. });
  73257. api.dispatchAction({
  73258. type: 'brush',
  73259. command: 'clear',
  73260. // Clear all areas of all brush components.
  73261. areas: []
  73262. });
  73263. } else {
  73264. api.dispatchAction({
  73265. type: 'takeGlobalCursor',
  73266. key: 'brush',
  73267. brushOption: {
  73268. brushType: type === 'keep' ? brushType : brushType === type ? false : type,
  73269. brushMode: type === 'keep' ? brushMode === 'multiple' ? 'single' : 'multiple' : brushMode
  73270. }
  73271. });
  73272. }
  73273. };
  73274. BrushFeature.getDefaultOption = function (ecModel) {
  73275. var defaultOption = {
  73276. show: true,
  73277. type: ICON_TYPES.slice(),
  73278. icon: {
  73279. /* eslint-disable */
  73280. rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13',
  73281. polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2',
  73282. lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4',
  73283. lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4',
  73284. keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z',
  73285. clear: 'M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2' // jshint ignore:line
  73286. /* eslint-enable */
  73287. },
  73288. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  73289. title: ecModel.getLocaleModel().get(['toolbox', 'brush', 'title'])
  73290. };
  73291. return defaultOption;
  73292. };
  73293. return BrushFeature;
  73294. }(ToolboxFeature);
  73295. function install$B(registers) {
  73296. registers.registerComponentView(BrushView);
  73297. registers.registerComponentModel(BrushModel);
  73298. registers.registerPreprocessor(brushPreprocessor);
  73299. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, brushVisual);
  73300. registers.registerAction({
  73301. type: 'brush',
  73302. event: 'brush',
  73303. update: 'updateVisual'
  73304. }, function (payload, ecModel) {
  73305. ecModel.eachComponent({
  73306. mainType: 'brush',
  73307. query: payload
  73308. }, function (brushModel) {
  73309. brushModel.setAreas(payload.areas);
  73310. });
  73311. });
  73312. /**
  73313. * payload: {
  73314. * brushComponents: [
  73315. * {
  73316. * brushId,
  73317. * brushIndex,
  73318. * brushName,
  73319. * series: [
  73320. * {
  73321. * seriesId,
  73322. * seriesIndex,
  73323. * seriesName,
  73324. * rawIndices: [21, 34, ...]
  73325. * },
  73326. * ...
  73327. * ]
  73328. * },
  73329. * ...
  73330. * ]
  73331. * }
  73332. */
  73333. registers.registerAction({
  73334. type: 'brushSelect',
  73335. event: 'brushSelected',
  73336. update: 'none'
  73337. }, noop);
  73338. registers.registerAction({
  73339. type: 'brushEnd',
  73340. event: 'brushEnd',
  73341. update: 'none'
  73342. }, noop);
  73343. registerFeature('brush', BrushFeature);
  73344. }
  73345. var TitleModel =
  73346. /** @class */
  73347. function (_super) {
  73348. __extends(TitleModel, _super);
  73349. function TitleModel() {
  73350. var _this = _super !== null && _super.apply(this, arguments) || this;
  73351. _this.type = TitleModel.type;
  73352. _this.layoutMode = {
  73353. type: 'box',
  73354. ignoreSize: true
  73355. };
  73356. return _this;
  73357. }
  73358. TitleModel.type = 'title';
  73359. TitleModel.defaultOption = {
  73360. // zlevel: 0,
  73361. z: 6,
  73362. show: true,
  73363. text: '',
  73364. target: 'blank',
  73365. subtext: '',
  73366. subtarget: 'blank',
  73367. left: 0,
  73368. top: 0,
  73369. backgroundColor: 'rgba(0,0,0,0)',
  73370. borderColor: '#ccc',
  73371. borderWidth: 0,
  73372. padding: 5,
  73373. itemGap: 10,
  73374. textStyle: {
  73375. fontSize: 18,
  73376. fontWeight: 'bold',
  73377. color: '#464646'
  73378. },
  73379. subtextStyle: {
  73380. fontSize: 12,
  73381. color: '#6E7079'
  73382. }
  73383. };
  73384. return TitleModel;
  73385. }(ComponentModel); // View
  73386. var TitleView =
  73387. /** @class */
  73388. function (_super) {
  73389. __extends(TitleView, _super);
  73390. function TitleView() {
  73391. var _this = _super !== null && _super.apply(this, arguments) || this;
  73392. _this.type = TitleView.type;
  73393. return _this;
  73394. }
  73395. TitleView.prototype.render = function (titleModel, ecModel, api) {
  73396. this.group.removeAll();
  73397. if (!titleModel.get('show')) {
  73398. return;
  73399. }
  73400. var group = this.group;
  73401. var textStyleModel = titleModel.getModel('textStyle');
  73402. var subtextStyleModel = titleModel.getModel('subtextStyle');
  73403. var textAlign = titleModel.get('textAlign');
  73404. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  73405. var textEl = new ZRText({
  73406. style: createTextStyle(textStyleModel, {
  73407. text: titleModel.get('text'),
  73408. fill: textStyleModel.getTextColor()
  73409. }, {
  73410. disableBox: true
  73411. }),
  73412. z2: 10
  73413. });
  73414. var textRect = textEl.getBoundingRect();
  73415. var subText = titleModel.get('subtext');
  73416. var subTextEl = new ZRText({
  73417. style: createTextStyle(subtextStyleModel, {
  73418. text: subText,
  73419. fill: subtextStyleModel.getTextColor(),
  73420. y: textRect.height + titleModel.get('itemGap'),
  73421. verticalAlign: 'top'
  73422. }, {
  73423. disableBox: true
  73424. }),
  73425. z2: 10
  73426. });
  73427. var link = titleModel.get('link');
  73428. var sublink = titleModel.get('sublink');
  73429. var triggerEvent = titleModel.get('triggerEvent', true);
  73430. textEl.silent = !link && !triggerEvent;
  73431. subTextEl.silent = !sublink && !triggerEvent;
  73432. if (link) {
  73433. textEl.on('click', function () {
  73434. windowOpen(link, '_' + titleModel.get('target'));
  73435. });
  73436. }
  73437. if (sublink) {
  73438. subTextEl.on('click', function () {
  73439. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  73440. });
  73441. }
  73442. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  73443. componentType: 'title',
  73444. componentIndex: titleModel.componentIndex
  73445. } : null;
  73446. group.add(textEl);
  73447. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  73448. var groupRect = group.getBoundingRect();
  73449. var layoutOption = titleModel.getBoxLayoutParams();
  73450. layoutOption.width = groupRect.width;
  73451. layoutOption.height = groupRect.height;
  73452. var layoutRect = getLayoutRect(layoutOption, {
  73453. width: api.getWidth(),
  73454. height: api.getHeight()
  73455. }, titleModel.get('padding')); // Adjust text align based on position
  73456. if (!textAlign) {
  73457. // Align left if title is on the left. center and right is same
  73458. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  73459. if (textAlign === 'middle') {
  73460. textAlign = 'center';
  73461. } // Adjust layout by text align
  73462. if (textAlign === 'right') {
  73463. layoutRect.x += layoutRect.width;
  73464. } else if (textAlign === 'center') {
  73465. layoutRect.x += layoutRect.width / 2;
  73466. }
  73467. }
  73468. if (!textVerticalAlign) {
  73469. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  73470. if (textVerticalAlign === 'center') {
  73471. textVerticalAlign = 'middle';
  73472. }
  73473. if (textVerticalAlign === 'bottom') {
  73474. layoutRect.y += layoutRect.height;
  73475. } else if (textVerticalAlign === 'middle') {
  73476. layoutRect.y += layoutRect.height / 2;
  73477. }
  73478. textVerticalAlign = textVerticalAlign || 'top';
  73479. }
  73480. group.x = layoutRect.x;
  73481. group.y = layoutRect.y;
  73482. group.markRedraw();
  73483. var alignStyle = {
  73484. align: textAlign,
  73485. verticalAlign: textVerticalAlign
  73486. };
  73487. textEl.setStyle(alignStyle);
  73488. subTextEl.setStyle(alignStyle); // Render background
  73489. // Get groupRect again because textAlign has been changed
  73490. groupRect = group.getBoundingRect();
  73491. var padding = layoutRect.margin;
  73492. var style = titleModel.getItemStyle(['color', 'opacity']);
  73493. style.fill = titleModel.get('backgroundColor');
  73494. var rect = new Rect({
  73495. shape: {
  73496. x: groupRect.x - padding[3],
  73497. y: groupRect.y - padding[0],
  73498. width: groupRect.width + padding[1] + padding[3],
  73499. height: groupRect.height + padding[0] + padding[2],
  73500. r: titleModel.get('borderRadius')
  73501. },
  73502. style: style,
  73503. subPixelOptimize: true,
  73504. silent: true
  73505. });
  73506. group.add(rect);
  73507. };
  73508. TitleView.type = 'title';
  73509. return TitleView;
  73510. }(ComponentView);
  73511. function install$C(registers) {
  73512. registers.registerComponentModel(TitleModel);
  73513. registers.registerComponentView(TitleView);
  73514. }
  73515. var TimelineModel =
  73516. /** @class */
  73517. function (_super) {
  73518. __extends(TimelineModel, _super);
  73519. function TimelineModel() {
  73520. var _this = _super !== null && _super.apply(this, arguments) || this;
  73521. _this.type = TimelineModel.type;
  73522. _this.layoutMode = 'box';
  73523. return _this;
  73524. }
  73525. /**
  73526. * @override
  73527. */
  73528. TimelineModel.prototype.init = function (option, parentModel, ecModel) {
  73529. this.mergeDefaultAndTheme(option, ecModel);
  73530. this._initData();
  73531. };
  73532. /**
  73533. * @override
  73534. */
  73535. TimelineModel.prototype.mergeOption = function (option) {
  73536. _super.prototype.mergeOption.apply(this, arguments);
  73537. this._initData();
  73538. };
  73539. TimelineModel.prototype.setCurrentIndex = function (currentIndex) {
  73540. if (currentIndex == null) {
  73541. currentIndex = this.option.currentIndex;
  73542. }
  73543. var count = this._data.count();
  73544. if (this.option.loop) {
  73545. currentIndex = (currentIndex % count + count) % count;
  73546. } else {
  73547. currentIndex >= count && (currentIndex = count - 1);
  73548. currentIndex < 0 && (currentIndex = 0);
  73549. }
  73550. this.option.currentIndex = currentIndex;
  73551. };
  73552. /**
  73553. * @return {number} currentIndex
  73554. */
  73555. TimelineModel.prototype.getCurrentIndex = function () {
  73556. return this.option.currentIndex;
  73557. };
  73558. /**
  73559. * @return {boolean}
  73560. */
  73561. TimelineModel.prototype.isIndexMax = function () {
  73562. return this.getCurrentIndex() >= this._data.count() - 1;
  73563. };
  73564. /**
  73565. * @param {boolean} state true: play, false: stop
  73566. */
  73567. TimelineModel.prototype.setPlayState = function (state) {
  73568. this.option.autoPlay = !!state;
  73569. };
  73570. /**
  73571. * @return {boolean} true: play, false: stop
  73572. */
  73573. TimelineModel.prototype.getPlayState = function () {
  73574. return !!this.option.autoPlay;
  73575. };
  73576. /**
  73577. * @private
  73578. */
  73579. TimelineModel.prototype._initData = function () {
  73580. var thisOption = this.option;
  73581. var dataArr = thisOption.data || [];
  73582. var axisType = thisOption.axisType;
  73583. var names = this._names = [];
  73584. var processedDataArr;
  73585. if (axisType === 'category') {
  73586. processedDataArr = [];
  73587. each(dataArr, function (item, index) {
  73588. var value = convertOptionIdName(getDataItemValue(item), '');
  73589. var newItem;
  73590. if (isObject(item)) {
  73591. newItem = clone(item);
  73592. newItem.value = index;
  73593. } else {
  73594. newItem = index;
  73595. }
  73596. processedDataArr.push(newItem);
  73597. names.push(value);
  73598. });
  73599. } else {
  73600. processedDataArr = dataArr;
  73601. }
  73602. var dimType = {
  73603. category: 'ordinal',
  73604. time: 'time',
  73605. value: 'number'
  73606. }[axisType] || 'number';
  73607. var data = this._data = new SeriesData([{
  73608. name: 'value',
  73609. type: dimType
  73610. }], this);
  73611. data.initData(processedDataArr, names);
  73612. };
  73613. TimelineModel.prototype.getData = function () {
  73614. return this._data;
  73615. };
  73616. /**
  73617. * @public
  73618. * @return {Array.<string>} categoreis
  73619. */
  73620. TimelineModel.prototype.getCategories = function () {
  73621. if (this.get('axisType') === 'category') {
  73622. return this._names.slice();
  73623. }
  73624. };
  73625. TimelineModel.type = 'timeline';
  73626. /**
  73627. * @protected
  73628. */
  73629. TimelineModel.defaultOption = {
  73630. // zlevel: 0, // 一级层叠
  73631. z: 4,
  73632. show: true,
  73633. axisType: 'time',
  73634. realtime: true,
  73635. left: '20%',
  73636. top: null,
  73637. right: '20%',
  73638. bottom: 0,
  73639. width: null,
  73640. height: 40,
  73641. padding: 5,
  73642. controlPosition: 'left',
  73643. autoPlay: false,
  73644. rewind: false,
  73645. loop: true,
  73646. playInterval: 2000,
  73647. currentIndex: 0,
  73648. itemStyle: {},
  73649. label: {
  73650. color: '#000'
  73651. },
  73652. data: []
  73653. };
  73654. return TimelineModel;
  73655. }(ComponentModel);
  73656. var SliderTimelineModel =
  73657. /** @class */
  73658. function (_super) {
  73659. __extends(SliderTimelineModel, _super);
  73660. function SliderTimelineModel() {
  73661. var _this = _super !== null && _super.apply(this, arguments) || this;
  73662. _this.type = SliderTimelineModel.type;
  73663. return _this;
  73664. }
  73665. SliderTimelineModel.type = 'timeline.slider';
  73666. /**
  73667. * @protected
  73668. */
  73669. SliderTimelineModel.defaultOption = inheritDefaultOption(TimelineModel.defaultOption, {
  73670. backgroundColor: 'rgba(0,0,0,0)',
  73671. borderColor: '#ccc',
  73672. borderWidth: 0,
  73673. orient: 'horizontal',
  73674. inverse: false,
  73675. tooltip: {
  73676. trigger: 'item' // data item may also have tootip attr.
  73677. },
  73678. symbol: 'circle',
  73679. symbolSize: 12,
  73680. lineStyle: {
  73681. show: true,
  73682. width: 2,
  73683. color: '#DAE1F5'
  73684. },
  73685. label: {
  73686. position: 'auto',
  73687. // When using number, label position is not
  73688. // restricted by viewRect.
  73689. // positive: right/bottom, negative: left/top
  73690. show: true,
  73691. interval: 'auto',
  73692. rotate: 0,
  73693. // formatter: null,
  73694. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73695. color: '#A4B1D7'
  73696. },
  73697. itemStyle: {
  73698. color: '#A4B1D7',
  73699. borderWidth: 1
  73700. },
  73701. checkpointStyle: {
  73702. symbol: 'circle',
  73703. symbolSize: 15,
  73704. color: '#316bf3',
  73705. borderColor: '#fff',
  73706. borderWidth: 2,
  73707. shadowBlur: 2,
  73708. shadowOffsetX: 1,
  73709. shadowOffsetY: 1,
  73710. shadowColor: 'rgba(0, 0, 0, 0.3)',
  73711. // borderColor: 'rgba(194,53,49, 0.5)',
  73712. animation: true,
  73713. animationDuration: 300,
  73714. animationEasing: 'quinticInOut'
  73715. },
  73716. controlStyle: {
  73717. show: true,
  73718. showPlayBtn: true,
  73719. showPrevBtn: true,
  73720. showNextBtn: true,
  73721. itemSize: 24,
  73722. itemGap: 12,
  73723. position: 'left',
  73724. playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z',
  73725. stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z',
  73726. // eslint-disable-next-line max-len
  73727. nextIcon: 'M2,18.5A1.52,1.52,0,0,1,.92,18a1.49,1.49,0,0,1,0-2.12L7.81,9.36,1,3.11A1.5,1.5,0,1,1,3,.89l8,7.34a1.48,1.48,0,0,1,.49,1.09,1.51,1.51,0,0,1-.46,1.1L3,18.08A1.5,1.5,0,0,1,2,18.5Z',
  73728. // eslint-disable-next-line max-len
  73729. prevIcon: 'M10,.5A1.52,1.52,0,0,1,11.08,1a1.49,1.49,0,0,1,0,2.12L4.19,9.64,11,15.89a1.5,1.5,0,1,1-2,2.22L1,10.77A1.48,1.48,0,0,1,.5,9.68,1.51,1.51,0,0,1,1,8.58L9,.92A1.5,1.5,0,0,1,10,.5Z',
  73730. prevBtnSize: 18,
  73731. nextBtnSize: 18,
  73732. color: '#A4B1D7',
  73733. borderColor: '#A4B1D7',
  73734. borderWidth: 1
  73735. },
  73736. emphasis: {
  73737. label: {
  73738. show: true,
  73739. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73740. color: '#6f778d'
  73741. },
  73742. itemStyle: {
  73743. color: '#316BF3'
  73744. },
  73745. controlStyle: {
  73746. color: '#316BF3',
  73747. borderColor: '#316BF3',
  73748. borderWidth: 2
  73749. }
  73750. },
  73751. progress: {
  73752. lineStyle: {
  73753. color: '#316BF3'
  73754. },
  73755. itemStyle: {
  73756. color: '#316BF3'
  73757. },
  73758. label: {
  73759. color: '#6f778d'
  73760. }
  73761. },
  73762. data: []
  73763. });
  73764. return SliderTimelineModel;
  73765. }(TimelineModel);
  73766. mixin(SliderTimelineModel, DataFormatMixin.prototype);
  73767. var TimelineView =
  73768. /** @class */
  73769. function (_super) {
  73770. __extends(TimelineView, _super);
  73771. function TimelineView() {
  73772. var _this = _super !== null && _super.apply(this, arguments) || this;
  73773. _this.type = TimelineView.type;
  73774. return _this;
  73775. }
  73776. TimelineView.type = 'timeline';
  73777. return TimelineView;
  73778. }(ComponentView);
  73779. /**
  73780. * Extend axis 2d
  73781. */
  73782. var TimelineAxis =
  73783. /** @class */
  73784. function (_super) {
  73785. __extends(TimelineAxis, _super);
  73786. function TimelineAxis(dim, scale, coordExtent, axisType) {
  73787. var _this = _super.call(this, dim, scale, coordExtent) || this;
  73788. _this.type = axisType || 'value';
  73789. return _this;
  73790. }
  73791. /**
  73792. * @override
  73793. */
  73794. TimelineAxis.prototype.getLabelModel = function () {
  73795. // Force override
  73796. return this.model.getModel('label');
  73797. };
  73798. /**
  73799. * @override
  73800. */
  73801. TimelineAxis.prototype.isHorizontal = function () {
  73802. return this.model.get('orient') === 'horizontal';
  73803. };
  73804. return TimelineAxis;
  73805. }(Axis);
  73806. var PI$8 = Math.PI;
  73807. var labelDataIndexStore = makeInner();
  73808. var SliderTimelineView =
  73809. /** @class */
  73810. function (_super) {
  73811. __extends(SliderTimelineView, _super);
  73812. function SliderTimelineView() {
  73813. var _this = _super !== null && _super.apply(this, arguments) || this;
  73814. _this.type = SliderTimelineView.type;
  73815. return _this;
  73816. }
  73817. SliderTimelineView.prototype.init = function (ecModel, api) {
  73818. this.api = api;
  73819. };
  73820. /**
  73821. * @override
  73822. */
  73823. SliderTimelineView.prototype.render = function (timelineModel, ecModel, api) {
  73824. this.model = timelineModel;
  73825. this.api = api;
  73826. this.ecModel = ecModel;
  73827. this.group.removeAll();
  73828. if (timelineModel.get('show', true)) {
  73829. var layoutInfo_1 = this._layout(timelineModel, api);
  73830. var mainGroup_1 = this._createGroup('_mainGroup');
  73831. var labelGroup = this._createGroup('_labelGroup');
  73832. var axis_1 = this._axis = this._createAxis(layoutInfo_1, timelineModel);
  73833. timelineModel.formatTooltip = function (dataIndex) {
  73834. var name = axis_1.scale.getLabel({
  73835. value: dataIndex
  73836. });
  73837. return createTooltipMarkup('nameValue', {
  73838. noName: true,
  73839. value: name
  73840. });
  73841. };
  73842. each(['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) {
  73843. this['_render' + name](layoutInfo_1, mainGroup_1, axis_1, timelineModel);
  73844. }, this);
  73845. this._renderAxisLabel(layoutInfo_1, labelGroup, axis_1, timelineModel);
  73846. this._position(layoutInfo_1, timelineModel);
  73847. }
  73848. this._doPlayStop();
  73849. this._updateTicksStatus();
  73850. };
  73851. /**
  73852. * @override
  73853. */
  73854. SliderTimelineView.prototype.remove = function () {
  73855. this._clearTimer();
  73856. this.group.removeAll();
  73857. };
  73858. /**
  73859. * @override
  73860. */
  73861. SliderTimelineView.prototype.dispose = function () {
  73862. this._clearTimer();
  73863. };
  73864. SliderTimelineView.prototype._layout = function (timelineModel, api) {
  73865. var labelPosOpt = timelineModel.get(['label', 'position']);
  73866. var orient = timelineModel.get('orient');
  73867. var viewRect = getViewRect$5(timelineModel, api);
  73868. var parsedLabelPos; // Auto label offset.
  73869. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73870. parsedLabelPos = orient === 'horizontal' ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-';
  73871. } else if (isString(labelPosOpt)) {
  73872. parsedLabelPos = {
  73873. horizontal: {
  73874. top: '-',
  73875. bottom: '+'
  73876. },
  73877. vertical: {
  73878. left: '-',
  73879. right: '+'
  73880. }
  73881. }[orient][labelPosOpt];
  73882. } else {
  73883. // is number
  73884. parsedLabelPos = labelPosOpt;
  73885. }
  73886. var labelAlignMap = {
  73887. horizontal: 'center',
  73888. vertical: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'left' : 'right'
  73889. };
  73890. var labelBaselineMap = {
  73891. horizontal: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'top' : 'bottom',
  73892. vertical: 'middle'
  73893. };
  73894. var rotationMap = {
  73895. horizontal: 0,
  73896. vertical: PI$8 / 2
  73897. }; // Position
  73898. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  73899. var controlModel = timelineModel.getModel('controlStyle');
  73900. var showControl = controlModel.get('show', true);
  73901. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  73902. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  73903. var sizePlusGap = controlSize + controlGap; // Special label rotate.
  73904. var labelRotation = timelineModel.get(['label', 'rotate']) || 0;
  73905. labelRotation = labelRotation * PI$8 / 180; // To radian.
  73906. var playPosition;
  73907. var prevBtnPosition;
  73908. var nextBtnPosition;
  73909. var controlPosition = controlModel.get('position', true);
  73910. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  73911. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  73912. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  73913. var xLeft = 0;
  73914. var xRight = mainLength; // position[0] means left, position[1] means middle.
  73915. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73916. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73917. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73918. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73919. } else {
  73920. // 'top' 'right'
  73921. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73922. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73923. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73924. }
  73925. var axisExtent = [xLeft, xRight];
  73926. if (timelineModel.get('inverse')) {
  73927. axisExtent.reverse();
  73928. }
  73929. return {
  73930. viewRect: viewRect,
  73931. mainLength: mainLength,
  73932. orient: orient,
  73933. rotation: rotationMap[orient],
  73934. labelRotation: labelRotation,
  73935. labelPosOpt: parsedLabelPos,
  73936. labelAlign: timelineModel.get(['label', 'align']) || labelAlignMap[orient],
  73937. labelBaseline: timelineModel.get(['label', 'verticalAlign']) || timelineModel.get(['label', 'baseline']) || labelBaselineMap[orient],
  73938. // Based on mainGroup.
  73939. playPosition: playPosition,
  73940. prevBtnPosition: prevBtnPosition,
  73941. nextBtnPosition: nextBtnPosition,
  73942. axisExtent: axisExtent,
  73943. controlSize: controlSize,
  73944. controlGap: controlGap
  73945. };
  73946. };
  73947. SliderTimelineView.prototype._position = function (layoutInfo, timelineModel) {
  73948. // Position is be called finally, because bounding rect is needed for
  73949. // adapt content to fill viewRect (auto adapt offset).
  73950. // Timeline may be not all in the viewRect when 'offset' is specified
  73951. // as a number, because it is more appropriate that label aligns at
  73952. // 'offset' but not the other edge defined by viewRect.
  73953. var mainGroup = this._mainGroup;
  73954. var labelGroup = this._labelGroup;
  73955. var viewRect = layoutInfo.viewRect;
  73956. if (layoutInfo.orient === 'vertical') {
  73957. // transform to horizontal, inverse rotate by left-top point.
  73958. var m = create$1();
  73959. var rotateOriginX = viewRect.x;
  73960. var rotateOriginY = viewRect.y + viewRect.height;
  73961. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73962. rotate(m, m, -PI$8 / 2);
  73963. translate(m, m, [rotateOriginX, rotateOriginY]);
  73964. viewRect = viewRect.clone();
  73965. viewRect.applyTransform(m);
  73966. }
  73967. var viewBound = getBound(viewRect);
  73968. var mainBound = getBound(mainGroup.getBoundingRect());
  73969. var labelBound = getBound(labelGroup.getBoundingRect());
  73970. var mainPosition = [mainGroup.x, mainGroup.y];
  73971. var labelsPosition = [labelGroup.x, labelGroup.y];
  73972. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73973. var labelPosOpt = layoutInfo.labelPosOpt;
  73974. if (labelPosOpt == null || isString(labelPosOpt)) {
  73975. // '+' or '-'
  73976. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73977. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73978. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73979. } else {
  73980. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73981. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73982. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73983. }
  73984. mainGroup.setPosition(mainPosition);
  73985. labelGroup.setPosition(labelsPosition);
  73986. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73987. setOrigin(mainGroup);
  73988. setOrigin(labelGroup);
  73989. function setOrigin(targetGroup) {
  73990. targetGroup.originX = viewBound[0][0] - targetGroup.x;
  73991. targetGroup.originY = viewBound[1][0] - targetGroup.y;
  73992. }
  73993. function getBound(rect) {
  73994. // [[xmin, xmax], [ymin, ymax]]
  73995. return [[rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height]];
  73996. }
  73997. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  73998. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  73999. }
  74000. };
  74001. SliderTimelineView.prototype._createAxis = function (layoutInfo, timelineModel) {
  74002. var data = timelineModel.getData();
  74003. var axisType = timelineModel.get('axisType');
  74004. var scale = createScaleByModel$1(timelineModel, axisType); // Customize scale. The `tickValue` is `dataIndex`.
  74005. scale.getTicks = function () {
  74006. return data.mapArray(['value'], function (value) {
  74007. return {
  74008. value: value
  74009. };
  74010. });
  74011. };
  74012. var dataExtent = data.getDataExtent('value');
  74013. scale.setExtent(dataExtent[0], dataExtent[1]);
  74014. scale.calcNiceTicks();
  74015. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  74016. axis.model = timelineModel;
  74017. return axis;
  74018. };
  74019. SliderTimelineView.prototype._createGroup = function (key) {
  74020. var newGroup = this[key] = new Group();
  74021. this.group.add(newGroup);
  74022. return newGroup;
  74023. };
  74024. SliderTimelineView.prototype._renderAxisLine = function (layoutInfo, group, axis, timelineModel) {
  74025. var axisExtent = axis.getExtent();
  74026. if (!timelineModel.get(['lineStyle', 'show'])) {
  74027. return;
  74028. }
  74029. var line = new Line({
  74030. shape: {
  74031. x1: axisExtent[0],
  74032. y1: 0,
  74033. x2: axisExtent[1],
  74034. y2: 0
  74035. },
  74036. style: extend({
  74037. lineCap: 'round'
  74038. }, timelineModel.getModel('lineStyle').getLineStyle()),
  74039. silent: true,
  74040. z2: 1
  74041. });
  74042. group.add(line);
  74043. var progressLine = this._progressLine = new Line({
  74044. shape: {
  74045. x1: axisExtent[0],
  74046. x2: this._currentPointer ? this._currentPointer.x : axisExtent[0],
  74047. y1: 0,
  74048. y2: 0
  74049. },
  74050. style: defaults({
  74051. lineCap: 'round',
  74052. lineWidth: line.style.lineWidth
  74053. }, timelineModel.getModel(['progress', 'lineStyle']).getLineStyle()),
  74054. silent: true,
  74055. z2: 1
  74056. });
  74057. group.add(progressLine);
  74058. };
  74059. SliderTimelineView.prototype._renderAxisTick = function (layoutInfo, group, axis, timelineModel) {
  74060. var _this = this;
  74061. var data = timelineModel.getData(); // Show all ticks, despite ignoring strategy.
  74062. var ticks = axis.scale.getTicks();
  74063. this._tickSymbols = []; // The value is dataIndex, see the customized scale.
  74064. each(ticks, function (tick) {
  74065. var tickCoord = axis.dataToCoord(tick.value);
  74066. var itemModel = data.getItemModel(tick.value);
  74067. var itemStyleModel = itemModel.getModel('itemStyle');
  74068. var hoverStyleModel = itemModel.getModel(['emphasis', 'itemStyle']);
  74069. var progressStyleModel = itemModel.getModel(['progress', 'itemStyle']);
  74070. var symbolOpt = {
  74071. x: tickCoord,
  74072. y: 0,
  74073. onclick: bind(_this._changeTimeline, _this, tick.value)
  74074. };
  74075. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  74076. el.ensureState('emphasis').style = hoverStyleModel.getItemStyle();
  74077. el.ensureState('progress').style = progressStyleModel.getItemStyle();
  74078. enableHoverEmphasis(el);
  74079. var ecData = getECData(el);
  74080. if (itemModel.get('tooltip')) {
  74081. ecData.dataIndex = tick.value;
  74082. ecData.dataModel = timelineModel;
  74083. } else {
  74084. ecData.dataIndex = ecData.dataModel = null;
  74085. }
  74086. _this._tickSymbols.push(el);
  74087. });
  74088. };
  74089. SliderTimelineView.prototype._renderAxisLabel = function (layoutInfo, group, axis, timelineModel) {
  74090. var _this = this;
  74091. var labelModel = axis.getLabelModel();
  74092. if (!labelModel.get('show')) {
  74093. return;
  74094. }
  74095. var data = timelineModel.getData();
  74096. var labels = axis.getViewLabels();
  74097. this._tickLabels = [];
  74098. each(labels, function (labelItem) {
  74099. // The tickValue is dataIndex, see the customized scale.
  74100. var dataIndex = labelItem.tickValue;
  74101. var itemModel = data.getItemModel(dataIndex);
  74102. var normalLabelModel = itemModel.getModel('label');
  74103. var hoverLabelModel = itemModel.getModel(['emphasis', 'label']);
  74104. var progressLabelModel = itemModel.getModel(['progress', 'label']);
  74105. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  74106. var textEl = new ZRText({
  74107. x: tickCoord,
  74108. y: 0,
  74109. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  74110. onclick: bind(_this._changeTimeline, _this, dataIndex),
  74111. silent: false,
  74112. style: createTextStyle(normalLabelModel, {
  74113. text: labelItem.formattedLabel,
  74114. align: layoutInfo.labelAlign,
  74115. verticalAlign: layoutInfo.labelBaseline
  74116. })
  74117. });
  74118. textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel);
  74119. textEl.ensureState('progress').style = createTextStyle(progressLabelModel);
  74120. group.add(textEl);
  74121. enableHoverEmphasis(textEl);
  74122. labelDataIndexStore(textEl).dataIndex = dataIndex;
  74123. _this._tickLabels.push(textEl);
  74124. });
  74125. };
  74126. SliderTimelineView.prototype._renderControl = function (layoutInfo, group, axis, timelineModel) {
  74127. var controlSize = layoutInfo.controlSize;
  74128. var rotation = layoutInfo.rotation;
  74129. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  74130. var hoverStyle = timelineModel.getModel(['emphasis', 'controlStyle']).getItemStyle();
  74131. var playState = timelineModel.getPlayState();
  74132. var inverse = timelineModel.get('inverse', true);
  74133. makeBtn(layoutInfo.nextBtnPosition, 'next', bind(this._changeTimeline, this, inverse ? '-' : '+'));
  74134. makeBtn(layoutInfo.prevBtnPosition, 'prev', bind(this._changeTimeline, this, inverse ? '+' : '-'));
  74135. makeBtn(layoutInfo.playPosition, playState ? 'stop' : 'play', bind(this._handlePlayClick, this, !playState), true);
  74136. function makeBtn(position, iconName, onclick, willRotate) {
  74137. if (!position) {
  74138. return;
  74139. }
  74140. var iconSize = parsePercent(retrieve2(timelineModel.get(['controlStyle', iconName + 'BtnSize']), controlSize), controlSize);
  74141. var rect = [0, -iconSize / 2, iconSize, iconSize];
  74142. var btn = makeControlIcon(timelineModel, iconName + 'Icon', rect, {
  74143. x: position[0],
  74144. y: position[1],
  74145. originX: controlSize / 2,
  74146. originY: 0,
  74147. rotation: willRotate ? -rotation : 0,
  74148. rectHover: true,
  74149. style: itemStyle,
  74150. onclick: onclick
  74151. });
  74152. btn.ensureState('emphasis').style = hoverStyle;
  74153. group.add(btn);
  74154. enableHoverEmphasis(btn);
  74155. }
  74156. };
  74157. SliderTimelineView.prototype._renderCurrentPointer = function (layoutInfo, group, axis, timelineModel) {
  74158. var data = timelineModel.getData();
  74159. var currentIndex = timelineModel.getCurrentIndex();
  74160. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  74161. var me = this;
  74162. var callback = {
  74163. onCreate: function (pointer) {
  74164. pointer.draggable = true;
  74165. pointer.drift = bind(me._handlePointerDrag, me);
  74166. pointer.ondragend = bind(me._handlePointerDragend, me);
  74167. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, true);
  74168. },
  74169. onUpdate: function (pointer) {
  74170. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel);
  74171. }
  74172. }; // Reuse when exists, for animation and drag.
  74173. this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback);
  74174. };
  74175. SliderTimelineView.prototype._handlePlayClick = function (nextState) {
  74176. this._clearTimer();
  74177. this.api.dispatchAction({
  74178. type: 'timelinePlayChange',
  74179. playState: nextState,
  74180. from: this.uid
  74181. });
  74182. };
  74183. SliderTimelineView.prototype._handlePointerDrag = function (dx, dy, e) {
  74184. this._clearTimer();
  74185. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  74186. };
  74187. SliderTimelineView.prototype._handlePointerDragend = function (e) {
  74188. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  74189. };
  74190. SliderTimelineView.prototype._pointerChangeTimeline = function (mousePos, trigger) {
  74191. var toCoord = this._toAxisCoord(mousePos)[0];
  74192. var axis = this._axis;
  74193. var axisExtent = asc(axis.getExtent().slice());
  74194. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  74195. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  74196. this._currentPointer.x = toCoord;
  74197. this._currentPointer.markRedraw();
  74198. var progressLine = this._progressLine;
  74199. if (progressLine) {
  74200. progressLine.shape.x2 = toCoord;
  74201. progressLine.dirty();
  74202. }
  74203. var targetDataIndex = this._findNearestTick(toCoord);
  74204. var timelineModel = this.model;
  74205. if (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) {
  74206. this._changeTimeline(targetDataIndex);
  74207. }
  74208. };
  74209. SliderTimelineView.prototype._doPlayStop = function () {
  74210. var _this = this;
  74211. this._clearTimer();
  74212. if (this.model.getPlayState()) {
  74213. this._timer = setTimeout(function () {
  74214. // Do not cache
  74215. var timelineModel = _this.model;
  74216. _this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1));
  74217. }, this.model.get('playInterval'));
  74218. }
  74219. };
  74220. SliderTimelineView.prototype._toAxisCoord = function (vertex) {
  74221. var trans = this._mainGroup.getLocalTransform();
  74222. return applyTransform$1(vertex, trans, true);
  74223. };
  74224. SliderTimelineView.prototype._findNearestTick = function (axisCoord) {
  74225. var data = this.model.getData();
  74226. var dist = Infinity;
  74227. var targetDataIndex;
  74228. var axis = this._axis;
  74229. data.each(['value'], function (value, dataIndex) {
  74230. var coord = axis.dataToCoord(value);
  74231. var d = Math.abs(coord - axisCoord);
  74232. if (d < dist) {
  74233. dist = d;
  74234. targetDataIndex = dataIndex;
  74235. }
  74236. });
  74237. return targetDataIndex;
  74238. };
  74239. SliderTimelineView.prototype._clearTimer = function () {
  74240. if (this._timer) {
  74241. clearTimeout(this._timer);
  74242. this._timer = null;
  74243. }
  74244. };
  74245. SliderTimelineView.prototype._changeTimeline = function (nextIndex) {
  74246. var currentIndex = this.model.getCurrentIndex();
  74247. if (nextIndex === '+') {
  74248. nextIndex = currentIndex + 1;
  74249. } else if (nextIndex === '-') {
  74250. nextIndex = currentIndex - 1;
  74251. }
  74252. this.api.dispatchAction({
  74253. type: 'timelineChange',
  74254. currentIndex: nextIndex,
  74255. from: this.uid
  74256. });
  74257. };
  74258. SliderTimelineView.prototype._updateTicksStatus = function () {
  74259. var currentIndex = this.model.getCurrentIndex();
  74260. var tickSymbols = this._tickSymbols;
  74261. var tickLabels = this._tickLabels;
  74262. if (tickSymbols) {
  74263. for (var i = 0; i < tickSymbols.length; i++) {
  74264. tickSymbols && tickSymbols[i] && tickSymbols[i].toggleState('progress', i < currentIndex);
  74265. }
  74266. }
  74267. if (tickLabels) {
  74268. for (var i = 0; i < tickLabels.length; i++) {
  74269. tickLabels && tickLabels[i] && tickLabels[i].toggleState('progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex);
  74270. }
  74271. }
  74272. };
  74273. SliderTimelineView.type = 'timeline.slider';
  74274. return SliderTimelineView;
  74275. }(TimelineView);
  74276. function createScaleByModel$1(model, axisType) {
  74277. axisType = axisType || model.get('type');
  74278. if (axisType) {
  74279. switch (axisType) {
  74280. // Buildin scale
  74281. case 'category':
  74282. return new OrdinalScale({
  74283. ordinalMeta: model.getCategories(),
  74284. extent: [Infinity, -Infinity]
  74285. });
  74286. case 'time':
  74287. return new TimeScale({
  74288. locale: model.ecModel.getLocaleModel(),
  74289. useUTC: model.ecModel.get('useUTC')
  74290. });
  74291. default:
  74292. // default to be value
  74293. return new IntervalScale();
  74294. }
  74295. }
  74296. }
  74297. function getViewRect$5(model, api) {
  74298. return getLayoutRect(model.getBoxLayoutParams(), {
  74299. width: api.getWidth(),
  74300. height: api.getHeight()
  74301. }, model.get('padding'));
  74302. }
  74303. function makeControlIcon(timelineModel, objPath, rect, opts) {
  74304. var style = opts.style;
  74305. var icon = createIcon(timelineModel.get(['controlStyle', objPath]), opts || {}, new BoundingRect(rect[0], rect[1], rect[2], rect[3])); // TODO createIcon won't use style in opt.
  74306. if (style) {
  74307. icon.setStyle(style);
  74308. }
  74309. return icon;
  74310. }
  74311. /**
  74312. * Create symbol or update symbol
  74313. * opt: basic position and event handlers
  74314. */
  74315. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  74316. var color = itemStyleModel.get('color');
  74317. if (!symbol) {
  74318. var symbolType = hostModel.get('symbol');
  74319. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  74320. symbol.setStyle('strokeNoScale', true);
  74321. group.add(symbol);
  74322. callback && callback.onCreate(symbol);
  74323. } else {
  74324. symbol.setColor(color);
  74325. group.add(symbol); // Group may be new, also need to add.
  74326. callback && callback.onUpdate(symbol);
  74327. } // Style
  74328. var itemStyle = itemStyleModel.getItemStyle(['color']);
  74329. symbol.setStyle(itemStyle); // Transform and events.
  74330. opt = merge({
  74331. rectHover: true,
  74332. z2: 100
  74333. }, opt, true);
  74334. var symbolSize = normalizeSymbolSize(hostModel.get('symbolSize'));
  74335. opt.scaleX = symbolSize[0] / 2;
  74336. opt.scaleY = symbolSize[1] / 2;
  74337. var symbolOffset = normalizeSymbolOffset(hostModel.get('symbolOffset'), symbolSize);
  74338. if (symbolOffset) {
  74339. opt.x = (opt.x || 0) + symbolOffset[0];
  74340. opt.y = (opt.y || 0) + symbolOffset[1];
  74341. }
  74342. var symbolRotate = hostModel.get('symbolRotate');
  74343. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  74344. symbol.attr(opt); // FIXME
  74345. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  74346. // getBoundingRect will return wrong result.
  74347. // (This is supposed to be resolved in zrender, but it is a little difficult to
  74348. // leverage performance and auto updateTransform)
  74349. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  74350. symbol.updateTransform();
  74351. return symbol;
  74352. }
  74353. function pointerMoveTo(pointer, progressLine, dataIndex, axis, timelineModel, noAnimation) {
  74354. if (pointer.dragging) {
  74355. return;
  74356. }
  74357. var pointerModel = timelineModel.getModel('checkpointStyle');
  74358. var toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex));
  74359. if (noAnimation || !pointerModel.get('animation', true)) {
  74360. pointer.attr({
  74361. x: toCoord,
  74362. y: 0
  74363. });
  74364. progressLine && progressLine.attr({
  74365. shape: {
  74366. x2: toCoord
  74367. }
  74368. });
  74369. } else {
  74370. var animationCfg = {
  74371. duration: pointerModel.get('animationDuration', true),
  74372. easing: pointerModel.get('animationEasing', true)
  74373. };
  74374. pointer.stopAnimation(null, true);
  74375. pointer.animateTo({
  74376. x: toCoord,
  74377. y: 0
  74378. }, animationCfg);
  74379. progressLine && progressLine.animateTo({
  74380. shape: {
  74381. x2: toCoord
  74382. }
  74383. }, animationCfg);
  74384. }
  74385. }
  74386. function installTimelineAction(registers) {
  74387. registers.registerAction({
  74388. type: 'timelineChange',
  74389. event: 'timelineChanged',
  74390. update: 'prepareAndUpdate'
  74391. }, function (payload, ecModel, api) {
  74392. var timelineModel = ecModel.getComponent('timeline');
  74393. if (timelineModel && payload.currentIndex != null) {
  74394. timelineModel.setCurrentIndex(payload.currentIndex);
  74395. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax() && timelineModel.getPlayState()) {
  74396. timelineModel.setPlayState(false); // The timeline has played to the end, trigger event
  74397. api.dispatchAction({
  74398. type: 'timelinePlayChange',
  74399. playState: false,
  74400. from: payload.from
  74401. });
  74402. }
  74403. } // Set normalized currentIndex to payload.
  74404. ecModel.resetOption('timeline', {
  74405. replaceMerge: timelineModel.get('replaceMerge', true)
  74406. });
  74407. return defaults({
  74408. currentIndex: timelineModel.option.currentIndex
  74409. }, payload);
  74410. });
  74411. registers.registerAction({
  74412. type: 'timelinePlayChange',
  74413. event: 'timelinePlayChanged',
  74414. update: 'update'
  74415. }, function (payload, ecModel) {
  74416. var timelineModel = ecModel.getComponent('timeline');
  74417. if (timelineModel && payload.playState != null) {
  74418. timelineModel.setPlayState(payload.playState);
  74419. }
  74420. });
  74421. }
  74422. function timelinePreprocessor(option) {
  74423. var timelineOpt = option && option.timeline;
  74424. if (!isArray(timelineOpt)) {
  74425. timelineOpt = timelineOpt ? [timelineOpt] : [];
  74426. }
  74427. each(timelineOpt, function (opt) {
  74428. if (!opt) {
  74429. return;
  74430. }
  74431. compatibleEC2(opt);
  74432. });
  74433. }
  74434. function compatibleEC2(opt) {
  74435. var type = opt.type;
  74436. var ec2Types = {
  74437. 'number': 'value',
  74438. 'time': 'time'
  74439. }; // Compatible with ec2
  74440. if (ec2Types[type]) {
  74441. opt.axisType = ec2Types[type];
  74442. delete opt.type;
  74443. }
  74444. transferItem(opt);
  74445. if (has(opt, 'controlPosition')) {
  74446. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  74447. if (!has(controlStyle, 'position')) {
  74448. controlStyle.position = opt.controlPosition;
  74449. }
  74450. if (controlStyle.position === 'none' && !has(controlStyle, 'show')) {
  74451. controlStyle.show = false;
  74452. delete controlStyle.position;
  74453. }
  74454. delete opt.controlPosition;
  74455. }
  74456. each(opt.data || [], function (dataItem) {
  74457. if (isObject(dataItem) && !isArray(dataItem)) {
  74458. if (!has(dataItem, 'value') && has(dataItem, 'name')) {
  74459. // In ec2, using name as value.
  74460. dataItem.value = dataItem.name;
  74461. }
  74462. transferItem(dataItem);
  74463. }
  74464. });
  74465. }
  74466. function transferItem(opt) {
  74467. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  74468. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out
  74469. var label = opt.label || opt.label || {};
  74470. var labelNormal = label.normal || (label.normal = {});
  74471. var excludeLabelAttr = {
  74472. normal: 1,
  74473. emphasis: 1
  74474. };
  74475. each(label, function (value, name) {
  74476. if (!excludeLabelAttr[name] && !has(labelNormal, name)) {
  74477. labelNormal[name] = value;
  74478. }
  74479. });
  74480. if (itemStyleEmphasis.label && !has(label, 'emphasis')) {
  74481. label.emphasis = itemStyleEmphasis.label;
  74482. delete itemStyleEmphasis.label;
  74483. }
  74484. }
  74485. function has(obj, attr) {
  74486. return obj.hasOwnProperty(attr);
  74487. }
  74488. function install$D(registers) {
  74489. registers.registerComponentModel(SliderTimelineModel);
  74490. registers.registerComponentView(SliderTimelineView);
  74491. registers.registerSubTypeDefaulter('timeline', function () {
  74492. // Only slider now.
  74493. return 'slider';
  74494. });
  74495. installTimelineAction(registers);
  74496. registers.registerPreprocessor(timelinePreprocessor);
  74497. }
  74498. function checkMarkerInSeries(seriesOpts, markerType) {
  74499. if (!seriesOpts) {
  74500. return false;
  74501. }
  74502. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  74503. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  74504. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  74505. return true;
  74506. }
  74507. }
  74508. return false;
  74509. }
  74510. function fillLabel(opt) {
  74511. defaultEmphasis(opt, 'label', ['show']);
  74512. } // { [componentType]: MarkerModel }
  74513. var inner$g = makeInner();
  74514. var MarkerModel =
  74515. /** @class */
  74516. function (_super) {
  74517. __extends(MarkerModel, _super);
  74518. function MarkerModel() {
  74519. var _this = _super !== null && _super.apply(this, arguments) || this;
  74520. _this.type = MarkerModel.type;
  74521. /**
  74522. * If marker model is created by self from series
  74523. */
  74524. _this.createdBySelf = false;
  74525. return _this;
  74526. }
  74527. /**
  74528. * @overrite
  74529. */
  74530. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  74531. if ("development" !== 'production') {
  74532. if (this.type === 'marker') {
  74533. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74534. }
  74535. }
  74536. this.mergeDefaultAndTheme(option, ecModel);
  74537. this._mergeOption(option, ecModel, false, true);
  74538. };
  74539. MarkerModel.prototype.isAnimationEnabled = function () {
  74540. if (env.node) {
  74541. return false;
  74542. }
  74543. var hostSeries = this.__hostSeries;
  74544. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74545. };
  74546. /**
  74547. * @overrite
  74548. */
  74549. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  74550. this._mergeOption(newOpt, ecModel, false, false);
  74551. };
  74552. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  74553. var componentType = this.mainType;
  74554. if (!createdBySelf) {
  74555. ecModel.eachSeries(function (seriesModel) {
  74556. // mainType can be markPoint, markLine, markArea
  74557. var markerOpt = seriesModel.get(this.mainType, true);
  74558. var markerModel = inner$g(seriesModel)[componentType];
  74559. if (!markerOpt || !markerOpt.data) {
  74560. inner$g(seriesModel)[componentType] = null;
  74561. return;
  74562. }
  74563. if (!markerModel) {
  74564. if (isInit) {
  74565. // Default label emphasis `position` and `show`
  74566. fillLabel(markerOpt);
  74567. }
  74568. each(markerOpt.data, function (item) {
  74569. // FIXME Overwrite fillLabel method ?
  74570. if (item instanceof Array) {
  74571. fillLabel(item[0]);
  74572. fillLabel(item[1]);
  74573. } else {
  74574. fillLabel(item);
  74575. }
  74576. });
  74577. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  74578. // markerOpt, this, ecModel
  74579. // );
  74580. extend(markerModel, {
  74581. mainType: this.mainType,
  74582. // Use the same series index and name
  74583. seriesIndex: seriesModel.seriesIndex,
  74584. name: seriesModel.name,
  74585. createdBySelf: true
  74586. });
  74587. markerModel.__hostSeries = seriesModel;
  74588. } else {
  74589. markerModel._mergeOption(markerOpt, ecModel, true);
  74590. }
  74591. inner$g(seriesModel)[componentType] = markerModel;
  74592. }, this);
  74593. }
  74594. };
  74595. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  74596. var data = this.getData();
  74597. var value = this.getRawValue(dataIndex);
  74598. var itemName = data.getName(dataIndex);
  74599. return createTooltipMarkup('section', {
  74600. header: this.name,
  74601. blocks: [createTooltipMarkup('nameValue', {
  74602. name: itemName,
  74603. value: value,
  74604. noName: !itemName,
  74605. noValue: value == null
  74606. })]
  74607. });
  74608. };
  74609. MarkerModel.prototype.getData = function () {
  74610. return this._data;
  74611. };
  74612. MarkerModel.prototype.setData = function (data) {
  74613. this._data = data;
  74614. };
  74615. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  74616. componentType) {
  74617. return inner$g(seriesModel)[componentType];
  74618. };
  74619. MarkerModel.type = 'marker';
  74620. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  74621. return MarkerModel;
  74622. }(ComponentModel);
  74623. mixin(MarkerModel, DataFormatMixin.prototype);
  74624. var MarkPointModel =
  74625. /** @class */
  74626. function (_super) {
  74627. __extends(MarkPointModel, _super);
  74628. function MarkPointModel() {
  74629. var _this = _super !== null && _super.apply(this, arguments) || this;
  74630. _this.type = MarkPointModel.type;
  74631. return _this;
  74632. }
  74633. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  74634. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  74635. };
  74636. MarkPointModel.type = 'markPoint';
  74637. MarkPointModel.defaultOption = {
  74638. // zlevel: 0,
  74639. z: 5,
  74640. symbol: 'pin',
  74641. symbolSize: 50,
  74642. // symbolRotate: 0,
  74643. // symbolOffset: [0, 0]
  74644. tooltip: {
  74645. trigger: 'item'
  74646. },
  74647. label: {
  74648. show: true,
  74649. position: 'inside'
  74650. },
  74651. itemStyle: {
  74652. borderWidth: 2
  74653. },
  74654. emphasis: {
  74655. label: {
  74656. show: true
  74657. }
  74658. }
  74659. };
  74660. return MarkPointModel;
  74661. }(MarkerModel);
  74662. function hasXOrY(item) {
  74663. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74664. }
  74665. function hasXAndY(item) {
  74666. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74667. }
  74668. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  74669. var coordArr = [];
  74670. var stacked = isDimensionStacked(data, targetDataDim
  74671. /* , otherDataDim */
  74672. );
  74673. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  74674. var value = numCalculate(data, calcDataDim, markerType);
  74675. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74676. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74677. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  74678. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  74679. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74680. precision = Math.min(precision, 20);
  74681. if (precision >= 0) {
  74682. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74683. }
  74684. return [coordArr, coordArrValue];
  74685. } // TODO Specified percent
  74686. var markerTypeCalculator = {
  74687. min: curry(markerTypeCalculatorWithExtent, 'min'),
  74688. max: curry(markerTypeCalculatorWithExtent, 'max'),
  74689. average: curry(markerTypeCalculatorWithExtent, 'average'),
  74690. median: curry(markerTypeCalculatorWithExtent, 'median')
  74691. };
  74692. /**
  74693. * Transform markPoint data item to format used in List by do the following
  74694. * 1. Calculate statistic like `max`, `min`, `average`
  74695. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74696. */
  74697. function dataTransform(seriesModel, item) {
  74698. if (!item) {
  74699. return;
  74700. }
  74701. var data = seriesModel.getData();
  74702. var coordSys = seriesModel.coordinateSystem;
  74703. var dims = coordSys && coordSys.dimensions; // 1. If not specify the position with pixel directly
  74704. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74705. // `yAxis` to specify the coord on each dimension
  74706. // parseFloat first because item.x and item.y can be percent string like '20%'
  74707. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  74708. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  74709. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74710. item = clone(item);
  74711. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  74712. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  74713. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  74714. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  74715. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  74716. // let item use the value without stack.
  74717. item.value = coordInfo[1];
  74718. } else {
  74719. // FIXME Only has one of xAxis and yAxis.
  74720. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  74721. }
  74722. } // x y is provided
  74723. if (item.coord == null || !isArray(dims)) {
  74724. item.coord = [];
  74725. } else {
  74726. // Each coord support max, min, average
  74727. var coord = item.coord;
  74728. for (var i = 0; i < 2; i++) {
  74729. if (markerTypeCalculator[coord[i]]) {
  74730. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74731. }
  74732. }
  74733. }
  74734. return item;
  74735. }
  74736. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74737. var ret = {};
  74738. if (item.valueIndex != null || item.valueDim != null) {
  74739. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  74740. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74741. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74742. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74743. } else {
  74744. ret.baseAxis = seriesModel.getBaseAxis();
  74745. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74746. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74747. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74748. }
  74749. return ret;
  74750. }
  74751. function dataDimToCoordDim(seriesModel, dataDim) {
  74752. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  74753. return dimItem && dimItem.coordDim;
  74754. }
  74755. /**
  74756. * Filter data which is out of coordinateSystem range
  74757. * [dataFilter description]
  74758. */
  74759. function dataFilter$1( // Currently only polar and cartesian has containData.
  74760. coordSys, item) {
  74761. // Always return true if there is no coordSys
  74762. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  74763. }
  74764. function zoneFilter( // Currently only polar and cartesian has containData.
  74765. coordSys, item1, item2) {
  74766. // Always return true if there is no coordSys
  74767. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  74768. }
  74769. function createMarkerDimValueGetter(inCoordSys, dims) {
  74770. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  74771. var rawVal = dimIndex < 2 // x, y, radius, angle
  74772. ? item.coord && item.coord[dimIndex] : item.value;
  74773. return parseDataValue(rawVal, dims[dimIndex]);
  74774. } : function (item, dimName, dataIndex, dimIndex) {
  74775. return parseDataValue(item.value, dims[dimIndex]);
  74776. };
  74777. }
  74778. function numCalculate(data, valueDataDim, type) {
  74779. if (type === 'average') {
  74780. var sum_1 = 0;
  74781. var count_1 = 0;
  74782. data.each(valueDataDim, function (val, idx) {
  74783. if (!isNaN(val)) {
  74784. sum_1 += val;
  74785. count_1++;
  74786. }
  74787. });
  74788. return sum_1 / count_1;
  74789. } else if (type === 'median') {
  74790. return data.getMedian(valueDataDim);
  74791. } else {
  74792. // max & min
  74793. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  74794. }
  74795. }
  74796. var inner$h = makeInner();
  74797. var MarkerView =
  74798. /** @class */
  74799. function (_super) {
  74800. __extends(MarkerView, _super);
  74801. function MarkerView() {
  74802. var _this = _super !== null && _super.apply(this, arguments) || this;
  74803. _this.type = MarkerView.type;
  74804. return _this;
  74805. }
  74806. MarkerView.prototype.init = function () {
  74807. this.markerGroupMap = createHashMap();
  74808. };
  74809. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  74810. var _this = this;
  74811. var markerGroupMap = this.markerGroupMap;
  74812. markerGroupMap.each(function (item) {
  74813. inner$h(item).keep = false;
  74814. });
  74815. ecModel.eachSeries(function (seriesModel) {
  74816. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  74817. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  74818. });
  74819. markerGroupMap.each(function (item) {
  74820. !inner$h(item).keep && _this.group.remove(item.group);
  74821. });
  74822. };
  74823. MarkerView.prototype.markKeep = function (drawGroup) {
  74824. inner$h(drawGroup).keep = true;
  74825. };
  74826. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  74827. var _this = this;
  74828. each(seriesModelList, function (seriesModel) {
  74829. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  74830. if (markerModel) {
  74831. var data = markerModel.getData();
  74832. data.eachItemGraphicEl(function (el) {
  74833. if (el) {
  74834. isBlur ? enterBlur(el) : leaveBlur(el);
  74835. }
  74836. });
  74837. }
  74838. });
  74839. };
  74840. MarkerView.type = 'marker';
  74841. return MarkerView;
  74842. }(ComponentView);
  74843. function updateMarkerLayout(mpData, seriesModel, api) {
  74844. var coordSys = seriesModel.coordinateSystem;
  74845. mpData.each(function (idx) {
  74846. var itemModel = mpData.getItemModel(idx);
  74847. var point;
  74848. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74849. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74850. if (!isNaN(xPx) && !isNaN(yPx)) {
  74851. point = [xPx, yPx];
  74852. } // Chart like bar may have there own marker positioning logic
  74853. else if (seriesModel.getMarkerPosition) {
  74854. // Use the getMarkerPosition
  74855. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  74856. } else if (coordSys) {
  74857. var x = mpData.get(coordSys.dimensions[0], idx);
  74858. var y = mpData.get(coordSys.dimensions[1], idx);
  74859. point = coordSys.dataToPoint([x, y]);
  74860. } // Use x, y if has any
  74861. if (!isNaN(xPx)) {
  74862. point[0] = xPx;
  74863. }
  74864. if (!isNaN(yPx)) {
  74865. point[1] = yPx;
  74866. }
  74867. mpData.setItemLayout(idx, point);
  74868. });
  74869. }
  74870. var MarkPointView =
  74871. /** @class */
  74872. function (_super) {
  74873. __extends(MarkPointView, _super);
  74874. function MarkPointView() {
  74875. var _this = _super !== null && _super.apply(this, arguments) || this;
  74876. _this.type = MarkPointView.type;
  74877. return _this;
  74878. }
  74879. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  74880. ecModel.eachSeries(function (seriesModel) {
  74881. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  74882. if (mpModel) {
  74883. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74884. this.markerGroupMap.get(seriesModel.id).updateLayout();
  74885. }
  74886. }, this);
  74887. };
  74888. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  74889. var coordSys = seriesModel.coordinateSystem;
  74890. var seriesId = seriesModel.id;
  74891. var seriesData = seriesModel.getData();
  74892. var symbolDrawMap = this.markerGroupMap;
  74893. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  74894. var mpData = createData(coordSys, seriesModel, mpModel); // FIXME
  74895. mpModel.setData(mpData);
  74896. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74897. mpData.each(function (idx) {
  74898. var itemModel = mpData.getItemModel(idx);
  74899. var symbol = itemModel.getShallow('symbol');
  74900. var symbolSize = itemModel.getShallow('symbolSize');
  74901. var symbolRotate = itemModel.getShallow('symbolRotate');
  74902. var symbolOffset = itemModel.getShallow('symbolOffset');
  74903. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect'); // TODO: refactor needed: single data item should not support callback function
  74904. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  74905. var rawIdx = mpModel.getRawValue(idx);
  74906. var dataParams = mpModel.getDataParams(idx);
  74907. if (isFunction(symbol)) {
  74908. symbol = symbol(rawIdx, dataParams);
  74909. }
  74910. if (isFunction(symbolSize)) {
  74911. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74912. symbolSize = symbolSize(rawIdx, dataParams);
  74913. }
  74914. if (isFunction(symbolRotate)) {
  74915. symbolRotate = symbolRotate(rawIdx, dataParams);
  74916. }
  74917. if (isFunction(symbolOffset)) {
  74918. symbolOffset = symbolOffset(rawIdx, dataParams);
  74919. }
  74920. }
  74921. var style = itemModel.getModel('itemStyle').getItemStyle();
  74922. var color = getVisualFromData(seriesData, 'color');
  74923. if (!style.fill) {
  74924. style.fill = color;
  74925. }
  74926. mpData.setItemVisual(idx, {
  74927. symbol: symbol,
  74928. symbolSize: symbolSize,
  74929. symbolRotate: symbolRotate,
  74930. symbolOffset: symbolOffset,
  74931. symbolKeepAspect: symbolKeepAspect,
  74932. style: style
  74933. });
  74934. }); // TODO Text are wrong
  74935. symbolDraw.updateData(mpData);
  74936. this.group.add(symbolDraw.group); // Set host model for tooltip
  74937. // FIXME
  74938. mpData.eachItemGraphicEl(function (el) {
  74939. el.traverse(function (child) {
  74940. getECData(child).dataModel = mpModel;
  74941. });
  74942. });
  74943. this.markKeep(symbolDraw);
  74944. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74945. };
  74946. MarkPointView.type = 'markPoint';
  74947. return MarkPointView;
  74948. }(MarkerView);
  74949. function createData(coordSys, seriesModel, mpModel) {
  74950. var coordDimsInfos;
  74951. if (coordSys) {
  74952. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74953. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74954. return extend(extend({}, info), {
  74955. name: coordDim,
  74956. // DON'T use ordinalMeta to parse and collect ordinal.
  74957. ordinalMeta: null
  74958. });
  74959. });
  74960. } else {
  74961. coordDimsInfos = [{
  74962. name: 'value',
  74963. type: 'float'
  74964. }];
  74965. }
  74966. var mpData = new SeriesData(coordDimsInfos, mpModel);
  74967. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  74968. if (coordSys) {
  74969. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  74970. }
  74971. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  74972. mpData.initData(dataOpt, null, dimValueGetter);
  74973. return mpData;
  74974. }
  74975. function install$E(registers) {
  74976. registers.registerComponentModel(MarkPointModel);
  74977. registers.registerComponentView(MarkPointView);
  74978. registers.registerPreprocessor(function (opt) {
  74979. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  74980. // Make sure markPoint component is enabled
  74981. opt.markPoint = opt.markPoint || {};
  74982. }
  74983. });
  74984. }
  74985. var MarkLineModel =
  74986. /** @class */
  74987. function (_super) {
  74988. __extends(MarkLineModel, _super);
  74989. function MarkLineModel() {
  74990. var _this = _super !== null && _super.apply(this, arguments) || this;
  74991. _this.type = MarkLineModel.type;
  74992. return _this;
  74993. }
  74994. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  74995. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  74996. };
  74997. MarkLineModel.type = 'markLine';
  74998. MarkLineModel.defaultOption = {
  74999. // zlevel: 0,
  75000. z: 5,
  75001. symbol: ['circle', 'arrow'],
  75002. symbolSize: [8, 16],
  75003. // symbolRotate: 0,
  75004. symbolOffset: 0,
  75005. precision: 2,
  75006. tooltip: {
  75007. trigger: 'item'
  75008. },
  75009. label: {
  75010. show: true,
  75011. position: 'end',
  75012. distance: 5
  75013. },
  75014. lineStyle: {
  75015. type: 'dashed'
  75016. },
  75017. emphasis: {
  75018. label: {
  75019. show: true
  75020. },
  75021. lineStyle: {
  75022. width: 3
  75023. }
  75024. },
  75025. animationEasing: 'linear'
  75026. };
  75027. return MarkLineModel;
  75028. }(MarkerModel);
  75029. var inner$i = makeInner();
  75030. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  75031. var data = seriesModel.getData();
  75032. var itemArray;
  75033. if (!isArray(item)) {
  75034. // Special type markLine like 'min', 'max', 'average', 'median'
  75035. var mlType = item.type;
  75036. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  75037. // data: [{
  75038. // yAxis: 10
  75039. // }]
  75040. || item.xAxis != null || item.yAxis != null) {
  75041. var valueAxis = void 0;
  75042. var value = void 0;
  75043. if (item.yAxis != null || item.xAxis != null) {
  75044. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  75045. value = retrieve(item.yAxis, item.xAxis);
  75046. } else {
  75047. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75048. valueAxis = axisInfo.valueAxis;
  75049. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  75050. value = numCalculate(data, valueDataDim, mlType);
  75051. }
  75052. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  75053. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  75054. var mlFrom = clone(item);
  75055. var mlTo = {
  75056. coord: []
  75057. };
  75058. mlFrom.type = null;
  75059. mlFrom.coord = [];
  75060. mlFrom.coord[baseIndex] = -Infinity;
  75061. mlTo.coord[baseIndex] = Infinity;
  75062. var precision = mlModel.get('precision');
  75063. if (precision >= 0 && isNumber(value)) {
  75064. value = +value.toFixed(Math.min(precision, 20));
  75065. }
  75066. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  75067. itemArray = [mlFrom, mlTo, {
  75068. type: mlType,
  75069. valueIndex: item.valueIndex,
  75070. // Force to use the value of calculated value.
  75071. value: value
  75072. }];
  75073. } else {
  75074. // Invalid data
  75075. if ("development" !== 'production') {
  75076. logError('Invalid markLine data.');
  75077. }
  75078. itemArray = [];
  75079. }
  75080. } else {
  75081. itemArray = item;
  75082. }
  75083. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  75084. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  75085. merge(normalizedItem[2], normalizedItem[0]);
  75086. merge(normalizedItem[2], normalizedItem[1]);
  75087. return normalizedItem;
  75088. };
  75089. function isInfinity(val) {
  75090. return !isNaN(val) && !isFinite(val);
  75091. } // If a markLine has one dim
  75092. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75093. var otherDimIndex = 1 - dimIndex;
  75094. var dimName = coordSys.dimensions[dimIndex];
  75095. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  75096. }
  75097. function markLineFilter(coordSys, item) {
  75098. if (coordSys.type === 'cartesian2d') {
  75099. var fromCoord = item[0].coord;
  75100. var toCoord = item[1].coord; // In case
  75101. // {
  75102. // markLine: {
  75103. // data: [{ yAxis: 2 }]
  75104. // }
  75105. // }
  75106. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  75107. return true;
  75108. }
  75109. }
  75110. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  75111. }
  75112. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  75113. var coordSys = seriesModel.coordinateSystem;
  75114. var itemModel = data.getItemModel(idx);
  75115. var point;
  75116. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75117. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75118. if (!isNaN(xPx) && !isNaN(yPx)) {
  75119. point = [xPx, yPx];
  75120. } else {
  75121. // Chart like bar may have there own marker positioning logic
  75122. if (seriesModel.getMarkerPosition) {
  75123. // Use the getMarkerPosition
  75124. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  75125. } else {
  75126. var dims = coordSys.dimensions;
  75127. var x = data.get(dims[0], idx);
  75128. var y = data.get(dims[1], idx);
  75129. point = coordSys.dataToPoint([x, y]);
  75130. } // Expand line to the edge of grid if value on one axis is Inifnity
  75131. // In case
  75132. // markLine: {
  75133. // data: [{
  75134. // yAxis: 2
  75135. // // or
  75136. // type: 'average'
  75137. // }]
  75138. // }
  75139. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75140. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  75141. var xAxis = coordSys.getAxis('x');
  75142. var yAxis = coordSys.getAxis('y');
  75143. var dims = coordSys.dimensions;
  75144. if (isInfinity(data.get(dims[0], idx))) {
  75145. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75146. } else if (isInfinity(data.get(dims[1], idx))) {
  75147. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75148. }
  75149. } // Use x, y if has any
  75150. if (!isNaN(xPx)) {
  75151. point[0] = xPx;
  75152. }
  75153. if (!isNaN(yPx)) {
  75154. point[1] = yPx;
  75155. }
  75156. }
  75157. data.setItemLayout(idx, point);
  75158. }
  75159. var MarkLineView =
  75160. /** @class */
  75161. function (_super) {
  75162. __extends(MarkLineView, _super);
  75163. function MarkLineView() {
  75164. var _this = _super !== null && _super.apply(this, arguments) || this;
  75165. _this.type = MarkLineView.type;
  75166. return _this;
  75167. }
  75168. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  75169. ecModel.eachSeries(function (seriesModel) {
  75170. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  75171. if (mlModel) {
  75172. var mlData_1 = mlModel.getData();
  75173. var fromData_1 = inner$i(mlModel).from;
  75174. var toData_1 = inner$i(mlModel).to; // Update visual and layout of from symbol and to symbol
  75175. fromData_1.each(function (idx) {
  75176. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  75177. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  75178. }); // Update layout of line
  75179. mlData_1.each(function (idx) {
  75180. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  75181. });
  75182. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75183. }
  75184. }, this);
  75185. };
  75186. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  75187. var coordSys = seriesModel.coordinateSystem;
  75188. var seriesId = seriesModel.id;
  75189. var seriesData = seriesModel.getData();
  75190. var lineDrawMap = this.markerGroupMap;
  75191. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  75192. this.group.add(lineDraw.group);
  75193. var mlData = createList$1(coordSys, seriesModel, mlModel);
  75194. var fromData = mlData.from;
  75195. var toData = mlData.to;
  75196. var lineData = mlData.line;
  75197. inner$i(mlModel).from = fromData;
  75198. inner$i(mlModel).to = toData; // Line data for tooltip and formatter
  75199. mlModel.setData(lineData); // TODO
  75200. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  75201. // But the related logic and type definition are not finished yet.
  75202. // Finish it if required
  75203. var symbolType = mlModel.get('symbol');
  75204. var symbolSize = mlModel.get('symbolSize');
  75205. var symbolRotate = mlModel.get('symbolRotate');
  75206. var symbolOffset = mlModel.get('symbolOffset'); // TODO: support callback function like markPoint
  75207. if (!isArray(symbolType)) {
  75208. symbolType = [symbolType, symbolType];
  75209. }
  75210. if (!isArray(symbolSize)) {
  75211. symbolSize = [symbolSize, symbolSize];
  75212. }
  75213. if (!isArray(symbolRotate)) {
  75214. symbolRotate = [symbolRotate, symbolRotate];
  75215. }
  75216. if (!isArray(symbolOffset)) {
  75217. symbolOffset = [symbolOffset, symbolOffset];
  75218. } // Update visual and layout of from symbol and to symbol
  75219. mlData.from.each(function (idx) {
  75220. updateDataVisualAndLayout(fromData, idx, true);
  75221. updateDataVisualAndLayout(toData, idx, false);
  75222. }); // Update visual and layout of line
  75223. lineData.each(function (idx) {
  75224. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  75225. // color: lineColor || fromData.getItemVisual(idx, 'color')
  75226. // });
  75227. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  75228. if (lineStyle.stroke == null) {
  75229. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  75230. }
  75231. lineData.setItemVisual(idx, {
  75232. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  75233. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  75234. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  75235. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  75236. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  75237. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  75238. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  75239. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  75240. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  75241. toSymbol: toData.getItemVisual(idx, 'symbol'),
  75242. style: lineStyle
  75243. });
  75244. });
  75245. lineDraw.updateData(lineData); // Set host model for tooltip
  75246. // FIXME
  75247. mlData.line.eachItemGraphicEl(function (el) {
  75248. getECData(el).dataModel = mlModel;
  75249. el.traverse(function (child) {
  75250. getECData(child).dataModel = mlModel;
  75251. });
  75252. });
  75253. function updateDataVisualAndLayout(data, idx, isFrom) {
  75254. var itemModel = data.getItemModel(idx);
  75255. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  75256. var style = itemModel.getModel('itemStyle').getItemStyle();
  75257. if (style.fill == null) {
  75258. style.fill = getVisualFromData(seriesData, 'color');
  75259. }
  75260. data.setItemVisual(idx, {
  75261. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  75262. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  75263. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  75264. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  75265. // TODO: when 2d array is supported, it should ignore parent
  75266. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  75267. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  75268. style: style
  75269. });
  75270. }
  75271. this.markKeep(lineDraw);
  75272. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75273. };
  75274. MarkLineView.type = 'markLine';
  75275. return MarkLineView;
  75276. }(MarkerView);
  75277. function createList$1(coordSys, seriesModel, mlModel) {
  75278. var coordDimsInfos;
  75279. if (coordSys) {
  75280. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75281. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75282. return extend(extend({}, info), {
  75283. name: coordDim,
  75284. // DON'T use ordinalMeta to parse and collect ordinal.
  75285. ordinalMeta: null
  75286. });
  75287. });
  75288. } else {
  75289. coordDimsInfos = [{
  75290. name: 'value',
  75291. type: 'float'
  75292. }];
  75293. }
  75294. var fromData = new SeriesData(coordDimsInfos, mlModel);
  75295. var toData = new SeriesData(coordDimsInfos, mlModel); // No dimensions
  75296. var lineData = new SeriesData([], mlModel);
  75297. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  75298. if (coordSys) {
  75299. optData = filter(optData, curry(markLineFilter, coordSys));
  75300. }
  75301. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  75302. fromData.initData(map(optData, function (item) {
  75303. return item[0];
  75304. }), null, dimValueGetter);
  75305. toData.initData(map(optData, function (item) {
  75306. return item[1];
  75307. }), null, dimValueGetter);
  75308. lineData.initData(map(optData, function (item) {
  75309. return item[2];
  75310. }));
  75311. lineData.hasItemOption = true;
  75312. return {
  75313. from: fromData,
  75314. to: toData,
  75315. line: lineData
  75316. };
  75317. }
  75318. function install$F(registers) {
  75319. registers.registerComponentModel(MarkLineModel);
  75320. registers.registerComponentView(MarkLineView);
  75321. registers.registerPreprocessor(function (opt) {
  75322. if (checkMarkerInSeries(opt.series, 'markLine')) {
  75323. // Make sure markLine component is enabled
  75324. opt.markLine = opt.markLine || {};
  75325. }
  75326. });
  75327. }
  75328. var MarkAreaModel =
  75329. /** @class */
  75330. function (_super) {
  75331. __extends(MarkAreaModel, _super);
  75332. function MarkAreaModel() {
  75333. var _this = _super !== null && _super.apply(this, arguments) || this;
  75334. _this.type = MarkAreaModel.type;
  75335. return _this;
  75336. }
  75337. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  75338. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  75339. };
  75340. MarkAreaModel.type = 'markArea';
  75341. MarkAreaModel.defaultOption = {
  75342. // zlevel: 0,
  75343. // PENDING
  75344. z: 1,
  75345. tooltip: {
  75346. trigger: 'item'
  75347. },
  75348. // markArea should fixed on the coordinate system
  75349. animation: false,
  75350. label: {
  75351. show: true,
  75352. position: 'top'
  75353. },
  75354. itemStyle: {
  75355. // color and borderColor default to use color from series
  75356. // color: 'auto'
  75357. // borderColor: 'auto'
  75358. borderWidth: 0
  75359. },
  75360. emphasis: {
  75361. label: {
  75362. show: true,
  75363. position: 'top'
  75364. }
  75365. }
  75366. };
  75367. return MarkAreaModel;
  75368. }(MarkerModel);
  75369. var inner$j = makeInner();
  75370. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75371. // item may be null
  75372. var item0 = item[0];
  75373. var item1 = item[1];
  75374. if (!item0 || !item1) {
  75375. return;
  75376. }
  75377. var lt = dataTransform(seriesModel, item0);
  75378. var rb = dataTransform(seriesModel, item1); // FIXME make sure lt is less than rb
  75379. var ltCoord = lt.coord;
  75380. var rbCoord = rb.coord;
  75381. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  75382. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  75383. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  75384. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  75385. var result = mergeAll([{}, lt, rb]);
  75386. result.coord = [lt.coord, rb.coord];
  75387. result.x0 = lt.x;
  75388. result.y0 = lt.y;
  75389. result.x1 = rb.x;
  75390. result.y1 = rb.y;
  75391. return result;
  75392. };
  75393. function isInfinity$1(val) {
  75394. return !isNaN(val) && !isFinite(val);
  75395. } // If a markArea has one dim
  75396. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75397. var otherDimIndex = 1 - dimIndex;
  75398. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  75399. }
  75400. function markAreaFilter(coordSys, item) {
  75401. var fromCoord = item.coord[0];
  75402. var toCoord = item.coord[1];
  75403. var item0 = {
  75404. coord: fromCoord,
  75405. x: item.x0,
  75406. y: item.y0
  75407. };
  75408. var item1 = {
  75409. coord: toCoord,
  75410. x: item.x1,
  75411. y: item.y1
  75412. };
  75413. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75414. // In case
  75415. // {
  75416. // markArea: {
  75417. // data: [{ yAxis: 2 }]
  75418. // }
  75419. // }
  75420. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  75421. return true;
  75422. } // Directly returning true may also do the work,
  75423. // because markArea will not be shown automatically
  75424. // when it's not included in coordinate system.
  75425. // But filtering ahead can avoid keeping rendering markArea
  75426. // when there are too many of them.
  75427. return zoneFilter(coordSys, item0, item1);
  75428. }
  75429. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  75430. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75431. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75432. var coordSys = seriesModel.coordinateSystem;
  75433. var itemModel = data.getItemModel(idx);
  75434. var point;
  75435. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75436. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75437. if (!isNaN(xPx) && !isNaN(yPx)) {
  75438. point = [xPx, yPx];
  75439. } else {
  75440. // Chart like bar may have there own marker positioning logic
  75441. if (seriesModel.getMarkerPosition) {
  75442. // Consider the case that user input the right-bottom point first
  75443. // Pick the larger x and y as 'x1' and 'y1'
  75444. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  75445. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  75446. var clampPointValue0 = coordSys.clampData(pointValue0);
  75447. var clampPointValue1 = coordSys.clampData(pointValue1);
  75448. var pointValue = [];
  75449. if (dims[0] === 'x0') {
  75450. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  75451. } else {
  75452. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  75453. }
  75454. if (dims[1] === 'y0') {
  75455. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  75456. } else {
  75457. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  75458. } // Use the getMarkerPosition
  75459. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  75460. } else {
  75461. var x = data.get(dims[0], idx);
  75462. var y = data.get(dims[1], idx);
  75463. var pt = [x, y];
  75464. coordSys.clampData && coordSys.clampData(pt, pt);
  75465. point = coordSys.dataToPoint(pt, true);
  75466. }
  75467. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75468. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  75469. var xAxis = coordSys.getAxis('x');
  75470. var yAxis = coordSys.getAxis('y');
  75471. var x = data.get(dims[0], idx);
  75472. var y = data.get(dims[1], idx);
  75473. if (isInfinity$1(x)) {
  75474. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75475. } else if (isInfinity$1(y)) {
  75476. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75477. }
  75478. } // Use x, y if has any
  75479. if (!isNaN(xPx)) {
  75480. point[0] = xPx;
  75481. }
  75482. if (!isNaN(yPx)) {
  75483. point[1] = yPx;
  75484. }
  75485. }
  75486. return point;
  75487. }
  75488. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75489. var MarkAreaView =
  75490. /** @class */
  75491. function (_super) {
  75492. __extends(MarkAreaView, _super);
  75493. function MarkAreaView() {
  75494. var _this = _super !== null && _super.apply(this, arguments) || this;
  75495. _this.type = MarkAreaView.type;
  75496. return _this;
  75497. }
  75498. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  75499. ecModel.eachSeries(function (seriesModel) {
  75500. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  75501. if (maModel) {
  75502. var areaData_1 = maModel.getData();
  75503. areaData_1.each(function (idx) {
  75504. var points = map(dimPermutations, function (dim) {
  75505. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  75506. }); // Layout
  75507. areaData_1.setItemLayout(idx, points);
  75508. var el = areaData_1.getItemGraphicEl(idx);
  75509. el.setShape('points', points);
  75510. });
  75511. }
  75512. }, this);
  75513. };
  75514. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  75515. var coordSys = seriesModel.coordinateSystem;
  75516. var seriesId = seriesModel.id;
  75517. var seriesData = seriesModel.getData();
  75518. var areaGroupMap = this.markerGroupMap;
  75519. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  75520. group: new Group()
  75521. });
  75522. this.group.add(polygonGroup.group);
  75523. this.markKeep(polygonGroup);
  75524. var areaData = createList$2(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  75525. maModel.setData(areaData); // Update visual and layout of line
  75526. areaData.each(function (idx) {
  75527. // Layout
  75528. var points = map(dimPermutations, function (dim) {
  75529. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75530. });
  75531. var xAxisScale = coordSys.getAxis('x').scale;
  75532. var yAxisScale = coordSys.getAxis('y').scale;
  75533. var xAxisExtent = xAxisScale.getExtent();
  75534. var yAxisExtent = yAxisScale.getExtent();
  75535. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  75536. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  75537. asc(xPointExtent);
  75538. asc(yPointExtent);
  75539. var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]); // If none of the area is inside coordSys, allClipped is set to be true
  75540. // in layout so that label will not be displayed. See #12591
  75541. var allClipped = !overlapped;
  75542. areaData.setItemLayout(idx, {
  75543. points: points,
  75544. allClipped: allClipped
  75545. });
  75546. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  75547. var color$1 = getVisualFromData(seriesData, 'color');
  75548. if (!style.fill) {
  75549. style.fill = color$1;
  75550. if (isString(style.fill)) {
  75551. style.fill = modifyAlpha(style.fill, 0.4);
  75552. }
  75553. }
  75554. if (!style.stroke) {
  75555. style.stroke = color$1;
  75556. } // Visual
  75557. areaData.setItemVisual(idx, 'style', style);
  75558. });
  75559. areaData.diff(inner$j(polygonGroup).data).add(function (idx) {
  75560. var layout = areaData.getItemLayout(idx);
  75561. if (!layout.allClipped) {
  75562. var polygon = new Polygon({
  75563. shape: {
  75564. points: layout.points
  75565. }
  75566. });
  75567. areaData.setItemGraphicEl(idx, polygon);
  75568. polygonGroup.group.add(polygon);
  75569. }
  75570. }).update(function (newIdx, oldIdx) {
  75571. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(oldIdx);
  75572. var layout = areaData.getItemLayout(newIdx);
  75573. if (!layout.allClipped) {
  75574. if (polygon) {
  75575. updateProps(polygon, {
  75576. shape: {
  75577. points: layout.points
  75578. }
  75579. }, maModel, newIdx);
  75580. } else {
  75581. polygon = new Polygon({
  75582. shape: {
  75583. points: layout.points
  75584. }
  75585. });
  75586. }
  75587. areaData.setItemGraphicEl(newIdx, polygon);
  75588. polygonGroup.group.add(polygon);
  75589. } else if (polygon) {
  75590. polygonGroup.group.remove(polygon);
  75591. }
  75592. }).remove(function (idx) {
  75593. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(idx);
  75594. polygonGroup.group.remove(polygon);
  75595. }).execute();
  75596. areaData.eachItemGraphicEl(function (polygon, idx) {
  75597. var itemModel = areaData.getItemModel(idx);
  75598. var style = areaData.getItemVisual(idx, 'style');
  75599. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  75600. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  75601. labelFetcher: maModel,
  75602. labelDataIndex: idx,
  75603. defaultText: areaData.getName(idx) || '',
  75604. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  75605. });
  75606. setStatesStylesFromModel(polygon, itemModel);
  75607. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  75608. getECData(polygon).dataModel = maModel;
  75609. });
  75610. inner$j(polygonGroup).data = areaData;
  75611. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75612. };
  75613. MarkAreaView.type = 'markArea';
  75614. return MarkAreaView;
  75615. }(MarkerView);
  75616. function createList$2(coordSys, seriesModel, maModel) {
  75617. var areaData;
  75618. var dataDims;
  75619. var dims = ['x0', 'y0', 'x1', 'y1'];
  75620. if (coordSys) {
  75621. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  75622. var data = seriesModel.getData();
  75623. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75624. return extend(extend({}, info), {
  75625. name: coordDim,
  75626. // DON'T use ordinalMeta to parse and collect ordinal.
  75627. ordinalMeta: null
  75628. });
  75629. });
  75630. dataDims = map(dims, function (dim, idx) {
  75631. return {
  75632. name: dim,
  75633. type: coordDimsInfos_1[idx % 2].type
  75634. };
  75635. });
  75636. areaData = new SeriesData(dataDims, maModel);
  75637. } else {
  75638. dataDims = [{
  75639. name: 'value',
  75640. type: 'float'
  75641. }];
  75642. areaData = new SeriesData(dataDims, maModel);
  75643. }
  75644. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  75645. if (coordSys) {
  75646. optData = filter(optData, curry(markAreaFilter, coordSys));
  75647. }
  75648. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75649. // TODO should convert to ParsedValue?
  75650. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75651. return parseDataValue(rawVal, dataDims[dimIndex]);
  75652. } : function (item, dimName, dataIndex, dimIndex) {
  75653. return parseDataValue(item.value, dataDims[dimIndex]);
  75654. };
  75655. areaData.initData(optData, null, dimValueGetter);
  75656. areaData.hasItemOption = true;
  75657. return areaData;
  75658. }
  75659. function install$G(registers) {
  75660. registers.registerComponentModel(MarkAreaModel);
  75661. registers.registerComponentView(MarkAreaView);
  75662. registers.registerPreprocessor(function (opt) {
  75663. if (checkMarkerInSeries(opt.series, 'markArea')) {
  75664. // Make sure markArea component is enabled
  75665. opt.markArea = opt.markArea || {};
  75666. }
  75667. });
  75668. }
  75669. var getDefaultSelectorOptions = function (ecModel, type) {
  75670. if (type === 'all') {
  75671. return {
  75672. type: 'all',
  75673. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  75674. };
  75675. } else if (type === 'inverse') {
  75676. return {
  75677. type: 'inverse',
  75678. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  75679. };
  75680. }
  75681. };
  75682. var LegendModel =
  75683. /** @class */
  75684. function (_super) {
  75685. __extends(LegendModel, _super);
  75686. function LegendModel() {
  75687. var _this = _super !== null && _super.apply(this, arguments) || this;
  75688. _this.type = LegendModel.type;
  75689. _this.layoutMode = {
  75690. type: 'box',
  75691. // legend.width/height are maxWidth/maxHeight actually,
  75692. // whereas real width/height is calculated by its content.
  75693. // (Setting {left: 10, right: 10} does not make sense).
  75694. // So consider the case:
  75695. // `setOption({legend: {left: 10});`
  75696. // then `setOption({legend: {right: 10});`
  75697. // The previous `left` should be cleared by setting `ignoreSize`.
  75698. ignoreSize: true
  75699. };
  75700. return _this;
  75701. }
  75702. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  75703. this.mergeDefaultAndTheme(option, ecModel);
  75704. option.selected = option.selected || {};
  75705. this._updateSelector(option);
  75706. };
  75707. LegendModel.prototype.mergeOption = function (option, ecModel) {
  75708. _super.prototype.mergeOption.call(this, option, ecModel);
  75709. this._updateSelector(option);
  75710. };
  75711. LegendModel.prototype._updateSelector = function (option) {
  75712. var selector = option.selector;
  75713. var ecModel = this.ecModel;
  75714. if (selector === true) {
  75715. selector = option.selector = ['all', 'inverse'];
  75716. }
  75717. if (isArray(selector)) {
  75718. each(selector, function (item, index) {
  75719. isString(item) && (item = {
  75720. type: item
  75721. });
  75722. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  75723. });
  75724. }
  75725. };
  75726. LegendModel.prototype.optionUpdated = function () {
  75727. this._updateData(this.ecModel);
  75728. var legendData = this._data; // If selectedMode is single, try to select one
  75729. if (legendData[0] && this.get('selectedMode') === 'single') {
  75730. var hasSelected = false; // If has any selected in option.selected
  75731. for (var i = 0; i < legendData.length; i++) {
  75732. var name_1 = legendData[i].get('name');
  75733. if (this.isSelected(name_1)) {
  75734. // Force to unselect others
  75735. this.select(name_1);
  75736. hasSelected = true;
  75737. break;
  75738. }
  75739. } // Try select the first if selectedMode is single
  75740. !hasSelected && this.select(legendData[0].get('name'));
  75741. }
  75742. };
  75743. LegendModel.prototype._updateData = function (ecModel) {
  75744. var potentialData = [];
  75745. var availableNames = [];
  75746. ecModel.eachRawSeries(function (seriesModel) {
  75747. var seriesName = seriesModel.name;
  75748. availableNames.push(seriesName);
  75749. var isPotential;
  75750. if (seriesModel.legendVisualProvider) {
  75751. var provider = seriesModel.legendVisualProvider;
  75752. var names = provider.getAllNames();
  75753. if (!ecModel.isSeriesFiltered(seriesModel)) {
  75754. availableNames = availableNames.concat(names);
  75755. }
  75756. if (names.length) {
  75757. potentialData = potentialData.concat(names);
  75758. } else {
  75759. isPotential = true;
  75760. }
  75761. } else {
  75762. isPotential = true;
  75763. }
  75764. if (isPotential && isNameSpecified(seriesModel)) {
  75765. potentialData.push(seriesModel.name);
  75766. }
  75767. });
  75768. /**
  75769. * @type {Array.<string>}
  75770. * @private
  75771. */
  75772. this._availableNames = availableNames; // If legend.data is not specified in option, use availableNames as data,
  75773. // which is convenient for user preparing option.
  75774. var rawData = this.get('data') || potentialData;
  75775. var legendNameMap = createHashMap();
  75776. var legendData = map(rawData, function (dataItem) {
  75777. // Can be string or number
  75778. if (isString(dataItem) || isNumber(dataItem)) {
  75779. dataItem = {
  75780. name: dataItem
  75781. };
  75782. }
  75783. if (legendNameMap.get(dataItem.name)) {
  75784. // remove legend name duplicate
  75785. return null;
  75786. }
  75787. legendNameMap.set(dataItem.name, true);
  75788. return new Model(dataItem, this, this.ecModel);
  75789. }, this);
  75790. /**
  75791. * @type {Array.<module:echarts/model/Model>}
  75792. * @private
  75793. */
  75794. this._data = filter(legendData, function (item) {
  75795. return !!item;
  75796. });
  75797. };
  75798. LegendModel.prototype.getData = function () {
  75799. return this._data;
  75800. };
  75801. LegendModel.prototype.select = function (name) {
  75802. var selected = this.option.selected;
  75803. var selectedMode = this.get('selectedMode');
  75804. if (selectedMode === 'single') {
  75805. var data = this._data;
  75806. each(data, function (dataItem) {
  75807. selected[dataItem.get('name')] = false;
  75808. });
  75809. }
  75810. selected[name] = true;
  75811. };
  75812. LegendModel.prototype.unSelect = function (name) {
  75813. if (this.get('selectedMode') !== 'single') {
  75814. this.option.selected[name] = false;
  75815. }
  75816. };
  75817. LegendModel.prototype.toggleSelected = function (name) {
  75818. var selected = this.option.selected; // Default is true
  75819. if (!selected.hasOwnProperty(name)) {
  75820. selected[name] = true;
  75821. }
  75822. this[selected[name] ? 'unSelect' : 'select'](name);
  75823. };
  75824. LegendModel.prototype.allSelect = function () {
  75825. var data = this._data;
  75826. var selected = this.option.selected;
  75827. each(data, function (dataItem) {
  75828. selected[dataItem.get('name', true)] = true;
  75829. });
  75830. };
  75831. LegendModel.prototype.inverseSelect = function () {
  75832. var data = this._data;
  75833. var selected = this.option.selected;
  75834. each(data, function (dataItem) {
  75835. var name = dataItem.get('name', true); // Initially, default value is true
  75836. if (!selected.hasOwnProperty(name)) {
  75837. selected[name] = true;
  75838. }
  75839. selected[name] = !selected[name];
  75840. });
  75841. };
  75842. LegendModel.prototype.isSelected = function (name) {
  75843. var selected = this.option.selected;
  75844. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  75845. };
  75846. LegendModel.prototype.getOrient = function () {
  75847. return this.get('orient') === 'vertical' ? {
  75848. index: 1,
  75849. name: 'vertical'
  75850. } : {
  75851. index: 0,
  75852. name: 'horizontal'
  75853. };
  75854. };
  75855. LegendModel.type = 'legend.plain';
  75856. LegendModel.dependencies = ['series'];
  75857. LegendModel.defaultOption = {
  75858. // zlevel: 0,
  75859. z: 4,
  75860. show: true,
  75861. orient: 'horizontal',
  75862. left: 'center',
  75863. // right: 'center',
  75864. top: 0,
  75865. // bottom: null,
  75866. align: 'auto',
  75867. backgroundColor: 'rgba(0,0,0,0)',
  75868. borderColor: '#ccc',
  75869. borderRadius: 0,
  75870. borderWidth: 0,
  75871. padding: 5,
  75872. itemGap: 10,
  75873. itemWidth: 25,
  75874. itemHeight: 14,
  75875. symbolRotate: 'inherit',
  75876. symbolKeepAspect: true,
  75877. inactiveColor: '#ccc',
  75878. inactiveBorderColor: '#ccc',
  75879. inactiveBorderWidth: 'auto',
  75880. itemStyle: {
  75881. color: 'inherit',
  75882. opacity: 'inherit',
  75883. borderColor: 'inherit',
  75884. borderWidth: 'auto',
  75885. borderCap: 'inherit',
  75886. borderJoin: 'inherit',
  75887. borderDashOffset: 'inherit',
  75888. borderMiterLimit: 'inherit'
  75889. },
  75890. lineStyle: {
  75891. width: 'auto',
  75892. color: 'inherit',
  75893. inactiveColor: '#ccc',
  75894. inactiveWidth: 2,
  75895. opacity: 'inherit',
  75896. type: 'inherit',
  75897. cap: 'inherit',
  75898. join: 'inherit',
  75899. dashOffset: 'inherit',
  75900. miterLimit: 'inherit'
  75901. },
  75902. textStyle: {
  75903. color: '#333'
  75904. },
  75905. selectedMode: true,
  75906. selector: false,
  75907. selectorLabel: {
  75908. show: true,
  75909. borderRadius: 10,
  75910. padding: [3, 5, 3, 5],
  75911. fontSize: 12,
  75912. fontFamily: 'sans-serif',
  75913. color: '#666',
  75914. borderWidth: 1,
  75915. borderColor: '#666'
  75916. },
  75917. emphasis: {
  75918. selectorLabel: {
  75919. show: true,
  75920. color: '#eee',
  75921. backgroundColor: '#666'
  75922. }
  75923. },
  75924. selectorPosition: 'auto',
  75925. selectorItemGap: 7,
  75926. selectorButtonGap: 10,
  75927. tooltip: {
  75928. show: false
  75929. }
  75930. };
  75931. return LegendModel;
  75932. }(ComponentModel);
  75933. var curry$1 = curry;
  75934. var each$c = each;
  75935. var Group$2 = Group;
  75936. var LegendView =
  75937. /** @class */
  75938. function (_super) {
  75939. __extends(LegendView, _super);
  75940. function LegendView() {
  75941. var _this = _super !== null && _super.apply(this, arguments) || this;
  75942. _this.type = LegendView.type;
  75943. _this.newlineDisabled = false;
  75944. return _this;
  75945. }
  75946. LegendView.prototype.init = function () {
  75947. this.group.add(this._contentGroup = new Group$2());
  75948. this.group.add(this._selectorGroup = new Group$2());
  75949. this._isFirstRender = true;
  75950. };
  75951. /**
  75952. * @protected
  75953. */
  75954. LegendView.prototype.getContentGroup = function () {
  75955. return this._contentGroup;
  75956. };
  75957. /**
  75958. * @protected
  75959. */
  75960. LegendView.prototype.getSelectorGroup = function () {
  75961. return this._selectorGroup;
  75962. };
  75963. /**
  75964. * @override
  75965. */
  75966. LegendView.prototype.render = function (legendModel, ecModel, api) {
  75967. var isFirstRender = this._isFirstRender;
  75968. this._isFirstRender = false;
  75969. this.resetInner();
  75970. if (!legendModel.get('show', true)) {
  75971. return;
  75972. }
  75973. var itemAlign = legendModel.get('align');
  75974. var orient = legendModel.get('orient');
  75975. if (!itemAlign || itemAlign === 'auto') {
  75976. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  75977. } // selector has been normalized to an array in model
  75978. var selector = legendModel.get('selector', true);
  75979. var selectorPosition = legendModel.get('selectorPosition', true);
  75980. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  75981. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  75982. }
  75983. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  75984. var positionInfo = legendModel.getBoxLayoutParams();
  75985. var viewportSize = {
  75986. width: api.getWidth(),
  75987. height: api.getHeight()
  75988. };
  75989. var padding = legendModel.get('padding');
  75990. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  75991. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  75992. var layoutRect = getLayoutRect(defaults({
  75993. width: mainRect.width,
  75994. height: mainRect.height
  75995. }, positionInfo), viewportSize, padding);
  75996. this.group.x = layoutRect.x - mainRect.x;
  75997. this.group.y = layoutRect.y - mainRect.y;
  75998. this.group.markRedraw(); // Render background after group is layout.
  75999. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  76000. };
  76001. LegendView.prototype.resetInner = function () {
  76002. this.getContentGroup().removeAll();
  76003. this._backgroundEl && this.group.remove(this._backgroundEl);
  76004. this.getSelectorGroup().removeAll();
  76005. };
  76006. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76007. var contentGroup = this.getContentGroup();
  76008. var legendDrawnMap = createHashMap();
  76009. var selectMode = legendModel.get('selectedMode');
  76010. var excludeSeriesId = [];
  76011. ecModel.eachRawSeries(function (seriesModel) {
  76012. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  76013. });
  76014. each$c(legendModel.getData(), function (legendItemModel, dataIndex) {
  76015. var name = legendItemModel.get('name'); // Use empty string or \n as a newline string
  76016. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  76017. var g = new Group$2(); // @ts-ignore
  76018. g.newline = true;
  76019. contentGroup.add(g);
  76020. return;
  76021. } // Representitive series.
  76022. var seriesModel = ecModel.getSeriesByName(name)[0];
  76023. if (legendDrawnMap.get(name)) {
  76024. // Have been drawn
  76025. return;
  76026. } // Legend to control series.
  76027. if (seriesModel) {
  76028. var data = seriesModel.getData();
  76029. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  76030. var legendIcon = data.getVisual('legendIcon');
  76031. /**
  76032. * `data.getVisual('style')` may be the color from the register
  76033. * in series. For example, for line series,
  76034. */
  76035. var style = data.getVisual('style');
  76036. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  76037. 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));
  76038. legendDrawnMap.set(name, true);
  76039. } else {
  76040. // Legend to control data. In pie and funnel.
  76041. ecModel.eachRawSeries(function (seriesModel) {
  76042. // In case multiple series has same data name
  76043. if (legendDrawnMap.get(name)) {
  76044. return;
  76045. }
  76046. if (seriesModel.legendVisualProvider) {
  76047. var provider = seriesModel.legendVisualProvider;
  76048. if (!provider.containName(name)) {
  76049. return;
  76050. }
  76051. var idx = provider.indexOfName(name);
  76052. var style = provider.getItemVisual(idx, 'style');
  76053. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  76054. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  76055. // Do not show nothing.
  76056. if (colorArr && colorArr[3] === 0) {
  76057. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  76058. style = extend(extend({}, style), {
  76059. fill: stringify(colorArr, 'rgba')
  76060. });
  76061. }
  76062. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api); // FIXME: consider different series has items with the same name.
  76063. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  76064. // more than one pie series.
  76065. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  76066. legendDrawnMap.set(name, true);
  76067. }
  76068. }, this);
  76069. }
  76070. if ("development" !== 'production') {
  76071. if (!legendDrawnMap.get(name)) {
  76072. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  76073. }
  76074. }
  76075. }, this);
  76076. if (selector) {
  76077. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  76078. }
  76079. };
  76080. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  76081. var selectorGroup = this.getSelectorGroup();
  76082. each$c(selector, function createSelectorButton(selectorItem) {
  76083. var type = selectorItem.type;
  76084. var labelText = new ZRText({
  76085. style: {
  76086. x: 0,
  76087. y: 0,
  76088. align: 'center',
  76089. verticalAlign: 'middle'
  76090. },
  76091. onclick: function () {
  76092. api.dispatchAction({
  76093. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  76094. });
  76095. }
  76096. });
  76097. selectorGroup.add(labelText);
  76098. var labelModel = legendModel.getModel('selectorLabel');
  76099. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  76100. setLabelStyle(labelText, {
  76101. normal: labelModel,
  76102. emphasis: emphasisLabelModel
  76103. }, {
  76104. defaultText: selectorItem.title
  76105. });
  76106. enableHoverEmphasis(labelText);
  76107. });
  76108. };
  76109. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  76110. var drawType = seriesModel.visualDrawType;
  76111. var itemWidth = legendModel.get('itemWidth');
  76112. var itemHeight = legendModel.get('itemHeight');
  76113. var isSelected = legendModel.isSelected(name);
  76114. var iconRotate = legendItemModel.get('symbolRotate');
  76115. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  76116. var legendIconType = legendItemModel.get('icon');
  76117. legendIcon = legendIconType || legendIcon || 'roundRect';
  76118. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  76119. var itemGroup = new Group$2();
  76120. var textStyleModel = legendItemModel.getModel('textStyle');
  76121. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  76122. // Series has specific way to define legend icon
  76123. itemGroup.add(seriesModel.getLegendIcon({
  76124. itemWidth: itemWidth,
  76125. itemHeight: itemHeight,
  76126. icon: legendIcon,
  76127. iconRotate: iconRotate,
  76128. itemStyle: style.itemStyle,
  76129. lineStyle: style.lineStyle,
  76130. symbolKeepAspect: symbolKeepAspect
  76131. }));
  76132. } else {
  76133. // Use default legend icon policy for most series
  76134. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  76135. itemGroup.add(getDefaultLegendIcon({
  76136. itemWidth: itemWidth,
  76137. itemHeight: itemHeight,
  76138. icon: legendIcon,
  76139. iconRotate: rotate,
  76140. itemStyle: style.itemStyle,
  76141. lineStyle: style.lineStyle,
  76142. symbolKeepAspect: symbolKeepAspect
  76143. }));
  76144. }
  76145. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  76146. var textAlign = itemAlign;
  76147. var formatter = legendModel.get('formatter');
  76148. var content = name;
  76149. if (isString(formatter) && formatter) {
  76150. content = formatter.replace('{name}', name != null ? name : '');
  76151. } else if (isFunction(formatter)) {
  76152. content = formatter(name);
  76153. }
  76154. var inactiveColor = legendItemModel.get('inactiveColor');
  76155. itemGroup.add(new ZRText({
  76156. style: createTextStyle(textStyleModel, {
  76157. text: content,
  76158. x: textX,
  76159. y: itemHeight / 2,
  76160. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  76161. align: textAlign,
  76162. verticalAlign: 'middle'
  76163. })
  76164. })); // Add a invisible rect to increase the area of mouse hover
  76165. var hitRect = new Rect({
  76166. shape: itemGroup.getBoundingRect(),
  76167. invisible: true
  76168. });
  76169. var tooltipModel = legendItemModel.getModel('tooltip');
  76170. if (tooltipModel.get('show')) {
  76171. setTooltipConfig({
  76172. el: hitRect,
  76173. componentModel: legendModel,
  76174. itemName: name,
  76175. itemTooltipOption: tooltipModel.option
  76176. });
  76177. }
  76178. itemGroup.add(hitRect);
  76179. itemGroup.eachChild(function (child) {
  76180. child.silent = true;
  76181. });
  76182. hitRect.silent = !selectMode;
  76183. this.getContentGroup().add(itemGroup);
  76184. enableHoverEmphasis(itemGroup); // @ts-ignore
  76185. itemGroup.__legendDataIndex = dataIndex;
  76186. return itemGroup;
  76187. };
  76188. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76189. var contentGroup = this.getContentGroup();
  76190. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  76191. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  76192. var contentRect = contentGroup.getBoundingRect();
  76193. var contentPos = [-contentRect.x, -contentRect.y];
  76194. selectorGroup.markRedraw();
  76195. contentGroup.markRedraw();
  76196. if (selector) {
  76197. // Place buttons in selectorGroup
  76198. box( // Buttons in selectorGroup always layout horizontally
  76199. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  76200. var selectorRect = selectorGroup.getBoundingRect();
  76201. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76202. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76203. var orientIdx = legendModel.getOrient().index;
  76204. var wh = orientIdx === 0 ? 'width' : 'height';
  76205. var hw = orientIdx === 0 ? 'height' : 'width';
  76206. var yx = orientIdx === 0 ? 'y' : 'x';
  76207. if (selectorPosition === 'end') {
  76208. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  76209. } else {
  76210. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  76211. } // Always align selector to content as 'middle'
  76212. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  76213. selectorGroup.x = selectorPos[0];
  76214. selectorGroup.y = selectorPos[1];
  76215. contentGroup.x = contentPos[0];
  76216. contentGroup.y = contentPos[1];
  76217. var mainRect = {
  76218. x: 0,
  76219. y: 0
  76220. };
  76221. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  76222. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  76223. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  76224. return mainRect;
  76225. } else {
  76226. contentGroup.x = contentPos[0];
  76227. contentGroup.y = contentPos[1];
  76228. return this.group.getBoundingRect();
  76229. }
  76230. };
  76231. /**
  76232. * @protected
  76233. */
  76234. LegendView.prototype.remove = function () {
  76235. this.getContentGroup().removeAll();
  76236. this._isFirstRender = true;
  76237. };
  76238. LegendView.type = 'legend.plain';
  76239. return LegendView;
  76240. }(ComponentView);
  76241. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  76242. /**
  76243. * Use series style if is inherit;
  76244. * elsewise, use legend style
  76245. */
  76246. function handleCommonProps(style, visualStyle) {
  76247. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  76248. if (style.lineWidth === 'auto') {
  76249. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  76250. }
  76251. each$c(style, function (propVal, propName) {
  76252. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  76253. });
  76254. } // itemStyle
  76255. var itemStyleModel = legendItemModel.getModel('itemStyle');
  76256. var itemStyle = itemStyleModel.getItemStyle();
  76257. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  76258. var decalStyle = itemStyleModel.getShallow('decal');
  76259. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  76260. if (itemStyle.fill === 'inherit') {
  76261. /**
  76262. * Series with visualDrawType as 'stroke' should have
  76263. * series stroke as legend fill
  76264. */
  76265. itemStyle.fill = itemVisualStyle[drawType];
  76266. }
  76267. if (itemStyle.stroke === 'inherit') {
  76268. /**
  76269. * icon type with "emptyXXX" should use fill color
  76270. * in visual style
  76271. */
  76272. itemStyle.stroke = itemVisualStyle[iconBrushType];
  76273. }
  76274. if (itemStyle.opacity === 'inherit') {
  76275. /**
  76276. * Use lineStyle.opacity if drawType is stroke
  76277. */
  76278. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  76279. }
  76280. handleCommonProps(itemStyle, itemVisualStyle); // lineStyle
  76281. var legendLineModel = legendItemModel.getModel('lineStyle');
  76282. var lineStyle = legendLineModel.getLineStyle();
  76283. handleCommonProps(lineStyle, lineVisualStyle); // Fix auto color to real color
  76284. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  76285. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  76286. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  76287. if (!isSelected) {
  76288. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  76289. /**
  76290. * Since stroke is set to be inactiveBorderColor, it may occur that
  76291. * there is no border in series but border in legend, so we need to
  76292. * use border only when series has border if is set to be auto
  76293. */
  76294. var visualHasBorder = itemStyle[iconBrushType];
  76295. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  76296. itemStyle.fill = legendItemModel.get('inactiveColor');
  76297. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  76298. lineStyle.stroke = legendLineModel.get('inactiveColor');
  76299. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  76300. }
  76301. return {
  76302. itemStyle: itemStyle,
  76303. lineStyle: lineStyle
  76304. };
  76305. }
  76306. function getDefaultLegendIcon(opt) {
  76307. var symboType = opt.icon || 'roundRect';
  76308. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  76309. icon.setStyle(opt.itemStyle);
  76310. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  76311. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  76312. if (symboType.indexOf('empty') > -1) {
  76313. icon.style.stroke = icon.style.fill;
  76314. icon.style.fill = '#fff';
  76315. icon.style.lineWidth = 2;
  76316. }
  76317. return icon;
  76318. }
  76319. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  76320. // downplay before unselect
  76321. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  76322. api.dispatchAction({
  76323. type: 'legendToggleSelect',
  76324. name: seriesName != null ? seriesName : dataName
  76325. }); // highlight after select
  76326. // TODO highlight immediately may cause animation loss.
  76327. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  76328. }
  76329. function isUseHoverLayer(api) {
  76330. var list = api.getZr().storage.getDisplayList();
  76331. var emphasisState;
  76332. var i = 0;
  76333. var len = list.length;
  76334. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  76335. i++;
  76336. }
  76337. return emphasisState && emphasisState.hoverLayer;
  76338. }
  76339. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  76340. // If element hover will move to a hoverLayer.
  76341. if (!isUseHoverLayer(api)) {
  76342. api.dispatchAction({
  76343. type: 'highlight',
  76344. seriesName: seriesName,
  76345. name: dataName,
  76346. excludeSeriesId: excludeSeriesId
  76347. });
  76348. }
  76349. }
  76350. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  76351. // If element hover will move to a hoverLayer.
  76352. if (!isUseHoverLayer(api)) {
  76353. api.dispatchAction({
  76354. type: 'downplay',
  76355. seriesName: seriesName,
  76356. name: dataName,
  76357. excludeSeriesId: excludeSeriesId
  76358. });
  76359. }
  76360. }
  76361. /*
  76362. * Licensed to the Apache Software Foundation (ASF) under one
  76363. * or more contributor license agreements. See the NOTICE file
  76364. * distributed with this work for additional information
  76365. * regarding copyright ownership. The ASF licenses this file
  76366. * to you under the Apache License, Version 2.0 (the
  76367. * "License"); you may not use this file except in compliance
  76368. * with the License. You may obtain a copy of the License at
  76369. *
  76370. * http://www.apache.org/licenses/LICENSE-2.0
  76371. *
  76372. * Unless required by applicable law or agreed to in writing,
  76373. * software distributed under the License is distributed on an
  76374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76375. * KIND, either express or implied. See the License for the
  76376. * specific language governing permissions and limitations
  76377. * under the License.
  76378. */
  76379. /**
  76380. * AUTO-GENERATED FILE. DO NOT MODIFY.
  76381. */
  76382. /*
  76383. * Licensed to the Apache Software Foundation (ASF) under one
  76384. * or more contributor license agreements. See the NOTICE file
  76385. * distributed with this work for additional information
  76386. * regarding copyright ownership. The ASF licenses this file
  76387. * to you under the Apache License, Version 2.0 (the
  76388. * "License"); you may not use this file except in compliance
  76389. * with the License. You may obtain a copy of the License at
  76390. *
  76391. * http://www.apache.org/licenses/LICENSE-2.0
  76392. *
  76393. * Unless required by applicable law or agreed to in writing,
  76394. * software distributed under the License is distributed on an
  76395. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76396. * KIND, either express or implied. See the License for the
  76397. * specific language governing permissions and limitations
  76398. * under the License.
  76399. */
  76400. function legendFilter(ecModel) {
  76401. var legendModels = ecModel.findComponents({
  76402. mainType: 'legend'
  76403. });
  76404. if (legendModels && legendModels.length) {
  76405. ecModel.filterSeries(function (series) {
  76406. // If in any legend component the status is not selected.
  76407. // Because in legend series is assumed selected when it is not in the legend data.
  76408. for (var i = 0; i < legendModels.length; i++) {
  76409. if (!legendModels[i].isSelected(series.name)) {
  76410. return false;
  76411. }
  76412. }
  76413. return true;
  76414. });
  76415. }
  76416. }
  76417. function legendSelectActionHandler(methodName, payload, ecModel) {
  76418. var selectedMap = {};
  76419. var isToggleSelect = methodName === 'toggleSelected';
  76420. var isSelected; // Update all legend components
  76421. ecModel.eachComponent('legend', function (legendModel) {
  76422. if (isToggleSelect && isSelected != null) {
  76423. // Force other legend has same selected status
  76424. // Or the first is toggled to true and other are toggled to false
  76425. // In the case one legend has some item unSelected in option. And if other legend
  76426. // doesn't has the item, they will assume it is selected.
  76427. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  76428. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  76429. legendModel[methodName]();
  76430. } else {
  76431. legendModel[methodName](payload.name);
  76432. isSelected = legendModel.isSelected(payload.name);
  76433. }
  76434. var legendData = legendModel.getData();
  76435. each(legendData, function (model) {
  76436. var name = model.get('name'); // Wrap element
  76437. if (name === '\n' || name === '') {
  76438. return;
  76439. }
  76440. var isItemSelected = legendModel.isSelected(name);
  76441. if (selectedMap.hasOwnProperty(name)) {
  76442. // Unselected if any legend is unselected
  76443. selectedMap[name] = selectedMap[name] && isItemSelected;
  76444. } else {
  76445. selectedMap[name] = isItemSelected;
  76446. }
  76447. });
  76448. }); // Return the event explicitly
  76449. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  76450. selected: selectedMap
  76451. } : {
  76452. name: payload.name,
  76453. selected: selectedMap
  76454. };
  76455. }
  76456. function installLegendAction(registers) {
  76457. /**
  76458. * @event legendToggleSelect
  76459. * @type {Object}
  76460. * @property {string} type 'legendToggleSelect'
  76461. * @property {string} [from]
  76462. * @property {string} name Series name or data item name
  76463. */
  76464. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  76465. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  76466. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  76467. /**
  76468. * @event legendSelect
  76469. * @type {Object}
  76470. * @property {string} type 'legendSelect'
  76471. * @property {string} name Series name or data item name
  76472. */
  76473. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  76474. /**
  76475. * @event legendUnSelect
  76476. * @type {Object}
  76477. * @property {string} type 'legendUnSelect'
  76478. * @property {string} name Series name or data item name
  76479. */
  76480. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  76481. }
  76482. function install$H(registers) {
  76483. registers.registerComponentModel(LegendModel);
  76484. registers.registerComponentView(LegendView);
  76485. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  76486. registers.registerSubTypeDefaulter('legend', function () {
  76487. return 'plain';
  76488. });
  76489. installLegendAction(registers);
  76490. }
  76491. var ScrollableLegendModel =
  76492. /** @class */
  76493. function (_super) {
  76494. __extends(ScrollableLegendModel, _super);
  76495. function ScrollableLegendModel() {
  76496. var _this = _super !== null && _super.apply(this, arguments) || this;
  76497. _this.type = ScrollableLegendModel.type;
  76498. return _this;
  76499. }
  76500. /**
  76501. * @param {number} scrollDataIndex
  76502. */
  76503. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  76504. this.option.scrollDataIndex = scrollDataIndex;
  76505. };
  76506. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  76507. var inputPositionParams = getLayoutParams(option);
  76508. _super.prototype.init.call(this, option, parentModel, ecModel);
  76509. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  76510. };
  76511. /**
  76512. * @override
  76513. */
  76514. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  76515. _super.prototype.mergeOption.call(this, option, ecModel);
  76516. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  76517. };
  76518. ScrollableLegendModel.type = 'legend.scroll';
  76519. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  76520. scrollDataIndex: 0,
  76521. pageButtonItemGap: 5,
  76522. pageButtonGap: null,
  76523. pageButtonPosition: 'end',
  76524. pageFormatter: '{current}/{total}',
  76525. pageIcons: {
  76526. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  76527. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  76528. },
  76529. pageIconColor: '#2f4554',
  76530. pageIconInactiveColor: '#aaa',
  76531. pageIconSize: 15,
  76532. pageTextStyle: {
  76533. color: '#333'
  76534. },
  76535. animationDurationUpdate: 800
  76536. });
  76537. return ScrollableLegendModel;
  76538. }(LegendModel);
  76539. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  76540. var orient = legendModel.getOrient();
  76541. var ignoreSize = [1, 1];
  76542. ignoreSize[orient.index] = 0;
  76543. mergeLayoutParam(target, raw, {
  76544. type: 'box',
  76545. ignoreSize: !!ignoreSize
  76546. });
  76547. }
  76548. var Group$3 = Group;
  76549. var WH$1 = ['width', 'height'];
  76550. var XY$1 = ['x', 'y'];
  76551. var ScrollableLegendView =
  76552. /** @class */
  76553. function (_super) {
  76554. __extends(ScrollableLegendView, _super);
  76555. function ScrollableLegendView() {
  76556. var _this = _super !== null && _super.apply(this, arguments) || this;
  76557. _this.type = ScrollableLegendView.type;
  76558. _this.newlineDisabled = true;
  76559. _this._currentIndex = 0;
  76560. return _this;
  76561. }
  76562. ScrollableLegendView.prototype.init = function () {
  76563. _super.prototype.init.call(this);
  76564. this.group.add(this._containerGroup = new Group$3());
  76565. this._containerGroup.add(this.getContentGroup());
  76566. this.group.add(this._controllerGroup = new Group$3());
  76567. };
  76568. /**
  76569. * @override
  76570. */
  76571. ScrollableLegendView.prototype.resetInner = function () {
  76572. _super.prototype.resetInner.call(this);
  76573. this._controllerGroup.removeAll();
  76574. this._containerGroup.removeClipPath();
  76575. this._containerGroup.__rectSize = null;
  76576. };
  76577. /**
  76578. * @override
  76579. */
  76580. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76581. var self = this; // Render content items.
  76582. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  76583. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  76584. // e.g., '3/12345' should not overlap with the control arrow button.
  76585. var pageIconSize = legendModel.get('pageIconSize', true);
  76586. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  76587. createPageButton('pagePrev', 0);
  76588. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  76589. controllerGroup.add(new ZRText({
  76590. name: 'pageText',
  76591. style: {
  76592. // Placeholder to calculate a proper layout.
  76593. text: 'xx/xx',
  76594. fill: pageTextStyleModel.getTextColor(),
  76595. font: pageTextStyleModel.getFont(),
  76596. verticalAlign: 'middle',
  76597. align: 'center'
  76598. },
  76599. silent: true
  76600. }));
  76601. createPageButton('pageNext', 1);
  76602. function createPageButton(name, iconIdx) {
  76603. var pageDataIndexName = name + 'DataIndex';
  76604. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  76605. // Buttons will be created in each render, so we do not need
  76606. // to worry about avoiding using legendModel kept in scope.
  76607. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  76608. }, {
  76609. x: -pageIconSizeArr[0] / 2,
  76610. y: -pageIconSizeArr[1] / 2,
  76611. width: pageIconSizeArr[0],
  76612. height: pageIconSizeArr[1]
  76613. });
  76614. icon.name = name;
  76615. controllerGroup.add(icon);
  76616. }
  76617. };
  76618. /**
  76619. * @override
  76620. */
  76621. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76622. var selectorGroup = this.getSelectorGroup();
  76623. var orientIdx = legendModel.getOrient().index;
  76624. var wh = WH$1[orientIdx];
  76625. var xy = XY$1[orientIdx];
  76626. var hw = WH$1[1 - orientIdx];
  76627. var yx = XY$1[1 - orientIdx];
  76628. selector && box( // Buttons in selectorGroup always layout horizontally
  76629. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  76630. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76631. var selectorRect = selectorGroup.getBoundingRect();
  76632. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76633. var processMaxSize = clone(maxSize);
  76634. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  76635. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  76636. if (selector) {
  76637. if (selectorPosition === 'end') {
  76638. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  76639. } else {
  76640. var offset = selectorRect[wh] + selectorButtonGap;
  76641. selectorPos[orientIdx] -= offset;
  76642. mainRect[xy] -= offset;
  76643. }
  76644. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  76645. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  76646. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  76647. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  76648. selectorGroup.x = selectorPos[0];
  76649. selectorGroup.y = selectorPos[1];
  76650. selectorGroup.markRedraw();
  76651. }
  76652. return mainRect;
  76653. };
  76654. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  76655. var contentGroup = this.getContentGroup();
  76656. var containerGroup = this._containerGroup;
  76657. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  76658. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  76659. box( // Buttons in controller are layout always horizontally.
  76660. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  76661. var contentRect = contentGroup.getBoundingRect();
  76662. var controllerRect = controllerGroup.getBoundingRect();
  76663. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  76664. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  76665. // If first rendering, `contentGroup.position` is [0, 0], which
  76666. // does not make sense and may cause unexepcted animation if adopted.
  76667. if (!isFirstRender) {
  76668. contentPos[orientIdx] = contentGroup[xy];
  76669. } // Layout container group based on 0.
  76670. var containerPos = [0, 0];
  76671. var controllerPos = [-controllerRect.x, -controllerRect.y];
  76672. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  76673. if (showController) {
  76674. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  76675. if (pageButtonPosition === 'end') {
  76676. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  76677. } // controller is on the left / top.
  76678. else {
  76679. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  76680. }
  76681. } // Always align controller to content as 'middle'.
  76682. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  76683. contentGroup.setPosition(contentPos);
  76684. containerGroup.setPosition(containerPos);
  76685. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  76686. // mainRect should not be calculated by `this.group.getBoundingRect()`
  76687. // for sake of the overflow.
  76688. var mainRect = {
  76689. x: 0,
  76690. y: 0
  76691. }; // Consider content may be overflow (should be clipped).
  76692. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  76693. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  76694. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  76695. containerGroup.__rectSize = maxSize[wh];
  76696. if (showController) {
  76697. var clipShape = {
  76698. x: 0,
  76699. y: 0
  76700. };
  76701. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  76702. clipShape[hw] = mainRect[hw];
  76703. containerGroup.setClipPath(new Rect({
  76704. shape: clipShape
  76705. })); // Consider content may be larger than container, container rect
  76706. // can not be obtained from `containerGroup.getBoundingRect()`.
  76707. containerGroup.__rectSize = clipShape[wh];
  76708. } else {
  76709. // Do not remove or ignore controller. Keep them set as placeholders.
  76710. controllerGroup.eachChild(function (child) {
  76711. child.attr({
  76712. invisible: true,
  76713. silent: true
  76714. });
  76715. });
  76716. } // Content translate animation.
  76717. var pageInfo = this._getPageInfo(legendModel);
  76718. pageInfo.pageIndex != null && updateProps(contentGroup, {
  76719. x: pageInfo.contentPosition[0],
  76720. y: pageInfo.contentPosition[1]
  76721. }, // When switch from "show controller" to "not show controller", view should be
  76722. // updated immediately without animation, otherwise causes weird effect.
  76723. showController ? legendModel : null);
  76724. this._updatePageInfoView(legendModel, pageInfo);
  76725. return mainRect;
  76726. };
  76727. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  76728. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  76729. scrollDataIndex != null && api.dispatchAction({
  76730. type: 'legendScroll',
  76731. scrollDataIndex: scrollDataIndex,
  76732. legendId: legendModel.id
  76733. });
  76734. };
  76735. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  76736. var controllerGroup = this._controllerGroup;
  76737. each(['pagePrev', 'pageNext'], function (name) {
  76738. var key = name + 'DataIndex';
  76739. var canJump = pageInfo[key] != null;
  76740. var icon = controllerGroup.childOfName(name);
  76741. if (icon) {
  76742. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  76743. icon.cursor = canJump ? 'pointer' : 'default';
  76744. }
  76745. });
  76746. var pageText = controllerGroup.childOfName('pageText');
  76747. var pageFormatter = legendModel.get('pageFormatter');
  76748. var pageIndex = pageInfo.pageIndex;
  76749. var current = pageIndex != null ? pageIndex + 1 : 0;
  76750. var total = pageInfo.pageCount;
  76751. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  76752. current: current,
  76753. total: total
  76754. }));
  76755. };
  76756. /**
  76757. * contentPosition: Array.<number>, null when data item not found.
  76758. * pageIndex: number, null when data item not found.
  76759. * pageCount: number, always be a number, can be 0.
  76760. * pagePrevDataIndex: number, null when no previous page.
  76761. * pageNextDataIndex: number, null when no next page.
  76762. * }
  76763. */
  76764. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  76765. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  76766. var contentGroup = this.getContentGroup();
  76767. var containerRectSize = this._containerGroup.__rectSize;
  76768. var orientIdx = legendModel.getOrient().index;
  76769. var wh = WH$1[orientIdx];
  76770. var xy = XY$1[orientIdx];
  76771. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  76772. var children = contentGroup.children();
  76773. var targetItem = children[targetItemIndex];
  76774. var itemCount = children.length;
  76775. var pCount = !itemCount ? 0 : 1;
  76776. var result = {
  76777. contentPosition: [contentGroup.x, contentGroup.y],
  76778. pageCount: pCount,
  76779. pageIndex: pCount - 1,
  76780. pagePrevDataIndex: null,
  76781. pageNextDataIndex: null
  76782. };
  76783. if (!targetItem) {
  76784. return result;
  76785. }
  76786. var targetItemInfo = getItemInfo(targetItem);
  76787. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  76788. // (1) Always align based on the left/top most item.
  76789. // (2) It is user-friendly that the last item shown in the
  76790. // current window is shown at the begining of next window.
  76791. // Otherwise if half of the last item is cut by the window,
  76792. // it will have no chance to display entirely.
  76793. // (3) Consider that item size probably be different, we
  76794. // have calculate pageIndex by size rather than item index,
  76795. // and we can not get page index directly by division.
  76796. // (4) The window is to narrow to contain more than
  76797. // one item, we should make sure that the page can be fliped.
  76798. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  76799. currItemInfo = getItemInfo(children[i]);
  76800. if ( // Half of the last item is out of the window.
  76801. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  76802. // can be started at the current item or the last item.
  76803. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  76804. if (winEndItemInfo.i > winStartItemInfo.i) {
  76805. winStartItemInfo = winEndItemInfo;
  76806. } else {
  76807. // e.g., when page size is smaller than item size.
  76808. winStartItemInfo = currItemInfo;
  76809. }
  76810. if (winStartItemInfo) {
  76811. if (result.pageNextDataIndex == null) {
  76812. result.pageNextDataIndex = winStartItemInfo.i;
  76813. }
  76814. ++result.pageCount;
  76815. }
  76816. }
  76817. winEndItemInfo = currItemInfo;
  76818. }
  76819. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  76820. currItemInfo = getItemInfo(children[i]);
  76821. if ( // If the the end item does not intersect with the window started
  76822. // from the current item, a page can be settled.
  76823. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  76824. winStartItemInfo.i < winEndItemInfo.i) {
  76825. winEndItemInfo = winStartItemInfo;
  76826. if (result.pagePrevDataIndex == null) {
  76827. result.pagePrevDataIndex = winStartItemInfo.i;
  76828. }
  76829. ++result.pageCount;
  76830. ++result.pageIndex;
  76831. }
  76832. winStartItemInfo = currItemInfo;
  76833. }
  76834. return result;
  76835. function getItemInfo(el) {
  76836. if (el) {
  76837. var itemRect = el.getBoundingRect();
  76838. var start = itemRect[xy] + el[xy];
  76839. return {
  76840. s: start,
  76841. e: start + itemRect[wh],
  76842. i: el.__legendDataIndex
  76843. };
  76844. }
  76845. }
  76846. function intersect(itemInfo, winStart) {
  76847. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  76848. }
  76849. };
  76850. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  76851. if (!this._showController) {
  76852. return 0;
  76853. }
  76854. var index;
  76855. var contentGroup = this.getContentGroup();
  76856. var defaultIndex;
  76857. contentGroup.eachChild(function (child, idx) {
  76858. var legendDataIdx = child.__legendDataIndex; // FIXME
  76859. // If the given targetDataIndex (from model) is illegal,
  76860. // we use defaultIndex. But the index on the legend model and
  76861. // action payload is still illegal. That case will not be
  76862. // changed until some scenario requires.
  76863. if (defaultIndex == null && legendDataIdx != null) {
  76864. defaultIndex = idx;
  76865. }
  76866. if (legendDataIdx === targetDataIndex) {
  76867. index = idx;
  76868. }
  76869. });
  76870. return index != null ? index : defaultIndex;
  76871. };
  76872. ScrollableLegendView.type = 'legend.scroll';
  76873. return ScrollableLegendView;
  76874. }(LegendView);
  76875. /*
  76876. * Licensed to the Apache Software Foundation (ASF) under one
  76877. * or more contributor license agreements. See the NOTICE file
  76878. * distributed with this work for additional information
  76879. * regarding copyright ownership. The ASF licenses this file
  76880. * to you under the Apache License, Version 2.0 (the
  76881. * "License"); you may not use this file except in compliance
  76882. * with the License. You may obtain a copy of the License at
  76883. *
  76884. * http://www.apache.org/licenses/LICENSE-2.0
  76885. *
  76886. * Unless required by applicable law or agreed to in writing,
  76887. * software distributed under the License is distributed on an
  76888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76889. * KIND, either express or implied. See the License for the
  76890. * specific language governing permissions and limitations
  76891. * under the License.
  76892. */
  76893. /**
  76894. * AUTO-GENERATED FILE. DO NOT MODIFY.
  76895. */
  76896. /*
  76897. * Licensed to the Apache Software Foundation (ASF) under one
  76898. * or more contributor license agreements. See the NOTICE file
  76899. * distributed with this work for additional information
  76900. * regarding copyright ownership. The ASF licenses this file
  76901. * to you under the Apache License, Version 2.0 (the
  76902. * "License"); you may not use this file except in compliance
  76903. * with the License. You may obtain a copy of the License at
  76904. *
  76905. * http://www.apache.org/licenses/LICENSE-2.0
  76906. *
  76907. * Unless required by applicable law or agreed to in writing,
  76908. * software distributed under the License is distributed on an
  76909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76910. * KIND, either express or implied. See the License for the
  76911. * specific language governing permissions and limitations
  76912. * under the License.
  76913. */
  76914. function installScrollableLegendAction(registers) {
  76915. /**
  76916. * @event legendScroll
  76917. * @type {Object}
  76918. * @property {string} type 'legendScroll'
  76919. * @property {string} scrollDataIndex
  76920. */
  76921. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  76922. var scrollDataIndex = payload.scrollDataIndex;
  76923. scrollDataIndex != null && ecModel.eachComponent({
  76924. mainType: 'legend',
  76925. subType: 'scroll',
  76926. query: payload
  76927. }, function (legendModel) {
  76928. legendModel.setScrollDataIndex(scrollDataIndex);
  76929. });
  76930. });
  76931. }
  76932. function install$I(registers) {
  76933. use(install$H);
  76934. registers.registerComponentModel(ScrollableLegendModel);
  76935. registers.registerComponentView(ScrollableLegendView);
  76936. installScrollableLegendAction(registers);
  76937. }
  76938. function install$J(registers) {
  76939. use(install$H);
  76940. use(install$I);
  76941. }
  76942. var InsideZoomModel =
  76943. /** @class */
  76944. function (_super) {
  76945. __extends(InsideZoomModel, _super);
  76946. function InsideZoomModel() {
  76947. var _this = _super !== null && _super.apply(this, arguments) || this;
  76948. _this.type = InsideZoomModel.type;
  76949. return _this;
  76950. }
  76951. InsideZoomModel.type = 'dataZoom.inside';
  76952. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  76953. disabled: false,
  76954. zoomLock: false,
  76955. zoomOnMouseWheel: true,
  76956. moveOnMouseMove: true,
  76957. moveOnMouseWheel: false,
  76958. preventDefaultMouseMove: true
  76959. });
  76960. return InsideZoomModel;
  76961. }(DataZoomModel);
  76962. var inner$k = makeInner();
  76963. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  76964. inner$k(api).coordSysRecordMap.each(function (coordSysRecord) {
  76965. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  76966. if (dzInfo) {
  76967. dzInfo.getRange = getRange;
  76968. }
  76969. });
  76970. }
  76971. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  76972. var coordSysRecordMap = inner$k(api).coordSysRecordMap;
  76973. var coordSysKeyArr = coordSysRecordMap.keys();
  76974. for (var i = 0; i < coordSysKeyArr.length; i++) {
  76975. var coordSysKey = coordSysKeyArr[i];
  76976. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  76977. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  76978. if (dataZoomInfoMap) {
  76979. var dzUid = dataZoomModel.uid;
  76980. var dzInfo = dataZoomInfoMap.get(dzUid);
  76981. if (dzInfo) {
  76982. dataZoomInfoMap.removeKey(dzUid);
  76983. if (!dataZoomInfoMap.keys().length) {
  76984. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  76985. }
  76986. }
  76987. }
  76988. }
  76989. }
  76990. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  76991. if (coordSysRecord) {
  76992. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  76993. var controller = coordSysRecord.controller;
  76994. controller && controller.dispose();
  76995. }
  76996. }
  76997. function createCoordSysRecord(api, coordSysModel) {
  76998. // These init props will never change after record created.
  76999. var coordSysRecord = {
  77000. model: coordSysModel,
  77001. containsPoint: curry(containsPoint, coordSysModel),
  77002. dispatchAction: curry(dispatchAction$1, api),
  77003. dataZoomInfoMap: null,
  77004. controller: null
  77005. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  77006. // because coordSysRecord not completed yet.
  77007. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  77008. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  77009. controller.on(eventName, function (event) {
  77010. var batch = [];
  77011. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  77012. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  77013. // moveOnMouseWheel, ...) enabled.
  77014. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  77015. return;
  77016. }
  77017. var method = (dzInfo.getRange || {})[eventName];
  77018. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  77019. !dzInfo.model.get('disabled', true) && range && batch.push({
  77020. dataZoomId: dzInfo.model.id,
  77021. start: range[0],
  77022. end: range[1]
  77023. });
  77024. });
  77025. batch.length && coordSysRecord.dispatchAction(batch);
  77026. });
  77027. });
  77028. return coordSysRecord;
  77029. }
  77030. /**
  77031. * This action will be throttled.
  77032. */
  77033. function dispatchAction$1(api, batch) {
  77034. if (!api.isDisposed()) {
  77035. api.dispatchAction({
  77036. type: 'dataZoom',
  77037. animation: {
  77038. easing: 'cubicOut',
  77039. duration: 100
  77040. },
  77041. batch: batch
  77042. });
  77043. }
  77044. }
  77045. function containsPoint(coordSysModel, e, x, y) {
  77046. return coordSysModel.coordinateSystem.containPoint([x, y]);
  77047. }
  77048. /**
  77049. * Merge roamController settings when multiple dataZooms share one roamController.
  77050. */
  77051. function mergeControllerParams(dataZoomInfoMap) {
  77052. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  77053. // as string, it is probably revert to reserved word by compress tool. See #7411.
  77054. var prefix = 'type_';
  77055. var typePriority = {
  77056. 'type_true': 2,
  77057. 'type_move': 1,
  77058. 'type_false': 0,
  77059. 'type_undefined': -1
  77060. };
  77061. var preventDefaultMouseMove = true;
  77062. dataZoomInfoMap.each(function (dataZoomInfo) {
  77063. var dataZoomModel = dataZoomInfo.model;
  77064. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  77065. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  77066. controlType = oneType;
  77067. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  77068. // users may be confused why it does not work when multiple insideZooms exist.
  77069. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  77070. });
  77071. return {
  77072. controlType: controlType,
  77073. opt: {
  77074. // RoamController will enable all of these functionalities,
  77075. // and the final behavior is determined by its event listener
  77076. // provided by each inside zoom.
  77077. zoomOnMouseWheel: true,
  77078. moveOnMouseMove: true,
  77079. moveOnMouseWheel: true,
  77080. preventDefaultMouseMove: !!preventDefaultMouseMove
  77081. }
  77082. };
  77083. }
  77084. function installDataZoomRoamProcessor(registers) {
  77085. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  77086. var apiInner = inner$k(api);
  77087. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  77088. coordSysRecordMap.each(function (coordSysRecord) {
  77089. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  77090. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  77091. coordSysRecord.dataZoomInfoMap = null;
  77092. });
  77093. ecModel.eachComponent({
  77094. mainType: 'dataZoom',
  77095. subType: 'inside'
  77096. }, function (dataZoomModel) {
  77097. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  77098. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  77099. var coordSysUid = dzCoordSysInfo.model.uid;
  77100. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  77101. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  77102. dataZoomInfoMap.set(dataZoomModel.uid, {
  77103. dzReferCoordSysInfo: dzCoordSysInfo,
  77104. model: dataZoomModel,
  77105. getRange: null
  77106. });
  77107. });
  77108. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  77109. // (2) Clear coord sys if not refered by any dataZoom.
  77110. coordSysRecordMap.each(function (coordSysRecord) {
  77111. var controller = coordSysRecord.controller;
  77112. var firstDzInfo;
  77113. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  77114. if (dataZoomInfoMap) {
  77115. var firstDzKey = dataZoomInfoMap.keys()[0];
  77116. if (firstDzKey != null) {
  77117. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  77118. }
  77119. }
  77120. if (!firstDzInfo) {
  77121. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  77122. return;
  77123. }
  77124. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  77125. controller.enable(controllerParams.controlType, controllerParams.opt);
  77126. controller.setPointerChecker(coordSysRecord.containsPoint);
  77127. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  77128. });
  77129. });
  77130. }
  77131. var InsideZoomView =
  77132. /** @class */
  77133. function (_super) {
  77134. __extends(InsideZoomView, _super);
  77135. function InsideZoomView() {
  77136. var _this = _super !== null && _super.apply(this, arguments) || this;
  77137. _this.type = 'dataZoom.inside';
  77138. return _this;
  77139. }
  77140. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  77141. _super.prototype.render.apply(this, arguments);
  77142. if (dataZoomModel.noTarget()) {
  77143. this._clear();
  77144. return;
  77145. } // Hence the `throttle` util ensures to preserve command order,
  77146. // here simply updating range all the time will not cause missing
  77147. // any of the the roam change.
  77148. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  77149. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  77150. pan: bind(getRangeHandlers.pan, this),
  77151. zoom: bind(getRangeHandlers.zoom, this),
  77152. scrollMove: bind(getRangeHandlers.scrollMove, this)
  77153. });
  77154. };
  77155. InsideZoomView.prototype.dispose = function () {
  77156. this._clear();
  77157. _super.prototype.dispose.apply(this, arguments);
  77158. };
  77159. InsideZoomView.prototype._clear = function () {
  77160. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  77161. this.range = null;
  77162. };
  77163. InsideZoomView.type = 'dataZoom.inside';
  77164. return InsideZoomView;
  77165. }(DataZoomView);
  77166. var getRangeHandlers = {
  77167. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  77168. var lastRange = this.range;
  77169. var range = lastRange.slice(); // Calculate transform by the first axis.
  77170. var axisModel = coordSysInfo.axisModels[0];
  77171. if (!axisModel) {
  77172. return;
  77173. }
  77174. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  77175. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  77176. var scale = Math.max(1 / e.scale, 0);
  77177. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  77178. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  77179. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77180. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  77181. this.range = range;
  77182. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  77183. return range;
  77184. }
  77185. },
  77186. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  77187. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  77188. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  77189. }),
  77190. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  77191. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  77192. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  77193. })
  77194. };
  77195. function makeMover(getPercentDelta) {
  77196. return function (coordSysInfo, coordSysMainType, controller, e) {
  77197. var lastRange = this.range;
  77198. var range = lastRange.slice(); // Calculate transform by the first axis.
  77199. var axisModel = coordSysInfo.axisModels[0];
  77200. if (!axisModel) {
  77201. return;
  77202. }
  77203. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  77204. sliderMove(percentDelta, range, [0, 100], 'all');
  77205. this.range = range;
  77206. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  77207. return range;
  77208. }
  77209. };
  77210. }
  77211. var getDirectionInfo = {
  77212. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77213. var axis = axisModel.axis;
  77214. var ret = {};
  77215. var rect = coordSysInfo.model.coordinateSystem.getRect();
  77216. oldPoint = oldPoint || [0, 0];
  77217. if (axis.dim === 'x') {
  77218. ret.pixel = newPoint[0] - oldPoint[0];
  77219. ret.pixelLength = rect.width;
  77220. ret.pixelStart = rect.x;
  77221. ret.signal = axis.inverse ? 1 : -1;
  77222. } else {
  77223. // axis.dim === 'y'
  77224. ret.pixel = newPoint[1] - oldPoint[1];
  77225. ret.pixelLength = rect.height;
  77226. ret.pixelStart = rect.y;
  77227. ret.signal = axis.inverse ? -1 : 1;
  77228. }
  77229. return ret;
  77230. },
  77231. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77232. var axis = axisModel.axis;
  77233. var ret = {};
  77234. var polar = coordSysInfo.model.coordinateSystem;
  77235. var radiusExtent = polar.getRadiusAxis().getExtent();
  77236. var angleExtent = polar.getAngleAxis().getExtent();
  77237. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  77238. newPoint = polar.pointToCoord(newPoint);
  77239. if (axisModel.mainType === 'radiusAxis') {
  77240. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  77241. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  77242. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  77243. ret.pixelStart = radiusExtent[0];
  77244. ret.signal = axis.inverse ? 1 : -1;
  77245. } else {
  77246. // 'angleAxis'
  77247. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  77248. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  77249. ret.pixelLength = angleExtent[1] - angleExtent[0];
  77250. ret.pixelStart = angleExtent[0];
  77251. ret.signal = axis.inverse ? -1 : 1;
  77252. }
  77253. return ret;
  77254. },
  77255. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77256. var axis = axisModel.axis;
  77257. var rect = coordSysInfo.model.coordinateSystem.getRect();
  77258. var ret = {};
  77259. oldPoint = oldPoint || [0, 0];
  77260. if (axis.orient === 'horizontal') {
  77261. ret.pixel = newPoint[0] - oldPoint[0];
  77262. ret.pixelLength = rect.width;
  77263. ret.pixelStart = rect.x;
  77264. ret.signal = axis.inverse ? 1 : -1;
  77265. } else {
  77266. // 'vertical'
  77267. ret.pixel = newPoint[1] - oldPoint[1];
  77268. ret.pixelLength = rect.height;
  77269. ret.pixelStart = rect.y;
  77270. ret.signal = axis.inverse ? -1 : 1;
  77271. }
  77272. return ret;
  77273. }
  77274. };
  77275. function install$K(registers) {
  77276. installCommon(registers);
  77277. registers.registerComponentModel(InsideZoomModel);
  77278. registers.registerComponentView(InsideZoomView);
  77279. installDataZoomRoamProcessor(registers);
  77280. }
  77281. var SliderZoomModel =
  77282. /** @class */
  77283. function (_super) {
  77284. __extends(SliderZoomModel, _super);
  77285. function SliderZoomModel() {
  77286. var _this = _super !== null && _super.apply(this, arguments) || this;
  77287. _this.type = SliderZoomModel.type;
  77288. return _this;
  77289. }
  77290. SliderZoomModel.type = 'dataZoom.slider';
  77291. SliderZoomModel.layoutMode = 'box';
  77292. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  77293. show: true,
  77294. // deault value can only be drived in view stage.
  77295. right: 'ph',
  77296. top: 'ph',
  77297. width: 'ph',
  77298. height: 'ph',
  77299. left: null,
  77300. bottom: null,
  77301. borderColor: '#d2dbee',
  77302. borderRadius: 3,
  77303. backgroundColor: 'rgba(47,69,84,0)',
  77304. // dataBackgroundColor: '#ddd',
  77305. dataBackground: {
  77306. lineStyle: {
  77307. color: '#d2dbee',
  77308. width: 0.5
  77309. },
  77310. areaStyle: {
  77311. color: '#d2dbee',
  77312. opacity: 0.2
  77313. }
  77314. },
  77315. selectedDataBackground: {
  77316. lineStyle: {
  77317. color: '#8fb0f7',
  77318. width: 0.5
  77319. },
  77320. areaStyle: {
  77321. color: '#8fb0f7',
  77322. opacity: 0.2
  77323. }
  77324. },
  77325. // Color of selected window.
  77326. fillerColor: 'rgba(135,175,274,0.2)',
  77327. 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',
  77328. // Percent of the slider height
  77329. handleSize: '100%',
  77330. handleStyle: {
  77331. color: '#fff',
  77332. borderColor: '#ACB8D1'
  77333. },
  77334. moveHandleSize: 7,
  77335. 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',
  77336. moveHandleStyle: {
  77337. color: '#D2DBEE',
  77338. opacity: 0.7
  77339. },
  77340. showDetail: true,
  77341. showDataShadow: 'auto',
  77342. realtime: true,
  77343. zoomLock: false,
  77344. textStyle: {
  77345. color: '#6E7079'
  77346. },
  77347. brushSelect: true,
  77348. brushStyle: {
  77349. color: 'rgba(135,175,274,0.15)'
  77350. },
  77351. emphasis: {
  77352. handleStyle: {
  77353. borderColor: '#8FB0F7'
  77354. },
  77355. moveHandleStyle: {
  77356. color: '#8FB0F7'
  77357. }
  77358. }
  77359. });
  77360. return SliderZoomModel;
  77361. }(DataZoomModel);
  77362. var Rect$2 = Rect; // Constants
  77363. var DEFAULT_LOCATION_EDGE_GAP = 7;
  77364. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  77365. var DEFAULT_FILLER_SIZE = 30;
  77366. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  77367. var HORIZONTAL = 'horizontal';
  77368. var VERTICAL = 'vertical';
  77369. var LABEL_GAP = 5;
  77370. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  77371. var REALTIME_ANIMATION_CONFIG = {
  77372. easing: 'cubicOut',
  77373. duration: 100,
  77374. delay: 0
  77375. };
  77376. var SliderZoomView =
  77377. /** @class */
  77378. function (_super) {
  77379. __extends(SliderZoomView, _super);
  77380. function SliderZoomView() {
  77381. var _this = _super !== null && _super.apply(this, arguments) || this;
  77382. _this.type = SliderZoomView.type;
  77383. _this._displayables = {};
  77384. return _this;
  77385. }
  77386. SliderZoomView.prototype.init = function (ecModel, api) {
  77387. this.api = api; // A unique handler for each dataZoom component
  77388. this._onBrush = bind(this._onBrush, this);
  77389. this._onBrushEnd = bind(this._onBrushEnd, this);
  77390. };
  77391. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  77392. _super.prototype.render.apply(this, arguments);
  77393. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  77394. this._orient = dataZoomModel.getOrient();
  77395. if (dataZoomModel.get('show') === false) {
  77396. this.group.removeAll();
  77397. return;
  77398. }
  77399. if (dataZoomModel.noTarget()) {
  77400. this._clear();
  77401. this.group.removeAll();
  77402. return;
  77403. } // Notice: this._resetInterval() should not be executed when payload.type
  77404. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  77405. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  77406. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  77407. this._buildView();
  77408. }
  77409. this._updateView();
  77410. };
  77411. SliderZoomView.prototype.dispose = function () {
  77412. this._clear();
  77413. _super.prototype.dispose.apply(this, arguments);
  77414. };
  77415. SliderZoomView.prototype._clear = function () {
  77416. clear(this, '_dispatchZoomAction');
  77417. var zr = this.api.getZr();
  77418. zr.off('mousemove', this._onBrush);
  77419. zr.off('mouseup', this._onBrushEnd);
  77420. };
  77421. SliderZoomView.prototype._buildView = function () {
  77422. var thisGroup = this.group;
  77423. thisGroup.removeAll();
  77424. this._brushing = false;
  77425. this._displayables.brushRect = null;
  77426. this._resetLocation();
  77427. this._resetInterval();
  77428. var barGroup = this._displayables.sliderGroup = new Group();
  77429. this._renderBackground();
  77430. this._renderHandle();
  77431. this._renderDataShadow();
  77432. thisGroup.add(barGroup);
  77433. this._positionGroup();
  77434. };
  77435. SliderZoomView.prototype._resetLocation = function () {
  77436. var dataZoomModel = this.dataZoomModel;
  77437. var api = this.api;
  77438. var showMoveHandle = dataZoomModel.get('brushSelect');
  77439. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  77440. // auto-adapt according to target grid.
  77441. var coordRect = this._findCoordRect();
  77442. var ecSize = {
  77443. width: api.getWidth(),
  77444. height: api.getHeight()
  77445. }; // Default align by coordinate system rect.
  77446. var positionInfo = this._orient === HORIZONTAL ? {
  77447. // Why using 'right', because right should be used in vertical,
  77448. // and it is better to be consistent for dealing with position param merge.
  77449. right: ecSize.width - coordRect.x - coordRect.width,
  77450. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  77451. width: coordRect.width,
  77452. height: DEFAULT_FILLER_SIZE
  77453. } : {
  77454. right: DEFAULT_LOCATION_EDGE_GAP,
  77455. top: coordRect.y,
  77456. width: DEFAULT_FILLER_SIZE,
  77457. height: coordRect.height
  77458. }; // Do not write back to option and replace value 'ph', because
  77459. // the 'ph' value should be recalculated when resize.
  77460. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  77461. each(['right', 'top', 'width', 'height'], function (name) {
  77462. if (layoutParams[name] === 'ph') {
  77463. layoutParams[name] = positionInfo[name];
  77464. }
  77465. });
  77466. var layoutRect = getLayoutRect(layoutParams, ecSize);
  77467. this._location = {
  77468. x: layoutRect.x,
  77469. y: layoutRect.y
  77470. };
  77471. this._size = [layoutRect.width, layoutRect.height];
  77472. this._orient === VERTICAL && this._size.reverse();
  77473. };
  77474. SliderZoomView.prototype._positionGroup = function () {
  77475. var thisGroup = this.group;
  77476. var location = this._location;
  77477. var orient = this._orient; // Just use the first axis to determine mapping.
  77478. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  77479. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  77480. var sliderGroup = this._displayables.sliderGroup;
  77481. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  77482. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  77483. scaleY: otherAxisInverse ? 1 : -1,
  77484. scaleX: 1
  77485. } : orient === HORIZONTAL && inverse ? {
  77486. scaleY: otherAxisInverse ? 1 : -1,
  77487. scaleX: -1
  77488. } : orient === VERTICAL && !inverse ? {
  77489. scaleY: otherAxisInverse ? -1 : 1,
  77490. scaleX: 1,
  77491. rotation: Math.PI / 2
  77492. } // Don't use Math.PI, considering shadow direction.
  77493. : {
  77494. scaleY: otherAxisInverse ? -1 : 1,
  77495. scaleX: -1,
  77496. rotation: Math.PI / 2
  77497. }); // Position barGroup
  77498. var rect = thisGroup.getBoundingRect([sliderGroup]);
  77499. thisGroup.x = location.x - rect.x;
  77500. thisGroup.y = location.y - rect.y;
  77501. thisGroup.markRedraw();
  77502. };
  77503. SliderZoomView.prototype._getViewExtent = function () {
  77504. return [0, this._size[0]];
  77505. };
  77506. SliderZoomView.prototype._renderBackground = function () {
  77507. var dataZoomModel = this.dataZoomModel;
  77508. var size = this._size;
  77509. var barGroup = this._displayables.sliderGroup;
  77510. var brushSelect = dataZoomModel.get('brushSelect');
  77511. barGroup.add(new Rect$2({
  77512. silent: true,
  77513. shape: {
  77514. x: 0,
  77515. y: 0,
  77516. width: size[0],
  77517. height: size[1]
  77518. },
  77519. style: {
  77520. fill: dataZoomModel.get('backgroundColor')
  77521. },
  77522. z2: -40
  77523. })); // Click panel, over shadow, below handles.
  77524. var clickPanel = new Rect$2({
  77525. shape: {
  77526. x: 0,
  77527. y: 0,
  77528. width: size[0],
  77529. height: size[1]
  77530. },
  77531. style: {
  77532. fill: 'transparent'
  77533. },
  77534. z2: 0,
  77535. onclick: bind(this._onClickPanel, this)
  77536. });
  77537. var zr = this.api.getZr();
  77538. if (brushSelect) {
  77539. clickPanel.on('mousedown', this._onBrushStart, this);
  77540. clickPanel.cursor = 'crosshair';
  77541. zr.on('mousemove', this._onBrush);
  77542. zr.on('mouseup', this._onBrushEnd);
  77543. } else {
  77544. zr.off('mousemove', this._onBrush);
  77545. zr.off('mouseup', this._onBrushEnd);
  77546. }
  77547. barGroup.add(clickPanel);
  77548. };
  77549. SliderZoomView.prototype._renderDataShadow = function () {
  77550. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  77551. this._displayables.dataShadowSegs = [];
  77552. if (!info) {
  77553. return;
  77554. }
  77555. var size = this._size;
  77556. var oldSize = this._shadowSize || [];
  77557. var seriesModel = info.series;
  77558. var data = seriesModel.getRawData();
  77559. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  77560. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  77561. : info.otherDim;
  77562. if (otherDim == null) {
  77563. return;
  77564. }
  77565. var polygonPts = this._shadowPolygonPts;
  77566. var polylinePts = this._shadowPolylinePts; // Not re-render if data doesn't change.
  77567. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  77568. var otherDataExtent_1 = data.getDataExtent(otherDim); // Nice extent.
  77569. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  77570. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  77571. var otherShadowExtent_1 = [0, size[1]];
  77572. var thisShadowExtent = [0, size[0]];
  77573. var areaPoints_1 = [[size[0], 0], [0, 0]];
  77574. var linePoints_1 = [];
  77575. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  77576. var thisCoord_1 = 0; // Optimize for large data shadow
  77577. var stride_1 = Math.round(data.count() / size[0]);
  77578. var lastIsEmpty_1;
  77579. data.each([otherDim], function (value, index) {
  77580. if (stride_1 > 0 && index % stride_1) {
  77581. thisCoord_1 += step_1;
  77582. return;
  77583. } // FIXME
  77584. // Should consider axis.min/axis.max when drawing dataShadow.
  77585. // FIXME
  77586. // 应该使用统一的空判断?还是在list里进行空判断?
  77587. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  77588. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true); // Attempt to draw data shadow precisely when there are empty value.
  77589. if (isEmpty && !lastIsEmpty_1 && index) {
  77590. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  77591. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  77592. } else if (!isEmpty && lastIsEmpty_1) {
  77593. areaPoints_1.push([thisCoord_1, 0]);
  77594. linePoints_1.push([thisCoord_1, 0]);
  77595. }
  77596. areaPoints_1.push([thisCoord_1, otherCoord]);
  77597. linePoints_1.push([thisCoord_1, otherCoord]);
  77598. thisCoord_1 += step_1;
  77599. lastIsEmpty_1 = isEmpty;
  77600. });
  77601. polygonPts = this._shadowPolygonPts = areaPoints_1;
  77602. polylinePts = this._shadowPolylinePts = linePoints_1;
  77603. }
  77604. this._shadowData = data;
  77605. this._shadowDim = otherDim;
  77606. this._shadowSize = [size[0], size[1]];
  77607. var dataZoomModel = this.dataZoomModel;
  77608. function createDataShadowGroup(isSelectedArea) {
  77609. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  77610. var group = new Group();
  77611. var polygon = new Polygon({
  77612. shape: {
  77613. points: polygonPts
  77614. },
  77615. segmentIgnoreThreshold: 1,
  77616. style: model.getModel('areaStyle').getAreaStyle(),
  77617. silent: true,
  77618. z2: -20
  77619. });
  77620. var polyline = new Polyline({
  77621. shape: {
  77622. points: polylinePts
  77623. },
  77624. segmentIgnoreThreshold: 1,
  77625. style: model.getModel('lineStyle').getLineStyle(),
  77626. silent: true,
  77627. z2: -19
  77628. });
  77629. group.add(polygon);
  77630. group.add(polyline);
  77631. return group;
  77632. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  77633. for (var i = 0; i < 3; i++) {
  77634. var group = createDataShadowGroup(i === 1);
  77635. this._displayables.sliderGroup.add(group);
  77636. this._displayables.dataShadowSegs.push(group);
  77637. }
  77638. };
  77639. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  77640. var dataZoomModel = this.dataZoomModel;
  77641. var showDataShadow = dataZoomModel.get('showDataShadow');
  77642. if (showDataShadow === false) {
  77643. return;
  77644. } // Find a representative series.
  77645. var result;
  77646. var ecModel = this.ecModel;
  77647. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  77648. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  77649. each(seriesModels, function (seriesModel) {
  77650. if (result) {
  77651. return;
  77652. }
  77653. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  77654. return;
  77655. }
  77656. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  77657. var otherDim = getOtherDim(axisDim);
  77658. var otherAxisInverse;
  77659. var coordSys = seriesModel.coordinateSystem;
  77660. if (otherDim != null && coordSys.getOtherAxis) {
  77661. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  77662. }
  77663. otherDim = seriesModel.getData().mapDimension(otherDim);
  77664. result = {
  77665. thisAxis: thisAxis,
  77666. series: seriesModel,
  77667. thisDim: axisDim,
  77668. otherDim: otherDim,
  77669. otherAxisInverse: otherAxisInverse
  77670. };
  77671. }, this);
  77672. }, this);
  77673. return result;
  77674. };
  77675. SliderZoomView.prototype._renderHandle = function () {
  77676. var thisGroup = this.group;
  77677. var displayables = this._displayables;
  77678. var handles = displayables.handles = [null, null];
  77679. var handleLabels = displayables.handleLabels = [null, null];
  77680. var sliderGroup = this._displayables.sliderGroup;
  77681. var size = this._size;
  77682. var dataZoomModel = this.dataZoomModel;
  77683. var api = this.api;
  77684. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  77685. var brushSelect = dataZoomModel.get('brushSelect');
  77686. var filler = displayables.filler = new Rect$2({
  77687. silent: brushSelect,
  77688. style: {
  77689. fill: dataZoomModel.get('fillerColor')
  77690. },
  77691. textConfig: {
  77692. position: 'inside'
  77693. }
  77694. });
  77695. sliderGroup.add(filler); // Frame border.
  77696. sliderGroup.add(new Rect$2({
  77697. silent: true,
  77698. subPixelOptimize: true,
  77699. shape: {
  77700. x: 0,
  77701. y: 0,
  77702. width: size[0],
  77703. height: size[1],
  77704. r: borderRadius
  77705. },
  77706. style: {
  77707. // deprecated option
  77708. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  77709. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  77710. fill: 'rgba(0,0,0,0)'
  77711. }
  77712. })); // Left and right handle to resize
  77713. each([0, 1], function (handleIndex) {
  77714. var iconStr = dataZoomModel.get('handleIcon');
  77715. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  77716. // Compatitable with the old icon parsers. Which can use a path string without path://
  77717. iconStr = 'path://' + iconStr;
  77718. if ("development" !== 'production') {
  77719. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  77720. }
  77721. }
  77722. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  77723. path.attr({
  77724. cursor: getCursor(this._orient),
  77725. draggable: true,
  77726. drift: bind(this._onDragMove, this, handleIndex),
  77727. ondragend: bind(this._onDragEnd, this),
  77728. onmouseover: bind(this._showDataInfo, this, true),
  77729. onmouseout: bind(this._showDataInfo, this, false),
  77730. z2: 5
  77731. });
  77732. var bRect = path.getBoundingRect();
  77733. var handleSize = dataZoomModel.get('handleSize');
  77734. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  77735. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  77736. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  77737. path.style.strokeNoScale = true;
  77738. path.rectHover = true;
  77739. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  77740. enableHoverEmphasis(path);
  77741. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  77742. // Compatitable with previous version
  77743. if (handleColor != null) {
  77744. path.style.fill = handleColor;
  77745. }
  77746. sliderGroup.add(handles[handleIndex] = path);
  77747. var textStyleModel = dataZoomModel.getModel('textStyle');
  77748. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  77749. silent: true,
  77750. invisible: true,
  77751. style: createTextStyle(textStyleModel, {
  77752. x: 0,
  77753. y: 0,
  77754. text: '',
  77755. verticalAlign: 'middle',
  77756. align: 'center',
  77757. fill: textStyleModel.getTextColor(),
  77758. font: textStyleModel.getFont()
  77759. }),
  77760. z2: 10
  77761. }));
  77762. }, this); // Handle to move. Only visible when brushSelect is set true.
  77763. var actualMoveZone = filler;
  77764. if (brushSelect) {
  77765. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  77766. var moveHandle_1 = displayables.moveHandle = new Rect({
  77767. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  77768. silent: true,
  77769. shape: {
  77770. r: [0, 0, 2, 2],
  77771. y: size[1] - 0.5,
  77772. height: moveHandleHeight
  77773. }
  77774. });
  77775. var iconSize = moveHandleHeight * 0.8;
  77776. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  77777. moveHandleIcon.silent = true;
  77778. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  77779. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  77780. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  77781. actualMoveZone = displayables.moveZone = new Rect({
  77782. invisible: true,
  77783. shape: {
  77784. y: size[1] - moveZoneExpandSize,
  77785. height: moveHandleHeight + moveZoneExpandSize
  77786. }
  77787. });
  77788. actualMoveZone.on('mouseover', function () {
  77789. api.enterEmphasis(moveHandle_1);
  77790. }).on('mouseout', function () {
  77791. api.leaveEmphasis(moveHandle_1);
  77792. });
  77793. sliderGroup.add(moveHandle_1);
  77794. sliderGroup.add(moveHandleIcon);
  77795. sliderGroup.add(actualMoveZone);
  77796. }
  77797. actualMoveZone.attr({
  77798. draggable: true,
  77799. cursor: getCursor(this._orient),
  77800. drift: bind(this._onDragMove, this, 'all'),
  77801. ondragstart: bind(this._showDataInfo, this, true),
  77802. ondragend: bind(this._onDragEnd, this),
  77803. onmouseover: bind(this._showDataInfo, this, true),
  77804. onmouseout: bind(this._showDataInfo, this, false)
  77805. });
  77806. };
  77807. SliderZoomView.prototype._resetInterval = function () {
  77808. var range = this._range = this.dataZoomModel.getPercentRange();
  77809. var viewExtent = this._getViewExtent();
  77810. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  77811. };
  77812. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  77813. var dataZoomModel = this.dataZoomModel;
  77814. var handleEnds = this._handleEnds;
  77815. var viewExtend = this._getViewExtent();
  77816. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77817. var percentExtent = [0, 100];
  77818. 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);
  77819. var lastRange = this._range;
  77820. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  77821. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  77822. };
  77823. SliderZoomView.prototype._updateView = function (nonRealtime) {
  77824. var displaybles = this._displayables;
  77825. var handleEnds = this._handleEnds;
  77826. var handleInterval = asc(handleEnds.slice());
  77827. var size = this._size;
  77828. each([0, 1], function (handleIndex) {
  77829. // Handles
  77830. var handle = displaybles.handles[handleIndex];
  77831. var handleHeight = this._handleHeight;
  77832. handle.attr({
  77833. scaleX: handleHeight / 2,
  77834. scaleY: handleHeight / 2,
  77835. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  77836. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  77837. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  77838. y: size[1] / 2 - handleHeight / 2
  77839. });
  77840. }, this); // Filler
  77841. displaybles.filler.setShape({
  77842. x: handleInterval[0],
  77843. y: 0,
  77844. width: handleInterval[1] - handleInterval[0],
  77845. height: size[1]
  77846. });
  77847. var viewExtent = {
  77848. x: handleInterval[0],
  77849. width: handleInterval[1] - handleInterval[0]
  77850. }; // Move handle
  77851. if (displaybles.moveHandle) {
  77852. displaybles.moveHandle.setShape(viewExtent);
  77853. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  77854. displaybles.moveZone.getBoundingRect();
  77855. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  77856. } // update clip path of shadow.
  77857. var dataShadowSegs = displaybles.dataShadowSegs;
  77858. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  77859. for (var i = 0; i < dataShadowSegs.length; i++) {
  77860. var segGroup = dataShadowSegs[i];
  77861. var clipPath = segGroup.getClipPath();
  77862. if (!clipPath) {
  77863. clipPath = new Rect();
  77864. segGroup.setClipPath(clipPath);
  77865. }
  77866. clipPath.setShape({
  77867. x: segIntervals[i],
  77868. y: 0,
  77869. width: segIntervals[i + 1] - segIntervals[i],
  77870. height: size[1]
  77871. });
  77872. }
  77873. this._updateDataInfo(nonRealtime);
  77874. };
  77875. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  77876. var dataZoomModel = this.dataZoomModel;
  77877. var displaybles = this._displayables;
  77878. var handleLabels = displaybles.handleLabels;
  77879. var orient = this._orient;
  77880. var labelTexts = ['', '']; // FIXME
  77881. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  77882. if (dataZoomModel.get('showDetail')) {
  77883. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  77884. if (axisProxy) {
  77885. var axis = axisProxy.getAxisModel().axis;
  77886. var range = this._range;
  77887. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  77888. ? axisProxy.calculateDataWindow({
  77889. start: range[0],
  77890. end: range[1]
  77891. }).valueWindow : axisProxy.getDataValueWindow();
  77892. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  77893. }
  77894. }
  77895. var orderedHandleEnds = asc(this._handleEnds.slice());
  77896. setLabel.call(this, 0);
  77897. setLabel.call(this, 1);
  77898. function setLabel(handleIndex) {
  77899. // Label
  77900. // Text should not transform by barGroup.
  77901. // Ignore handlers transform
  77902. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  77903. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  77904. var offset = this._handleWidth / 2 + LABEL_GAP;
  77905. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  77906. handleLabels[handleIndex].setStyle({
  77907. x: textPoint[0],
  77908. y: textPoint[1],
  77909. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  77910. align: orient === HORIZONTAL ? direction : 'center',
  77911. text: labelTexts[handleIndex]
  77912. });
  77913. }
  77914. };
  77915. SliderZoomView.prototype._formatLabel = function (value, axis) {
  77916. var dataZoomModel = this.dataZoomModel;
  77917. var labelFormatter = dataZoomModel.get('labelFormatter');
  77918. var labelPrecision = dataZoomModel.get('labelPrecision');
  77919. if (labelPrecision == null || labelPrecision === 'auto') {
  77920. labelPrecision = axis.getPixelPrecision();
  77921. }
  77922. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  77923. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  77924. value: Math.round(value)
  77925. }) // param of toFixed should less then 20.
  77926. : value.toFixed(Math.min(labelPrecision, 20));
  77927. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  77928. };
  77929. /**
  77930. * @param showOrHide true: show, false: hide
  77931. */
  77932. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  77933. // Always show when drgging.
  77934. showOrHide = this._dragging || showOrHide;
  77935. var displayables = this._displayables;
  77936. var handleLabels = displayables.handleLabels;
  77937. handleLabels[0].attr('invisible', !showOrHide);
  77938. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  77939. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  77940. };
  77941. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  77942. this._dragging = true; // For mobile device, prevent screen slider on the button.
  77943. stop(event.event); // Transform dx, dy to bar coordination.
  77944. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  77945. var vertex = applyTransform$1([dx, dy], barTransform, true);
  77946. var changed = this._updateInterval(handleIndex, vertex[0]);
  77947. var realtime = this.dataZoomModel.get('realtime');
  77948. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  77949. // which cause bad visual effect when progressive enabled.
  77950. changed && realtime && this._dispatchZoomAction(true);
  77951. };
  77952. SliderZoomView.prototype._onDragEnd = function () {
  77953. this._dragging = false;
  77954. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  77955. // drag end will cause the whole view rerender, which is unnecessary.
  77956. var realtime = this.dataZoomModel.get('realtime');
  77957. !realtime && this._dispatchZoomAction(false);
  77958. };
  77959. SliderZoomView.prototype._onClickPanel = function (e) {
  77960. var size = this._size;
  77961. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  77962. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  77963. return;
  77964. }
  77965. var handleEnds = this._handleEnds;
  77966. var center = (handleEnds[0] + handleEnds[1]) / 2;
  77967. var changed = this._updateInterval('all', localPoint[0] - center);
  77968. this._updateView();
  77969. changed && this._dispatchZoomAction(false);
  77970. };
  77971. SliderZoomView.prototype._onBrushStart = function (e) {
  77972. var x = e.offsetX;
  77973. var y = e.offsetY;
  77974. this._brushStart = new Point(x, y);
  77975. this._brushing = true;
  77976. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  77977. };
  77978. SliderZoomView.prototype._onBrushEnd = function (e) {
  77979. if (!this._brushing) {
  77980. return;
  77981. }
  77982. var brushRect = this._displayables.brushRect;
  77983. this._brushing = false;
  77984. if (!brushRect) {
  77985. return;
  77986. }
  77987. brushRect.attr('ignore', true);
  77988. var brushShape = brushRect.shape;
  77989. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  77990. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  77991. // Will treat it as a click
  77992. return;
  77993. }
  77994. var viewExtend = this._getViewExtent();
  77995. var percentExtent = [0, 100];
  77996. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  77997. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  77998. this._updateView();
  77999. this._dispatchZoomAction(false);
  78000. };
  78001. SliderZoomView.prototype._onBrush = function (e) {
  78002. if (this._brushing) {
  78003. // For mobile device, prevent screen slider on the button.
  78004. stop(e.event);
  78005. this._updateBrushRect(e.offsetX, e.offsetY);
  78006. }
  78007. };
  78008. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  78009. var displayables = this._displayables;
  78010. var dataZoomModel = this.dataZoomModel;
  78011. var brushRect = displayables.brushRect;
  78012. if (!brushRect) {
  78013. brushRect = displayables.brushRect = new Rect$2({
  78014. silent: true,
  78015. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  78016. });
  78017. displayables.sliderGroup.add(brushRect);
  78018. }
  78019. brushRect.attr('ignore', false);
  78020. var brushStart = this._brushStart;
  78021. var sliderGroup = this._displayables.sliderGroup;
  78022. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  78023. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  78024. var size = this._size;
  78025. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  78026. brushRect.setShape({
  78027. x: startPoint[0],
  78028. y: 0,
  78029. width: endPoint[0] - startPoint[0],
  78030. height: size[1]
  78031. });
  78032. };
  78033. /**
  78034. * This action will be throttled.
  78035. */
  78036. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  78037. var range = this._range;
  78038. this.api.dispatchAction({
  78039. type: 'dataZoom',
  78040. from: this.uid,
  78041. dataZoomId: this.dataZoomModel.id,
  78042. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  78043. start: range[0],
  78044. end: range[1]
  78045. });
  78046. };
  78047. SliderZoomView.prototype._findCoordRect = function () {
  78048. // Find the grid corresponding to the first axis referred by dataZoom.
  78049. var rect;
  78050. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  78051. if (!rect && coordSysInfoList.length) {
  78052. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  78053. rect = coordSys.getRect && coordSys.getRect();
  78054. }
  78055. if (!rect) {
  78056. var width = this.api.getWidth();
  78057. var height = this.api.getHeight();
  78058. rect = {
  78059. x: width * 0.2,
  78060. y: height * 0.2,
  78061. width: width * 0.6,
  78062. height: height * 0.6
  78063. };
  78064. }
  78065. return rect;
  78066. };
  78067. SliderZoomView.type = 'dataZoom.slider';
  78068. return SliderZoomView;
  78069. }(DataZoomView);
  78070. function getOtherDim(thisDim) {
  78071. // FIXME
  78072. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  78073. var map = {
  78074. x: 'y',
  78075. y: 'x',
  78076. radius: 'angle',
  78077. angle: 'radius'
  78078. };
  78079. return map[thisDim];
  78080. }
  78081. function getCursor(orient) {
  78082. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  78083. }
  78084. function install$L(registers) {
  78085. registers.registerComponentModel(SliderZoomModel);
  78086. registers.registerComponentView(SliderZoomView);
  78087. installCommon(registers);
  78088. }
  78089. function install$M(registers) {
  78090. use(install$K);
  78091. use(install$L); // Do not install './dataZoomSelect',
  78092. // since it only work for toolbox dataZoom.
  78093. }
  78094. var visualDefault = {
  78095. /**
  78096. * @public
  78097. */
  78098. get: function (visualType, key, isCategory) {
  78099. var value = clone((defaultOption$1[visualType] || {})[key]);
  78100. return isCategory ? isArray(value) ? value[value.length - 1] : value : value;
  78101. }
  78102. };
  78103. var defaultOption$1 = {
  78104. color: {
  78105. active: ['#006edd', '#e0ffff'],
  78106. inactive: ['rgba(0,0,0,0)']
  78107. },
  78108. colorHue: {
  78109. active: [0, 360],
  78110. inactive: [0, 0]
  78111. },
  78112. colorSaturation: {
  78113. active: [0.3, 1],
  78114. inactive: [0, 0]
  78115. },
  78116. colorLightness: {
  78117. active: [0.9, 0.5],
  78118. inactive: [0, 0]
  78119. },
  78120. colorAlpha: {
  78121. active: [0.3, 1],
  78122. inactive: [0, 0]
  78123. },
  78124. opacity: {
  78125. active: [0.3, 1],
  78126. inactive: [0, 0]
  78127. },
  78128. symbol: {
  78129. active: ['circle', 'roundRect', 'diamond'],
  78130. inactive: ['none']
  78131. },
  78132. symbolSize: {
  78133. active: [10, 50],
  78134. inactive: [0, 0]
  78135. }
  78136. };
  78137. var mapVisual$1 = VisualMapping.mapVisual;
  78138. var eachVisual = VisualMapping.eachVisual;
  78139. var isArray$1 = isArray;
  78140. var each$d = each;
  78141. var asc$2 = asc;
  78142. var linearMap$1 = linearMap;
  78143. var VisualMapModel =
  78144. /** @class */
  78145. function (_super) {
  78146. __extends(VisualMapModel, _super);
  78147. function VisualMapModel() {
  78148. var _this = _super !== null && _super.apply(this, arguments) || this;
  78149. _this.type = VisualMapModel.type;
  78150. _this.stateList = ['inRange', 'outOfRange'];
  78151. _this.replacableOptionKeys = ['inRange', 'outOfRange', 'target', 'controller', 'color'];
  78152. _this.layoutMode = {
  78153. type: 'box',
  78154. ignoreSize: true
  78155. };
  78156. /**
  78157. * [lowerBound, upperBound]
  78158. */
  78159. _this.dataBound = [-Infinity, Infinity];
  78160. _this.targetVisuals = {};
  78161. _this.controllerVisuals = {};
  78162. return _this;
  78163. }
  78164. VisualMapModel.prototype.init = function (option, parentModel, ecModel) {
  78165. this.mergeDefaultAndTheme(option, ecModel);
  78166. };
  78167. /**
  78168. * @protected
  78169. */
  78170. VisualMapModel.prototype.optionUpdated = function (newOption, isInit) {
  78171. var thisOption = this.option;
  78172. !isInit && replaceVisualOption(thisOption, newOption, this.replacableOptionKeys);
  78173. this.textStyleModel = this.getModel('textStyle');
  78174. this.resetItemSize();
  78175. this.completeVisualOption();
  78176. };
  78177. /**
  78178. * @protected
  78179. */
  78180. VisualMapModel.prototype.resetVisual = function (supplementVisualOption) {
  78181. var stateList = this.stateList;
  78182. supplementVisualOption = bind(supplementVisualOption, this);
  78183. this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption);
  78184. this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption);
  78185. };
  78186. /**
  78187. * @public
  78188. */
  78189. VisualMapModel.prototype.getItemSymbol = function () {
  78190. return null;
  78191. };
  78192. /**
  78193. * @protected
  78194. * @return {Array.<number>} An array of series indices.
  78195. */
  78196. VisualMapModel.prototype.getTargetSeriesIndices = function () {
  78197. var optionSeriesIndex = this.option.seriesIndex;
  78198. var seriesIndices = [];
  78199. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  78200. this.ecModel.eachSeries(function (seriesModel, index) {
  78201. seriesIndices.push(index);
  78202. });
  78203. } else {
  78204. seriesIndices = normalizeToArray(optionSeriesIndex);
  78205. }
  78206. return seriesIndices;
  78207. };
  78208. /**
  78209. * @public
  78210. */
  78211. VisualMapModel.prototype.eachTargetSeries = function (callback, context) {
  78212. each(this.getTargetSeriesIndices(), function (seriesIndex) {
  78213. var seriesModel = this.ecModel.getSeriesByIndex(seriesIndex);
  78214. if (seriesModel) {
  78215. callback.call(context, seriesModel);
  78216. }
  78217. }, this);
  78218. };
  78219. /**
  78220. * @pubilc
  78221. */
  78222. VisualMapModel.prototype.isTargetSeries = function (seriesModel) {
  78223. var is = false;
  78224. this.eachTargetSeries(function (model) {
  78225. model === seriesModel && (is = true);
  78226. });
  78227. return is;
  78228. };
  78229. /**
  78230. * @example
  78231. * this.formatValueText(someVal); // format single numeric value to text.
  78232. * this.formatValueText(someVal, true); // format single category value to text.
  78233. * this.formatValueText([min, max]); // format numeric min-max to text.
  78234. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  78235. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  78236. *
  78237. * @param value Real value, or this.dataBound[0 or 1].
  78238. * @param isCategory Only available when value is number.
  78239. * @param edgeSymbols Open-close symbol when value is interval.
  78240. * @protected
  78241. */
  78242. VisualMapModel.prototype.formatValueText = function (value, isCategory, edgeSymbols) {
  78243. var option = this.option;
  78244. var precision = option.precision;
  78245. var dataBound = this.dataBound;
  78246. var formatter = option.formatter;
  78247. var isMinMax;
  78248. edgeSymbols = edgeSymbols || ['<', '>'];
  78249. if (isArray(value)) {
  78250. value = value.slice();
  78251. isMinMax = true;
  78252. }
  78253. var textValue = isCategory ? value // Value is string when isCategory
  78254. : isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value);
  78255. if (isString(formatter)) {
  78256. return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue);
  78257. } else if (isFunction(formatter)) {
  78258. return isMinMax ? formatter(value[0], value[1]) : formatter(value);
  78259. }
  78260. if (isMinMax) {
  78261. if (value[0] === dataBound[0]) {
  78262. return edgeSymbols[0] + ' ' + textValue[1];
  78263. } else if (value[1] === dataBound[1]) {
  78264. return edgeSymbols[1] + ' ' + textValue[0];
  78265. } else {
  78266. return textValue[0] + ' - ' + textValue[1];
  78267. }
  78268. } else {
  78269. // Format single value (includes category case).
  78270. return textValue;
  78271. }
  78272. function toFixed(val) {
  78273. return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20));
  78274. }
  78275. };
  78276. /**
  78277. * @protected
  78278. */
  78279. VisualMapModel.prototype.resetExtent = function () {
  78280. var thisOption = this.option; // Can not calculate data extent by data here.
  78281. // Because series and data may be modified in processing stage.
  78282. // So we do not support the feature "auto min/max".
  78283. var extent = asc$2([thisOption.min, thisOption.max]);
  78284. this._dataExtent = extent;
  78285. };
  78286. /**
  78287. * PENDING:
  78288. * delete this method if no outer usage.
  78289. *
  78290. * Return Concrete dimension. If null/undefined is returned, no dimension is used.
  78291. */
  78292. // getDataDimension(data: SeriesData) {
  78293. // const optDim = this.option.dimension;
  78294. // if (optDim != null) {
  78295. // return data.getDimension(optDim);
  78296. // }
  78297. // const dimNames = data.dimensions;
  78298. // for (let i = dimNames.length - 1; i >= 0; i--) {
  78299. // const dimName = dimNames[i];
  78300. // const dimInfo = data.getDimensionInfo(dimName);
  78301. // if (!dimInfo.isCalculationCoord) {
  78302. // return dimName;
  78303. // }
  78304. // }
  78305. // }
  78306. VisualMapModel.prototype.getDataDimensionIndex = function (data) {
  78307. var optDim = this.option.dimension;
  78308. if (optDim != null) {
  78309. return data.getDimensionIndex(optDim);
  78310. }
  78311. var dimNames = data.dimensions;
  78312. for (var i = dimNames.length - 1; i >= 0; i--) {
  78313. var dimName = dimNames[i];
  78314. var dimInfo = data.getDimensionInfo(dimName);
  78315. if (!dimInfo.isCalculationCoord) {
  78316. return dimInfo.storeDimIndex;
  78317. }
  78318. }
  78319. };
  78320. VisualMapModel.prototype.getExtent = function () {
  78321. return this._dataExtent.slice();
  78322. };
  78323. VisualMapModel.prototype.completeVisualOption = function () {
  78324. var ecModel = this.ecModel;
  78325. var thisOption = this.option;
  78326. var base = {
  78327. inRange: thisOption.inRange,
  78328. outOfRange: thisOption.outOfRange
  78329. };
  78330. var target = thisOption.target || (thisOption.target = {});
  78331. var controller = thisOption.controller || (thisOption.controller = {});
  78332. merge(target, base); // Do not override
  78333. merge(controller, base); // Do not override
  78334. var isCategory = this.isCategory();
  78335. completeSingle.call(this, target);
  78336. completeSingle.call(this, controller);
  78337. completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange');
  78338. completeController.call(this, controller);
  78339. function completeSingle(base) {
  78340. // Compatible with ec2 dataRange.color.
  78341. // The mapping order of dataRange.color is: [high value, ..., low value]
  78342. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  78343. // Notice: ec2 has no inverse.
  78344. if (isArray$1(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake.
  78345. // So adding color only when no inRange defined.
  78346. && !base.inRange) {
  78347. base.inRange = {
  78348. color: thisOption.color.slice().reverse()
  78349. };
  78350. } // Compatible with previous logic, always give a default color, otherwise
  78351. // simple config with no inRange and outOfRange will not work.
  78352. // Originally we use visualMap.color as the default color, but setOption at
  78353. // the second time the default color will be erased. So we change to use
  78354. // constant DEFAULT_COLOR.
  78355. // If user do not want the default color, set inRange: {color: null}.
  78356. base.inRange = base.inRange || {
  78357. color: ecModel.get('gradientColor')
  78358. };
  78359. }
  78360. function completeInactive(base, stateExist, stateAbsent) {
  78361. var optExist = base[stateExist];
  78362. var optAbsent = base[stateAbsent];
  78363. if (optExist && !optAbsent) {
  78364. optAbsent = base[stateAbsent] = {};
  78365. each$d(optExist, function (visualData, visualType) {
  78366. if (!VisualMapping.isValidType(visualType)) {
  78367. return;
  78368. }
  78369. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  78370. if (defa != null) {
  78371. optAbsent[visualType] = defa; // Compatibable with ec2:
  78372. // Only inactive color to rgba(0,0,0,0) can not
  78373. // make label transparent, so use opacity also.
  78374. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha')) {
  78375. optAbsent.opacity = [0, 0];
  78376. }
  78377. }
  78378. });
  78379. }
  78380. }
  78381. function completeController(controller) {
  78382. var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol;
  78383. var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize;
  78384. var inactiveColor = this.get('inactiveColor');
  78385. var itemSymbol = this.getItemSymbol();
  78386. var defaultSymbol = itemSymbol || 'roundRect';
  78387. each$d(this.stateList, function (state) {
  78388. var itemSize = this.itemSize;
  78389. var visuals = controller[state]; // Set inactive color for controller if no other color
  78390. // attr (like colorAlpha) specified.
  78391. if (!visuals) {
  78392. visuals = controller[state] = {
  78393. color: isCategory ? inactiveColor : [inactiveColor]
  78394. };
  78395. } // Consistent symbol and symbolSize if not specified.
  78396. if (visuals.symbol == null) {
  78397. visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? defaultSymbol : [defaultSymbol]);
  78398. }
  78399. if (visuals.symbolSize == null) {
  78400. visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  78401. } // Filter none
  78402. visuals.symbol = mapVisual$1(visuals.symbol, function (symbol) {
  78403. return symbol === 'none' ? defaultSymbol : symbol;
  78404. }); // Normalize symbolSize
  78405. var symbolSize = visuals.symbolSize;
  78406. if (symbolSize != null) {
  78407. var max_1 = -Infinity; // symbolSize can be object when categories defined.
  78408. eachVisual(symbolSize, function (value) {
  78409. value > max_1 && (max_1 = value);
  78410. });
  78411. visuals.symbolSize = mapVisual$1(symbolSize, function (value) {
  78412. return linearMap$1(value, [0, max_1], [0, itemSize[0]], true);
  78413. });
  78414. }
  78415. }, this);
  78416. }
  78417. };
  78418. VisualMapModel.prototype.resetItemSize = function () {
  78419. this.itemSize = [parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight'))];
  78420. };
  78421. VisualMapModel.prototype.isCategory = function () {
  78422. return !!this.option.categories;
  78423. };
  78424. /**
  78425. * @public
  78426. * @abstract
  78427. */
  78428. VisualMapModel.prototype.setSelected = function (selected) {};
  78429. VisualMapModel.prototype.getSelected = function () {
  78430. return null;
  78431. };
  78432. /**
  78433. * @public
  78434. * @abstract
  78435. */
  78436. VisualMapModel.prototype.getValueState = function (value) {
  78437. return null;
  78438. };
  78439. /**
  78440. * FIXME
  78441. * Do not publish to thirt-part-dev temporarily
  78442. * util the interface is stable. (Should it return
  78443. * a function but not visual meta?)
  78444. *
  78445. * @pubilc
  78446. * @abstract
  78447. * @param getColorVisual
  78448. * params: value, valueState
  78449. * return: color
  78450. * @return {Object} visualMeta
  78451. * should includes {stops, outerColors}
  78452. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  78453. */
  78454. VisualMapModel.prototype.getVisualMeta = function (getColorVisual) {
  78455. return null;
  78456. };
  78457. VisualMapModel.type = 'visualMap';
  78458. VisualMapModel.dependencies = ['series'];
  78459. VisualMapModel.defaultOption = {
  78460. show: true,
  78461. // zlevel: 0,
  78462. z: 4,
  78463. seriesIndex: 'all',
  78464. min: 0,
  78465. max: 200,
  78466. left: 0,
  78467. right: null,
  78468. top: null,
  78469. bottom: 0,
  78470. itemWidth: null,
  78471. itemHeight: null,
  78472. inverse: false,
  78473. orient: 'vertical',
  78474. backgroundColor: 'rgba(0,0,0,0)',
  78475. borderColor: '#ccc',
  78476. contentColor: '#5793f3',
  78477. inactiveColor: '#aaa',
  78478. borderWidth: 0,
  78479. padding: 5,
  78480. // 接受数组分别设定上右下左边距,同css
  78481. textGap: 10,
  78482. precision: 0,
  78483. textStyle: {
  78484. color: '#333' // 值域文字颜色
  78485. }
  78486. };
  78487. return VisualMapModel;
  78488. }(ComponentModel);
  78489. var DEFAULT_BAR_BOUND = [20, 140];
  78490. var ContinuousModel =
  78491. /** @class */
  78492. function (_super) {
  78493. __extends(ContinuousModel, _super);
  78494. function ContinuousModel() {
  78495. var _this = _super !== null && _super.apply(this, arguments) || this;
  78496. _this.type = ContinuousModel.type;
  78497. return _this;
  78498. }
  78499. /**
  78500. * @override
  78501. */
  78502. ContinuousModel.prototype.optionUpdated = function (newOption, isInit) {
  78503. _super.prototype.optionUpdated.apply(this, arguments);
  78504. this.resetExtent();
  78505. this.resetVisual(function (mappingOption) {
  78506. mappingOption.mappingMethod = 'linear';
  78507. mappingOption.dataExtent = this.getExtent();
  78508. });
  78509. this._resetRange();
  78510. };
  78511. /**
  78512. * @protected
  78513. * @override
  78514. */
  78515. ContinuousModel.prototype.resetItemSize = function () {
  78516. _super.prototype.resetItemSize.apply(this, arguments);
  78517. var itemSize = this.itemSize;
  78518. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  78519. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  78520. };
  78521. /**
  78522. * @private
  78523. */
  78524. ContinuousModel.prototype._resetRange = function () {
  78525. var dataExtent = this.getExtent();
  78526. var range = this.option.range;
  78527. if (!range || range.auto) {
  78528. // `range` should always be array (so we don't use other
  78529. // value like 'auto') for user-friend. (consider getOption).
  78530. dataExtent.auto = 1;
  78531. this.option.range = dataExtent;
  78532. } else if (isArray(range)) {
  78533. if (range[0] > range[1]) {
  78534. range.reverse();
  78535. }
  78536. range[0] = Math.max(range[0], dataExtent[0]);
  78537. range[1] = Math.min(range[1], dataExtent[1]);
  78538. }
  78539. };
  78540. /**
  78541. * @protected
  78542. * @override
  78543. */
  78544. ContinuousModel.prototype.completeVisualOption = function () {
  78545. _super.prototype.completeVisualOption.apply(this, arguments);
  78546. each(this.stateList, function (state) {
  78547. var symbolSize = this.option.controller[state].symbolSize;
  78548. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  78549. symbolSize[0] = symbolSize[1] / 3; // For good looking.
  78550. }
  78551. }, this);
  78552. };
  78553. /**
  78554. * @override
  78555. */
  78556. ContinuousModel.prototype.setSelected = function (selected) {
  78557. this.option.range = selected.slice();
  78558. this._resetRange();
  78559. };
  78560. /**
  78561. * @public
  78562. */
  78563. ContinuousModel.prototype.getSelected = function () {
  78564. var dataExtent = this.getExtent();
  78565. var dataInterval = asc((this.get('range') || []).slice()); // Clamp
  78566. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  78567. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  78568. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  78569. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  78570. return dataInterval;
  78571. };
  78572. /**
  78573. * @override
  78574. */
  78575. ContinuousModel.prototype.getValueState = function (value) {
  78576. var range = this.option.range;
  78577. var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  78578. // range[1] is processed likewise.
  78579. return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange';
  78580. };
  78581. ContinuousModel.prototype.findTargetDataIndices = function (range) {
  78582. var result = [];
  78583. this.eachTargetSeries(function (seriesModel) {
  78584. var dataIndices = [];
  78585. var data = seriesModel.getData();
  78586. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  78587. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  78588. }, this);
  78589. result.push({
  78590. seriesId: seriesModel.id,
  78591. dataIndex: dataIndices
  78592. });
  78593. }, this);
  78594. return result;
  78595. };
  78596. /**
  78597. * @implement
  78598. */
  78599. ContinuousModel.prototype.getVisualMeta = function (getColorVisual) {
  78600. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  78601. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  78602. var stops = [];
  78603. function setStop(value, valueState) {
  78604. stops.push({
  78605. value: value,
  78606. color: getColorVisual(value, valueState)
  78607. });
  78608. } // Format to: outOfRange -- inRange -- outOfRange.
  78609. var iIdx = 0;
  78610. var oIdx = 0;
  78611. var iLen = iVals.length;
  78612. var oLen = oVals.length;
  78613. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  78614. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  78615. if (oVals[oIdx] < iVals[iIdx]) {
  78616. setStop(oVals[oIdx], 'outOfRange');
  78617. }
  78618. }
  78619. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  78620. // If range is full, value beyond min, max will be clamped.
  78621. // make a singularity
  78622. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  78623. setStop(iVals[iIdx], 'inRange');
  78624. }
  78625. for (var first = 1; oIdx < oLen; oIdx++) {
  78626. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  78627. // make a singularity
  78628. if (first) {
  78629. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  78630. first = 0;
  78631. }
  78632. setStop(oVals[oIdx], 'outOfRange');
  78633. }
  78634. }
  78635. var stopsLen = stops.length;
  78636. return {
  78637. stops: stops,
  78638. outerColors: [stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent']
  78639. };
  78640. };
  78641. ContinuousModel.type = 'visualMap.continuous';
  78642. ContinuousModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  78643. align: 'auto',
  78644. calculable: false,
  78645. hoverLink: true,
  78646. realtime: true,
  78647. handleIcon: 'path://M-11.39,9.77h0a3.5,3.5,0,0,1-3.5,3.5h-22a3.5,3.5,0,0,1-3.5-3.5h0a3.5,3.5,0,0,1,3.5-3.5h22A3.5,3.5,0,0,1-11.39,9.77Z',
  78648. handleSize: '120%',
  78649. handleStyle: {
  78650. borderColor: '#fff',
  78651. borderWidth: 1
  78652. },
  78653. indicatorIcon: 'circle',
  78654. indicatorSize: '50%',
  78655. indicatorStyle: {
  78656. borderColor: '#fff',
  78657. borderWidth: 2,
  78658. shadowBlur: 2,
  78659. shadowOffsetX: 1,
  78660. shadowOffsetY: 1,
  78661. shadowColor: 'rgba(0,0,0,0.2)'
  78662. } // emphasis: {
  78663. // handleStyle: {
  78664. // shadowBlur: 3,
  78665. // shadowOffsetX: 1,
  78666. // shadowOffsetY: 1,
  78667. // shadowColor: 'rgba(0,0,0,0.2)'
  78668. // }
  78669. // }
  78670. });
  78671. return ContinuousModel;
  78672. }(VisualMapModel);
  78673. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  78674. if (dataExtent[0] === dataExtent[1]) {
  78675. return dataExtent.slice();
  78676. } // When using colorHue mapping, it is not linear color any more.
  78677. // Moreover, canvas gradient seems not to be accurate linear.
  78678. // FIXME
  78679. // Should be arbitrary value 100? or based on pixel size?
  78680. var count = 200;
  78681. var step = (dataExtent[1] - dataExtent[0]) / count;
  78682. var value = dataExtent[0];
  78683. var stopValues = [];
  78684. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  78685. stopValues.push(value);
  78686. value += step;
  78687. }
  78688. stopValues.push(dataExtent[1]);
  78689. return stopValues;
  78690. }
  78691. var VisualMapView =
  78692. /** @class */
  78693. function (_super) {
  78694. __extends(VisualMapView, _super);
  78695. function VisualMapView() {
  78696. var _this = _super !== null && _super.apply(this, arguments) || this;
  78697. _this.type = VisualMapView.type;
  78698. _this.autoPositionValues = {
  78699. left: 1,
  78700. right: 1,
  78701. top: 1,
  78702. bottom: 1
  78703. };
  78704. return _this;
  78705. }
  78706. VisualMapView.prototype.init = function (ecModel, api) {
  78707. this.ecModel = ecModel;
  78708. this.api = api;
  78709. };
  78710. /**
  78711. * @protected
  78712. */
  78713. VisualMapView.prototype.render = function (visualMapModel, ecModel, api, payload // TODO: TYPE
  78714. ) {
  78715. this.visualMapModel = visualMapModel;
  78716. if (visualMapModel.get('show') === false) {
  78717. this.group.removeAll();
  78718. return;
  78719. }
  78720. this.doRender(visualMapModel, ecModel, api, payload);
  78721. };
  78722. /**
  78723. * @protected
  78724. */
  78725. VisualMapView.prototype.renderBackground = function (group) {
  78726. var visualMapModel = this.visualMapModel;
  78727. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  78728. var rect = group.getBoundingRect();
  78729. group.add(new Rect({
  78730. z2: -1,
  78731. silent: true,
  78732. shape: {
  78733. x: rect.x - padding[3],
  78734. y: rect.y - padding[0],
  78735. width: rect.width + padding[3] + padding[1],
  78736. height: rect.height + padding[0] + padding[2]
  78737. },
  78738. style: {
  78739. fill: visualMapModel.get('backgroundColor'),
  78740. stroke: visualMapModel.get('borderColor'),
  78741. lineWidth: visualMapModel.get('borderWidth')
  78742. }
  78743. }));
  78744. };
  78745. /**
  78746. * @protected
  78747. * @param targetValue can be Infinity or -Infinity
  78748. * @param visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  78749. * @param opts
  78750. * @param opts.forceState Specify state, instead of using getValueState method.
  78751. * @param opts.convertOpacityToAlpha For color gradient in controller widget.
  78752. * @return {*} Visual value.
  78753. */
  78754. VisualMapView.prototype.getControllerVisual = function (targetValue, visualCluster, opts) {
  78755. opts = opts || {};
  78756. var forceState = opts.forceState;
  78757. var visualMapModel = this.visualMapModel;
  78758. var visualObj = {}; // Default values.
  78759. if (visualCluster === 'color') {
  78760. var defaultColor = visualMapModel.get('contentColor');
  78761. visualObj.color = defaultColor;
  78762. }
  78763. function getter(key) {
  78764. return visualObj[key];
  78765. }
  78766. function setter(key, value) {
  78767. visualObj[key] = value;
  78768. }
  78769. var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)];
  78770. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  78771. each(visualTypes, function (type) {
  78772. var visualMapping = mappings[type];
  78773. if (opts.convertOpacityToAlpha && type === 'opacity') {
  78774. type = 'colorAlpha';
  78775. visualMapping = mappings.__alphaForOpacity;
  78776. }
  78777. if (VisualMapping.dependsOn(type, visualCluster)) {
  78778. visualMapping && visualMapping.applyVisual(targetValue, getter, setter);
  78779. }
  78780. });
  78781. return visualObj[visualCluster];
  78782. };
  78783. VisualMapView.prototype.positionGroup = function (group) {
  78784. var model = this.visualMapModel;
  78785. var api = this.api;
  78786. positionElement(group, model.getBoxLayoutParams(), {
  78787. width: api.getWidth(),
  78788. height: api.getHeight()
  78789. });
  78790. };
  78791. VisualMapView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {};
  78792. VisualMapView.type = 'visualMap';
  78793. return VisualMapView;
  78794. }(ComponentView);
  78795. var paramsSet = [['left', 'right', 'width'], ['top', 'bottom', 'height']];
  78796. /**
  78797. * @param visualMapModel
  78798. * @param api
  78799. * @param itemSize always [short, long]
  78800. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  78801. */
  78802. function getItemAlign(visualMapModel, api, itemSize) {
  78803. var modelOption = visualMapModel.option;
  78804. var itemAlign = modelOption.align;
  78805. if (itemAlign != null && itemAlign !== 'auto') {
  78806. return itemAlign;
  78807. } // Auto decision align.
  78808. var ecSize = {
  78809. width: api.getWidth(),
  78810. height: api.getHeight()
  78811. };
  78812. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  78813. var reals = paramsSet[realIndex];
  78814. var fakeValue = [0, null, 10];
  78815. var layoutInput = {};
  78816. for (var i = 0; i < 3; i++) {
  78817. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  78818. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  78819. }
  78820. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  78821. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  78822. return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1];
  78823. }
  78824. /**
  78825. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  78826. * dataIndexInside means filtered index.
  78827. */
  78828. // TODO: TYPE more specified payload types.
  78829. function makeHighDownBatch(batch, visualMapModel) {
  78830. each(batch || [], function (batchItem) {
  78831. if (batchItem.dataIndex != null) {
  78832. batchItem.dataIndexInside = batchItem.dataIndex;
  78833. batchItem.dataIndex = null;
  78834. }
  78835. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  78836. });
  78837. return batch;
  78838. }
  78839. var linearMap$2 = linearMap;
  78840. var each$e = each;
  78841. var mathMin$a = Math.min;
  78842. var mathMax$a = Math.max; // Arbitrary value
  78843. var HOVER_LINK_SIZE = 12;
  78844. var HOVER_LINK_OUT = 6; // Notice:
  78845. // Any "interval" should be by the order of [low, high].
  78846. // "handle0" (handleIndex === 0) maps to
  78847. // low data value: this._dataInterval[0] and has low coord.
  78848. // "handle1" (handleIndex === 1) maps to
  78849. // high data value: this._dataInterval[1] and has high coord.
  78850. // The logic of transform is implemented in this._createBarGroup.
  78851. var ContinuousView =
  78852. /** @class */
  78853. function (_super) {
  78854. __extends(ContinuousView, _super);
  78855. function ContinuousView() {
  78856. var _this = _super !== null && _super.apply(this, arguments) || this;
  78857. _this.type = ContinuousView.type;
  78858. _this._shapes = {};
  78859. _this._dataInterval = [];
  78860. _this._handleEnds = [];
  78861. _this._hoverLinkDataIndices = [];
  78862. return _this;
  78863. }
  78864. ContinuousView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {
  78865. this._api = api;
  78866. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  78867. this._buildView();
  78868. }
  78869. };
  78870. ContinuousView.prototype._buildView = function () {
  78871. this.group.removeAll();
  78872. var visualMapModel = this.visualMapModel;
  78873. var thisGroup = this.group;
  78874. this._orient = visualMapModel.get('orient');
  78875. this._useHandle = visualMapModel.get('calculable');
  78876. this._resetInterval();
  78877. this._renderBar(thisGroup);
  78878. var dataRangeText = visualMapModel.get('text');
  78879. this._renderEndsText(thisGroup, dataRangeText, 0);
  78880. this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation.
  78881. this._updateView(true); // After updating view, inner shapes is built completely,
  78882. // and then background can be rendered.
  78883. this.renderBackground(thisGroup); // Real update view
  78884. this._updateView();
  78885. this._enableHoverLinkToSeries();
  78886. this._enableHoverLinkFromSeries();
  78887. this.positionGroup(thisGroup);
  78888. };
  78889. ContinuousView.prototype._renderEndsText = function (group, dataRangeText, endsIndex) {
  78890. if (!dataRangeText) {
  78891. return;
  78892. } // Compatible with ec2, text[0] map to high value, text[1] map low value.
  78893. var text = dataRangeText[1 - endsIndex];
  78894. text = text != null ? text + '' : '';
  78895. var visualMapModel = this.visualMapModel;
  78896. var textGap = visualMapModel.get('textGap');
  78897. var itemSize = visualMapModel.itemSize;
  78898. var barGroup = this._shapes.mainGroup;
  78899. var position = this._applyTransform([itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap], barGroup);
  78900. var align = this._applyTransform(endsIndex === 0 ? 'bottom' : 'top', barGroup);
  78901. var orient = this._orient;
  78902. var textStyleModel = this.visualMapModel.textStyleModel;
  78903. this.group.add(new ZRText({
  78904. style: createTextStyle(textStyleModel, {
  78905. x: position[0],
  78906. y: position[1],
  78907. verticalAlign: orient === 'horizontal' ? 'middle' : align,
  78908. align: orient === 'horizontal' ? align : 'center',
  78909. text: text
  78910. })
  78911. }));
  78912. };
  78913. ContinuousView.prototype._renderBar = function (targetGroup) {
  78914. var visualMapModel = this.visualMapModel;
  78915. var shapes = this._shapes;
  78916. var itemSize = visualMapModel.itemSize;
  78917. var orient = this._orient;
  78918. var useHandle = this._useHandle;
  78919. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  78920. var mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign);
  78921. var gradientBarGroup = new Group();
  78922. mainGroup.add(gradientBarGroup); // Bar
  78923. gradientBarGroup.add(shapes.outOfRange = createPolygon());
  78924. gradientBarGroup.add(shapes.inRange = createPolygon(null, useHandle ? getCursor$1(this._orient) : null, bind(this._dragHandle, this, 'all', false), bind(this._dragHandle, this, 'all', true))); // A border radius clip.
  78925. gradientBarGroup.setClipPath(new Rect({
  78926. shape: {
  78927. x: 0,
  78928. y: 0,
  78929. width: itemSize[0],
  78930. height: itemSize[1],
  78931. r: 3
  78932. }
  78933. }));
  78934. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  78935. var textSize = mathMax$a(textRect.width, textRect.height); // Handle
  78936. if (useHandle) {
  78937. shapes.handleThumbs = [];
  78938. shapes.handleLabels = [];
  78939. shapes.handleLabelPoints = [];
  78940. this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient);
  78941. this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient);
  78942. }
  78943. this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient);
  78944. targetGroup.add(mainGroup);
  78945. };
  78946. ContinuousView.prototype._createHandle = function (visualMapModel, mainGroup, handleIndex, itemSize, textSize, orient) {
  78947. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  78948. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  78949. var handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]);
  78950. var handleThumb = createSymbol(visualMapModel.get('handleIcon'), -handleSize / 2, -handleSize / 2, handleSize, handleSize, null, true);
  78951. var cursor = getCursor$1(this._orient);
  78952. handleThumb.attr({
  78953. cursor: cursor,
  78954. draggable: true,
  78955. drift: onDrift,
  78956. ondragend: onDragEnd,
  78957. onmousemove: function (e) {
  78958. stop(e.event);
  78959. }
  78960. });
  78961. handleThumb.x = itemSize[0] / 2;
  78962. handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle());
  78963. handleThumb.setStyle({
  78964. strokeNoScale: true,
  78965. strokeFirst: true
  78966. });
  78967. handleThumb.style.lineWidth *= 2;
  78968. handleThumb.ensureState('emphasis').style = visualMapModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  78969. setAsHighDownDispatcher(handleThumb, true);
  78970. mainGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by
  78971. // transform (orient/inverse). So label is built separately but not
  78972. // use zrender/graphic/helper/RectText, and is located based on view
  78973. // group (according to handleLabelPoint) but not barGroup.
  78974. var textStyleModel = this.visualMapModel.textStyleModel;
  78975. var handleLabel = new ZRText({
  78976. cursor: cursor,
  78977. draggable: true,
  78978. drift: onDrift,
  78979. onmousemove: function (e) {
  78980. // For mobile device, prevent screen slider on the button.
  78981. stop(e.event);
  78982. },
  78983. ondragend: onDragEnd,
  78984. style: createTextStyle(textStyleModel, {
  78985. x: 0,
  78986. y: 0,
  78987. text: ''
  78988. })
  78989. });
  78990. handleLabel.ensureState('blur').style = {
  78991. opacity: 0.1
  78992. };
  78993. handleLabel.stateTransition = {
  78994. duration: 200
  78995. };
  78996. this.group.add(handleLabel);
  78997. var handleLabelPoint = [handleSize, 0];
  78998. var shapes = this._shapes;
  78999. shapes.handleThumbs[handleIndex] = handleThumb;
  79000. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  79001. shapes.handleLabels[handleIndex] = handleLabel;
  79002. };
  79003. ContinuousView.prototype._createIndicator = function (visualMapModel, mainGroup, itemSize, textSize, orient) {
  79004. var scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]);
  79005. var indicator = createSymbol(visualMapModel.get('indicatorIcon'), -scale / 2, -scale / 2, scale, scale, null, true);
  79006. indicator.attr({
  79007. cursor: 'move',
  79008. invisible: true,
  79009. silent: true,
  79010. x: itemSize[0] / 2
  79011. });
  79012. var indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle();
  79013. if (indicator instanceof ZRImage) {
  79014. var pathStyle = indicator.style;
  79015. indicator.useStyle(extend({
  79016. // TODO other properties like x, y ?
  79017. image: pathStyle.image,
  79018. x: pathStyle.x,
  79019. y: pathStyle.y,
  79020. width: pathStyle.width,
  79021. height: pathStyle.height
  79022. }, indicatorStyle));
  79023. } else {
  79024. indicator.useStyle(indicatorStyle);
  79025. }
  79026. mainGroup.add(indicator);
  79027. var textStyleModel = this.visualMapModel.textStyleModel;
  79028. var indicatorLabel = new ZRText({
  79029. silent: true,
  79030. invisible: true,
  79031. style: createTextStyle(textStyleModel, {
  79032. x: 0,
  79033. y: 0,
  79034. text: ''
  79035. })
  79036. });
  79037. this.group.add(indicatorLabel);
  79038. var indicatorLabelPoint = [(orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT) + itemSize[0] / 2, 0];
  79039. var shapes = this._shapes;
  79040. shapes.indicator = indicator;
  79041. shapes.indicatorLabel = indicatorLabel;
  79042. shapes.indicatorLabelPoint = indicatorLabelPoint;
  79043. this._firstShowIndicator = true;
  79044. };
  79045. ContinuousView.prototype._dragHandle = function (handleIndex, isEnd, // dx is event from ondragend if isEnd is true. It's not used
  79046. dx, dy) {
  79047. if (!this._useHandle) {
  79048. return;
  79049. }
  79050. this._dragging = !isEnd;
  79051. if (!isEnd) {
  79052. // Transform dx, dy to bar coordination.
  79053. var vertex = this._applyTransform([dx, dy], this._shapes.mainGroup, true);
  79054. this._updateInterval(handleIndex, vertex[1]);
  79055. this._hideIndicator(); // Considering realtime, update view should be executed
  79056. // before dispatch action.
  79057. this._updateView();
  79058. } // dragEnd do not dispatch action when realtime.
  79059. if (isEnd === !this.visualMapModel.get('realtime')) {
  79060. // jshint ignore:line
  79061. this.api.dispatchAction({
  79062. type: 'selectDataRange',
  79063. from: this.uid,
  79064. visualMapId: this.visualMapModel.id,
  79065. selected: this._dataInterval.slice()
  79066. });
  79067. }
  79068. if (isEnd) {
  79069. !this._hovering && this._clearHoverLinkToSeries();
  79070. } else if (useHoverLinkOnHandle(this.visualMapModel)) {
  79071. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  79072. }
  79073. };
  79074. ContinuousView.prototype._resetInterval = function () {
  79075. var visualMapModel = this.visualMapModel;
  79076. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  79077. var dataExtent = visualMapModel.getExtent();
  79078. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79079. this._handleEnds = [linearMap$2(dataInterval[0], dataExtent, sizeExtent, true), linearMap$2(dataInterval[1], dataExtent, sizeExtent, true)];
  79080. };
  79081. /**
  79082. * @private
  79083. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  79084. * @param {number} dx
  79085. * @param {number} dy
  79086. */
  79087. ContinuousView.prototype._updateInterval = function (handleIndex, delta) {
  79088. delta = delta || 0;
  79089. var visualMapModel = this.visualMapModel;
  79090. var handleEnds = this._handleEnds;
  79091. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79092. sliderMove(delta, handleEnds, sizeExtent, handleIndex, // cross is forbidden
  79093. 0);
  79094. var dataExtent = visualMapModel.getExtent(); // Update data interval.
  79095. this._dataInterval = [linearMap$2(handleEnds[0], sizeExtent, dataExtent, true), linearMap$2(handleEnds[1], sizeExtent, dataExtent, true)];
  79096. };
  79097. ContinuousView.prototype._updateView = function (forSketch) {
  79098. var visualMapModel = this.visualMapModel;
  79099. var dataExtent = visualMapModel.getExtent();
  79100. var shapes = this._shapes;
  79101. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  79102. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  79103. var visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange');
  79104. var visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange');
  79105. shapes.inRange.setStyle({
  79106. fill: visualInRange.barColor // opacity: visualInRange.opacity
  79107. }).setShape('points', visualInRange.barPoints);
  79108. shapes.outOfRange.setStyle({
  79109. fill: visualOutOfRange.barColor // opacity: visualOutOfRange.opacity
  79110. }).setShape('points', visualOutOfRange.barPoints);
  79111. this._updateHandle(inRangeHandleEnds, visualInRange);
  79112. };
  79113. ContinuousView.prototype._createBarVisual = function (dataInterval, dataExtent, handleEnds, forceState) {
  79114. var opts = {
  79115. forceState: forceState,
  79116. convertOpacityToAlpha: true
  79117. };
  79118. var colorStops = this._makeColorGradient(dataInterval, opts);
  79119. var symbolSizes = [this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts)];
  79120. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  79121. return {
  79122. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  79123. barPoints: barPoints,
  79124. handlesColor: [colorStops[0].color, colorStops[colorStops.length - 1].color]
  79125. };
  79126. };
  79127. ContinuousView.prototype._makeColorGradient = function (dataInterval, opts) {
  79128. // Considering colorHue, which is not linear, so we have to sample
  79129. // to calculate gradient color stops, but not only calculate head
  79130. // and tail.
  79131. var sampleNumber = 100; // Arbitrary value.
  79132. var colorStops = [];
  79133. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  79134. colorStops.push({
  79135. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  79136. offset: 0
  79137. });
  79138. for (var i = 1; i < sampleNumber; i++) {
  79139. var currValue = dataInterval[0] + step * i;
  79140. if (currValue > dataInterval[1]) {
  79141. break;
  79142. }
  79143. colorStops.push({
  79144. color: this.getControllerVisual(currValue, 'color', opts),
  79145. offset: i / sampleNumber
  79146. });
  79147. }
  79148. colorStops.push({
  79149. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  79150. offset: 1
  79151. });
  79152. return colorStops;
  79153. };
  79154. ContinuousView.prototype._createBarPoints = function (handleEnds, symbolSizes) {
  79155. var itemSize = this.visualMapModel.itemSize;
  79156. return [[itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]]];
  79157. };
  79158. ContinuousView.prototype._createBarGroup = function (itemAlign) {
  79159. var orient = this._orient;
  79160. var inverse = this.visualMapModel.get('inverse');
  79161. return new Group(orient === 'horizontal' && !inverse ? {
  79162. scaleX: itemAlign === 'bottom' ? 1 : -1,
  79163. rotation: Math.PI / 2
  79164. } : orient === 'horizontal' && inverse ? {
  79165. scaleX: itemAlign === 'bottom' ? -1 : 1,
  79166. rotation: -Math.PI / 2
  79167. } : orient === 'vertical' && !inverse ? {
  79168. scaleX: itemAlign === 'left' ? 1 : -1,
  79169. scaleY: -1
  79170. } : {
  79171. scaleX: itemAlign === 'left' ? 1 : -1
  79172. });
  79173. };
  79174. ContinuousView.prototype._updateHandle = function (handleEnds, visualInRange) {
  79175. if (!this._useHandle) {
  79176. return;
  79177. }
  79178. var shapes = this._shapes;
  79179. var visualMapModel = this.visualMapModel;
  79180. var handleThumbs = shapes.handleThumbs;
  79181. var handleLabels = shapes.handleLabels;
  79182. var itemSize = visualMapModel.itemSize;
  79183. var dataExtent = visualMapModel.getExtent();
  79184. each$e([0, 1], function (handleIndex) {
  79185. var handleThumb = handleThumbs[handleIndex];
  79186. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  79187. handleThumb.y = handleEnds[handleIndex];
  79188. var val = linearMap$2(handleEnds[handleIndex], [0, itemSize[1]], dataExtent, true);
  79189. var symbolSize = this.getControllerVisual(val, 'symbolSize');
  79190. handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0];
  79191. handleThumb.x = itemSize[0] - symbolSize / 2; // Update handle label position.
  79192. var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group));
  79193. handleLabels[handleIndex].setStyle({
  79194. x: textPoint[0],
  79195. y: textPoint[1],
  79196. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  79197. verticalAlign: 'middle',
  79198. align: this._orient === 'vertical' ? this._applyTransform('left', shapes.mainGroup) : 'center'
  79199. });
  79200. }, this);
  79201. };
  79202. ContinuousView.prototype._showIndicator = function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  79203. var visualMapModel = this.visualMapModel;
  79204. var dataExtent = visualMapModel.getExtent();
  79205. var itemSize = visualMapModel.itemSize;
  79206. var sizeExtent = [0, itemSize[1]];
  79207. var shapes = this._shapes;
  79208. var indicator = shapes.indicator;
  79209. if (!indicator) {
  79210. return;
  79211. }
  79212. indicator.attr('invisible', false);
  79213. var opts = {
  79214. convertOpacityToAlpha: true
  79215. };
  79216. var color = this.getControllerVisual(cursorValue, 'color', opts);
  79217. var symbolSize = this.getControllerVisual(cursorValue, 'symbolSize');
  79218. var y = linearMap$2(cursorValue, dataExtent, sizeExtent, true);
  79219. var x = itemSize[0] - symbolSize / 2;
  79220. var oldIndicatorPos = {
  79221. x: indicator.x,
  79222. y: indicator.y
  79223. }; // Update handle label position.
  79224. indicator.y = y;
  79225. indicator.x = x;
  79226. var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group));
  79227. var indicatorLabel = shapes.indicatorLabel;
  79228. indicatorLabel.attr('invisible', false);
  79229. var align = this._applyTransform('left', shapes.mainGroup);
  79230. var orient = this._orient;
  79231. var isHorizontal = orient === 'horizontal';
  79232. indicatorLabel.setStyle({
  79233. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  79234. verticalAlign: isHorizontal ? align : 'middle',
  79235. align: isHorizontal ? 'center' : align
  79236. });
  79237. var indicatorNewProps = {
  79238. x: x,
  79239. y: y,
  79240. style: {
  79241. fill: color
  79242. }
  79243. };
  79244. var labelNewProps = {
  79245. style: {
  79246. x: textPoint[0],
  79247. y: textPoint[1]
  79248. }
  79249. };
  79250. if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) {
  79251. var animationCfg = {
  79252. duration: 100,
  79253. easing: 'cubicInOut',
  79254. additive: true
  79255. };
  79256. indicator.x = oldIndicatorPos.x;
  79257. indicator.y = oldIndicatorPos.y;
  79258. indicator.animateTo(indicatorNewProps, animationCfg);
  79259. indicatorLabel.animateTo(labelNewProps, animationCfg);
  79260. } else {
  79261. indicator.attr(indicatorNewProps);
  79262. indicatorLabel.attr(labelNewProps);
  79263. }
  79264. this._firstShowIndicator = false;
  79265. var handleLabels = this._shapes.handleLabels;
  79266. if (handleLabels) {
  79267. for (var i = 0; i < handleLabels.length; i++) {
  79268. // Fade out handle labels.
  79269. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  79270. this._api.enterBlur(handleLabels[i]);
  79271. }
  79272. }
  79273. };
  79274. ContinuousView.prototype._enableHoverLinkToSeries = function () {
  79275. var self = this;
  79276. this._shapes.mainGroup.on('mousemove', function (e) {
  79277. self._hovering = true;
  79278. if (!self._dragging) {
  79279. var itemSize = self.visualMapModel.itemSize;
  79280. var pos = self._applyTransform([e.offsetX, e.offsetY], self._shapes.mainGroup, true, true); // For hover link show when hover handle, which might be
  79281. // below or upper than sizeExtent.
  79282. pos[1] = mathMin$a(mathMax$a(0, pos[1]), itemSize[1]);
  79283. self._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]);
  79284. }
  79285. }).on('mouseout', function () {
  79286. // When mouse is out of handle, hoverLink still need
  79287. // to be displayed when realtime is set as false.
  79288. self._hovering = false;
  79289. !self._dragging && self._clearHoverLinkToSeries();
  79290. });
  79291. };
  79292. ContinuousView.prototype._enableHoverLinkFromSeries = function () {
  79293. var zr = this.api.getZr();
  79294. if (this.visualMapModel.option.hoverLink) {
  79295. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  79296. zr.on('mouseout', this._hideIndicator, this);
  79297. } else {
  79298. this._clearHoverLinkFromSeries();
  79299. }
  79300. };
  79301. ContinuousView.prototype._doHoverLinkToSeries = function (cursorPos, hoverOnBar) {
  79302. var visualMapModel = this.visualMapModel;
  79303. var itemSize = visualMapModel.itemSize;
  79304. if (!visualMapModel.option.hoverLink) {
  79305. return;
  79306. }
  79307. var sizeExtent = [0, itemSize[1]];
  79308. var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent.
  79309. cursorPos = mathMin$a(mathMax$a(sizeExtent[0], cursorPos), sizeExtent[1]);
  79310. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  79311. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  79312. var cursorValue = linearMap$2(cursorPos, sizeExtent, dataExtent, true);
  79313. var valueRange = [linearMap$2(hoverRange[0], sizeExtent, dataExtent, true), linearMap$2(hoverRange[1], sizeExtent, dataExtent, true)]; // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  79314. // where china and india has very large population.
  79315. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  79316. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle,
  79317. // otherwise labels overlap, especially when dragging.
  79318. if (hoverOnBar) {
  79319. if (valueRange[0] === -Infinity) {
  79320. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  79321. } else if (valueRange[1] === Infinity) {
  79322. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  79323. } else {
  79324. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  79325. }
  79326. } // When realtime is set as false, handles, which are in barGroup,
  79327. // also trigger hoverLink, which help user to realize where they
  79328. // focus on when dragging. (see test/heatmap-large.html)
  79329. // When realtime is set as true, highlight will not show when hover
  79330. // handle, because the label on handle, which displays a exact value
  79331. // but not range, might mislead users.
  79332. var oldBatch = this._hoverLinkDataIndices;
  79333. var newBatch = [];
  79334. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  79335. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  79336. }
  79337. var resultBatches = compressBatches(oldBatch, newBatch);
  79338. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  79339. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  79340. };
  79341. ContinuousView.prototype._hoverLinkFromSeriesMouseOver = function (e) {
  79342. var ecData;
  79343. findEventDispatcher(e.target, function (target) {
  79344. var currECData = getECData(target);
  79345. if (currECData.dataIndex != null) {
  79346. ecData = currECData;
  79347. return true;
  79348. }
  79349. }, true);
  79350. if (!ecData) {
  79351. return;
  79352. }
  79353. var dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex);
  79354. var visualMapModel = this.visualMapModel;
  79355. if (!visualMapModel.isTargetSeries(dataModel)) {
  79356. return;
  79357. }
  79358. var data = dataModel.getData(ecData.dataType);
  79359. var value = data.getStore().get(visualMapModel.getDataDimensionIndex(data), ecData.dataIndex);
  79360. if (!isNaN(value)) {
  79361. this._showIndicator(value, value);
  79362. }
  79363. };
  79364. ContinuousView.prototype._hideIndicator = function () {
  79365. var shapes = this._shapes;
  79366. shapes.indicator && shapes.indicator.attr('invisible', true);
  79367. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  79368. var handleLabels = this._shapes.handleLabels;
  79369. if (handleLabels) {
  79370. for (var i = 0; i < handleLabels.length; i++) {
  79371. // Fade out handle labels.
  79372. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  79373. this._api.leaveBlur(handleLabels[i]);
  79374. }
  79375. }
  79376. };
  79377. ContinuousView.prototype._clearHoverLinkToSeries = function () {
  79378. this._hideIndicator();
  79379. var indices = this._hoverLinkDataIndices;
  79380. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  79381. indices.length = 0;
  79382. };
  79383. ContinuousView.prototype._clearHoverLinkFromSeries = function () {
  79384. this._hideIndicator();
  79385. var zr = this.api.getZr();
  79386. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  79387. zr.off('mouseout', this._hideIndicator);
  79388. };
  79389. ContinuousView.prototype._applyTransform = function (vertex, element, inverse, global) {
  79390. var transform = getTransform(element, global ? null : this.group);
  79391. return isArray(vertex) ? applyTransform$1(vertex, transform, inverse) : transformDirection(vertex, transform, inverse);
  79392. }; // TODO: TYPE more specified payload types.
  79393. ContinuousView.prototype._dispatchHighDown = function (type, batch) {
  79394. batch && batch.length && this.api.dispatchAction({
  79395. type: type,
  79396. batch: batch
  79397. });
  79398. };
  79399. /**
  79400. * @override
  79401. */
  79402. ContinuousView.prototype.dispose = function () {
  79403. this._clearHoverLinkFromSeries();
  79404. this._clearHoverLinkToSeries();
  79405. };
  79406. /**
  79407. * @override
  79408. */
  79409. ContinuousView.prototype.remove = function () {
  79410. this._clearHoverLinkFromSeries();
  79411. this._clearHoverLinkToSeries();
  79412. };
  79413. ContinuousView.type = 'visualMap.continuous';
  79414. return ContinuousView;
  79415. }(VisualMapView);
  79416. function createPolygon(points, cursor, onDrift, onDragEnd) {
  79417. return new Polygon({
  79418. shape: {
  79419. points: points
  79420. },
  79421. draggable: !!onDrift,
  79422. cursor: cursor,
  79423. drift: onDrift,
  79424. onmousemove: function (e) {
  79425. // For mobile device, prevent screen slider on the button.
  79426. stop(e.event);
  79427. },
  79428. ondragend: onDragEnd
  79429. });
  79430. }
  79431. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  79432. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  79433. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  79434. if (hoverLinkDataSize) {
  79435. halfHoverLinkSize = linearMap$2(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  79436. }
  79437. return halfHoverLinkSize;
  79438. }
  79439. function useHoverLinkOnHandle(visualMapModel) {
  79440. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  79441. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  79442. }
  79443. function getCursor$1(orient) {
  79444. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  79445. }
  79446. /*
  79447. * Licensed to the Apache Software Foundation (ASF) under one
  79448. * or more contributor license agreements. See the NOTICE file
  79449. * distributed with this work for additional information
  79450. * regarding copyright ownership. The ASF licenses this file
  79451. * to you under the Apache License, Version 2.0 (the
  79452. * "License"); you may not use this file except in compliance
  79453. * with the License. You may obtain a copy of the License at
  79454. *
  79455. * http://www.apache.org/licenses/LICENSE-2.0
  79456. *
  79457. * Unless required by applicable law or agreed to in writing,
  79458. * software distributed under the License is distributed on an
  79459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79460. * KIND, either express or implied. See the License for the
  79461. * specific language governing permissions and limitations
  79462. * under the License.
  79463. */
  79464. /**
  79465. * AUTO-GENERATED FILE. DO NOT MODIFY.
  79466. */
  79467. /*
  79468. * Licensed to the Apache Software Foundation (ASF) under one
  79469. * or more contributor license agreements. See the NOTICE file
  79470. * distributed with this work for additional information
  79471. * regarding copyright ownership. The ASF licenses this file
  79472. * to you under the Apache License, Version 2.0 (the
  79473. * "License"); you may not use this file except in compliance
  79474. * with the License. You may obtain a copy of the License at
  79475. *
  79476. * http://www.apache.org/licenses/LICENSE-2.0
  79477. *
  79478. * Unless required by applicable law or agreed to in writing,
  79479. * software distributed under the License is distributed on an
  79480. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79481. * KIND, either express or implied. See the License for the
  79482. * specific language governing permissions and limitations
  79483. * under the License.
  79484. */
  79485. var visualMapActionInfo = {
  79486. type: 'selectDataRange',
  79487. event: 'dataRangeSelected',
  79488. // FIXME use updateView appears wrong
  79489. update: 'update'
  79490. };
  79491. var visualMapActionHander = function (payload, ecModel) {
  79492. ecModel.eachComponent({
  79493. mainType: 'visualMap',
  79494. query: payload
  79495. }, function (model) {
  79496. model.setSelected(payload.selected);
  79497. });
  79498. };
  79499. var visualMapEncodingHandlers = [{
  79500. createOnAllSeries: true,
  79501. reset: function (seriesModel, ecModel) {
  79502. var resetDefines = [];
  79503. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79504. var pipelineContext = seriesModel.pipelineContext;
  79505. if (!visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large) {
  79506. return;
  79507. }
  79508. resetDefines.push(incrementalApplyVisual(visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimensionIndex(seriesModel.getData())));
  79509. });
  79510. return resetDefines;
  79511. }
  79512. }, // Only support color.
  79513. {
  79514. createOnAllSeries: true,
  79515. reset: function (seriesModel, ecModel) {
  79516. var data = seriesModel.getData();
  79517. var visualMetaList = [];
  79518. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79519. if (visualMapModel.isTargetSeries(seriesModel)) {
  79520. var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || {
  79521. stops: [],
  79522. outerColors: []
  79523. };
  79524. var dimIdx = visualMapModel.getDataDimensionIndex(data);
  79525. if (dimIdx >= 0) {
  79526. // visualMeta.dimension should be dimension index, but not concrete dimension.
  79527. visualMeta.dimension = dimIdx;
  79528. visualMetaList.push(visualMeta);
  79529. }
  79530. }
  79531. }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  79532. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  79533. }
  79534. }]; // FIXME
  79535. // performance and export for heatmap?
  79536. // value can be Infinity or -Infinity
  79537. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  79538. var mappings = visualMapModel.targetVisuals[valueState];
  79539. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  79540. var resultVisual = {
  79541. color: getVisualFromData(seriesModel.getData(), 'color') // default color.
  79542. };
  79543. for (var i = 0, len = visualTypes.length; i < len; i++) {
  79544. var type = visualTypes[i];
  79545. var mapping = mappings[type === 'opacity' ? '__alphaForOpacity' : type];
  79546. mapping && mapping.applyVisual(value, getVisual, setVisual);
  79547. }
  79548. return resultVisual.color;
  79549. function getVisual(key) {
  79550. return resultVisual[key];
  79551. }
  79552. function setVisual(key, value) {
  79553. resultVisual[key] = value;
  79554. }
  79555. }
  79556. var each$f = each;
  79557. function visualMapPreprocessor(option) {
  79558. var visualMap = option && option.visualMap;
  79559. if (!isArray(visualMap)) {
  79560. visualMap = visualMap ? [visualMap] : [];
  79561. }
  79562. each$f(visualMap, function (opt) {
  79563. if (!opt) {
  79564. return;
  79565. } // rename splitList to pieces
  79566. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  79567. opt.pieces = opt.splitList;
  79568. delete opt.splitList;
  79569. }
  79570. var pieces = opt.pieces;
  79571. if (pieces && isArray(pieces)) {
  79572. each$f(pieces, function (piece) {
  79573. if (isObject(piece)) {
  79574. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  79575. piece.min = piece.start;
  79576. }
  79577. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  79578. piece.max = piece.end;
  79579. }
  79580. }
  79581. });
  79582. }
  79583. });
  79584. }
  79585. function has$1(obj, name) {
  79586. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  79587. }
  79588. var installed$1 = false;
  79589. function installCommon$1(registers) {
  79590. if (installed$1) {
  79591. return;
  79592. }
  79593. installed$1 = true;
  79594. registers.registerSubTypeDefaulter('visualMap', function (option) {
  79595. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  79596. return !option.categories && (!(option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) || option.calculable) ? 'continuous' : 'piecewise';
  79597. });
  79598. registers.registerAction(visualMapActionInfo, visualMapActionHander);
  79599. each(visualMapEncodingHandlers, function (handler) {
  79600. registers.registerVisual(registers.PRIORITY.VISUAL.COMPONENT, handler);
  79601. });
  79602. registers.registerPreprocessor(visualMapPreprocessor);
  79603. }
  79604. function install$N(registers) {
  79605. registers.registerComponentModel(ContinuousModel);
  79606. registers.registerComponentView(ContinuousView);
  79607. installCommon$1(registers);
  79608. }
  79609. var PiecewiseModel =
  79610. /** @class */
  79611. function (_super) {
  79612. __extends(PiecewiseModel, _super);
  79613. function PiecewiseModel() {
  79614. var _this = _super !== null && _super.apply(this, arguments) || this;
  79615. _this.type = PiecewiseModel.type;
  79616. /**
  79617. * The order is always [low, ..., high].
  79618. * [{text: string, interval: Array.<number>}, ...]
  79619. */
  79620. _this._pieceList = [];
  79621. return _this;
  79622. }
  79623. PiecewiseModel.prototype.optionUpdated = function (newOption, isInit) {
  79624. _super.prototype.optionUpdated.apply(this, arguments);
  79625. this.resetExtent();
  79626. var mode = this._mode = this._determineMode();
  79627. this._pieceList = [];
  79628. resetMethods[this._mode].call(this, this._pieceList);
  79629. this._resetSelected(newOption, isInit);
  79630. var categories = this.option.categories;
  79631. this.resetVisual(function (mappingOption, state) {
  79632. if (mode === 'categories') {
  79633. mappingOption.mappingMethod = 'category';
  79634. mappingOption.categories = clone(categories);
  79635. } else {
  79636. mappingOption.dataExtent = this.getExtent();
  79637. mappingOption.mappingMethod = 'piecewise';
  79638. mappingOption.pieceList = map(this._pieceList, function (piece) {
  79639. piece = clone(piece);
  79640. if (state !== 'inRange') {
  79641. // FIXME
  79642. // outOfRange do not support special visual in pieces.
  79643. piece.visual = null;
  79644. }
  79645. return piece;
  79646. });
  79647. }
  79648. });
  79649. };
  79650. /**
  79651. * @protected
  79652. * @override
  79653. */
  79654. PiecewiseModel.prototype.completeVisualOption = function () {
  79655. // Consider this case:
  79656. // visualMap: {
  79657. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  79658. // }
  79659. // where no inRange/outOfRange set but only pieces. So we should make
  79660. // default inRange/outOfRange for this case, otherwise visuals that only
  79661. // appear in `pieces` will not be taken into account in visual encoding.
  79662. var option = this.option;
  79663. var visualTypesInPieces = {};
  79664. var visualTypes = VisualMapping.listVisualTypes();
  79665. var isCategory = this.isCategory();
  79666. each(option.pieces, function (piece) {
  79667. each(visualTypes, function (visualType) {
  79668. if (piece.hasOwnProperty(visualType)) {
  79669. visualTypesInPieces[visualType] = 1;
  79670. }
  79671. });
  79672. });
  79673. each(visualTypesInPieces, function (v, visualType) {
  79674. var exists = false;
  79675. each(this.stateList, function (state) {
  79676. exists = exists || has(option, state, visualType) || has(option.target, state, visualType);
  79677. }, this);
  79678. !exists && each(this.stateList, function (state) {
  79679. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, state === 'inRange' ? 'active' : 'inactive', isCategory);
  79680. });
  79681. }, this);
  79682. function has(obj, state, visualType) {
  79683. return obj && obj[state] && obj[state].hasOwnProperty(visualType);
  79684. }
  79685. _super.prototype.completeVisualOption.apply(this, arguments);
  79686. };
  79687. PiecewiseModel.prototype._resetSelected = function (newOption, isInit) {
  79688. var thisOption = this.option;
  79689. var pieceList = this._pieceList; // Selected do not merge but all override.
  79690. var selected = (isInit ? thisOption : newOption).selected || {};
  79691. thisOption.selected = selected; // Consider 'not specified' means true.
  79692. each(pieceList, function (piece, index) {
  79693. var key = this.getSelectedMapKey(piece);
  79694. if (!selected.hasOwnProperty(key)) {
  79695. selected[key] = true;
  79696. }
  79697. }, this);
  79698. if (thisOption.selectedMode === 'single') {
  79699. // Ensure there is only one selected.
  79700. var hasSel_1 = false;
  79701. each(pieceList, function (piece, index) {
  79702. var key = this.getSelectedMapKey(piece);
  79703. if (selected[key]) {
  79704. hasSel_1 ? selected[key] = false : hasSel_1 = true;
  79705. }
  79706. }, this);
  79707. } // thisOption.selectedMode === 'multiple', default: all selected.
  79708. };
  79709. /**
  79710. * @public
  79711. */
  79712. PiecewiseModel.prototype.getItemSymbol = function () {
  79713. return this.get('itemSymbol');
  79714. };
  79715. /**
  79716. * @public
  79717. */
  79718. PiecewiseModel.prototype.getSelectedMapKey = function (piece) {
  79719. return this._mode === 'categories' ? piece.value + '' : piece.index + '';
  79720. };
  79721. /**
  79722. * @public
  79723. */
  79724. PiecewiseModel.prototype.getPieceList = function () {
  79725. return this._pieceList;
  79726. };
  79727. /**
  79728. * @return {string}
  79729. */
  79730. PiecewiseModel.prototype._determineMode = function () {
  79731. var option = this.option;
  79732. return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber';
  79733. };
  79734. /**
  79735. * @override
  79736. */
  79737. PiecewiseModel.prototype.setSelected = function (selected) {
  79738. this.option.selected = clone(selected);
  79739. };
  79740. /**
  79741. * @override
  79742. */
  79743. PiecewiseModel.prototype.getValueState = function (value) {
  79744. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  79745. return index != null ? this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' : 'outOfRange';
  79746. };
  79747. /**
  79748. * @public
  79749. * @param pieceIndex piece index in visualMapModel.getPieceList()
  79750. */
  79751. PiecewiseModel.prototype.findTargetDataIndices = function (pieceIndex) {
  79752. var result = [];
  79753. var pieceList = this._pieceList;
  79754. this.eachTargetSeries(function (seriesModel) {
  79755. var dataIndices = [];
  79756. var data = seriesModel.getData();
  79757. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  79758. // Should always base on model pieceList, because it is order sensitive.
  79759. var pIdx = VisualMapping.findPieceIndex(value, pieceList);
  79760. pIdx === pieceIndex && dataIndices.push(dataIndex);
  79761. }, this);
  79762. result.push({
  79763. seriesId: seriesModel.id,
  79764. dataIndex: dataIndices
  79765. });
  79766. }, this);
  79767. return result;
  79768. };
  79769. /**
  79770. * @private
  79771. * @param piece piece.value or piece.interval is required.
  79772. * @return Can be Infinity or -Infinity
  79773. */
  79774. PiecewiseModel.prototype.getRepresentValue = function (piece) {
  79775. var representValue;
  79776. if (this.isCategory()) {
  79777. representValue = piece.value;
  79778. } else {
  79779. if (piece.value != null) {
  79780. representValue = piece.value;
  79781. } else {
  79782. var pieceInterval = piece.interval || [];
  79783. representValue = pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2;
  79784. }
  79785. }
  79786. return representValue;
  79787. };
  79788. PiecewiseModel.prototype.getVisualMeta = function (getColorVisual) {
  79789. // Do not support category. (category axis is ordinal, numerical)
  79790. if (this.isCategory()) {
  79791. return;
  79792. }
  79793. var stops = [];
  79794. var outerColors = ['', ''];
  79795. var visualMapModel = this;
  79796. function setStop(interval, valueState) {
  79797. var representValue = visualMapModel.getRepresentValue({
  79798. interval: interval
  79799. }); // Not category
  79800. if (!valueState) {
  79801. valueState = visualMapModel.getValueState(representValue);
  79802. }
  79803. var color = getColorVisual(representValue, valueState);
  79804. if (interval[0] === -Infinity) {
  79805. outerColors[0] = color;
  79806. } else if (interval[1] === Infinity) {
  79807. outerColors[1] = color;
  79808. } else {
  79809. stops.push({
  79810. value: interval[0],
  79811. color: color
  79812. }, {
  79813. value: interval[1],
  79814. color: color
  79815. });
  79816. }
  79817. } // Suplement
  79818. var pieceList = this._pieceList.slice();
  79819. if (!pieceList.length) {
  79820. pieceList.push({
  79821. interval: [-Infinity, Infinity]
  79822. });
  79823. } else {
  79824. var edge = pieceList[0].interval[0];
  79825. edge !== -Infinity && pieceList.unshift({
  79826. interval: [-Infinity, edge]
  79827. });
  79828. edge = pieceList[pieceList.length - 1].interval[1];
  79829. edge !== Infinity && pieceList.push({
  79830. interval: [edge, Infinity]
  79831. });
  79832. }
  79833. var curr = -Infinity;
  79834. each(pieceList, function (piece) {
  79835. var interval = piece.interval;
  79836. if (interval) {
  79837. // Fulfill gap.
  79838. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  79839. setStop(interval.slice());
  79840. curr = interval[1];
  79841. }
  79842. }, this);
  79843. return {
  79844. stops: stops,
  79845. outerColors: outerColors
  79846. };
  79847. };
  79848. PiecewiseModel.type = 'visualMap.piecewise';
  79849. PiecewiseModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  79850. selected: null,
  79851. minOpen: false,
  79852. maxOpen: false,
  79853. align: 'auto',
  79854. itemWidth: 20,
  79855. itemHeight: 14,
  79856. itemSymbol: 'roundRect',
  79857. pieces: null,
  79858. categories: null,
  79859. splitNumber: 5,
  79860. selectedMode: 'multiple',
  79861. itemGap: 10,
  79862. hoverLink: true // Enable hover highlight.
  79863. });
  79864. return PiecewiseModel;
  79865. }(VisualMapModel);
  79866. /**
  79867. * Key is this._mode
  79868. * @type {Object}
  79869. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  79870. */
  79871. var resetMethods = {
  79872. splitNumber: function (outPieceList) {
  79873. var thisOption = this.option;
  79874. var precision = Math.min(thisOption.precision, 20);
  79875. var dataExtent = this.getExtent();
  79876. var splitNumber = thisOption.splitNumber;
  79877. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  79878. thisOption.splitNumber = splitNumber;
  79879. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption
  79880. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  79881. precision++;
  79882. }
  79883. thisOption.precision = precision;
  79884. splitStep = +splitStep.toFixed(precision);
  79885. if (thisOption.minOpen) {
  79886. outPieceList.push({
  79887. interval: [-Infinity, dataExtent[0]],
  79888. close: [0, 0]
  79889. });
  79890. }
  79891. for (var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++) {
  79892. var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep;
  79893. outPieceList.push({
  79894. interval: [curr, max],
  79895. close: [1, 1]
  79896. });
  79897. }
  79898. if (thisOption.maxOpen) {
  79899. outPieceList.push({
  79900. interval: [dataExtent[1], Infinity],
  79901. close: [0, 0]
  79902. });
  79903. }
  79904. reformIntervals(outPieceList);
  79905. each(outPieceList, function (piece, index) {
  79906. piece.index = index;
  79907. piece.text = this.formatValueText(piece.interval);
  79908. }, this);
  79909. },
  79910. categories: function (outPieceList) {
  79911. var thisOption = this.option;
  79912. each(thisOption.categories, function (cate) {
  79913. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  79914. // 是否改一致。
  79915. outPieceList.push({
  79916. text: this.formatValueText(cate, true),
  79917. value: cate
  79918. });
  79919. }, this); // See "Order Rule".
  79920. normalizeReverse(thisOption, outPieceList);
  79921. },
  79922. pieces: function (outPieceList) {
  79923. var thisOption = this.option;
  79924. each(thisOption.pieces, function (pieceListItem, index) {
  79925. if (!isObject(pieceListItem)) {
  79926. pieceListItem = {
  79927. value: pieceListItem
  79928. };
  79929. }
  79930. var item = {
  79931. text: '',
  79932. index: index
  79933. };
  79934. if (pieceListItem.label != null) {
  79935. item.text = pieceListItem.label;
  79936. }
  79937. if (pieceListItem.hasOwnProperty('value')) {
  79938. var value = item.value = pieceListItem.value;
  79939. item.interval = [value, value];
  79940. item.close = [1, 1];
  79941. } else {
  79942. // `min` `max` is legacy option.
  79943. // `lt` `gt` `lte` `gte` is recommended.
  79944. var interval = item.interval = [];
  79945. var close_1 = item.close = [0, 0];
  79946. var closeList = [1, 0, 1];
  79947. var infinityList = [-Infinity, Infinity];
  79948. var useMinMax = [];
  79949. for (var lg = 0; lg < 2; lg++) {
  79950. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  79951. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  79952. interval[lg] = pieceListItem[names[i]];
  79953. close_1[lg] = closeList[i];
  79954. useMinMax[lg] = i === 2;
  79955. }
  79956. interval[lg] == null && (interval[lg] = infinityList[lg]);
  79957. }
  79958. useMinMax[0] && interval[1] === Infinity && (close_1[0] = 0);
  79959. useMinMax[1] && interval[0] === -Infinity && (close_1[1] = 0);
  79960. if ("development" !== 'production') {
  79961. if (interval[0] > interval[1]) {
  79962. console.warn('Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.');
  79963. }
  79964. }
  79965. if (interval[0] === interval[1] && close_1[0] && close_1[1]) {
  79966. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  79967. // we use value to lift the priority when min === max
  79968. item.value = interval[0];
  79969. }
  79970. }
  79971. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  79972. outPieceList.push(item);
  79973. }, this); // See "Order Rule".
  79974. normalizeReverse(thisOption, outPieceList); // Only pieces
  79975. reformIntervals(outPieceList);
  79976. each(outPieceList, function (piece) {
  79977. var close = piece.close;
  79978. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  79979. piece.text = piece.text || this.formatValueText(piece.value != null ? piece.value : piece.interval, false, edgeSymbols);
  79980. }, this);
  79981. }
  79982. };
  79983. function normalizeReverse(thisOption, pieceList) {
  79984. var inverse = thisOption.inverse;
  79985. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  79986. pieceList.reverse();
  79987. }
  79988. }
  79989. var PiecewiseVisualMapView =
  79990. /** @class */
  79991. function (_super) {
  79992. __extends(PiecewiseVisualMapView, _super);
  79993. function PiecewiseVisualMapView() {
  79994. var _this = _super !== null && _super.apply(this, arguments) || this;
  79995. _this.type = PiecewiseVisualMapView.type;
  79996. return _this;
  79997. }
  79998. PiecewiseVisualMapView.prototype.doRender = function () {
  79999. var thisGroup = this.group;
  80000. thisGroup.removeAll();
  80001. var visualMapModel = this.visualMapModel;
  80002. var textGap = visualMapModel.get('textGap');
  80003. var textStyleModel = visualMapModel.textStyleModel;
  80004. var textFont = textStyleModel.getFont();
  80005. var textFill = textStyleModel.getTextColor();
  80006. var itemAlign = this._getItemAlign();
  80007. var itemSize = visualMapModel.itemSize;
  80008. var viewData = this._getViewData();
  80009. var endsText = viewData.endsText;
  80010. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  80011. endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign);
  80012. each(viewData.viewPieceList, function (item) {
  80013. var piece = item.piece;
  80014. var itemGroup = new Group();
  80015. itemGroup.onclick = bind(this._onItemClick, this, piece);
  80016. this._enableHoverLink(itemGroup, item.indexInModelPieceList); // TODO Category
  80017. var representValue = visualMapModel.getRepresentValue(piece);
  80018. this._createItemSymbol(itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]);
  80019. if (showLabel) {
  80020. var visualState = this.visualMapModel.getValueState(representValue);
  80021. itemGroup.add(new ZRText({
  80022. style: {
  80023. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  80024. y: itemSize[1] / 2,
  80025. text: piece.text,
  80026. verticalAlign: 'middle',
  80027. align: itemAlign,
  80028. font: textFont,
  80029. fill: textFill,
  80030. opacity: visualState === 'outOfRange' ? 0.5 : 1
  80031. }
  80032. }));
  80033. }
  80034. thisGroup.add(itemGroup);
  80035. }, this);
  80036. endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign);
  80037. box(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap'));
  80038. this.renderBackground(thisGroup);
  80039. this.positionGroup(thisGroup);
  80040. };
  80041. PiecewiseVisualMapView.prototype._enableHoverLink = function (itemGroup, pieceIndex) {
  80042. var _this = this;
  80043. itemGroup.on('mouseover', function () {
  80044. return onHoverLink('highlight');
  80045. }).on('mouseout', function () {
  80046. return onHoverLink('downplay');
  80047. });
  80048. var onHoverLink = function (method) {
  80049. var visualMapModel = _this.visualMapModel; // TODO: TYPE More detailed action types
  80050. visualMapModel.option.hoverLink && _this.api.dispatchAction({
  80051. type: method,
  80052. batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel)
  80053. });
  80054. };
  80055. };
  80056. PiecewiseVisualMapView.prototype._getItemAlign = function () {
  80057. var visualMapModel = this.visualMapModel;
  80058. var modelOption = visualMapModel.option;
  80059. if (modelOption.orient === 'vertical') {
  80060. return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize);
  80061. } else {
  80062. // horizontal, most case left unless specifying right.
  80063. var align = modelOption.align;
  80064. if (!align || align === 'auto') {
  80065. align = 'left';
  80066. }
  80067. return align;
  80068. }
  80069. };
  80070. PiecewiseVisualMapView.prototype._renderEndsText = function (group, text, itemSize, showLabel, itemAlign) {
  80071. if (!text) {
  80072. return;
  80073. }
  80074. var itemGroup = new Group();
  80075. var textStyleModel = this.visualMapModel.textStyleModel;
  80076. itemGroup.add(new ZRText({
  80077. style: createTextStyle(textStyleModel, {
  80078. x: showLabel ? itemAlign === 'right' ? itemSize[0] : 0 : itemSize[0] / 2,
  80079. y: itemSize[1] / 2,
  80080. verticalAlign: 'middle',
  80081. align: showLabel ? itemAlign : 'center',
  80082. text: text
  80083. })
  80084. }));
  80085. group.add(itemGroup);
  80086. };
  80087. /**
  80088. * @private
  80089. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  80090. */
  80091. PiecewiseVisualMapView.prototype._getViewData = function () {
  80092. var visualMapModel = this.visualMapModel;
  80093. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  80094. return {
  80095. piece: piece,
  80096. indexInModelPieceList: index
  80097. };
  80098. });
  80099. var endsText = visualMapModel.get('text'); // Consider orient and inverse.
  80100. var orient = visualMapModel.get('orient');
  80101. var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high]
  80102. if (orient === 'horizontal' ? inverse : !inverse) {
  80103. viewPieceList.reverse();
  80104. } // Origin order of endsText is [high, low]
  80105. else if (endsText) {
  80106. endsText = endsText.slice().reverse();
  80107. }
  80108. return {
  80109. viewPieceList: viewPieceList,
  80110. endsText: endsText
  80111. };
  80112. };
  80113. PiecewiseVisualMapView.prototype._createItemSymbol = function (group, representValue, shapeParam) {
  80114. group.add(createSymbol( // symbol will be string
  80115. this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], // color will be string
  80116. this.getControllerVisual(representValue, 'color')));
  80117. };
  80118. PiecewiseVisualMapView.prototype._onItemClick = function (piece) {
  80119. var visualMapModel = this.visualMapModel;
  80120. var option = visualMapModel.option;
  80121. var selectedMode = option.selectedMode;
  80122. if (!selectedMode) {
  80123. return;
  80124. }
  80125. var selected = clone(option.selected);
  80126. var newKey = visualMapModel.getSelectedMapKey(piece);
  80127. if (selectedMode === 'single' || selectedMode === true) {
  80128. selected[newKey] = true;
  80129. each(selected, function (o, key) {
  80130. selected[key] = key === newKey;
  80131. });
  80132. } else {
  80133. selected[newKey] = !selected[newKey];
  80134. }
  80135. this.api.dispatchAction({
  80136. type: 'selectDataRange',
  80137. from: this.uid,
  80138. visualMapId: this.visualMapModel.id,
  80139. selected: selected
  80140. });
  80141. };
  80142. PiecewiseVisualMapView.type = 'visualMap.piecewise';
  80143. return PiecewiseVisualMapView;
  80144. }(VisualMapView);
  80145. function install$O(registers) {
  80146. registers.registerComponentModel(PiecewiseModel);
  80147. registers.registerComponentView(PiecewiseVisualMapView);
  80148. installCommon$1(registers);
  80149. }
  80150. function install$P(registers) {
  80151. use(install$N);
  80152. use(install$O); // Do not install './dataZoomSelect',
  80153. // since it only work for toolbox dataZoom.
  80154. }
  80155. var DEFAULT_OPTION = {
  80156. label: {
  80157. enabled: true
  80158. },
  80159. decal: {
  80160. show: false
  80161. }
  80162. };
  80163. var inner$l = makeInner();
  80164. var decalPaletteScope = {};
  80165. function ariaVisual(ecModel, api) {
  80166. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  80167. if (!ariaModel.get('enabled')) {
  80168. return;
  80169. }
  80170. var defaultOption = clone(DEFAULT_OPTION);
  80171. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  80172. merge(ariaModel.option, defaultOption, false);
  80173. setDecal();
  80174. setLabel();
  80175. function setDecal() {
  80176. var decalModel = ariaModel.getModel('decal');
  80177. var useDecal = decalModel.get('show');
  80178. if (useDecal) {
  80179. // Each type of series use one scope.
  80180. // Pie and funnel are using different scopes.
  80181. var paletteScopeGroupByType_1 = createHashMap();
  80182. ecModel.eachSeries(function (seriesModel) {
  80183. if (seriesModel.isColorBySeries()) {
  80184. return;
  80185. }
  80186. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  80187. if (!decalScope) {
  80188. decalScope = {};
  80189. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  80190. }
  80191. inner$l(seriesModel).scope = decalScope;
  80192. });
  80193. ecModel.eachRawSeries(function (seriesModel) {
  80194. if (ecModel.isSeriesFiltered(seriesModel)) {
  80195. return;
  80196. }
  80197. if (isFunction(seriesModel.enableAriaDecal)) {
  80198. // Let series define how to use decal palette on data
  80199. seriesModel.enableAriaDecal();
  80200. return;
  80201. }
  80202. var data = seriesModel.getData();
  80203. if (!seriesModel.isColorBySeries()) {
  80204. var dataAll_1 = seriesModel.getRawData();
  80205. var idxMap_1 = {};
  80206. var decalScope_1 = inner$l(seriesModel).scope;
  80207. data.each(function (idx) {
  80208. var rawIdx = data.getRawIndex(idx);
  80209. idxMap_1[rawIdx] = idx;
  80210. });
  80211. var dataCount_1 = dataAll_1.count();
  80212. dataAll_1.each(function (rawIdx) {
  80213. var idx = idxMap_1[rawIdx];
  80214. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  80215. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  80216. var specifiedDecal = data.getItemVisual(idx, 'decal');
  80217. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  80218. });
  80219. } else {
  80220. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  80221. var specifiedDecal = data.getVisual('decal');
  80222. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  80223. }
  80224. function mergeDecal(specifiedDecal, paletteDecal) {
  80225. // Merge decal from palette to decal from itemStyle.
  80226. // User do not need to specify all of the decal props.
  80227. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  80228. resultDecal.dirty = true;
  80229. return resultDecal;
  80230. }
  80231. });
  80232. }
  80233. }
  80234. function setLabel() {
  80235. var labelLocale = ecModel.getLocaleModel().get('aria');
  80236. var labelModel = ariaModel.getModel('label');
  80237. labelModel.option = defaults(labelModel.option, labelLocale);
  80238. if (!labelModel.get('enabled')) {
  80239. return;
  80240. }
  80241. var dom = api.getZr().dom;
  80242. if (labelModel.get('description')) {
  80243. dom.setAttribute('aria-label', labelModel.get('description'));
  80244. return;
  80245. }
  80246. var seriesCnt = ecModel.getSeriesCount();
  80247. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  80248. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  80249. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  80250. var ariaLabel;
  80251. if (seriesCnt < 1) {
  80252. // No series, no aria label
  80253. return;
  80254. } else {
  80255. var title = getTitle();
  80256. if (title) {
  80257. var withTitle = labelModel.get(['general', 'withTitle']);
  80258. ariaLabel = replace(withTitle, {
  80259. title: title
  80260. });
  80261. } else {
  80262. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  80263. }
  80264. var seriesLabels_1 = [];
  80265. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  80266. ariaLabel += replace(prefix, {
  80267. seriesCount: seriesCnt
  80268. });
  80269. ecModel.eachSeries(function (seriesModel, idx) {
  80270. if (idx < displaySeriesCnt) {
  80271. var seriesLabel = void 0;
  80272. var seriesName = seriesModel.get('name');
  80273. var withName = seriesName ? 'withName' : 'withoutName';
  80274. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  80275. seriesLabel = replace(seriesLabel, {
  80276. seriesId: seriesModel.seriesIndex,
  80277. seriesName: seriesModel.get('name'),
  80278. seriesType: getSeriesTypeName(seriesModel.subType)
  80279. });
  80280. var data = seriesModel.getData();
  80281. if (data.count() > maxDataCnt) {
  80282. // Show part of data
  80283. var partialLabel = labelModel.get(['data', 'partialData']);
  80284. seriesLabel += replace(partialLabel, {
  80285. displayCnt: maxDataCnt
  80286. });
  80287. } else {
  80288. seriesLabel += labelModel.get(['data', 'allData']);
  80289. }
  80290. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  80291. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  80292. var dataLabels = [];
  80293. for (var i = 0; i < data.count(); i++) {
  80294. if (i < maxDataCnt) {
  80295. var name_1 = data.getName(i);
  80296. var value = data.getValues(i);
  80297. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  80298. dataLabels.push(replace(dataLabel, {
  80299. name: name_1,
  80300. value: value.join(middleSeparator_1)
  80301. }));
  80302. }
  80303. }
  80304. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  80305. seriesLabels_1.push(seriesLabel);
  80306. }
  80307. });
  80308. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  80309. var middleSeparator = separatorModel.get('middle');
  80310. var endSeparator = separatorModel.get('end');
  80311. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  80312. dom.setAttribute('aria-label', ariaLabel);
  80313. }
  80314. }
  80315. function replace(str, keyValues) {
  80316. if (!isString(str)) {
  80317. return str;
  80318. }
  80319. var result = str;
  80320. each(keyValues, function (value, key) {
  80321. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  80322. });
  80323. return result;
  80324. }
  80325. function getTitle() {
  80326. var title = ecModel.get('title');
  80327. if (title && title.length) {
  80328. title = title[0];
  80329. }
  80330. return title && title.text;
  80331. }
  80332. function getSeriesTypeName(type) {
  80333. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  80334. }
  80335. }
  80336. function ariaPreprocessor(option) {
  80337. if (!option || !option.aria) {
  80338. return;
  80339. }
  80340. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  80341. if (aria.show != null) {
  80342. aria.enabled = aria.show;
  80343. }
  80344. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  80345. each(['description', 'general', 'series', 'data'], function (name) {
  80346. if (aria[name] != null) {
  80347. aria.label[name] = aria[name];
  80348. }
  80349. });
  80350. }
  80351. function install$Q(registers) {
  80352. registers.registerPreprocessor(ariaPreprocessor);
  80353. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  80354. }
  80355. var RELATIONAL_EXPRESSION_OP_ALIAS_MAP = {
  80356. value: 'eq',
  80357. // PENDING: not good for literal semantic?
  80358. '<': 'lt',
  80359. '<=': 'lte',
  80360. '>': 'gt',
  80361. '>=': 'gte',
  80362. '=': 'eq',
  80363. '!=': 'ne',
  80364. '<>': 'ne' // Might be misleading for sake of the difference between '==' and '===',
  80365. // so don't support them.
  80366. // '==': 'eq',
  80367. // '===': 'seq',
  80368. // '!==': 'sne'
  80369. // PENDING: Whether support some common alias "ge", "le", "neq"?
  80370. // ge: 'gte',
  80371. // le: 'lte',
  80372. // neq: 'ne',
  80373. }; // type RelationalExpressionOpEvaluate = (tarVal: unknown, condVal: unknown) => boolean;
  80374. var RegExpEvaluator =
  80375. /** @class */
  80376. function () {
  80377. function RegExpEvaluator(rVal) {
  80378. // Support condVal: RegExp | string
  80379. var condValue = this._condVal = isString(rVal) ? new RegExp(rVal) : isRegExp(rVal) ? rVal : null;
  80380. if (condValue == null) {
  80381. var errMsg = '';
  80382. if ("development" !== 'production') {
  80383. errMsg = makePrintable('Illegal regexp', rVal, 'in');
  80384. }
  80385. throwError(errMsg);
  80386. }
  80387. }
  80388. RegExpEvaluator.prototype.evaluate = function (lVal) {
  80389. var type = typeof lVal;
  80390. return isString(type) ? this._condVal.test(lVal) : isNumber(type) ? this._condVal.test(lVal + '') : false;
  80391. };
  80392. return RegExpEvaluator;
  80393. }();
  80394. var ConstConditionInternal =
  80395. /** @class */
  80396. function () {
  80397. function ConstConditionInternal() {}
  80398. ConstConditionInternal.prototype.evaluate = function () {
  80399. return this.value;
  80400. };
  80401. return ConstConditionInternal;
  80402. }();
  80403. var AndConditionInternal =
  80404. /** @class */
  80405. function () {
  80406. function AndConditionInternal() {}
  80407. AndConditionInternal.prototype.evaluate = function () {
  80408. var children = this.children;
  80409. for (var i = 0; i < children.length; i++) {
  80410. if (!children[i].evaluate()) {
  80411. return false;
  80412. }
  80413. }
  80414. return true;
  80415. };
  80416. return AndConditionInternal;
  80417. }();
  80418. var OrConditionInternal =
  80419. /** @class */
  80420. function () {
  80421. function OrConditionInternal() {}
  80422. OrConditionInternal.prototype.evaluate = function () {
  80423. var children = this.children;
  80424. for (var i = 0; i < children.length; i++) {
  80425. if (children[i].evaluate()) {
  80426. return true;
  80427. }
  80428. }
  80429. return false;
  80430. };
  80431. return OrConditionInternal;
  80432. }();
  80433. var NotConditionInternal =
  80434. /** @class */
  80435. function () {
  80436. function NotConditionInternal() {}
  80437. NotConditionInternal.prototype.evaluate = function () {
  80438. return !this.child.evaluate();
  80439. };
  80440. return NotConditionInternal;
  80441. }();
  80442. var RelationalConditionInternal =
  80443. /** @class */
  80444. function () {
  80445. function RelationalConditionInternal() {}
  80446. RelationalConditionInternal.prototype.evaluate = function () {
  80447. var needParse = !!this.valueParser; // Call getValue with no `this`.
  80448. var getValue = this.getValue;
  80449. var tarValRaw = getValue(this.valueGetterParam);
  80450. var tarValParsed = needParse ? this.valueParser(tarValRaw) : null; // Relational cond follow "and" logic internally.
  80451. for (var i = 0; i < this.subCondList.length; i++) {
  80452. if (!this.subCondList[i].evaluate(needParse ? tarValParsed : tarValRaw)) {
  80453. return false;
  80454. }
  80455. }
  80456. return true;
  80457. };
  80458. return RelationalConditionInternal;
  80459. }();
  80460. function parseOption(exprOption, getters) {
  80461. if (exprOption === true || exprOption === false) {
  80462. var cond = new ConstConditionInternal();
  80463. cond.value = exprOption;
  80464. return cond;
  80465. }
  80466. var errMsg = '';
  80467. if (!isObjectNotArray(exprOption)) {
  80468. if ("development" !== 'production') {
  80469. errMsg = makePrintable('Illegal config. Expect a plain object but actually', exprOption);
  80470. }
  80471. throwError(errMsg);
  80472. }
  80473. if (exprOption.and) {
  80474. return parseAndOrOption('and', exprOption, getters);
  80475. } else if (exprOption.or) {
  80476. return parseAndOrOption('or', exprOption, getters);
  80477. } else if (exprOption.not) {
  80478. return parseNotOption(exprOption, getters);
  80479. }
  80480. return parseRelationalOption(exprOption, getters);
  80481. }
  80482. function parseAndOrOption(op, exprOption, getters) {
  80483. var subOptionArr = exprOption[op];
  80484. var errMsg = '';
  80485. if ("development" !== 'production') {
  80486. errMsg = makePrintable('"and"/"or" condition should only be `' + op + ': [...]` and must not be empty array.', 'Illegal condition:', exprOption);
  80487. }
  80488. if (!isArray(subOptionArr)) {
  80489. throwError(errMsg);
  80490. }
  80491. if (!subOptionArr.length) {
  80492. throwError(errMsg);
  80493. }
  80494. var cond = op === 'and' ? new AndConditionInternal() : new OrConditionInternal();
  80495. cond.children = map(subOptionArr, function (subOption) {
  80496. return parseOption(subOption, getters);
  80497. });
  80498. if (!cond.children.length) {
  80499. throwError(errMsg);
  80500. }
  80501. return cond;
  80502. }
  80503. function parseNotOption(exprOption, getters) {
  80504. var subOption = exprOption.not;
  80505. var errMsg = '';
  80506. if ("development" !== 'production') {
  80507. errMsg = makePrintable('"not" condition should only be `not: {}`.', 'Illegal condition:', exprOption);
  80508. }
  80509. if (!isObjectNotArray(subOption)) {
  80510. throwError(errMsg);
  80511. }
  80512. var cond = new NotConditionInternal();
  80513. cond.child = parseOption(subOption, getters);
  80514. if (!cond.child) {
  80515. throwError(errMsg);
  80516. }
  80517. return cond;
  80518. }
  80519. function parseRelationalOption(exprOption, getters) {
  80520. var errMsg = '';
  80521. var valueGetterParam = getters.prepareGetValue(exprOption);
  80522. var subCondList = [];
  80523. var exprKeys = keys(exprOption);
  80524. var parserName = exprOption.parser;
  80525. var valueParser = parserName ? getRawValueParser(parserName) : null;
  80526. for (var i = 0; i < exprKeys.length; i++) {
  80527. var keyRaw = exprKeys[i];
  80528. if (keyRaw === 'parser' || getters.valueGetterAttrMap.get(keyRaw)) {
  80529. continue;
  80530. }
  80531. var op = hasOwn(RELATIONAL_EXPRESSION_OP_ALIAS_MAP, keyRaw) ? RELATIONAL_EXPRESSION_OP_ALIAS_MAP[keyRaw] : keyRaw;
  80532. var condValueRaw = exprOption[keyRaw];
  80533. var condValueParsed = valueParser ? valueParser(condValueRaw) : condValueRaw;
  80534. var evaluator = createFilterComparator(op, condValueParsed) || op === 'reg' && new RegExpEvaluator(condValueParsed);
  80535. if (!evaluator) {
  80536. if ("development" !== 'production') {
  80537. errMsg = makePrintable('Illegal relational operation: "' + keyRaw + '" in condition:', exprOption);
  80538. }
  80539. throwError(errMsg);
  80540. }
  80541. subCondList.push(evaluator);
  80542. }
  80543. if (!subCondList.length) {
  80544. if ("development" !== 'production') {
  80545. errMsg = makePrintable('Relational condition must have at least one operator.', 'Illegal condition:', exprOption);
  80546. } // No relational operator always disabled in case of dangers result.
  80547. throwError(errMsg);
  80548. }
  80549. var cond = new RelationalConditionInternal();
  80550. cond.valueGetterParam = valueGetterParam;
  80551. cond.valueParser = valueParser;
  80552. cond.getValue = getters.getValue;
  80553. cond.subCondList = subCondList;
  80554. return cond;
  80555. }
  80556. function isObjectNotArray(val) {
  80557. return isObject(val) && !isArrayLike(val);
  80558. }
  80559. var ConditionalExpressionParsed =
  80560. /** @class */
  80561. function () {
  80562. function ConditionalExpressionParsed(exprOption, getters) {
  80563. this._cond = parseOption(exprOption, getters);
  80564. }
  80565. ConditionalExpressionParsed.prototype.evaluate = function () {
  80566. return this._cond.evaluate();
  80567. };
  80568. return ConditionalExpressionParsed;
  80569. }();
  80570. function parseConditionalExpression(exprOption, getters) {
  80571. return new ConditionalExpressionParsed(exprOption, getters);
  80572. }
  80573. var filterTransform = {
  80574. type: 'echarts:filter',
  80575. // PENDING: enhance to filter by index rather than create new data
  80576. transform: function (params) {
  80577. // [Caveat] Fail-Fast:
  80578. // Do not return the whole dataset unless user config indicates it explicitly.
  80579. // For example, if no condition is specified by mistake, returning an empty result
  80580. // is better than returning the entire raw source for the user to find the mistake.
  80581. var upstream = params.upstream;
  80582. var rawItem;
  80583. var condition = parseConditionalExpression(params.config, {
  80584. valueGetterAttrMap: createHashMap({
  80585. dimension: true
  80586. }),
  80587. prepareGetValue: function (exprOption) {
  80588. var errMsg = '';
  80589. var dimLoose = exprOption.dimension;
  80590. if (!hasOwn(exprOption, 'dimension')) {
  80591. if ("development" !== 'production') {
  80592. errMsg = makePrintable('Relation condition must has prop "dimension" specified.', 'Illegal condition:', exprOption);
  80593. }
  80594. throwError(errMsg);
  80595. }
  80596. var dimInfo = upstream.getDimensionInfo(dimLoose);
  80597. if (!dimInfo) {
  80598. if ("development" !== 'production') {
  80599. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal condition:', exprOption, '.\n');
  80600. }
  80601. throwError(errMsg);
  80602. }
  80603. return {
  80604. dimIdx: dimInfo.index
  80605. };
  80606. },
  80607. getValue: function (param) {
  80608. return upstream.retrieveValueFromItem(rawItem, param.dimIdx);
  80609. }
  80610. });
  80611. var resultData = [];
  80612. for (var i = 0, len = upstream.count(); i < len; i++) {
  80613. rawItem = upstream.getRawDataItem(i);
  80614. if (condition.evaluate()) {
  80615. resultData.push(rawItem);
  80616. }
  80617. }
  80618. return {
  80619. data: resultData
  80620. };
  80621. }
  80622. };
  80623. var sampleLog = '';
  80624. if ("development" !== 'production') {
  80625. sampleLog = ['Valid config is like:', '{ dimension: "age", order: "asc" }', 'or [{ dimension: "age", order: "asc"], { dimension: "date", order: "desc" }]'].join(' ');
  80626. }
  80627. var sortTransform = {
  80628. type: 'echarts:sort',
  80629. transform: function (params) {
  80630. var upstream = params.upstream;
  80631. var config = params.config;
  80632. var errMsg = ''; // Normalize
  80633. // const orderExprList: OrderExpression[] = isArray(config[0])
  80634. // ? config as OrderExpression[]
  80635. // : [config as OrderExpression];
  80636. var orderExprList = normalizeToArray(config);
  80637. if (!orderExprList.length) {
  80638. if ("development" !== 'production') {
  80639. errMsg = 'Empty `config` in sort transform.';
  80640. }
  80641. throwError(errMsg);
  80642. }
  80643. var orderDefList = [];
  80644. each(orderExprList, function (orderExpr) {
  80645. var dimLoose = orderExpr.dimension;
  80646. var order = orderExpr.order;
  80647. var parserName = orderExpr.parser;
  80648. var incomparable = orderExpr.incomparable;
  80649. if (dimLoose == null) {
  80650. if ("development" !== 'production') {
  80651. errMsg = 'Sort transform config must has "dimension" specified.' + sampleLog;
  80652. }
  80653. throwError(errMsg);
  80654. }
  80655. if (order !== 'asc' && order !== 'desc') {
  80656. if ("development" !== 'production') {
  80657. errMsg = 'Sort transform config must has "order" specified.' + sampleLog;
  80658. }
  80659. throwError(errMsg);
  80660. }
  80661. if (incomparable && incomparable !== 'min' && incomparable !== 'max') {
  80662. var errMsg_1 = '';
  80663. if ("development" !== 'production') {
  80664. errMsg_1 = 'incomparable must be "min" or "max" rather than "' + incomparable + '".';
  80665. }
  80666. throwError(errMsg_1);
  80667. }
  80668. if (order !== 'asc' && order !== 'desc') {
  80669. var errMsg_2 = '';
  80670. if ("development" !== 'production') {
  80671. errMsg_2 = 'order must be "asc" or "desc" rather than "' + order + '".';
  80672. }
  80673. throwError(errMsg_2);
  80674. }
  80675. var dimInfo = upstream.getDimensionInfo(dimLoose);
  80676. if (!dimInfo) {
  80677. if ("development" !== 'production') {
  80678. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal config:', orderExpr, '.\n');
  80679. }
  80680. throwError(errMsg);
  80681. }
  80682. var parser = parserName ? getRawValueParser(parserName) : null;
  80683. if (parserName && !parser) {
  80684. if ("development" !== 'production') {
  80685. errMsg = makePrintable('Invalid parser name ' + parserName + '.\n', 'Illegal config:', orderExpr, '.\n');
  80686. }
  80687. throwError(errMsg);
  80688. }
  80689. orderDefList.push({
  80690. dimIdx: dimInfo.index,
  80691. parser: parser,
  80692. comparator: new SortOrderComparator(order, incomparable)
  80693. });
  80694. }); // TODO: support it?
  80695. var sourceFormat = upstream.sourceFormat;
  80696. if (sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  80697. if ("development" !== 'production') {
  80698. errMsg = 'sourceFormat "' + sourceFormat + '" is not supported yet';
  80699. }
  80700. throwError(errMsg);
  80701. } // Other upstream format are all array.
  80702. var resultData = [];
  80703. for (var i = 0, len = upstream.count(); i < len; i++) {
  80704. resultData.push(upstream.getRawDataItem(i));
  80705. }
  80706. resultData.sort(function (item0, item1) {
  80707. for (var i = 0; i < orderDefList.length; i++) {
  80708. var orderDef = orderDefList[i];
  80709. var val0 = upstream.retrieveValueFromItem(item0, orderDef.dimIdx);
  80710. var val1 = upstream.retrieveValueFromItem(item1, orderDef.dimIdx);
  80711. if (orderDef.parser) {
  80712. val0 = orderDef.parser(val0);
  80713. val1 = orderDef.parser(val1);
  80714. }
  80715. var result = orderDef.comparator.evaluate(val0, val1);
  80716. if (result !== 0) {
  80717. return result;
  80718. }
  80719. }
  80720. return 0;
  80721. });
  80722. return {
  80723. data: resultData
  80724. };
  80725. }
  80726. };
  80727. function install$R(registers) {
  80728. registers.registerTransform(filterTransform);
  80729. registers.registerTransform(sortTransform);
  80730. }
  80731. var DatasetModel =
  80732. /** @class */
  80733. function (_super) {
  80734. __extends(DatasetModel, _super);
  80735. function DatasetModel() {
  80736. var _this = _super !== null && _super.apply(this, arguments) || this;
  80737. _this.type = 'dataset';
  80738. return _this;
  80739. }
  80740. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  80741. _super.prototype.init.call(this, option, parentModel, ecModel);
  80742. this._sourceManager = new SourceManager(this);
  80743. disableTransformOptionMerge(this);
  80744. };
  80745. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  80746. _super.prototype.mergeOption.call(this, newOption, ecModel);
  80747. disableTransformOptionMerge(this);
  80748. };
  80749. DatasetModel.prototype.optionUpdated = function () {
  80750. this._sourceManager.dirty();
  80751. };
  80752. DatasetModel.prototype.getSourceManager = function () {
  80753. return this._sourceManager;
  80754. };
  80755. DatasetModel.type = 'dataset';
  80756. DatasetModel.defaultOption = {
  80757. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  80758. };
  80759. return DatasetModel;
  80760. }(ComponentModel);
  80761. var DatasetView =
  80762. /** @class */
  80763. function (_super) {
  80764. __extends(DatasetView, _super);
  80765. function DatasetView() {
  80766. var _this = _super !== null && _super.apply(this, arguments) || this;
  80767. _this.type = 'dataset';
  80768. return _this;
  80769. }
  80770. DatasetView.type = 'dataset';
  80771. return DatasetView;
  80772. }(ComponentView);
  80773. function install$S(registers) {
  80774. registers.registerComponentModel(DatasetModel);
  80775. registers.registerComponentView(DatasetView);
  80776. }
  80777. var CMD$4 = PathProxy.CMD;
  80778. function aroundEqual(a, b) {
  80779. return Math.abs(a - b) < 1e-5;
  80780. }
  80781. function pathToBezierCurves(path) {
  80782. var data = path.data;
  80783. var len = path.len();
  80784. var bezierArrayGroups = [];
  80785. var currentSubpath;
  80786. var xi = 0;
  80787. var yi = 0;
  80788. var x0 = 0;
  80789. var y0 = 0;
  80790. function createNewSubpath(x, y) {
  80791. if (currentSubpath && currentSubpath.length > 2) {
  80792. bezierArrayGroups.push(currentSubpath);
  80793. }
  80794. currentSubpath = [x, y];
  80795. }
  80796. function addLine(x0, y0, x1, y1) {
  80797. if (!(aroundEqual(x0, x1) && aroundEqual(y0, y1))) {
  80798. currentSubpath.push(x0, y0, x1, y1, x1, y1);
  80799. }
  80800. }
  80801. function addArc(startAngle, endAngle, cx, cy, rx, ry) {
  80802. var delta = Math.abs(endAngle - startAngle);
  80803. var len = Math.tan(delta / 4) * 4 / 3;
  80804. var dir = endAngle < startAngle ? -1 : 1;
  80805. var c1 = Math.cos(startAngle);
  80806. var s1 = Math.sin(startAngle);
  80807. var c2 = Math.cos(endAngle);
  80808. var s2 = Math.sin(endAngle);
  80809. var x1 = c1 * rx + cx;
  80810. var y1 = s1 * ry + cy;
  80811. var x4 = c2 * rx + cx;
  80812. var y4 = s2 * ry + cy;
  80813. var hx = rx * len * dir;
  80814. var hy = ry * len * dir;
  80815. currentSubpath.push(x1 - hx * s1, y1 + hy * c1, x4 + hx * s2, y4 - hy * c2, x4, y4);
  80816. }
  80817. var x1;
  80818. var y1;
  80819. var x2;
  80820. var y2;
  80821. for (var i = 0; i < len;) {
  80822. var cmd = data[i++];
  80823. var isFirst = i === 1;
  80824. if (isFirst) {
  80825. xi = data[i];
  80826. yi = data[i + 1];
  80827. x0 = xi;
  80828. y0 = yi;
  80829. if (cmd === CMD$4.L || cmd === CMD$4.C || cmd === CMD$4.Q) {
  80830. currentSubpath = [x0, y0];
  80831. }
  80832. }
  80833. switch (cmd) {
  80834. case CMD$4.M:
  80835. xi = x0 = data[i++];
  80836. yi = y0 = data[i++];
  80837. createNewSubpath(x0, y0);
  80838. break;
  80839. case CMD$4.L:
  80840. x1 = data[i++];
  80841. y1 = data[i++];
  80842. addLine(xi, yi, x1, y1);
  80843. xi = x1;
  80844. yi = y1;
  80845. break;
  80846. case CMD$4.C:
  80847. currentSubpath.push(data[i++], data[i++], data[i++], data[i++], xi = data[i++], yi = data[i++]);
  80848. break;
  80849. case CMD$4.Q:
  80850. x1 = data[i++];
  80851. y1 = data[i++];
  80852. x2 = data[i++];
  80853. y2 = data[i++];
  80854. currentSubpath.push(xi + 2 / 3 * (x1 - xi), yi + 2 / 3 * (y1 - yi), x2 + 2 / 3 * (x1 - x2), y2 + 2 / 3 * (y1 - y2), x2, y2);
  80855. xi = x2;
  80856. yi = y2;
  80857. break;
  80858. case CMD$4.A:
  80859. var cx = data[i++];
  80860. var cy = data[i++];
  80861. var rx = data[i++];
  80862. var ry = data[i++];
  80863. var startAngle = data[i++];
  80864. var endAngle = data[i++] + startAngle;
  80865. i += 1;
  80866. var anticlockwise = !data[i++];
  80867. x1 = Math.cos(startAngle) * rx + cx;
  80868. y1 = Math.sin(startAngle) * ry + cy;
  80869. if (isFirst) {
  80870. x0 = x1;
  80871. y0 = y1;
  80872. createNewSubpath(x0, y0);
  80873. }
  80874. else {
  80875. addLine(xi, yi, x1, y1);
  80876. }
  80877. xi = Math.cos(endAngle) * rx + cx;
  80878. yi = Math.sin(endAngle) * ry + cy;
  80879. var step = (anticlockwise ? -1 : 1) * Math.PI / 2;
  80880. for (var angle = startAngle; anticlockwise ? angle > endAngle : angle < endAngle; angle += step) {
  80881. var nextAngle = anticlockwise ? Math.max(angle + step, endAngle)
  80882. : Math.min(angle + step, endAngle);
  80883. addArc(angle, nextAngle, cx, cy, rx, ry);
  80884. }
  80885. break;
  80886. case CMD$4.R:
  80887. x0 = xi = data[i++];
  80888. y0 = yi = data[i++];
  80889. x1 = x0 + data[i++];
  80890. y1 = y0 + data[i++];
  80891. createNewSubpath(x1, y0);
  80892. addLine(x1, y0, x1, y1);
  80893. addLine(x1, y1, x0, y1);
  80894. addLine(x0, y1, x0, y0);
  80895. addLine(x0, y0, x1, y0);
  80896. break;
  80897. case CMD$4.Z:
  80898. currentSubpath && addLine(xi, yi, x0, y0);
  80899. xi = x0;
  80900. yi = y0;
  80901. break;
  80902. }
  80903. }
  80904. if (currentSubpath && currentSubpath.length > 2) {
  80905. bezierArrayGroups.push(currentSubpath);
  80906. }
  80907. return bezierArrayGroups;
  80908. }
  80909. function adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, out, scale) {
  80910. if (aroundEqual(x0, x1) && aroundEqual(y0, y1) && aroundEqual(x2, x3) && aroundEqual(y2, y3)) {
  80911. out.push(x3, y3);
  80912. return;
  80913. }
  80914. var PIXEL_DISTANCE = 2 / scale;
  80915. var PIXEL_DISTANCE_SQR = PIXEL_DISTANCE * PIXEL_DISTANCE;
  80916. var dx = x3 - x0;
  80917. var dy = y3 - y0;
  80918. var d = Math.sqrt(dx * dx + dy * dy);
  80919. dx /= d;
  80920. dy /= d;
  80921. var dx1 = x1 - x0;
  80922. var dy1 = y1 - y0;
  80923. var dx2 = x2 - x3;
  80924. var dy2 = y2 - y3;
  80925. var cp1LenSqr = dx1 * dx1 + dy1 * dy1;
  80926. var cp2LenSqr = dx2 * dx2 + dy2 * dy2;
  80927. if (cp1LenSqr < PIXEL_DISTANCE_SQR && cp2LenSqr < PIXEL_DISTANCE_SQR) {
  80928. out.push(x3, y3);
  80929. return;
  80930. }
  80931. var projLen1 = dx * dx1 + dy * dy1;
  80932. var projLen2 = -dx * dx2 - dy * dy2;
  80933. var d1Sqr = cp1LenSqr - projLen1 * projLen1;
  80934. var d2Sqr = cp2LenSqr - projLen2 * projLen2;
  80935. if (d1Sqr < PIXEL_DISTANCE_SQR && projLen1 >= 0
  80936. && d2Sqr < PIXEL_DISTANCE_SQR && projLen2 >= 0) {
  80937. out.push(x3, y3);
  80938. return;
  80939. }
  80940. var tmpSegX = [];
  80941. var tmpSegY = [];
  80942. cubicSubdivide(x0, x1, x2, x3, 0.5, tmpSegX);
  80943. cubicSubdivide(y0, y1, y2, y3, 0.5, tmpSegY);
  80944. adpativeBezier(tmpSegX[0], tmpSegY[0], tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], tmpSegX[3], tmpSegY[3], out, scale);
  80945. adpativeBezier(tmpSegX[4], tmpSegY[4], tmpSegX[5], tmpSegY[5], tmpSegX[6], tmpSegY[6], tmpSegX[7], tmpSegY[7], out, scale);
  80946. }
  80947. function pathToPolygons(path, scale) {
  80948. var bezierArrayGroups = pathToBezierCurves(path);
  80949. var polygons = [];
  80950. scale = scale || 1;
  80951. for (var i = 0; i < bezierArrayGroups.length; i++) {
  80952. var beziers = bezierArrayGroups[i];
  80953. var polygon = [];
  80954. var x0 = beziers[0];
  80955. var y0 = beziers[1];
  80956. polygon.push(x0, y0);
  80957. for (var k = 2; k < beziers.length;) {
  80958. var x1 = beziers[k++];
  80959. var y1 = beziers[k++];
  80960. var x2 = beziers[k++];
  80961. var y2 = beziers[k++];
  80962. var x3 = beziers[k++];
  80963. var y3 = beziers[k++];
  80964. adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, polygon, scale);
  80965. x0 = x3;
  80966. y0 = y3;
  80967. }
  80968. polygons.push(polygon);
  80969. }
  80970. return polygons;
  80971. }
  80972. function getDividingGrids(dimSize, rowDim, count) {
  80973. var rowSize = dimSize[rowDim];
  80974. var columnSize = dimSize[1 - rowDim];
  80975. var ratio = Math.abs(rowSize / columnSize);
  80976. var rowCount = Math.ceil(Math.sqrt(ratio * count));
  80977. var columnCount = Math.floor(count / rowCount);
  80978. if (columnCount === 0) {
  80979. columnCount = 1;
  80980. rowCount = count;
  80981. }
  80982. var grids = [];
  80983. for (var i = 0; i < rowCount; i++) {
  80984. grids.push(columnCount);
  80985. }
  80986. var currentCount = rowCount * columnCount;
  80987. var remained = count - currentCount;
  80988. if (remained > 0) {
  80989. for (var i = 0; i < remained; i++) {
  80990. grids[i % rowCount] += 1;
  80991. }
  80992. }
  80993. return grids;
  80994. }
  80995. function divideSector(sectorShape, count, outShapes) {
  80996. var r0 = sectorShape.r0;
  80997. var r = sectorShape.r;
  80998. var startAngle = sectorShape.startAngle;
  80999. var endAngle = sectorShape.endAngle;
  81000. var angle = Math.abs(endAngle - startAngle);
  81001. var arcLen = angle * r;
  81002. var deltaR = r - r0;
  81003. var isAngleRow = arcLen > Math.abs(deltaR);
  81004. var grids = getDividingGrids([arcLen, deltaR], isAngleRow ? 0 : 1, count);
  81005. var rowSize = (isAngleRow ? angle : deltaR) / grids.length;
  81006. for (var row = 0; row < grids.length; row++) {
  81007. var columnSize = (isAngleRow ? deltaR : angle) / grids[row];
  81008. for (var column = 0; column < grids[row]; column++) {
  81009. var newShape = {};
  81010. if (isAngleRow) {
  81011. newShape.startAngle = startAngle + rowSize * row;
  81012. newShape.endAngle = startAngle + rowSize * (row + 1);
  81013. newShape.r0 = r0 + columnSize * column;
  81014. newShape.r = r0 + columnSize * (column + 1);
  81015. }
  81016. else {
  81017. newShape.startAngle = startAngle + columnSize * column;
  81018. newShape.endAngle = startAngle + columnSize * (column + 1);
  81019. newShape.r0 = r0 + rowSize * row;
  81020. newShape.r = r0 + rowSize * (row + 1);
  81021. }
  81022. newShape.clockwise = sectorShape.clockwise;
  81023. newShape.cx = sectorShape.cx;
  81024. newShape.cy = sectorShape.cy;
  81025. outShapes.push(newShape);
  81026. }
  81027. }
  81028. }
  81029. function divideRect(rectShape, count, outShapes) {
  81030. var width = rectShape.width;
  81031. var height = rectShape.height;
  81032. var isHorizontalRow = width > height;
  81033. var grids = getDividingGrids([width, height], isHorizontalRow ? 0 : 1, count);
  81034. var rowSizeDim = isHorizontalRow ? 'width' : 'height';
  81035. var columnSizeDim = isHorizontalRow ? 'height' : 'width';
  81036. var rowDim = isHorizontalRow ? 'x' : 'y';
  81037. var columnDim = isHorizontalRow ? 'y' : 'x';
  81038. var rowSize = rectShape[rowSizeDim] / grids.length;
  81039. for (var row = 0; row < grids.length; row++) {
  81040. var columnSize = rectShape[columnSizeDim] / grids[row];
  81041. for (var column = 0; column < grids[row]; column++) {
  81042. var newShape = {};
  81043. newShape[rowDim] = row * rowSize;
  81044. newShape[columnDim] = column * columnSize;
  81045. newShape[rowSizeDim] = rowSize;
  81046. newShape[columnSizeDim] = columnSize;
  81047. newShape.x += rectShape.x;
  81048. newShape.y += rectShape.y;
  81049. outShapes.push(newShape);
  81050. }
  81051. }
  81052. }
  81053. function crossProduct2d$1(x1, y1, x2, y2) {
  81054. return x1 * y2 - x2 * y1;
  81055. }
  81056. function lineLineIntersect$1(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  81057. var mx = a2x - a1x;
  81058. var my = a2y - a1y;
  81059. var nx = b2x - b1x;
  81060. var ny = b2y - b1y;
  81061. var nmCrossProduct = crossProduct2d$1(nx, ny, mx, my);
  81062. if (Math.abs(nmCrossProduct) < 1e-6) {
  81063. return null;
  81064. }
  81065. var b1a1x = a1x - b1x;
  81066. var b1a1y = a1y - b1y;
  81067. var p = crossProduct2d$1(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  81068. if (p < 0 || p > 1) {
  81069. return null;
  81070. }
  81071. return new Point(p * mx + a1x, p * my + a1y);
  81072. }
  81073. function projPtOnLine(pt, lineA, lineB) {
  81074. var dir = new Point();
  81075. Point.sub(dir, lineB, lineA);
  81076. dir.normalize();
  81077. var dir2 = new Point();
  81078. Point.sub(dir2, pt, lineA);
  81079. var len = dir2.dot(dir);
  81080. return len;
  81081. }
  81082. function addToPoly(poly, pt) {
  81083. var last = poly[poly.length - 1];
  81084. if (last && last[0] === pt[0] && last[1] === pt[1]) {
  81085. return;
  81086. }
  81087. poly.push(pt);
  81088. }
  81089. function splitPolygonByLine(points, lineA, lineB) {
  81090. var len = points.length;
  81091. var intersections = [];
  81092. for (var i = 0; i < len; i++) {
  81093. var p0 = points[i];
  81094. var p1 = points[(i + 1) % len];
  81095. var intersectionPt = lineLineIntersect$1(p0[0], p0[1], p1[0], p1[1], lineA.x, lineA.y, lineB.x, lineB.y);
  81096. if (intersectionPt) {
  81097. intersections.push({
  81098. projPt: projPtOnLine(intersectionPt, lineA, lineB),
  81099. pt: intersectionPt,
  81100. idx: i
  81101. });
  81102. }
  81103. }
  81104. if (intersections.length < 2) {
  81105. return [{ points: points }, { points: points }];
  81106. }
  81107. intersections.sort(function (a, b) {
  81108. return a.projPt - b.projPt;
  81109. });
  81110. var splitPt0 = intersections[0];
  81111. var splitPt1 = intersections[intersections.length - 1];
  81112. if (splitPt1.idx < splitPt0.idx) {
  81113. var tmp = splitPt0;
  81114. splitPt0 = splitPt1;
  81115. splitPt1 = tmp;
  81116. }
  81117. var splitPt0Arr = [splitPt0.pt.x, splitPt0.pt.y];
  81118. var splitPt1Arr = [splitPt1.pt.x, splitPt1.pt.y];
  81119. var newPolyA = [splitPt0Arr];
  81120. var newPolyB = [splitPt1Arr];
  81121. for (var i = splitPt0.idx + 1; i <= splitPt1.idx; i++) {
  81122. addToPoly(newPolyA, points[i].slice());
  81123. }
  81124. addToPoly(newPolyA, splitPt1Arr);
  81125. addToPoly(newPolyA, splitPt0Arr);
  81126. for (var i = splitPt1.idx + 1; i <= splitPt0.idx + len; i++) {
  81127. addToPoly(newPolyB, points[i % len].slice());
  81128. }
  81129. addToPoly(newPolyB, splitPt0Arr);
  81130. addToPoly(newPolyB, splitPt1Arr);
  81131. return [{
  81132. points: newPolyA
  81133. }, {
  81134. points: newPolyB
  81135. }];
  81136. }
  81137. function binaryDividePolygon(polygonShape) {
  81138. var points = polygonShape.points;
  81139. var min = [];
  81140. var max = [];
  81141. fromPoints(points, min, max);
  81142. var boundingRect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  81143. var width = boundingRect.width;
  81144. var height = boundingRect.height;
  81145. var x = boundingRect.x;
  81146. var y = boundingRect.y;
  81147. var pt0 = new Point();
  81148. var pt1 = new Point();
  81149. if (width > height) {
  81150. pt0.x = pt1.x = x + width / 2;
  81151. pt0.y = y;
  81152. pt1.y = y + height;
  81153. }
  81154. else {
  81155. pt0.y = pt1.y = y + height / 2;
  81156. pt0.x = x;
  81157. pt1.x = x + width;
  81158. }
  81159. return splitPolygonByLine(points, pt0, pt1);
  81160. }
  81161. function binaryDivideRecursive(divider, shape, count, out) {
  81162. if (count === 1) {
  81163. out.push(shape);
  81164. }
  81165. else {
  81166. var mid = Math.floor(count / 2);
  81167. var sub = divider(shape);
  81168. binaryDivideRecursive(divider, sub[0], mid, out);
  81169. binaryDivideRecursive(divider, sub[1], count - mid, out);
  81170. }
  81171. return out;
  81172. }
  81173. function clone$4(path, count) {
  81174. var paths = [];
  81175. for (var i = 0; i < count; i++) {
  81176. paths.push(clonePath(path));
  81177. }
  81178. return paths;
  81179. }
  81180. function copyPathProps(source, target) {
  81181. target.setStyle(source.style);
  81182. target.z = source.z;
  81183. target.z2 = source.z2;
  81184. target.zlevel = source.zlevel;
  81185. }
  81186. function polygonConvert(points) {
  81187. var out = [];
  81188. for (var i = 0; i < points.length;) {
  81189. out.push([points[i++], points[i++]]);
  81190. }
  81191. return out;
  81192. }
  81193. function split(path, count) {
  81194. var outShapes = [];
  81195. var shape = path.shape;
  81196. var OutShapeCtor;
  81197. switch (path.type) {
  81198. case 'rect':
  81199. divideRect(shape, count, outShapes);
  81200. OutShapeCtor = Rect;
  81201. break;
  81202. case 'sector':
  81203. divideSector(shape, count, outShapes);
  81204. OutShapeCtor = Sector;
  81205. break;
  81206. case 'circle':
  81207. divideSector({
  81208. r0: 0, r: shape.r, startAngle: 0, endAngle: Math.PI * 2,
  81209. cx: shape.cx, cy: shape.cy
  81210. }, count, outShapes);
  81211. OutShapeCtor = Sector;
  81212. break;
  81213. default:
  81214. var m = path.getComputedTransform();
  81215. var scale = m ? Math.sqrt(Math.max(m[0] * m[0] + m[1] * m[1], m[2] * m[2] + m[3] * m[3])) : 1;
  81216. var polygons = map(pathToPolygons(path.getUpdatedPathProxy(), scale), function (poly) { return polygonConvert(poly); });
  81217. var polygonCount = polygons.length;
  81218. if (polygonCount === 0) {
  81219. binaryDivideRecursive(binaryDividePolygon, {
  81220. points: polygons[0]
  81221. }, count, outShapes);
  81222. }
  81223. else if (polygonCount === count) {
  81224. for (var i = 0; i < polygonCount; i++) {
  81225. outShapes.push({
  81226. points: polygons[i]
  81227. });
  81228. }
  81229. }
  81230. else {
  81231. var totalArea_1 = 0;
  81232. var items = map(polygons, function (poly) {
  81233. var min = [];
  81234. var max = [];
  81235. fromPoints(poly, min, max);
  81236. var area = (max[1] - min[1]) * (max[0] - min[0]);
  81237. totalArea_1 += area;
  81238. return { poly: poly, area: area };
  81239. });
  81240. items.sort(function (a, b) { return b.area - a.area; });
  81241. var left = count;
  81242. for (var i = 0; i < polygonCount; i++) {
  81243. var item = items[i];
  81244. if (left <= 0) {
  81245. break;
  81246. }
  81247. var selfCount = i === polygonCount - 1
  81248. ? left
  81249. : Math.ceil(item.area / totalArea_1 * count);
  81250. if (selfCount < 0) {
  81251. continue;
  81252. }
  81253. binaryDivideRecursive(binaryDividePolygon, {
  81254. points: item.poly
  81255. }, selfCount, outShapes);
  81256. left -= selfCount;
  81257. }
  81258. }
  81259. OutShapeCtor = Polygon;
  81260. break;
  81261. }
  81262. if (!OutShapeCtor) {
  81263. return clone$4(path, count);
  81264. }
  81265. var out = [];
  81266. for (var i = 0; i < outShapes.length; i++) {
  81267. var subPath = new OutShapeCtor();
  81268. subPath.setShape(outShapes[i]);
  81269. copyPathProps(path, subPath);
  81270. out.push(subPath);
  81271. }
  81272. return out;
  81273. }
  81274. function alignSubpath(subpath1, subpath2) {
  81275. var len1 = subpath1.length;
  81276. var len2 = subpath2.length;
  81277. if (len1 === len2) {
  81278. return [subpath1, subpath2];
  81279. }
  81280. var tmpSegX = [];
  81281. var tmpSegY = [];
  81282. var shorterPath = len1 < len2 ? subpath1 : subpath2;
  81283. var shorterLen = Math.min(len1, len2);
  81284. var diff = Math.abs(len2 - len1) / 6;
  81285. var shorterBezierCount = (shorterLen - 2) / 6;
  81286. var eachCurveSubDivCount = Math.ceil(diff / shorterBezierCount) + 1;
  81287. var newSubpath = [shorterPath[0], shorterPath[1]];
  81288. var remained = diff;
  81289. for (var i = 2; i < shorterLen;) {
  81290. var x0 = shorterPath[i - 2];
  81291. var y0 = shorterPath[i - 1];
  81292. var x1 = shorterPath[i++];
  81293. var y1 = shorterPath[i++];
  81294. var x2 = shorterPath[i++];
  81295. var y2 = shorterPath[i++];
  81296. var x3 = shorterPath[i++];
  81297. var y3 = shorterPath[i++];
  81298. if (remained <= 0) {
  81299. newSubpath.push(x1, y1, x2, y2, x3, y3);
  81300. continue;
  81301. }
  81302. var actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1;
  81303. for (var k = 1; k <= actualSubDivCount; k++) {
  81304. var p = k / actualSubDivCount;
  81305. cubicSubdivide(x0, x1, x2, x3, p, tmpSegX);
  81306. cubicSubdivide(y0, y1, y2, y3, p, tmpSegY);
  81307. x0 = tmpSegX[3];
  81308. y0 = tmpSegY[3];
  81309. newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0);
  81310. x1 = tmpSegX[5];
  81311. y1 = tmpSegY[5];
  81312. x2 = tmpSegX[6];
  81313. y2 = tmpSegY[6];
  81314. }
  81315. remained -= actualSubDivCount - 1;
  81316. }
  81317. return shorterPath === subpath1 ? [newSubpath, subpath2] : [subpath1, newSubpath];
  81318. }
  81319. function createSubpath(lastSubpathSubpath, otherSubpath) {
  81320. var len = lastSubpathSubpath.length;
  81321. var lastX = lastSubpathSubpath[len - 2];
  81322. var lastY = lastSubpathSubpath[len - 1];
  81323. var newSubpath = [];
  81324. for (var i = 0; i < otherSubpath.length;) {
  81325. newSubpath[i++] = lastX;
  81326. newSubpath[i++] = lastY;
  81327. }
  81328. return newSubpath;
  81329. }
  81330. function alignBezierCurves(array1, array2) {
  81331. var _a;
  81332. var lastSubpath1;
  81333. var lastSubpath2;
  81334. var newArray1 = [];
  81335. var newArray2 = [];
  81336. for (var i = 0; i < Math.max(array1.length, array2.length); i++) {
  81337. var subpath1 = array1[i];
  81338. var subpath2 = array2[i];
  81339. var newSubpath1 = void 0;
  81340. var newSubpath2 = void 0;
  81341. if (!subpath1) {
  81342. newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2);
  81343. newSubpath2 = subpath2;
  81344. }
  81345. else if (!subpath2) {
  81346. newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1);
  81347. newSubpath1 = subpath1;
  81348. }
  81349. else {
  81350. _a = alignSubpath(subpath1, subpath2), newSubpath1 = _a[0], newSubpath2 = _a[1];
  81351. lastSubpath1 = newSubpath1;
  81352. lastSubpath2 = newSubpath2;
  81353. }
  81354. newArray1.push(newSubpath1);
  81355. newArray2.push(newSubpath2);
  81356. }
  81357. return [newArray1, newArray2];
  81358. }
  81359. function centroid$1(array) {
  81360. var signedArea = 0;
  81361. var cx = 0;
  81362. var cy = 0;
  81363. var len = array.length;
  81364. for (var i = 0, j = len - 2; i < len; j = i, i += 2) {
  81365. var x0 = array[j];
  81366. var y0 = array[j + 1];
  81367. var x1 = array[i];
  81368. var y1 = array[i + 1];
  81369. var a = x0 * y1 - x1 * y0;
  81370. signedArea += a;
  81371. cx += (x0 + x1) * a;
  81372. cy += (y0 + y1) * a;
  81373. }
  81374. if (signedArea === 0) {
  81375. return [array[0] || 0, array[1] || 0];
  81376. }
  81377. return [cx / signedArea / 3, cy / signedArea / 3, signedArea];
  81378. }
  81379. function findBestRingOffset(fromSubBeziers, toSubBeziers, fromCp, toCp) {
  81380. var bezierCount = (fromSubBeziers.length - 2) / 6;
  81381. var bestScore = Infinity;
  81382. var bestOffset = 0;
  81383. var len = fromSubBeziers.length;
  81384. var len2 = len - 2;
  81385. for (var offset = 0; offset < bezierCount; offset++) {
  81386. var cursorOffset = offset * 6;
  81387. var score = 0;
  81388. for (var k = 0; k < len; k += 2) {
  81389. var idx = k === 0 ? cursorOffset : ((cursorOffset + k - 2) % len2 + 2);
  81390. var x0 = fromSubBeziers[idx] - fromCp[0];
  81391. var y0 = fromSubBeziers[idx + 1] - fromCp[1];
  81392. var x1 = toSubBeziers[k] - toCp[0];
  81393. var y1 = toSubBeziers[k + 1] - toCp[1];
  81394. var dx = x1 - x0;
  81395. var dy = y1 - y0;
  81396. score += dx * dx + dy * dy;
  81397. }
  81398. if (score < bestScore) {
  81399. bestScore = score;
  81400. bestOffset = offset;
  81401. }
  81402. }
  81403. return bestOffset;
  81404. }
  81405. function reverse(array) {
  81406. var newArr = [];
  81407. var len = array.length;
  81408. for (var i = 0; i < len; i += 2) {
  81409. newArr[i] = array[len - i - 2];
  81410. newArr[i + 1] = array[len - i - 1];
  81411. }
  81412. return newArr;
  81413. }
  81414. function findBestMorphingRotation(fromArr, toArr, searchAngleIteration, searchAngleRange) {
  81415. var result = [];
  81416. var fromNeedsReverse;
  81417. for (var i = 0; i < fromArr.length; i++) {
  81418. var fromSubpathBezier = fromArr[i];
  81419. var toSubpathBezier = toArr[i];
  81420. var fromCp = centroid$1(fromSubpathBezier);
  81421. var toCp = centroid$1(toSubpathBezier);
  81422. if (fromNeedsReverse == null) {
  81423. fromNeedsReverse = fromCp[2] < 0 !== toCp[2] < 0;
  81424. }
  81425. var newFromSubpathBezier = [];
  81426. var newToSubpathBezier = [];
  81427. var bestAngle = 0;
  81428. var bestScore = Infinity;
  81429. var tmpArr = [];
  81430. var len = fromSubpathBezier.length;
  81431. if (fromNeedsReverse) {
  81432. fromSubpathBezier = reverse(fromSubpathBezier);
  81433. }
  81434. var offset = findBestRingOffset(fromSubpathBezier, toSubpathBezier, fromCp, toCp) * 6;
  81435. var len2 = len - 2;
  81436. for (var k = 0; k < len2; k += 2) {
  81437. var idx = (offset + k) % len2 + 2;
  81438. newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0];
  81439. newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1];
  81440. }
  81441. newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0];
  81442. newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1];
  81443. if (searchAngleIteration > 0) {
  81444. var step = searchAngleRange / searchAngleIteration;
  81445. for (var angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step) {
  81446. var sa = Math.sin(angle);
  81447. var ca = Math.cos(angle);
  81448. var score = 0;
  81449. for (var k = 0; k < fromSubpathBezier.length; k += 2) {
  81450. var x0 = newFromSubpathBezier[k];
  81451. var y0 = newFromSubpathBezier[k + 1];
  81452. var x1 = toSubpathBezier[k] - toCp[0];
  81453. var y1 = toSubpathBezier[k + 1] - toCp[1];
  81454. var newX1 = x1 * ca - y1 * sa;
  81455. var newY1 = x1 * sa + y1 * ca;
  81456. tmpArr[k] = newX1;
  81457. tmpArr[k + 1] = newY1;
  81458. var dx = newX1 - x0;
  81459. var dy = newY1 - y0;
  81460. score += dx * dx + dy * dy;
  81461. }
  81462. if (score < bestScore) {
  81463. bestScore = score;
  81464. bestAngle = angle;
  81465. for (var m = 0; m < tmpArr.length; m++) {
  81466. newToSubpathBezier[m] = tmpArr[m];
  81467. }
  81468. }
  81469. }
  81470. }
  81471. else {
  81472. for (var i_1 = 0; i_1 < len; i_1 += 2) {
  81473. newToSubpathBezier[i_1] = toSubpathBezier[i_1] - toCp[0];
  81474. newToSubpathBezier[i_1 + 1] = toSubpathBezier[i_1 + 1] - toCp[1];
  81475. }
  81476. }
  81477. result.push({
  81478. from: newFromSubpathBezier,
  81479. to: newToSubpathBezier,
  81480. fromCp: fromCp,
  81481. toCp: toCp,
  81482. rotation: -bestAngle
  81483. });
  81484. }
  81485. return result;
  81486. }
  81487. function isCombineMorphing(path) {
  81488. return path.__isCombineMorphing;
  81489. }
  81490. var SAVED_METHOD_PREFIX = '__mOriginal_';
  81491. function saveAndModifyMethod(obj, methodName, modifiers) {
  81492. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  81493. var originalMethod = obj[savedMethodName] || obj[methodName];
  81494. if (!obj[savedMethodName]) {
  81495. obj[savedMethodName] = obj[methodName];
  81496. }
  81497. var replace = modifiers.replace;
  81498. var after = modifiers.after;
  81499. var before = modifiers.before;
  81500. obj[methodName] = function () {
  81501. var args = arguments;
  81502. var res;
  81503. before && before.apply(this, args);
  81504. if (replace) {
  81505. res = replace.apply(this, args);
  81506. }
  81507. else {
  81508. res = originalMethod.apply(this, args);
  81509. }
  81510. after && after.apply(this, args);
  81511. return res;
  81512. };
  81513. }
  81514. function restoreMethod(obj, methodName) {
  81515. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  81516. if (obj[savedMethodName]) {
  81517. obj[methodName] = obj[savedMethodName];
  81518. obj[savedMethodName] = null;
  81519. }
  81520. }
  81521. function applyTransformOnBeziers(bezierCurves, mm) {
  81522. for (var i = 0; i < bezierCurves.length; i++) {
  81523. var subBeziers = bezierCurves[i];
  81524. for (var k = 0; k < subBeziers.length;) {
  81525. var x = subBeziers[k];
  81526. var y = subBeziers[k + 1];
  81527. subBeziers[k++] = mm[0] * x + mm[2] * y + mm[4];
  81528. subBeziers[k++] = mm[1] * x + mm[3] * y + mm[5];
  81529. }
  81530. }
  81531. }
  81532. function prepareMorphPath(fromPath, toPath) {
  81533. var fromPathProxy = fromPath.getUpdatedPathProxy();
  81534. var toPathProxy = toPath.getUpdatedPathProxy();
  81535. var _a = alignBezierCurves(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy)), fromBezierCurves = _a[0], toBezierCurves = _a[1];
  81536. var fromPathTransform = fromPath.getComputedTransform();
  81537. var toPathTransform = toPath.getComputedTransform();
  81538. function updateIdentityTransform() {
  81539. this.transform = null;
  81540. }
  81541. fromPathTransform && applyTransformOnBeziers(fromBezierCurves, fromPathTransform);
  81542. toPathTransform && applyTransformOnBeziers(toBezierCurves, toPathTransform);
  81543. saveAndModifyMethod(toPath, 'updateTransform', { replace: updateIdentityTransform });
  81544. toPath.transform = null;
  81545. var morphingData = findBestMorphingRotation(fromBezierCurves, toBezierCurves, 10, Math.PI);
  81546. var tmpArr = [];
  81547. saveAndModifyMethod(toPath, 'buildPath', { replace: function (path) {
  81548. var t = toPath.__morphT;
  81549. var onet = 1 - t;
  81550. var newCp = [];
  81551. for (var i = 0; i < morphingData.length; i++) {
  81552. var item = morphingData[i];
  81553. var from = item.from;
  81554. var to = item.to;
  81555. var angle = item.rotation * t;
  81556. var fromCp = item.fromCp;
  81557. var toCp = item.toCp;
  81558. var sa = Math.sin(angle);
  81559. var ca = Math.cos(angle);
  81560. lerp(newCp, fromCp, toCp, t);
  81561. for (var m = 0; m < from.length; m += 2) {
  81562. var x0_1 = from[m];
  81563. var y0_1 = from[m + 1];
  81564. var x1 = to[m];
  81565. var y1 = to[m + 1];
  81566. var x = x0_1 * onet + x1 * t;
  81567. var y = y0_1 * onet + y1 * t;
  81568. tmpArr[m] = (x * ca - y * sa) + newCp[0];
  81569. tmpArr[m + 1] = (x * sa + y * ca) + newCp[1];
  81570. }
  81571. var x0 = tmpArr[0];
  81572. var y0 = tmpArr[1];
  81573. path.moveTo(x0, y0);
  81574. for (var m = 2; m < from.length;) {
  81575. var x1 = tmpArr[m++];
  81576. var y1 = tmpArr[m++];
  81577. var x2 = tmpArr[m++];
  81578. var y2 = tmpArr[m++];
  81579. var x3 = tmpArr[m++];
  81580. var y3 = tmpArr[m++];
  81581. if (x0 === x1 && y0 === y1 && x2 === x3 && y2 === y3) {
  81582. path.lineTo(x3, y3);
  81583. }
  81584. else {
  81585. path.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  81586. }
  81587. x0 = x3;
  81588. y0 = y3;
  81589. }
  81590. }
  81591. } });
  81592. }
  81593. function morphPath(fromPath, toPath, animationOpts) {
  81594. if (!fromPath || !toPath) {
  81595. return toPath;
  81596. }
  81597. var oldDone = animationOpts.done;
  81598. var oldDuring = animationOpts.during;
  81599. prepareMorphPath(fromPath, toPath);
  81600. toPath.__morphT = 0;
  81601. function restoreToPath() {
  81602. restoreMethod(toPath, 'buildPath');
  81603. restoreMethod(toPath, 'updateTransform');
  81604. toPath.__morphT = -1;
  81605. toPath.createPathProxy();
  81606. toPath.dirtyShape();
  81607. }
  81608. toPath.animateTo({
  81609. __morphT: 1
  81610. }, defaults({
  81611. during: function (p) {
  81612. toPath.dirtyShape();
  81613. oldDuring && oldDuring(p);
  81614. },
  81615. done: function () {
  81616. restoreToPath();
  81617. oldDone && oldDone();
  81618. }
  81619. }, animationOpts));
  81620. return toPath;
  81621. }
  81622. function hilbert(x, y, minX, minY, maxX, maxY) {
  81623. var bits = 16;
  81624. x = (maxX === minX) ? 0 : Math.round(32767 * (x - minX) / (maxX - minX));
  81625. y = (maxY === minY) ? 0 : Math.round(32767 * (y - minY) / (maxY - minY));
  81626. var d = 0;
  81627. var tmp;
  81628. for (var s = (1 << bits) / 2; s > 0; s /= 2) {
  81629. var rx = 0;
  81630. var ry = 0;
  81631. if ((x & s) > 0) {
  81632. rx = 1;
  81633. }
  81634. if ((y & s) > 0) {
  81635. ry = 1;
  81636. }
  81637. d += s * s * ((3 * rx) ^ ry);
  81638. if (ry === 0) {
  81639. if (rx === 1) {
  81640. x = s - 1 - x;
  81641. y = s - 1 - y;
  81642. }
  81643. tmp = x;
  81644. x = y;
  81645. y = tmp;
  81646. }
  81647. }
  81648. return d;
  81649. }
  81650. function sortPaths(pathList) {
  81651. var xMin = Infinity;
  81652. var yMin = Infinity;
  81653. var xMax = -Infinity;
  81654. var yMax = -Infinity;
  81655. var cps = map(pathList, function (path) {
  81656. var rect = path.getBoundingRect();
  81657. var m = path.getComputedTransform();
  81658. var x = rect.x + rect.width / 2 + (m ? m[4] : 0);
  81659. var y = rect.y + rect.height / 2 + (m ? m[5] : 0);
  81660. xMin = Math.min(x, xMin);
  81661. yMin = Math.min(y, yMin);
  81662. xMax = Math.max(x, xMax);
  81663. yMax = Math.max(y, yMax);
  81664. return [x, y];
  81665. });
  81666. var items = map(cps, function (cp, idx) {
  81667. return {
  81668. cp: cp,
  81669. z: hilbert(cp[0], cp[1], xMin, yMin, xMax, yMax),
  81670. path: pathList[idx]
  81671. };
  81672. });
  81673. return items.sort(function (a, b) { return a.z - b.z; }).map(function (item) { return item.path; });
  81674. }
  81675. function defaultDividePath(param) {
  81676. return split(param.path, param.count);
  81677. }
  81678. function createEmptyReturn() {
  81679. return {
  81680. fromIndividuals: [],
  81681. toIndividuals: [],
  81682. count: 0
  81683. };
  81684. }
  81685. function combineMorph(fromList, toPath, animationOpts) {
  81686. var fromPathList = [];
  81687. function addFromPath(fromList) {
  81688. for (var i = 0; i < fromList.length; i++) {
  81689. var from = fromList[i];
  81690. if (isCombineMorphing(from)) {
  81691. addFromPath(from.childrenRef());
  81692. }
  81693. else if (from instanceof Path) {
  81694. fromPathList.push(from);
  81695. }
  81696. }
  81697. }
  81698. addFromPath(fromList);
  81699. var separateCount = fromPathList.length;
  81700. if (!separateCount) {
  81701. return createEmptyReturn();
  81702. }
  81703. var dividePath = animationOpts.dividePath || defaultDividePath;
  81704. var toSubPathList = dividePath({
  81705. path: toPath, count: separateCount
  81706. });
  81707. if (toSubPathList.length !== separateCount) {
  81708. console.error('Invalid morphing: unmatched splitted path');
  81709. return createEmptyReturn();
  81710. }
  81711. fromPathList = sortPaths(fromPathList);
  81712. toSubPathList = sortPaths(toSubPathList);
  81713. var oldDone = animationOpts.done;
  81714. var oldDuring = animationOpts.during;
  81715. var individualDelay = animationOpts.individualDelay;
  81716. var identityTransform = new Transformable();
  81717. for (var i = 0; i < separateCount; i++) {
  81718. var from = fromPathList[i];
  81719. var to = toSubPathList[i];
  81720. to.parent = toPath;
  81721. to.copyTransform(identityTransform);
  81722. if (!individualDelay) {
  81723. prepareMorphPath(from, to);
  81724. }
  81725. }
  81726. toPath.__isCombineMorphing = true;
  81727. toPath.childrenRef = function () {
  81728. return toSubPathList;
  81729. };
  81730. function addToSubPathListToZr(zr) {
  81731. for (var i = 0; i < toSubPathList.length; i++) {
  81732. toSubPathList[i].addSelfToZr(zr);
  81733. }
  81734. }
  81735. saveAndModifyMethod(toPath, 'addSelfToZr', {
  81736. after: function (zr) {
  81737. addToSubPathListToZr(zr);
  81738. }
  81739. });
  81740. saveAndModifyMethod(toPath, 'removeSelfFromZr', {
  81741. after: function (zr) {
  81742. for (var i = 0; i < toSubPathList.length; i++) {
  81743. toSubPathList[i].removeSelfFromZr(zr);
  81744. }
  81745. }
  81746. });
  81747. function restoreToPath() {
  81748. toPath.__isCombineMorphing = false;
  81749. toPath.__morphT = -1;
  81750. toPath.childrenRef = null;
  81751. restoreMethod(toPath, 'addSelfToZr');
  81752. restoreMethod(toPath, 'removeSelfFromZr');
  81753. }
  81754. var toLen = toSubPathList.length;
  81755. if (individualDelay) {
  81756. var animating_1 = toLen;
  81757. var eachDone = function () {
  81758. animating_1--;
  81759. if (animating_1 === 0) {
  81760. restoreToPath();
  81761. oldDone && oldDone();
  81762. }
  81763. };
  81764. for (var i = 0; i < toLen; i++) {
  81765. var indivdualAnimationOpts = individualDelay ? defaults({
  81766. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toSubPathList[i]),
  81767. done: eachDone
  81768. }, animationOpts) : animationOpts;
  81769. morphPath(fromPathList[i], toSubPathList[i], indivdualAnimationOpts);
  81770. }
  81771. }
  81772. else {
  81773. toPath.__morphT = 0;
  81774. toPath.animateTo({
  81775. __morphT: 1
  81776. }, defaults({
  81777. during: function (p) {
  81778. for (var i = 0; i < toLen; i++) {
  81779. var child = toSubPathList[i];
  81780. child.__morphT = toPath.__morphT;
  81781. child.dirtyShape();
  81782. }
  81783. oldDuring && oldDuring(p);
  81784. },
  81785. done: function () {
  81786. restoreToPath();
  81787. for (var i = 0; i < fromList.length; i++) {
  81788. restoreMethod(fromList[i], 'updateTransform');
  81789. }
  81790. oldDone && oldDone();
  81791. }
  81792. }, animationOpts));
  81793. }
  81794. if (toPath.__zr) {
  81795. addToSubPathListToZr(toPath.__zr);
  81796. }
  81797. return {
  81798. fromIndividuals: fromPathList,
  81799. toIndividuals: toSubPathList,
  81800. count: toLen
  81801. };
  81802. }
  81803. function separateMorph(fromPath, toPathList, animationOpts) {
  81804. var toLen = toPathList.length;
  81805. var fromPathList = [];
  81806. var dividePath = animationOpts.dividePath || defaultDividePath;
  81807. function addFromPath(fromList) {
  81808. for (var i = 0; i < fromList.length; i++) {
  81809. var from = fromList[i];
  81810. if (isCombineMorphing(from)) {
  81811. addFromPath(from.childrenRef());
  81812. }
  81813. else if (from instanceof Path) {
  81814. fromPathList.push(from);
  81815. }
  81816. }
  81817. }
  81818. if (isCombineMorphing(fromPath)) {
  81819. addFromPath(fromPath.childrenRef());
  81820. var fromLen = fromPathList.length;
  81821. if (fromLen < toLen) {
  81822. var k = 0;
  81823. for (var i = fromLen; i < toLen; i++) {
  81824. fromPathList.push(clonePath(fromPathList[k++ % fromLen]));
  81825. }
  81826. }
  81827. fromPathList.length = toLen;
  81828. }
  81829. else {
  81830. fromPathList = dividePath({ path: fromPath, count: toLen });
  81831. var fromPathTransform = fromPath.getComputedTransform();
  81832. for (var i = 0; i < fromPathList.length; i++) {
  81833. fromPathList[i].setLocalTransform(fromPathTransform);
  81834. }
  81835. if (fromPathList.length !== toLen) {
  81836. console.error('Invalid morphing: unmatched splitted path');
  81837. return createEmptyReturn();
  81838. }
  81839. }
  81840. fromPathList = sortPaths(fromPathList);
  81841. toPathList = sortPaths(toPathList);
  81842. var individualDelay = animationOpts.individualDelay;
  81843. for (var i = 0; i < toLen; i++) {
  81844. var indivdualAnimationOpts = individualDelay ? defaults({
  81845. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toPathList[i])
  81846. }, animationOpts) : animationOpts;
  81847. morphPath(fromPathList[i], toPathList[i], indivdualAnimationOpts);
  81848. }
  81849. return {
  81850. fromIndividuals: fromPathList,
  81851. toIndividuals: toPathList,
  81852. count: toPathList.length
  81853. };
  81854. }
  81855. function isMultiple(elements) {
  81856. return isArray(elements[0]);
  81857. }
  81858. function prepareMorphBatches(one, many) {
  81859. var batches = [];
  81860. var batchCount = one.length;
  81861. for (var i = 0; i < batchCount; i++) {
  81862. batches.push({
  81863. one: one[i],
  81864. many: []
  81865. });
  81866. }
  81867. for (var i = 0; i < many.length; i++) {
  81868. var len = many[i].length;
  81869. var k = void 0;
  81870. for (k = 0; k < len; k++) {
  81871. batches[k % batchCount].many.push(many[i][k]);
  81872. }
  81873. }
  81874. var off = 0; // If one has more paths than each one of many. average them.
  81875. for (var i = batchCount - 1; i >= 0; i--) {
  81876. if (!batches[i].many.length) {
  81877. var moveFrom = batches[off].many;
  81878. if (moveFrom.length <= 1) {
  81879. // Not enough
  81880. // Start from the first one.
  81881. if (off) {
  81882. off = 0;
  81883. } else {
  81884. return batches;
  81885. }
  81886. }
  81887. var len = moveFrom.length;
  81888. var mid = Math.ceil(len / 2);
  81889. batches[i].many = moveFrom.slice(mid, len);
  81890. batches[off].many = moveFrom.slice(0, mid);
  81891. off++;
  81892. }
  81893. }
  81894. return batches;
  81895. }
  81896. var pathDividers = {
  81897. clone: function (params) {
  81898. var ret = []; // Fitting the alpha
  81899. var approxOpacity = 1 - Math.pow(1 - params.path.style.opacity, 1 / params.count);
  81900. for (var i = 0; i < params.count; i++) {
  81901. var cloned = clonePath(params.path);
  81902. cloned.setStyle('opacity', approxOpacity);
  81903. ret.push(cloned);
  81904. }
  81905. return ret;
  81906. },
  81907. // Use the default divider
  81908. split: null
  81909. };
  81910. function applyMorphAnimation(from, to, divideShape, seriesModel, dataIndex, animateOtherProps) {
  81911. if (!from.length || !to.length) {
  81912. return;
  81913. }
  81914. var updateAnimationCfg = getAnimationConfig('update', seriesModel, dataIndex);
  81915. if (!(updateAnimationCfg && updateAnimationCfg.duration > 0)) {
  81916. return;
  81917. }
  81918. var animationDelay = seriesModel.getModel('universalTransition').get('delay');
  81919. var animationCfg = Object.assign({
  81920. // Need to setToFinal so the further calculation based on the style can be correct.
  81921. // Like emphasis color.
  81922. setToFinal: true
  81923. }, updateAnimationCfg);
  81924. var many;
  81925. var one;
  81926. if (isMultiple(from)) {
  81927. // manyToOne
  81928. many = from;
  81929. one = to;
  81930. }
  81931. if (isMultiple(to)) {
  81932. // oneToMany
  81933. many = to;
  81934. one = from;
  81935. }
  81936. function morphOneBatch(batch, fromIsMany, animateIndex, animateCount, forceManyOne) {
  81937. var batchMany = batch.many;
  81938. var batchOne = batch.one;
  81939. if (batchMany.length === 1 && !forceManyOne) {
  81940. // Is one to one
  81941. var batchFrom = fromIsMany ? batchMany[0] : batchOne;
  81942. var batchTo = fromIsMany ? batchOne : batchMany[0];
  81943. if (isCombineMorphing(batchFrom)) {
  81944. // Keep doing combine animation.
  81945. morphOneBatch({
  81946. many: [batchFrom],
  81947. one: batchTo
  81948. }, true, animateIndex, animateCount, true);
  81949. } else {
  81950. var individualAnimationCfg = animationDelay ? defaults({
  81951. delay: animationDelay(animateIndex, animateCount)
  81952. }, animationCfg) : animationCfg;
  81953. morphPath(batchFrom, batchTo, individualAnimationCfg);
  81954. animateOtherProps(batchFrom, batchTo, batchFrom, batchTo, individualAnimationCfg);
  81955. }
  81956. } else {
  81957. var separateAnimationCfg = defaults({
  81958. dividePath: pathDividers[divideShape],
  81959. individualDelay: animationDelay && function (idx, count, fromPath, toPath) {
  81960. return animationDelay(idx + animateIndex, animateCount);
  81961. }
  81962. }, animationCfg);
  81963. var _a = fromIsMany ? combineMorph(batchMany, batchOne, separateAnimationCfg) : separateMorph(batchOne, batchMany, separateAnimationCfg),
  81964. fromIndividuals = _a.fromIndividuals,
  81965. toIndividuals = _a.toIndividuals;
  81966. var count = fromIndividuals.length;
  81967. for (var k = 0; k < count; k++) {
  81968. var individualAnimationCfg = animationDelay ? defaults({
  81969. delay: animationDelay(k, count)
  81970. }, animationCfg) : animationCfg;
  81971. animateOtherProps(fromIndividuals[k], toIndividuals[k], fromIsMany ? batchMany[k] : batch.one, fromIsMany ? batch.one : batchMany[k], individualAnimationCfg);
  81972. }
  81973. }
  81974. }
  81975. var fromIsMany = many ? many === from // Is one to one. If the path number not match. also needs do merge and separate morphing.
  81976. : from.length > to.length;
  81977. var morphBatches = many ? prepareMorphBatches(one, many) : prepareMorphBatches(fromIsMany ? to : from, [fromIsMany ? from : to]);
  81978. var animateCount = 0;
  81979. for (var i = 0; i < morphBatches.length; i++) {
  81980. animateCount += morphBatches[i].many.length;
  81981. }
  81982. var animateIndex = 0;
  81983. for (var i = 0; i < morphBatches.length; i++) {
  81984. morphOneBatch(morphBatches[i], fromIsMany, animateIndex, animateCount);
  81985. animateIndex += morphBatches[i].many.length;
  81986. }
  81987. }
  81988. function getPathList(elements) {
  81989. if (!elements) {
  81990. return [];
  81991. }
  81992. if (isArray(elements)) {
  81993. var pathList_1 = [];
  81994. for (var i = 0; i < elements.length; i++) {
  81995. pathList_1.push(getPathList(elements[i]));
  81996. }
  81997. return pathList_1;
  81998. }
  81999. var pathList = [];
  82000. elements.traverse(function (el) {
  82001. if (el instanceof Path && !el.disableMorphing && !el.invisible && !el.ignore) {
  82002. pathList.push(el);
  82003. }
  82004. });
  82005. return pathList;
  82006. }
  82007. var DATA_COUNT_THRESHOLD = 1e4;
  82008. var getUniversalTransitionGlobalStore = makeInner();
  82009. function getGroupIdDimension(data) {
  82010. var dimensions = data.dimensions;
  82011. for (var i = 0; i < dimensions.length; i++) {
  82012. var dimInfo = data.getDimensionInfo(dimensions[i]);
  82013. if (dimInfo && dimInfo.otherDims.itemGroupId === 0) {
  82014. return dimensions[i];
  82015. }
  82016. }
  82017. }
  82018. function flattenDataDiffItems(list) {
  82019. var items = [];
  82020. each(list, function (seriesInfo) {
  82021. var data = seriesInfo.data;
  82022. if (data.count() > DATA_COUNT_THRESHOLD) {
  82023. if ("development" !== 'production') {
  82024. warn('Universal transition is disabled on large data > 10k.');
  82025. }
  82026. return;
  82027. }
  82028. var indices = data.getIndices();
  82029. var groupDim = getGroupIdDimension(data);
  82030. for (var dataIndex = 0; dataIndex < indices.length; dataIndex++) {
  82031. items.push({
  82032. dataGroupId: seriesInfo.dataGroupId,
  82033. data: data,
  82034. dim: seriesInfo.dim || groupDim,
  82035. divide: seriesInfo.divide,
  82036. dataIndex: dataIndex
  82037. });
  82038. }
  82039. });
  82040. return items;
  82041. }
  82042. function fadeInElement(newEl, newSeries, newIndex) {
  82043. newEl.traverse(function (el) {
  82044. if (el instanceof Path) {
  82045. // TODO use fade in animation for target element.
  82046. initProps(el, {
  82047. style: {
  82048. opacity: 0
  82049. }
  82050. }, newSeries, {
  82051. dataIndex: newIndex,
  82052. isFrom: true
  82053. });
  82054. }
  82055. });
  82056. }
  82057. function removeEl$1(el) {
  82058. if (el.parent) {
  82059. // Bake parent transform to element.
  82060. // So it can still have proper transform to transition after it's removed.
  82061. var computedTransform = el.getComputedTransform();
  82062. el.setLocalTransform(computedTransform);
  82063. el.parent.remove(el);
  82064. }
  82065. }
  82066. function stopAnimation(el) {
  82067. el.stopAnimation();
  82068. if (el.isGroup) {
  82069. el.traverse(function (child) {
  82070. child.stopAnimation();
  82071. });
  82072. }
  82073. }
  82074. function animateElementStyles(el, dataIndex, seriesModel) {
  82075. var animationConfig = getAnimationConfig('update', seriesModel, dataIndex);
  82076. animationConfig && el.traverse(function (child) {
  82077. if (child instanceof Displayable) {
  82078. var oldStyle = getOldStyle(child);
  82079. if (oldStyle) {
  82080. child.animateFrom({
  82081. style: oldStyle
  82082. }, animationConfig);
  82083. }
  82084. }
  82085. });
  82086. }
  82087. function isAllIdSame(oldDiffItems, newDiffItems) {
  82088. var len = oldDiffItems.length;
  82089. if (len !== newDiffItems.length) {
  82090. return false;
  82091. }
  82092. for (var i = 0; i < len; i++) {
  82093. var oldItem = oldDiffItems[i];
  82094. var newItem = newDiffItems[i];
  82095. if (oldItem.data.getId(oldItem.dataIndex) !== newItem.data.getId(newItem.dataIndex)) {
  82096. return false;
  82097. }
  82098. }
  82099. return true;
  82100. }
  82101. function transitionBetween(oldList, newList, api) {
  82102. var oldDiffItems = flattenDataDiffItems(oldList);
  82103. var newDiffItems = flattenDataDiffItems(newList);
  82104. function updateMorphingPathProps(from, to, rawFrom, rawTo, animationCfg) {
  82105. if (rawFrom || from) {
  82106. to.animateFrom({
  82107. style: rawFrom && rawFrom !== from ? // dividingMethod like clone may override the style(opacity)
  82108. // So extend it to raw style.
  82109. extend(extend({}, rawFrom.style), from.style) : from.style
  82110. }, animationCfg);
  82111. }
  82112. }
  82113. function findKeyDim(items) {
  82114. for (var i = 0; i < items.length; i++) {
  82115. if (items[i].dim) {
  82116. return items[i].dim;
  82117. }
  82118. }
  82119. }
  82120. var oldKeyDim = findKeyDim(oldDiffItems);
  82121. var newKeyDim = findKeyDim(newDiffItems);
  82122. var hasMorphAnimation = false;
  82123. function createKeyGetter(isOld, onlyGetId) {
  82124. return function (diffItem) {
  82125. var data = diffItem.data;
  82126. var dataIndex = diffItem.dataIndex; // TODO if specified dim
  82127. if (onlyGetId) {
  82128. return data.getId(dataIndex);
  82129. } // Use group id as transition key by default.
  82130. // So we can achieve multiple to multiple animation like drilldown / up naturally.
  82131. // If group id not exits. Use id instead. If so, only one to one transition will be applied.
  82132. var dataGroupId = diffItem.dataGroupId; // If specified key dimension(itemGroupId by default). Use this same dimension from other data.
  82133. // PENDING: If only use key dimension of newData.
  82134. var keyDim = isOld ? oldKeyDim || newKeyDim : newKeyDim || oldKeyDim;
  82135. var dimInfo = keyDim && data.getDimensionInfo(keyDim);
  82136. var dimOrdinalMeta = dimInfo && dimInfo.ordinalMeta;
  82137. if (dimInfo) {
  82138. // Get from encode.itemGroupId.
  82139. var key = data.get(dimInfo.name, dataIndex);
  82140. if (dimOrdinalMeta) {
  82141. return dimOrdinalMeta.categories[key] || key + '';
  82142. }
  82143. return key + '';
  82144. } // Get groupId from raw item. { groupId: '' }
  82145. var itemVal = data.getRawDataItem(dataIndex);
  82146. if (itemVal && itemVal.groupId) {
  82147. return itemVal.groupId + '';
  82148. }
  82149. return dataGroupId || data.getId(dataIndex);
  82150. };
  82151. } // Use id if it's very likely to be an one to one animation
  82152. // It's more robust than groupId
  82153. // TODO Check if key dimension is specified.
  82154. var useId = isAllIdSame(oldDiffItems, newDiffItems);
  82155. var isElementStillInChart = {};
  82156. if (!useId) {
  82157. // We may have different diff strategy with basicTransition if we use other dimension as key.
  82158. // If so, we can't simply check if oldEl is same with newEl. We need a map to check if oldEl is still being used in the new chart.
  82159. // We can't use the elements that already being morphed. Let it keep it's original basic transition.
  82160. for (var i = 0; i < newDiffItems.length; i++) {
  82161. var newItem = newDiffItems[i];
  82162. var el = newItem.data.getItemGraphicEl(newItem.dataIndex);
  82163. if (el) {
  82164. isElementStillInChart[el.id] = true;
  82165. }
  82166. }
  82167. }
  82168. function updateOneToOne(newIndex, oldIndex) {
  82169. var oldItem = oldDiffItems[oldIndex];
  82170. var newItem = newDiffItems[newIndex];
  82171. var newSeries = newItem.data.hostModel; // TODO Mark this elements is morphed and don't morph them anymore
  82172. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex);
  82173. var newEl = newItem.data.getItemGraphicEl(newItem.dataIndex); // Can't handle same elements.
  82174. if (oldEl === newEl) {
  82175. newEl && animateElementStyles(newEl, newItem.dataIndex, newSeries);
  82176. return;
  82177. }
  82178. if ( // We can't use the elements that already being morphed
  82179. oldEl && isElementStillInChart[oldEl.id]) {
  82180. return;
  82181. }
  82182. if (newEl) {
  82183. // TODO: If keep animating the group in case
  82184. // some of the elements don't want to be morphed.
  82185. // TODO Label?
  82186. stopAnimation(newEl);
  82187. if (oldEl) {
  82188. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  82189. removeEl$1(oldEl);
  82190. hasMorphAnimation = true;
  82191. applyMorphAnimation(getPathList(oldEl), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  82192. } else {
  82193. fadeInElement(newEl, newSeries, newIndex);
  82194. }
  82195. } // else keep oldEl leaving animation.
  82196. }
  82197. new DataDiffer(oldDiffItems, newDiffItems, createKeyGetter(true, useId), createKeyGetter(false, useId), null, 'multiple').update(updateOneToOne).updateManyToOne(function (newIndex, oldIndices) {
  82198. var newItem = newDiffItems[newIndex];
  82199. var newData = newItem.data;
  82200. var newSeries = newData.hostModel;
  82201. var newEl = newData.getItemGraphicEl(newItem.dataIndex);
  82202. var oldElsList = filter(map(oldIndices, function (idx) {
  82203. return oldDiffItems[idx].data.getItemGraphicEl(oldDiffItems[idx].dataIndex);
  82204. }), function (oldEl) {
  82205. return oldEl && oldEl !== newEl && !isElementStillInChart[oldEl.id];
  82206. });
  82207. if (newEl) {
  82208. stopAnimation(newEl);
  82209. if (oldElsList.length) {
  82210. // If old element is doing leaving animation. stop it and remove it immediately.
  82211. each(oldElsList, function (oldEl) {
  82212. stopAnimation(oldEl);
  82213. removeEl$1(oldEl);
  82214. });
  82215. hasMorphAnimation = true;
  82216. applyMorphAnimation(getPathList(oldElsList), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  82217. } else {
  82218. fadeInElement(newEl, newSeries, newItem.dataIndex);
  82219. }
  82220. } // else keep oldEl leaving animation.
  82221. }).updateOneToMany(function (newIndices, oldIndex) {
  82222. var oldItem = oldDiffItems[oldIndex];
  82223. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex); // We can't use the elements that already being morphed
  82224. if (oldEl && isElementStillInChart[oldEl.id]) {
  82225. return;
  82226. }
  82227. var newElsList = filter(map(newIndices, function (idx) {
  82228. return newDiffItems[idx].data.getItemGraphicEl(newDiffItems[idx].dataIndex);
  82229. }), function (el) {
  82230. return el && el !== oldEl;
  82231. });
  82232. var newSeris = newDiffItems[newIndices[0]].data.hostModel;
  82233. if (newElsList.length) {
  82234. each(newElsList, function (newEl) {
  82235. return stopAnimation(newEl);
  82236. });
  82237. if (oldEl) {
  82238. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  82239. removeEl$1(oldEl);
  82240. hasMorphAnimation = true;
  82241. applyMorphAnimation(getPathList(oldEl), getPathList(newElsList), oldItem.divide, // Use divide on old.
  82242. newSeris, newIndices[0], updateMorphingPathProps);
  82243. } else {
  82244. each(newElsList, function (newEl) {
  82245. return fadeInElement(newEl, newSeris, newIndices[0]);
  82246. });
  82247. }
  82248. } // else keep oldEl leaving animation.
  82249. }).updateManyToMany(function (newIndices, oldIndices) {
  82250. // If two data are same and both have groupId.
  82251. // Normally they should be diff by id.
  82252. new DataDiffer(oldIndices, newIndices, function (rawIdx) {
  82253. return oldDiffItems[rawIdx].data.getId(oldDiffItems[rawIdx].dataIndex);
  82254. }, function (rawIdx) {
  82255. return newDiffItems[rawIdx].data.getId(newDiffItems[rawIdx].dataIndex);
  82256. }).update(function (newIndex, oldIndex) {
  82257. // Use the original index
  82258. updateOneToOne(newIndices[newIndex], oldIndices[oldIndex]);
  82259. }).execute();
  82260. }).execute();
  82261. if (hasMorphAnimation) {
  82262. each(newList, function (_a) {
  82263. var data = _a.data;
  82264. var seriesModel = data.hostModel;
  82265. var view = seriesModel && api.getViewOfSeriesModel(seriesModel);
  82266. var animationCfg = getAnimationConfig('update', seriesModel, 0); // use 0 index.
  82267. if (view && seriesModel.isAnimationEnabled() && animationCfg && animationCfg.duration > 0) {
  82268. view.group.traverse(function (el) {
  82269. if (el instanceof Path && !el.animators.length) {
  82270. // We can't accept there still exists element that has no animation
  82271. // if universalTransition is enabled
  82272. el.animateFrom({
  82273. style: {
  82274. opacity: 0
  82275. }
  82276. }, animationCfg);
  82277. }
  82278. });
  82279. }
  82280. });
  82281. }
  82282. }
  82283. function getSeriesTransitionKey(series) {
  82284. var seriesKey = series.getModel('universalTransition').get('seriesKey');
  82285. if (!seriesKey) {
  82286. // Use series id by default.
  82287. return series.id;
  82288. }
  82289. return seriesKey;
  82290. }
  82291. function convertArraySeriesKeyToString(seriesKey) {
  82292. if (isArray(seriesKey)) {
  82293. // Order independent.
  82294. return seriesKey.sort().join(',');
  82295. }
  82296. return seriesKey;
  82297. }
  82298. function getDivideShapeFromData(data) {
  82299. if (data.hostModel) {
  82300. return data.hostModel.getModel('universalTransition').get('divideShape');
  82301. }
  82302. }
  82303. function findTransitionSeriesBatches(globalStore, params) {
  82304. var updateBatches = createHashMap();
  82305. var oldDataMap = createHashMap(); // Map that only store key in array seriesKey.
  82306. // Which is used to query the old data when transition from one to multiple series.
  82307. var oldDataMapForSplit = createHashMap();
  82308. each(globalStore.oldSeries, function (series, idx) {
  82309. var oldDataGroupId = globalStore.oldDataGroupIds[idx];
  82310. var oldData = globalStore.oldData[idx];
  82311. var transitionKey = getSeriesTransitionKey(series);
  82312. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey);
  82313. oldDataMap.set(transitionKeyStr, {
  82314. dataGroupId: oldDataGroupId,
  82315. data: oldData
  82316. });
  82317. if (isArray(transitionKey)) {
  82318. // Same key can't in different array seriesKey.
  82319. each(transitionKey, function (key) {
  82320. oldDataMapForSplit.set(key, {
  82321. key: transitionKeyStr,
  82322. dataGroupId: oldDataGroupId,
  82323. data: oldData
  82324. });
  82325. });
  82326. }
  82327. });
  82328. function checkTransitionSeriesKeyDuplicated(transitionKeyStr) {
  82329. if (updateBatches.get(transitionKeyStr)) {
  82330. warn("Duplicated seriesKey in universalTransition " + transitionKeyStr);
  82331. }
  82332. }
  82333. each(params.updatedSeries, function (series) {
  82334. if (series.isUniversalTransitionEnabled() && series.isAnimationEnabled()) {
  82335. var newDataGroupId = series.get('dataGroupId');
  82336. var newData = series.getData();
  82337. var transitionKey = getSeriesTransitionKey(series);
  82338. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey); // Only transition between series with same id.
  82339. var oldData = oldDataMap.get(transitionKeyStr); // string transition key is the best match.
  82340. if (oldData) {
  82341. if ("development" !== 'production') {
  82342. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  82343. } // TODO check if data is same?
  82344. updateBatches.set(transitionKeyStr, {
  82345. oldSeries: [{
  82346. dataGroupId: oldData.dataGroupId,
  82347. divide: getDivideShapeFromData(oldData.data),
  82348. data: oldData.data
  82349. }],
  82350. newSeries: [{
  82351. dataGroupId: newDataGroupId,
  82352. divide: getDivideShapeFromData(newData),
  82353. data: newData
  82354. }]
  82355. });
  82356. } else {
  82357. // Transition from multiple series.
  82358. if (isArray(transitionKey)) {
  82359. if ("development" !== 'production') {
  82360. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  82361. }
  82362. var oldSeries_1 = [];
  82363. each(transitionKey, function (key) {
  82364. var oldData = oldDataMap.get(key);
  82365. if (oldData.data) {
  82366. oldSeries_1.push({
  82367. dataGroupId: oldData.dataGroupId,
  82368. divide: getDivideShapeFromData(oldData.data),
  82369. data: oldData.data
  82370. });
  82371. }
  82372. });
  82373. if (oldSeries_1.length) {
  82374. updateBatches.set(transitionKeyStr, {
  82375. oldSeries: oldSeries_1,
  82376. newSeries: [{
  82377. dataGroupId: newDataGroupId,
  82378. data: newData,
  82379. divide: getDivideShapeFromData(newData)
  82380. }]
  82381. });
  82382. }
  82383. } else {
  82384. // Try transition to multiple series.
  82385. var oldData_1 = oldDataMapForSplit.get(transitionKey);
  82386. if (oldData_1) {
  82387. var batch = updateBatches.get(oldData_1.key);
  82388. if (!batch) {
  82389. batch = {
  82390. oldSeries: [{
  82391. dataGroupId: oldData_1.dataGroupId,
  82392. data: oldData_1.data,
  82393. divide: getDivideShapeFromData(oldData_1.data)
  82394. }],
  82395. newSeries: []
  82396. };
  82397. updateBatches.set(oldData_1.key, batch);
  82398. }
  82399. batch.newSeries.push({
  82400. dataGroupId: newDataGroupId,
  82401. data: newData,
  82402. divide: getDivideShapeFromData(newData)
  82403. });
  82404. }
  82405. }
  82406. }
  82407. }
  82408. });
  82409. return updateBatches;
  82410. }
  82411. function querySeries(series, finder) {
  82412. for (var i = 0; i < series.length; i++) {
  82413. var found = finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id;
  82414. if (found) {
  82415. return i;
  82416. }
  82417. }
  82418. }
  82419. function transitionSeriesFromOpt(transitionOpt, globalStore, params, api) {
  82420. var from = [];
  82421. var to = [];
  82422. each(normalizeToArray(transitionOpt.from), function (finder) {
  82423. var idx = querySeries(globalStore.oldSeries, finder);
  82424. if (idx >= 0) {
  82425. from.push({
  82426. dataGroupId: globalStore.oldDataGroupIds[idx],
  82427. data: globalStore.oldData[idx],
  82428. // TODO can specify divideShape in transition.
  82429. divide: getDivideShapeFromData(globalStore.oldData[idx]),
  82430. dim: finder.dimension
  82431. });
  82432. }
  82433. });
  82434. each(normalizeToArray(transitionOpt.to), function (finder) {
  82435. var idx = querySeries(params.updatedSeries, finder);
  82436. if (idx >= 0) {
  82437. var data = params.updatedSeries[idx].getData();
  82438. to.push({
  82439. dataGroupId: globalStore.oldDataGroupIds[idx],
  82440. data: data,
  82441. divide: getDivideShapeFromData(data),
  82442. dim: finder.dimension
  82443. });
  82444. }
  82445. });
  82446. if (from.length > 0 && to.length > 0) {
  82447. transitionBetween(from, to, api);
  82448. }
  82449. }
  82450. function installUniversalTransition(registers) {
  82451. registers.registerUpdateLifecycle('series:beforeupdate', function (ecMOdel, api, params) {
  82452. each(normalizeToArray(params.seriesTransition), function (transOpt) {
  82453. each(normalizeToArray(transOpt.to), function (finder) {
  82454. var series = params.updatedSeries;
  82455. for (var i = 0; i < series.length; i++) {
  82456. if (finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id) {
  82457. series[i][SERIES_UNIVERSAL_TRANSITION_PROP] = true;
  82458. }
  82459. }
  82460. });
  82461. });
  82462. });
  82463. registers.registerUpdateLifecycle('series:transition', function (ecModel, api, params) {
  82464. // TODO api provide an namespace that can save stuff per instance
  82465. var globalStore = getUniversalTransitionGlobalStore(api); // TODO multiple to multiple series.
  82466. if (globalStore.oldSeries && params.updatedSeries && params.optionChanged) {
  82467. // Use give transition config if its' give;
  82468. var transitionOpt = params.seriesTransition;
  82469. if (transitionOpt) {
  82470. each(normalizeToArray(transitionOpt), function (opt) {
  82471. transitionSeriesFromOpt(opt, globalStore, params, api);
  82472. });
  82473. } else {
  82474. // Else guess from series based on transition series key.
  82475. var updateBatches_1 = findTransitionSeriesBatches(globalStore, params);
  82476. each(updateBatches_1.keys(), function (key) {
  82477. var batch = updateBatches_1.get(key);
  82478. transitionBetween(batch.oldSeries, batch.newSeries, api);
  82479. });
  82480. } // Reset
  82481. each(params.updatedSeries, function (series) {
  82482. // Reset;
  82483. if (series[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  82484. series[SERIES_UNIVERSAL_TRANSITION_PROP] = false;
  82485. }
  82486. });
  82487. } // Save all series of current update. Not only the updated one.
  82488. var allSeries = ecModel.getSeries();
  82489. var savedSeries = globalStore.oldSeries = [];
  82490. var savedDataGroupIds = globalStore.oldDataGroupIds = [];
  82491. var savedData = globalStore.oldData = [];
  82492. for (var i = 0; i < allSeries.length; i++) {
  82493. var data = allSeries[i].getData(); // Only save the data that can have transition.
  82494. // Avoid large data costing too much extra memory
  82495. if (data.count() < DATA_COUNT_THRESHOLD) {
  82496. savedSeries.push(allSeries[i]);
  82497. savedDataGroupIds.push(allSeries[i].get('dataGroupId'));
  82498. savedData.push(data);
  82499. }
  82500. }
  82501. });
  82502. }
  82503. // Render engines
  82504. // -----------------
  82505. // Render via Canvas.
  82506. // echarts.init(dom, null, { renderer: 'canvas' })
  82507. use([install$1]); // Render via SVG.
  82508. // echarts.init(dom, null, { renderer: 'svg' })
  82509. use([install]); // ----------------
  82510. // Charts (series)
  82511. // ----------------
  82512. // All of the series types, for example:
  82513. // chart.setOption({
  82514. // series: [{
  82515. // type: 'line' // or 'bar', 'pie', ...
  82516. // }]
  82517. // });
  82518. use([install$2, install$3, install$4, install$6, install$8, install$a, install$b, install$c, install$d, install$e, install$f, install$h, install$i, install$j, install$k, install$l, install$m, install$n, install$o, install$p, install$q, install$r]); // -------------------
  82519. // Coordinate systems
  82520. // -------------------
  82521. // All of the axis modules have been included in the
  82522. // coordinate system module below, do not need to
  82523. // make extra import.
  82524. // `cartesian` coordinate system. For some historical
  82525. // reasons, it is named as grid, for example:
  82526. // chart.setOption({
  82527. // grid: {...},
  82528. // xAxis: {...},
  82529. // yAxis: {...},
  82530. // series: [{...}]
  82531. // });
  82532. use(install$t); // `polar` coordinate system, for example:
  82533. // chart.setOption({
  82534. // polar: {...},
  82535. // radiusAxis: {...},
  82536. // angleAxis: {...},
  82537. // series: [{
  82538. // coordinateSystem: 'polar'
  82539. // }]
  82540. // });
  82541. use(install$u); // `geo` coordinate system, for example:
  82542. // chart.setOption({
  82543. // geo: {...},
  82544. // series: [{
  82545. // coordinateSystem: 'geo'
  82546. // }]
  82547. // });
  82548. use(install$9); // `singleAxis` coordinate system (notice, it is a coordinate system
  82549. // with only one axis, work for chart like theme river), for example:
  82550. // chart.setOption({
  82551. // singleAxis: {...}
  82552. // series: [{type: 'themeRiver', ...}]
  82553. // });
  82554. use(install$v); // `parallel` coordinate system, only work for parallel series, for example:
  82555. // chart.setOption({
  82556. // parallel: {...},
  82557. // parallelAxis: [{...}, ...],
  82558. // series: [{
  82559. // type: 'parallel'
  82560. // }]
  82561. // });
  82562. use(install$g); // `calendar` coordinate system. for example,
  82563. // chart.setOptionp({
  82564. // calendar: {...},
  82565. // series: [{
  82566. // coordinateSystem: 'calendar'
  82567. // }]
  82568. // );
  82569. use(install$w); // ------------------
  82570. // Other components
  82571. // ------------------
  82572. // `graphic` component, for example:
  82573. // chart.setOption({
  82574. // graphic: {...}
  82575. // });
  82576. use(install$x); // `toolbox` component, for example:
  82577. // chart.setOption({
  82578. // toolbox: {...}
  82579. // });
  82580. use(install$z); // `tooltip` component, for example:
  82581. // chart.setOption({
  82582. // tooltip: {...}
  82583. // });
  82584. use(install$A); // `axisPointer` component, for example:
  82585. // chart.setOption({
  82586. // tooltip: {axisPointer: {...}, ...}
  82587. // });
  82588. // Or
  82589. // chart.setOption({
  82590. // axisPointer: {...}
  82591. // });
  82592. use(install$s); // `brush` component, for example:
  82593. // chart.setOption({
  82594. // brush: {...}
  82595. // });
  82596. // Or
  82597. // chart.setOption({
  82598. // tooltip: {feature: {brush: {...}}
  82599. // })
  82600. use(install$B); // `title` component, for example:
  82601. // chart.setOption({
  82602. // title: {...}
  82603. // });
  82604. use(install$C); // `timeline` component, for example:
  82605. // chart.setOption({
  82606. // timeline: {...}
  82607. // });
  82608. use(install$D); // `markPoint` component, for example:
  82609. // chart.setOption({
  82610. // series: [{markPoint: {...}}]
  82611. // });
  82612. use(install$E); // `markLine` component, for example:
  82613. // chart.setOption({
  82614. // series: [{markLine: {...}}]
  82615. // });
  82616. use(install$F); // `markArea` component, for example:
  82617. // chart.setOption({
  82618. // series: [{markArea: {...}}]
  82619. // });
  82620. use(install$G); // `legend` component not scrollable. for example:
  82621. // chart.setOption({
  82622. // legend: {...}
  82623. // });
  82624. use(install$J); // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  82625. use(install$M); // `dataZoom` component providing drag, pinch, wheel behaviors
  82626. // inside coodinate system, for example:
  82627. // chart.setOption({
  82628. // dataZoom: {type: 'inside'}
  82629. // });
  82630. use(install$K); // `dataZoom` component providing a slider bar, for example:
  82631. // chart.setOption({
  82632. // dataZoom: {type: 'slider'}
  82633. // });
  82634. use(install$L); // `visualMap` component including both `visualMapContinuous` and `visualMapPiecewise`.
  82635. use(install$P); // `visualMap` component providing continuous bar, for example:
  82636. // chart.setOption({
  82637. // visualMap: {type: 'continuous'}
  82638. // });
  82639. use(install$N); // `visualMap` component providing pieces bar, for example:
  82640. // chart.setOption({
  82641. // visualMap: {type: 'piecewise'}
  82642. // });
  82643. use(install$O); // `aria` component providing aria, for example:
  82644. // chart.setOption({
  82645. // aria: {...}
  82646. // });
  82647. use(install$Q); // dataset transform
  82648. // chart.setOption({
  82649. // dataset: {
  82650. // transform: []
  82651. // }
  82652. // });
  82653. use(install$R);
  82654. use(install$S); // universal transition
  82655. // chart.setOption({
  82656. // series: {
  82657. // universalTransition: { enabled: true }
  82658. // }
  82659. // })
  82660. use(installUniversalTransition); // label layout
  82661. // chart.setOption({
  82662. // series: {
  82663. // labelLayout: { hideOverlap: true }
  82664. // }
  82665. // })
  82666. use(installLabelLayout);
  82667. export { Axis, ChartView, ComponentModel, ComponentView, SeriesData as List, Model, PRIORITY, SeriesModel, color, connect, dataTool, dependencies, disConnect, disconnect, dispose$1 as dispose, env, extendChartView, extendComponentModel, extendComponentView, extendSeriesModel, format$1 as format, getCoordinateSystemDimensions, getInstanceByDom, getInstanceById, getMap, graphic$1 as graphic, helper, init$1 as init, brushSingle as innerDrawElementOnCanvas, matrix, number, parseGeoJSON, parseGeoJSON as parseGeoJson, registerAction, registerCoordinateSystem, registerLayout, registerLoading, registerLocale, registerMap, registerPostInit, registerPostUpdate, registerPreprocessor, registerProcessor, registerTheme, registerTransform, registerUpdateLifecycle, registerVisual, setCanvasCreator, setPlatformAPI, throttle, time, use, util$1 as util, vector, version$1 as version, util as zrUtil, zrender };
  82668. //# sourceMappingURL=echarts.esm.js.map